Ejemplo n.º 1
0
def test_intenum():
    assert_is_instance(Python.two, int)
    assert_eq('Python.two', repr(Python.two))
    assert_eq('2', json.dumps(Python.two))
    assert_in(Python.two, Python)
    assert_in(2, Python)
    assert_not_in(4, Python)
Ejemplo n.º 2
0
def test_cached_per_instance_pickling():

    # make sure cached stuff doesn't appear in the pickled representation

    obj = PickleTestClass()
    obj.attr = 'spam'
    assert_is(False, hasattr(obj, '__lib_cache'))
    obj.f('my hovercraft is full of eels')
    assert_eq(1, len(obj.__lib_cache))

    serialized = pickle.dumps(obj)
    assert_not_in(b'my hovercraft is full of eels', serialized)
    assert_in(b'spam', serialized)

    restored = pickle.loads(serialized)
    assert_is(False, hasattr(restored, '__lib_cache'))
    restored.f('my hovercraft is full of eels')
    assert_eq(1, len(restored.__lib_cache))
    assert_eq('spam', obj.attr)

    # make sure we can't use this with a custom __getstate__

    with AssertRaises(AssertionError):

        class X(object):
            @cached_per_instance()
            def f(self, x):
                return x

            def __getstate__(self):
                return {}

        X().f(1)
Ejemplo n.º 3
0
def test_cached_per_instance_pickling():

    # make sure cached stuff doesn't appear in the pickled representation

    obj = PickleTestClass()
    obj.attr = 'spam'
    assert_eq(set(),
              set(PickleTestClass.f.__cached_per_instance_cache__.keys()))
    obj.f('my hovercraft is full of eels')
    assert_eq({id(obj)},
              set(PickleTestClass.f.__cached_per_instance_cache__.keys()))

    serialized = pickle.dumps(obj)
    assert_not_in(b'my hovercraft is full of eels', serialized)
    assert_in(b'spam', serialized)

    restored = pickle.loads(serialized)
    assert_eq({id(obj)},
              set(PickleTestClass.f.__cached_per_instance_cache__.keys()))
    restored.f('my hovercraft is full of eels')
    assert_eq({id(obj), id(restored)},
              set(PickleTestClass.f.__cached_per_instance_cache__.keys()))
    assert_eq('spam', obj.attr)

    # make sure we can use this with a custom __getstate__

    class X(object):
        @cached_per_instance()
        def f(self, x):
            return x

        def __getstate__(self):
            return {}

    X().f(1)
Ejemplo n.º 4
0
    def test_current_and_module_scope(self):
        assert_in("foo", self.scopes.current_scope())
        assert_in("foo", self.scopes.module_scope())

        with self.scopes.add_scope(ScopeType.function_scope, scope_node=None):
            assert_not_in("foo", self.scopes.current_scope())
            assert_in("foo", self.scopes.module_scope())

        assert_in("foo", self.scopes.current_scope())
        assert_in("foo", self.scopes.module_scope())
Ejemplo n.º 5
0
def test_mock_async_dict():
    assert_eq('guinea pigs', IMPORTANT_DICTIONARY['capybaras'])

    with asynq.mock.patch.dict(
            'asynq.tests.test_mock.IMPORTANT_DICTIONARY', {'capybaras': 'maras'}):
        assert_eq('maras', IMPORTANT_DICTIONARY['capybaras'])
        assert_eq('coypus', IMPORTANT_DICTIONARY['hutias'])
    assert_eq('guinea pigs', IMPORTANT_DICTIONARY['capybaras'])

    with asynq.mock.patch.dict('asynq.tests.test_mock.IMPORTANT_DICTIONARY', {'capybaras': 'maras'},
                               clear=True):
        assert_eq('maras', IMPORTANT_DICTIONARY['capybaras'])
        assert_not_in('hutias', IMPORTANT_DICTIONARY)
Ejemplo n.º 6
0
def test_mock_async_dict():
    assert_eq("guinea pigs", IMPORTANT_DICTIONARY["capybaras"])

    with asynq.mock.patch.dict("asynq.tests.test_mock.IMPORTANT_DICTIONARY",
                               {"capybaras": "maras"}):
        assert_eq("maras", IMPORTANT_DICTIONARY["capybaras"])
        assert_eq("coypus", IMPORTANT_DICTIONARY["hutias"])
    assert_eq("guinea pigs", IMPORTANT_DICTIONARY["capybaras"])

    with asynq.mock.patch.dict("asynq.tests.test_mock.IMPORTANT_DICTIONARY",
                               {"capybaras": "maras"},
                               clear=True):
        assert_eq("maras", IMPORTANT_DICTIONARY["capybaras"])
        assert_not_in("hutias", IMPORTANT_DICTIONARY)
Ejemplo n.º 7
0
    def test_get(self):
        c = LRUCache(3)
        c[0] = 'a'
        c[1] = 'b'
        c[2] = 'c'

        # Getting a value should make it MRU
        assert_in(1, c)
        assert_eq('b', c.get(1))
        self._check_order([(0, 'a'), (2, 'c'), (1, 'b')], c)

        # Missing value should have no effect
        assert_not_in(100, c)
        assert_eq(miss, c.get(100))
        self._check_order([(0, 'a'), (2, 'c'), (1, 'b')], c)
Ejemplo n.º 8
0
    def test_get(self):
        c = LRUCache(3)
        c[0] = "a"
        c[1] = "b"
        c[2] = "c"

        # Getting a value should make it MRU
        assert_in(1, c)
        assert_eq("b", c.get(1))
        self._check_order([(0, "a"), (2, "c"), (1, "b")], c)

        # Missing value should have no effect
        assert_not_in(100, c)
        assert_eq(miss, c.get(100))
        self._check_order([(0, "a"), (2, "c"), (1, "b")], c)
Ejemplo n.º 9
0
def test_assert_not_in():
    # test truncation of very long strings
    seq = 'a' * 1000 + 'bbb' + 'a' * 1000
    with AssertRaises(AssertionError) as ar:
        assert_not_in('bbb', seq)
    e = ar.expected_exception_found
    assert_eq(
        "'bbb' is in '(truncated) ...%sbbb%s... (truncated)'" %
        ('a' * 50, 'a' * 50), str(e))

    # same as above when the match is at index 0
    seq = 'a' * 1000
    with AssertRaises(AssertionError) as ar:
        assert_not_in('aaa', seq)
    e = ar.expected_exception_found
    assert_eq("'aaa' is in 'aaa%s... (truncated)'" % ('a' * 50), str(e))
Ejemplo n.º 10
0
def test_event_hub():
    h = qcore.EventHub()

    assert_eq(0, len(h))
    assert_eq('EventHub({})', repr(h))

    with AssertRaises(AttributeError):
        h.doesnt_start_with_on

    h_e = h.on_e
    assert_is_instance(h_e, qcore.EventHook)
    assert_eq(1, len(h))
    assert_is(h_e, h['e'])
    assert_eq("EventHub({'e': %r})" % h_e, repr(h))
    assert_is(h, h.safe_trigger('e'))
    assert_is(h, h.trigger('e'))

    h_e.subscribe(lambda: 0)

    assert_in('e', h)
    assert_not_in('f', h)

    h['f'] = None
    assert_is(None, h['f'])
    assert_in('f', h)
    assert_eq(2, len(h))

    del h['f']
    assert_not_in('f', h)
    assert_eq(1, len(h))

    for k, v in h:
        assert_eq('e', k)
        assert_is(h_e, v)

    def bad_fn(*args):
        raise NotImplementedError()

    m = mock.MagicMock()
    h.on_test.subscribe(bad_fn)
    with AssertRaises(NotImplementedError):
        h.on('test', m).safe_trigger('test', 1)
    m.assert_called_once_with(1)
    m.reset_mock()

    h.off('test', bad_fn).trigger('test', 2, 3)
    m.assert_called_once_with(2, 3)
Ejemplo n.º 11
0
def test_sinking_event_hook():
    def failing_handler():
        raise RuntimeError

    events = qcore.events.SinkingEventHook()
    assert_eq([], list(events))
    events.subscribe(failing_handler)
    assert_eq([], list(events))
    events.unsubscribe(failing_handler)
    assert_eq([], list(events))

    events.trigger()
    events.safe_trigger()
    events()

    assert_not_in(None, events)
    assert_not_in(False, events)
    assert_eq('SinkingEventHook()', str(events))
Ejemplo n.º 12
0
    def test_lineno(self):
        code_string = """# line 1
# line 2
# line 3
# line 4
h.translate('{foo')  # line 5
# line 6
# line 7
# line 8
# line 9
"""
        try:
            self.assert_passes(code_string)
        except VisitorError as e:
            assert_not_in("   1:", str(e))
            for lineno in range(2, 9):
                assert_in("   %d:" % lineno, str(e))
                assert_in("# line %d" % lineno, str(e))
            # should be outside the three context lines
            for lineno in (1, 9):
                assert_not_in("   %d:" % lineno, str(e))
                assert_not_in("# line %d" % lineno, str(e))
        else:
            assert False, "Expected a parse error"
Ejemplo n.º 13
0
def test_events():
    global count
    h0 = lambda: handler(0)
    h1 = lambda: handler(1)
    h2 = lambda: handler(2)
    h0e = lambda: handler(0, True)

    count = 0
    events = qcore.EventHook()
    assert_eq('EventHook()', str(events))
    assert_eq('EventHook()', repr(events))

    events.subscribe(h0)
    assert_eq('EventHook(%r,)' % h0, str(events))
    assert_eq('EventHook(%r,)' % h0, repr(events))

    events()
    assert_eq(count, 1)

    count = 0
    events = qcore.EventHook()
    assert_eq([], list(events))
    events.subscribe(h0)
    events.subscribe(h1)
    assert_eq([h0, h1], list(events))
    assert_in(h0, events)
    assert_in(h1, events)
    assert_not_in(h2, events)

    events()
    assert_eq(count, 2)

    count = 0
    events = qcore.EventHook()
    events.subscribe(h0e)
    events.subscribe(h1)
    try:
        events()
    except BaseException:
        pass
    assert_eq(count, 1)

    count = 0
    events = qcore.EventHook()
    events.subscribe(h0e)
    events.subscribe(h1)
    try:
        events.safe_trigger()
    except BaseException:
        pass
    assert_eq(count, 2)

    count = 0
    events = qcore.EventHook()
    events.subscribe(h0)
    events.subscribe(h1)
    events()
    assert_eq(count, 2)
    count = 0
    events.unsubscribe(h1)
    events()
    assert_eq(count, 1)
    count = 0
    events.unsubscribe(h0)
    events()
    assert_eq(count, 0)

    events = qcore.EventHook()
    events.subscribe(h0)
    events.subscribe(h1)
    events.unsubscribe(h0)
    count = 1
    events()
    assert_eq(count, 2)
    count = 0
    events.unsubscribe(h1)
    events()
    assert_eq(count, 0)

    events = qcore.EventHook()
    events.subscribe(h0)
    events.subscribe(h1)
    events.subscribe(h2)
    events.unsubscribe(h1)
    events.unsubscribe(h0)
    events.unsubscribe(h2)
    count = 0
    events()
    assert_eq(count, 0)
Ejemplo n.º 14
0
def test_instances():
    assert_eq(0, Gender.undefined)
    assert_eq(1, Gender.male)
    assert_eq(2, Gender.female)

    assert_eq(0, Gender.undefined())
    assert_eq(1, Gender.male())
    assert_eq(2, Gender.female())

    assert_eq(0, Gender.undefined.value)
    assert_eq(1, Gender.male.value)
    assert_eq(2, Gender.female.value)

    assert_eq(Gender(0), Gender.undefined)
    assert_eq(Gender(1), Gender.male)
    assert_eq(Gender(2), Gender.female)

    assert Gender(0).is_valid()

    g0 = Gender.parse(0)
    assert isinstance(g0, Gender)
    assert_eq(0, g0.value)
    g1 = Gender.parse(1)
    assert isinstance(g1, Gender)
    assert_eq(1, g1.value)
    assert_is(None, Gender.parse(4, None))
    assert_raises(lambda: Gender.parse(4), KeyError)
    assert_eq(hash(2), hash(Gender(2)))

    assert_eq('xy', str(Xyz.xy))
    assert_eq('Xyz.xy', repr(Xyz.xy))

    assert_eq(Xyz.xy, Xyz.x | Xyz.y)
    assert_eq(5, Xyz.x | Xyz.y)
    assert_eq(5, Xyz.x | 4)
    assert_eq(5, Xyz.x | Xyz.y)

    assert_eq(Xyz.xy, Xyz.x | Xyz.y)
    assert_eq(8 | 5, Xyz.z | Xyz.xy)

    assert_eq(Xyzna.na, Xyz.x & Xyz.y)

    assert_in(Xyz.x, Xyz.xy)
    assert_in(Xyz.y, Xyz.xy)
    assert_in(Xyz.xy, Xyz.xy)
    assert_not_in(Xyz.z, Xyz.xy)
    assert_not_in(Xyz.z, Xyz.x)
    assert_not_in(Xyz.z, Xyz.y)

    assert_in(Xyz.x(), Xyz.xy)
    assert_in(Xyz.y(), Xyz.xy)
    assert_in(Xyz.xy(), Xyz.xy)
    assert_not_in(Xyz.z(), Xyz.xy)
    assert_not_in(Xyz.z(), Xyz.x)
    assert_not_in(Xyz.z(), Xyz.y)

    assert_in(Xyzna.na, Xyzna.x)
    assert_in(Xyzna.na, Xyzna.y)
    assert_in(Xyzna.na, Xyzna.xy)
    assert_in(Xyzna.na, Xyzna.z)
    assert_in(Xyzna.na, Xyzna.na)

    xyz1 = Xyz.parse('z,xy')
    xyz2 = Xyz.parse('x,y,z')
    xyz3 = Xyz.parse('xy,z')
    xyz4 = Xyz.parse(8 | 5)
    assert isinstance(xyz1, Xyz)
    assert isinstance(xyz2, Xyz)
    assert isinstance(xyz3, Xyz)
    assert isinstance(xyz4, Xyz)
    assert_eq(8 | 5, xyz1.value)
    assert_eq(8 | 5, xyz2.value)
    assert_eq(8 | 5, xyz3.value)
    assert_eq(8 | 5, xyz4.value)
    assert_is(None, Xyz.parse(100, None))
    assert_raises(lambda: Xyz.parse(100), KeyError)

    na1 = Xyz.parse('')
    na2 = Xyzna.parse('na')
    na3 = Xyzna.parse('na')
    assert isinstance(na1, Xyz)
    assert isinstance(na2, Xyzna)
    assert isinstance(na3, Xyzna)
    assert_eq(0, na1)
    assert_eq(0, na2)
    assert_eq(0, na3)