def test_message(): try: assert_is(1, None, message='custom message') except AssertionError as e: assert_in('custom message', str(e)) else: assert False, 'should have thrown assertion error'
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)
def test_errors(): def f1(): assert 0, 'holy moly' def raise_later(e): errors.reraise(e) def f2(): try: f1() except AssertionError as e: prepared_e = errors.prepare_for_reraise(e) else: assert False, 'f1 should have raised AssertionError' raise_later(prepared_e) try: f2() except AssertionError: formatted = traceback.format_tb(sys.exc_info()[2]) formatted_message = ''.join(formatted) assert_in('holy moly', formatted_message) assert_in('f1', formatted_message) else: assert False, 'f2 should have raised AssertionError'
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)
def test_message(): try: assert_is(1, None, message="custom message") except AssertionError as e: assert_in("custom message", str(e)) else: assert False, "should have thrown assertion error"
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)
def test_unbound_method_value(): val = value.UnboundMethodValue("get_prop_with_get", tests.PropertyObject) assert_eq("<method get_prop_with_get on pyanalyze.tests.PropertyObject>", str(val)) assert_eq("get_prop_with_get", val.attr_name) assert_is(tests.PropertyObject, val.typ) assert_is(None, val.secondary_attr_name) assert_eq(tests.PropertyObject.get_prop_with_get, val.get_method()) assert val.is_type(object) assert not val.is_type(str) val = value.UnboundMethodValue("get_prop_with_get", tests.PropertyObject, secondary_attr_name="asynq") assert_eq( "<method get_prop_with_get.asynq on pyanalyze.tests.PropertyObject>", str(val)) assert_eq("get_prop_with_get", val.attr_name) assert_is(tests.PropertyObject, val.typ) assert_eq("asynq", val.secondary_attr_name) method = val.get_method() assert_in(method.__name__, tests.ASYNQ_METHOD_NAMES) assert_eq(tests.PropertyObject.get_prop_with_get, method.__self__) assert val.is_type(object) assert not val.is_type(str)
def test_format_error(): assert_is(None, asynq.debug.format_error(None)) # Syntax highlighting adds color text between words asynq.debug.enable_traceback_syntax_highlight(False) e = RuntimeError() expected = 'RuntimeError\n' assert_eq(expected, asynq.debug.format_error(e)) e._task = async_fn.asynq() formatted = asynq.debug.format_error(e) assert_in(expected, formatted) try: raise RuntimeError except RuntimeError: e._traceback = sys.exc_info()[2] formatted = asynq.debug.format_error(e) assert_in(expected, formatted) assert_in('Traceback', formatted) # Each single word, and unformatted text should be present asynq.debug.enable_traceback_syntax_highlight(True) expected = 'RuntimeError' formatted = asynq.debug.format_error(e) assert_in(expected, formatted) assert_in('Traceback', formatted)
def assert_eq_extracted_traceback_entry( entry, filename, fn_name, line): entry_filename, _, entry_fn_name, entry_line = entry assert_in(filename.rstrip('c'), entry_filename) assert_eq(fn_name, entry_fn_name) assert_eq(line, entry_line)
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())
def test_dump_stack(): buf = StringIO() with asynq.mock.patch('sys.stdout', buf): def inner(): asynq.debug.dump_stack() inner() printed = buf.getvalue() assert_in('test_dump_stack', printed) assert_in('Stack trace:', printed)
def test_dump_stack(): buf = StringIO() with asynq.mock.patch("sys.stdout", buf): def inner(): asynq.debug.dump_stack() inner() printed = buf.getvalue() assert_in("test_dump_stack", printed) assert_in("Stack trace:", printed)
def test_dump_asynq_stack(): @asynq.asynq() def caller(): yield asynq.debug.dump_asynq_stack() buf = StringIO() with asynq.mock.patch('sys.stdout', buf): caller() printed = buf.getvalue() assert_in('caller', printed)
def test_assert_dict_eq(): assert_dict_eq({"a": 1}, {"a": 1}) with AssertRaises(AssertionError): assert_dict_eq({"a": 1}, {"b": 1}) with AssertRaises(AssertionError): assert_dict_eq({"a": "abc"}, {"a": "xyz"}) try: assert_dict_eq({"a": {"b": {"c": 1}}}, {"a": {"b": {"d": 1}}}) except AssertionError as e: assert_in("'a'->'b'", str(e)) else: assert False, "should have thrown assertion error"
def test_assert_dict_eq(): assert_dict_eq({'a': 1}, {'a': 1}) with AssertRaises(AssertionError): assert_dict_eq({'a': 1}, {'b': 1}) with AssertRaises(AssertionError): assert_dict_eq({'a': 'abc'}, {'a': 'xyz'}) try: assert_dict_eq({'a': {'b': {'c': 1}}}, {'a': {'b': {'d': 1}}}) except AssertionError as e: assert_in('\'a\'->\'b\'', str(e)) else: assert False, 'should have thrown assertion error'
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)
def test_sets(self): c = LRUCache(3) c[0] = "a" c[1] = "b" c[2] = "c" # Updating a value should make it MRU c[0] = "d" assert_in(0, c) self._check_order([(1, "b"), (2, "c"), (0, "d")], c) # Update order and evict the LRU item c[3] = "e" assert_in(3, c) self._check_order([(2, "c"), (0, "d"), (3, "e")], c)
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)
def test_sets(self): c = LRUCache(3) c[0] = 'a' c[1] = 'b' c[2] = 'c' # Updating a value should make it MRU c[0] = 'd' assert_in(0, c) self._check_order([(1, 'b'), (2, 'c'), (0, 'd')], c) # Update order and evict the LRU item c[3] = 'e' assert_in(3, c) self._check_order([(2, 'c'), (0, 'd'), (3, 'e')], c)
def test_exact_gender(cls): assert_eq([cls.male, cls.female], cls.get_members()) assert_eq([cls.male, cls.female], list(cls)) assert_eq(1, cls.male) assert_eq(2, cls.female) assert_eq(cls.male, Gender.male) assert_eq(cls.female, Gender.female) assert_in(cls.male, cls) assert_eq(cls.male, cls.parse(1)) assert_eq(cls.male, cls.parse('male')) assert_eq(cls.male, cls.parse(cls.male)) assert_eq(cls.male, cls(1)) assert_eq(cls.male, cls('male')) assert_eq(cls.male, cls(cls.male))
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)
def test_format_asynq_stack(): format_list = [] @asynq.asynq() def level1(arg): if arg == 0: format_list.append(asynq.debug.format_asynq_stack()) result(arg) return @asynq.asynq() def level2(arg): result((yield level1.asynq(arg))) return @asynq.asynq() def root(): vals = yield [level2.asynq(i) for i in range(5)] result(vals) return root() traceback = '\n'.join(format_list[0]) assert_in('root', traceback) assert_in('level1', traceback) assert_in('level2', traceback)
def test_extra(): try: assert_eq('thing1', 'thing2', extra='something extra') except AssertionError as e: assert_in('thing1', str(e)) assert_in('thing2', str(e)) assert_in('something extra', str(e)) else: assert False, 'should have thrown assertion error'
def test_extra(): try: assert_eq("thing1", "thing2", extra="something extra") except AssertionError as e: assert_in("thing1", str(e)) assert_in("thing2", str(e)) assert_in("something extra", str(e)) else: assert False, "should have thrown assertion error"
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"
def test_asynq_traceback_gets_glued_at_each_task_level(): # tests that exceptions are producting the right tracebacks traceback_to_verify = None try: async_function_whose_child_async_task_will_throw_an_error() except ValueError: traceback_to_verify = sys.exc_info()[2] assert_is_not(None, traceback_to_verify) traceback_printed = '\n'.join(traceback.format_tb(traceback_to_verify)) assert_in(non_async_function_that_raises_an_error.__name__, traceback_printed) assert_in(async_function_that_raises_an_error.__name__, traceback_printed) assert_in(async_function_whose_child_async_task_will_throw_an_error.__name__, traceback_printed)
def test_format_error_chaining(): if six.PY2: return # py2 doesn't have chaining try: try: raise ValueError except ValueError: raise KeyError except KeyError as e: prepare_for_reraise(e) exc = e formatted = asynq.debug.format_error(exc) assert_in('raise ValueError', formatted) assert_in('raise KeyError', formatted) assert_in('During handling of the', formatted)
def test_format_error(): assert_is(None, asynq.debug.format_error(None)) e = RuntimeError() expected = '\nRuntimeError\n' assert_eq(expected, asynq.debug.format_error(e)) e._task = async_fn.asynq() formatted = asynq.debug.format_error(e) assert_in(expected, formatted) try: raise RuntimeError except RuntimeError: e._traceback = sys.exc_info()[2] formatted = asynq.debug.format_error(e) assert_in(expected, formatted) assert_in('Traceback', formatted)
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)
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)