import gobject

# store finalized status of a source
class WasFinalized(object):
    def __nonzero__(self):
        try:
            return self.finalized
        except:
            return False

# source which reports its death
class DerivedSource(gobject.Source):
    def __init__(self, wf):
        gobject.Source.__init__(self)

        self.wf = wf

    def finalize(self):
        self.wf.finalized = True

# unattached, should be dealloced after return
def after_return():
    wf = WasFinalized()
    s = DerivedSource(wf)

    return wf

# attached, should be dealloced after destroy() and return
def after_destroy():
    wf = WasFinalized()
    wf.c = gobject.MainContext()
    s = DerivedSource(wf)

    s.attach(wf.c)
    s.destroy()

    return wf

# should be dealloced after context is destroyed on return
def after_context_death():
    wf = WasFinalized()
    c = gobject.MainContext()
    s = DerivedSource(wf)

    s.attach(c)

    return wf

# should not be dealloced, still attached
def still_attached():
    wf = WasFinalized()
    wf.c = gobject.MainContext()
    s = DerivedSource(wf)

    s.attach(wf.c)

    return wf

# assert correct behavior
def assert_tests():
    assert after_return()
    assert after_destroy()
    assert after_context_death()
    assert not still_attached()

# run on invocation
if __name__ == '__main__':
    assert_tests()

