def writeline_flushed(self): self.set_writer(stream=FlushStream()) self.writer.writeline('foo') self.writer.writeline('foo', flush=True) Assert(self.stream.contents) == ['foo\n', True, 'foo\n', True] self.writer.writeline('foo', flush=False) Assert(self.stream.contents) == ['foo\n', True, 'foo\n', True, 'foo\n']
def tuple_dict(): PT = procrustes.Tuple(I, S, I) PD = procrustes.Dict({'a': I, 'b': S, 'c': PT}) pd = PD({'b': 'kuku', 'c': (None, 'Lorem', 91)}) Assert(pd.data) == {'a': None, 'c': (None, 'Lorem', None), 'b': 'kuku'} pd = PD({'b': 'kuku', 'c': (None, 'Lorem', 90)}) Assert(pd.data) == {'a': None, 'c': (None, 'Lorem', 90), 'b': 'kuku'}
def popitem(self): d = self.dict_class() with Assert.raises(TypeError): d.popitem() d = self.dict_class([(1, 2)]) with Assert.raises(TypeError): d.popitem()
def bound_row(): class SimpleTable(tables.Table): name = tables.Column() occupation = tables.Column() age = tables.Column() record = {'name': 'Bradley', 'age': 20, 'occupation': 'programmer'} table = SimpleTable([record]) row = table.rows[0] # integer indexing into a row Assert(row[0]) == record['name'] Assert(row[1]) == record['occupation'] Assert(row[2]) == record['age'] with Assert.raises(IndexError) as error: row[3] # column name indexing into a row Assert(row['name']) == record['name'] Assert(row['occupation']) == record['occupation'] Assert(row['age']) == record['age'] with Assert.raises(KeyError) as error: row['gamma']
def test_unique(): tests = [('aabbcc', 'abc'), ('aa', 'a'), (([1, 2], [1, 2], [3, 4], 5, 5, 5), ([1, 2], [3, 4], 5))] for test, result in tests: Assert(list(unique(test))) == list(result) Assert(list(unique('aaabbbbccc', seen='ab'))) == ['c']
def getslice(self): s = self.sequence_cls([[0, 1, 2], [3, 4, 5]]) Assert(s[:]) == range(6) Assert(s[:3]) == s[:-3] == [0, 1, 2] Assert(s[3:]) == s[-3:] == [3, 4, 5] Assert(s[2:]) == [2, 3, 4, 5] Assert(s[-2:]) == [4, 5]
def model_table(): """ The ``model`` option on a table causes the table to dynamically add columns based on the fields. """ class OccupationTable(tables.Table): class Meta: model = Occupation Assert(["id", "name", "region"]) == OccupationTable.base_columns.keys() class OccupationTable2(tables.Table): extra = tables.Column() class Meta: model = Occupation Assert(["id", "name", "region", "extra"]) == OccupationTable2.base_columns.keys() # be aware here, we already have *models* variable, but we're importing # over the top from django.db import models class ComplexModel(models.Model): char = models.CharField(max_length=200) fk = models.ForeignKey("self") m2m = models.ManyToManyField("self") class ComplexTable(tables.Table): class Meta: model = ComplexModel Assert(["id", "char", "fk"]) == ComplexTable.base_columns.keys()
def delslice(self): data = range(10) l = LazyList(self._genrange(10)) del data[3:6] del l[3:6] Assert(l.exhausted) == False Assert(l) == data
def pop(self): s = OrderedSet() with Assert.raises(KeyError): s.pop() s = OrderedSet([1, 2, 3]) Assert(s.pop()) == 3 Assert(s.pop(last=False)) == 1
def difference(self): a = OrderedSet('abc') Assert(a.difference('abc')) == OrderedSet() Assert(a.difference('a', 'b', 'c')) == OrderedSet() Assert(a - OrderedSet('ab')) == OrderedSet('c') with Assert.raises(TypeError): a - 'abc'
def symmetric_difference_update(self): old = s = OrderedSet('abc') s ^= OrderedSet('def') Assert(s) == OrderedSet('abcdef') Assert(s).is_(old) with Assert.raises(TypeError): s ^= 'ghi'
def union(self): a = OrderedSet('abc') b = OrderedSet('def') Assert(a.union('def', 'ghi')) == OrderedSet('abcdefghi') Assert(a | b) == OrderedSet('abcdef') with Assert.raises(TypeError): a | 'abc'
def intersection_update(self): old = s = OrderedSet('abc') with Assert.raises(TypeError): s &= 'ab' s &= OrderedSet('ab') Assert(s) == OrderedSet('ab') Assert(s).is_(old)
def decorate(self): @LRUCache.decorate(2) def foo(*args, **kwargs): time.sleep(.1) return args, kwargs tests = [(('foo', 'bar'), {}), (('foo', 'bar'), { 'spam': 'eggs' }), ((1, 2), {})] times = [] for test in tests: args, kwargs = test old = time.time() Assert(foo(*args, **kwargs)) == test new = time.time() uncached_time = new - old old = time.time() Assert(foo(*args, **kwargs)) == test new = time.time() cached_time = new - old Assert(cached_time) < uncached_time times.append((uncached_time, cached_time)) old = time.time() foo(*tests[0][0], **tests[0][1]) new = time.time() Assert(new - old) > times[0][1]
def mixed_arbitary_arguments(self): func = curried(lambda a, b, c, *args, **kwargs: (a, b, c, args, kwargs)) Assert(func(1, 2, 3)) == (1, 2, 3, (), {}) Assert(func(1, 2, 3, 4, 5)) == (1, 2, 3, (4, 5), {}) Assert(func(1, 2, 3, foo=4)) == (1, 2, 3, (), dict(foo=4)) Assert(func(1, 2, 3, 4, foo=5)) == (1, 2, 3, (4, ), dict(foo=5))
def multiple_thread_contexts(self): csm = ThreadContextStackManager() def make_func(name): def func(csm, queue, event): csm.push_thread(name) queue.put(list(csm.iter_current_stack())) event.wait() func.__name__ = name return func foo_queue = Queue() bar_queue = Queue() foo_event = Event() bar_event = Event() foo_thread = Thread(target=make_func('foo'), args=(csm, foo_queue, foo_event)) bar_thread = Thread(target=make_func('bar'), args=(csm, bar_queue, bar_event)) foo_thread.start() # during that time foo should have pushed an object on # the thread local stack time.sleep(1) bar_thread.start() foo_event.set() bar_event.set() Assert(foo_queue.get()) == ['foo'] Assert(bar_queue.get()) == ['bar'] Assert(list(csm.iter_current_stack())) == []
def inplace_update(self): old = s = OrderedSet() with Assert.raises(TypeError): s |= 'abc' s |= OrderedSet('abc') Assert(s) == OrderedSet('abc') Assert(s).is_(old)
def invalid_name(self): cases = [('brownie:itools.chain', 'itools.chain'), ('brownie-itools:chain', 'brownie-itools')] for test, invalid_identifier in cases: with Assert.raises(ValueError) as exc: import_string(test) Assert(invalid_identifier).in_(exc.args[0])
def unicode(): """Test LinkColumn""" # test unicode values + headings class UnicodeTable(tables.Table): first_name = tables.LinkColumn('person', args=[A('pk')]) last_name = tables.LinkColumn('person', args=[A('pk')], verbose_name=u'äÚ¨´ˆÁ˜¨ˆ˜˘Ú…Ò˚ˆπ∆ˆ´') dataset = [ { 'pk': 1, 'first_name': u'Brädley', 'last_name': u'∆yers' }, { 'pk': 2, 'first_name': u'Chr…s', 'last_name': u'DÒble' }, ] table = UnicodeTable(dataset) request = RequestFactory().get('/some-url/') template = Template('{% load django_tables2 %}{% render_table table %}') html = template.render(Context({'request': request, 'table': table})) Assert(u'Brädley' in html) Assert(u'∆yers' in html) Assert(u'Chr…s' in html) Assert(u'DÒble' in html)
def table(self): content = [['foo', 'bar'], ['spam', 'eggs']] self.writer.table(content) self.writer.table(content, padding=2) self.writer.table(content, ['hello', 'wo\nrld']) Assert(self.stream.getvalue()) == textwrap.dedent("""\ foo | bar spam | eggs foo | bar spam | eggs hello | wo\\nrld ------+-------- foo | bar spam | eggs """) with Assert.raises(ValueError): self.writer.table([]) with Assert.raises(ValueError): self.writer.table([['foo', 'bar'], ['spam']]) with Assert.raises(ValueError): self.writer.table([['foo', 'bar']], ['spam']) self.set_writer(stream=FlushStream()) self.writer.table(content) Assert(len(self.stream.contents)) == 2 Assert.isinstance(self.stream.contents[0], basestring) Assert(self.stream.contents[1]) == True
def colon_notation(self): import brownie.itools module = import_string('brownie:itools') Assert(module).is_(brownie.itools) func = import_string('brownie.itools:chain') Assert(func).is_(brownie.itools.chain)
def context_inheritance(self): class FooContextManager(ContextStackManagerEventletMixin, ContextStackManagerThreadMixin, ContextStackManagerBase): pass csm = FooContextManager() csm.push_application('foo') def foo(csm, queue): csm.push_thread('bar') queue.put(list(csm.iter_current_stack())) eventlet.spawn(bar, csm, queue).wait() queue.put(list(csm.iter_current_stack())) def bar(csm, queue): csm.push_coroutine('baz') queue.put(list(csm.iter_current_stack())) queue = Queue() thread = Thread(target=foo, args=(csm, queue)) thread.start() Assert(queue.get()) == ['bar', 'foo'] Assert(queue.get()) == ['baz', 'bar', 'foo'] Assert(queue.get()) == ['bar', 'foo'] Assert(list(csm.iter_current_stack())) == ['foo']
def simple_dict(): PD = procrustes.Dict({'a': I, 'b': S}) pd = PD({'a': None, 'b': 'Lorem Ipsum'}) Assert(pd.data) == {'a': None, 'b': 'Lorem Ipsum'} pd = PD({'b': 'Lorem Ipsum'}) Assert(pd.data) == {'a': None, 'b': 'Lorem Ipsum'}
def index(self): s = self.sequence_cls([[1, 1, 2], [3, 1, 4]]) Assert(s.index(1)) == 0 Assert(s.index(1, 1)) == 1 Assert(s.index(1, 2)) == 4 with Assert.raises(ValueError): s.index(1, 2, 3)
def setitem(self): data = ['foo', 'bar', 'baz'] l = LazyList(iter(data)) l[0] = 'spam' Assert(l.exhausted) == False Assert(l[0]) == 'spam' Assert(l) != data
def arguments_only_positionals(self): sig = Signature.from_function(lambda a, b, c: None) Assert(sig.bind_arguments((1, 2, 3))) == dict(a=1, b=2, c=3) Assert(sig.bind_arguments((1, 2), {'c': 3})) == dict(a=1, b=2, c=3) tests = [ ([('a', 1), ('b', 2)], "'.' is missing"), ([('a', 1)], "'.' and '.' are missing"), ([], "'.', '.' and '.' are missing") ] all_names = set('abc') for args, message in tests: names, values = [], [] for name, value in args: names.append(name) values.append(value) with Assert.raises(ValueError) as exc_args: sig.bind_arguments(values) with Assert.raises(ValueError) as exc_kwargs: sig.bind_arguments(kwargs=dict(args)) for exc in [exc_args, exc_kwargs]: err_msg = exc.args[0].obj assert re.match(message, err_msg) is not None for name in all_names.difference(names): assert name in err_msg with Assert.raises(ValueError) as exc: sig.bind_arguments((1, 2, 3), {'c': 4}) Assert(exc.args[0]) == "got multiple values for 'c'"
def update(self): writer = TerminalWriter(StringIO()) progressbar = ProgressBar([], writer) widget = Widget() with Assert.raises(NotImplementedError) as exc: widget.update(progressbar, writer.get_width()) Assert(exc.args[0]) == 'Widget.update'
def arguments_no_args(self): sig = Signature.from_function(lambda: None) Assert(sig.bind_arguments()) == {} with Assert.raises(ValueError) as exc: sig.bind_arguments((1, ), {}) Assert(exc.args[0]) == 'expected at most 0 positional arguments, got 1' tests = [ ({'a': 1}, "got unexpected keyword argument '.'"), ({'a': 1, 'b': 2}, "got unexpected keyword arguments '.' and '.'"), ( {'a': 1, 'b': 2, 'c': 3}, "got unexpected keyword arguments '.', '.' and '.'" ) ] for kwargs, message in tests: with Assert.raises(ValueError) as exc: sig.bind_arguments(kwargs=kwargs) err_msg = exc.args[0].obj assert re.match(message, err_msg) is not None for name in kwargs: assert name in err_msg
def _replace(self): nt = namedtuple('foo', ['spam', 'eggs']) t = nt(1, 2) Assert(t._replace(spam=3)) == (3, 2) Assert(t._replace(eggs=4)) == (1, 4) with Assert.raises(ValueError): t._replace(foo=1)
def exhausted(self): l = LazyList(range(10)) Assert(l.exhausted) == True l = LazyList(self._genrange(10)) Assert(l.exhausted) == False l[-1] Assert(l.exhausted) == True
def reverse(self): foo, bar = [1, 2, 3], [4, 5, 6] s = self.sequence_cls([foo, bar]) s.reverse() Assert(s) == [6, 5, 4, 3, 2, 1] Assert(foo) == [6, 5, 4] Assert(bar) == [3, 2, 1]
def sort(self): foo, bar = [3, 1, 2], [4, 6, 5] s = self.sequence_cls([foo, bar]) s.sort() Assert(s) == [1, 2, 3, 4, 5, 6] Assert(foo) == [1, 2, 3] Assert(bar) == [4, 5, 6]
def delslice(self): foo, bar = [0, 1, 2], [3, 4, 5] s = self.sequence_cls([foo, bar]) del s[2:4] Assert(s) == [0, 1, 4, 5] Assert(foo) == [0, 1] Assert(bar) == [4, 5]
def forms_simple(): str = forms.String()('kukuku') Assert(str.data) == 'kukuku' FT = forms.Tuple(forms.String(), forms.String()) ft = FT() widgets = [widget.render() for widget in ft.widgets()] Assert(widgets) == [ '<input id="form__0" name="form__0" parent="" value="">', '<input id="form__1" name="form__1" parent="" value="">' ] ft = FT(('kuku', 'kuku')) widgets = [widget.render() for widget in ft.widgets()] Assert(widgets) == [ '<input id="form__0" name="form__0" parent="" value="kuku">', '<input id="form__1" name="form__1" parent="" value="kuku">' ] FL = forms.List(forms.String()) fl = FL(['kuku', 'dsfasfd', 'xcvxczvx']) widgets = [widget.render() for widget in fl.widgets() if widget.render()] Assert(widgets) == [ '<input id="form__0" name="form__0" parent="" value="kuku">', '<input id="form__1" name="form__1" parent="" value="dsfasfd">', '<input id="form__2" name="form__2" parent="" value="xcvxczvx">' ]
def inplace_multiply(self): old = a = LazyList(self._genrange(10)) b = range(10) a *= 5 b *= 5 Assert(a) == b Assert(a).is_(old)
def orderbytuple(): obt = OrderByTuple('abc') Assert(obt) == (OrderBy('a'), OrderBy('b'), OrderBy('c')) Assert(obt[0]) == OrderBy('a') Assert(obt['b']) == OrderBy('b') with Assert.raises(IndexError) as error: obt['d'] with Assert.raises(TypeError) as error: obt[('tuple', )]
def pop(self): s = self.sequence_cls([]) with Assert.raises(IndexError): s.pop() s = self.sequence_cls([[0, 1, 2]]) with Assert.raises(IndexError): s.pop(3) Assert(s.pop()) == 2 Assert(s.pop(0)) == 0
def popitemlist(self): d = self.dict_class({'foo': 'bar'}) Assert(d.popitemlist()) == ('foo', ['bar']) with Assert.raises(KeyError): d.popitemlist() d = self.dict_class({'foo': ['bar', 'baz']}) Assert(d.popitemlist()) == ('foo', ['bar', 'baz']) with Assert.raises(KeyError): d.popitemlist()
def pop(self): d = self.dict_class() with Assert.raises(TypeError): d.pop(1) with Assert.raises(TypeError): d.pop(1, 2) d = self.dict_class({1: 2}) with Assert.raises(TypeError): d.pop(1)
def equality(): """Assert() == and !=""" Assert(1) == 1 Assert(1) != 0 with Assert.raises(AssertionError): Assert(1) == 0 with Assert.raises(AssertionError): Assert(1) != 1
def get_storage_should_return_correct_class(): assert get_storage('formwizard.storage.Storage') == Storage assert get_storage('formwizard.storage.CookieStorage') == CookieStorage assert get_storage('formwizard.storage.DummyStorage') == DummyStorage assert get_storage('formwizard.storage.SessionStorage') == SessionStorage with Assert.raises(MissingStorageModule): get_storage('formwizard.idontexist.NonExistentStorage') with Assert.raises(MissingStorageClass): get_storage('formwizard.storage.NonExistentStorage')
def type_checks_work(self): class Foo(object): __metaclass__ = ABCMeta class Bar(object): pass Foo.register(Bar) Assert.issubclass(Bar, Foo) Assert.isinstance(Bar(), Foo)
def json(): """Assert.json""" Assert('{"works": true}').json == dict(works=True) Assert('{"works": true}').json != dict(works=False) with Assert.raises(AssertionError): Assert('{"works": true}').json != dict(works=True) with Assert.raises(AssertionError): Assert('{"works": true}').json == dict(works=False)
def not_raising(): """Assert.not_raising""" with Assert.raises(AssertionError): with Assert.not_raising(RuntimeError): raise RuntimeError try: with Assert.not_raising(RuntimeError): pass except Exception: raise AssertionError("failed despite not raising RuntimeError")
def init(self): writer = TerminalWriter(StringIO()) progressbar = ProgressBar([], writer, maxsteps=20) widget = StepWidget() Assert(widget.init(progressbar, writer.get_width())) == '0 of 20' Assert(widget.size_hint(progressbar)) == 7 with Assert.raises(ValueError): StepWidget('foo') with Assert.not_raising(ValueError): StepWidget('bytes')
def stacking(self): s = StackedObject([]) with Assert.raises(AttributeError): s.foo with Assert.raises(RuntimeError): s.pop() s.push({'foo': False}) Assert(s.foo) == False s.push({'foo': True}) Assert(s.foo) == True s.pop() Assert(s.foo) == False
def disable_imports(): with attest.disable_imports('sys', 'os'): with Assert.raises(ImportError): import sys with Assert.raises(ImportError): import os import sys import os with attest.disable_imports(): import datetime assert datetime is sys.modules['datetime']
def contains(): """Assert() membership""" 1 in Assert([0, 1, 2]) Assert(1).in_([0, 1, 2]) Assert(3).not_in([0, 1, 2]) with Assert.raises(AssertionError): 3 in Assert([0, 1, 2]) with Assert.raises(AssertionError): Assert(3).in_([0, 1, 2]) with Assert.raises(AssertionError): Assert(1).not_in([0, 1, 2])
def pagination(): class BookTable(tables.Table): name = tables.Column() # create some sample data data = [] for i in range(100): data.append({"name": "Book No. %d" % i}) books = BookTable(data) # external paginator paginator = Paginator(books.rows, 10) assert paginator.num_pages == 10 page = paginator.page(1) assert page.has_previous() is False assert page.has_next() is True # integrated paginator books.paginate(page=1) Assert(hasattr(books, "page")) is True books.paginate(page=1, per_page=10) Assert(len(list(books.page.object_list))) == 10 # new attributes Assert(books.paginator.num_pages) == 10 Assert(books.page.has_previous()) is False Assert(books.page.has_next()) is True # exceptions are converted into 404s with Assert.raises(Http404) as error: books.paginate(Paginator, page=9999, per_page=10) books.paginate(Paginator, page='abc', per_page=10)
def run(): """Tests().run""" col = Tests() @col.test def fail(): assert 1 == 2 @col.test def succeed(): assert 1 == 1 @col.test def exit(): raise SystemExit result = TestReporter() with Assert.not_raising(SystemExit): col.run(result) assert len(result.failed) == 2 assert len(result.succeeded) == 1 assert result.failed[0].test.__wrapped__ is fail assert result.failed[0].exc_info[0] is TestFailure assert result.succeeded[0].test.__wrapped__ is succeed
def arguments_mixed_positionals(self): sig = Signature.from_function(lambda a, b, *args: None) Assert(sig.bind_arguments((1, 2))) == dict(a=1, b=2, args=()) Assert(sig.bind_arguments((1, 2, 3))) == dict(a=1, b=2, args=(3, )) with Assert.raises(ValueError): Assert(sig.bind_arguments())
def pop(self): d = self.dict_class() d[1] = 2 Assert(d.pop(1)) == 2 with Assert.raises(KeyError): d.pop(1) Assert(d.pop(1, 2)) == 2
def hashability(self): a = self.dict_class([(1, 2), (3, 4)]) b = self.dict_class(a) Assert(hash(a)) == hash(b) Assert(hash(a)) != hash(ImmutableDict([(1, 2), (5, 6)])) with Assert.raises(TypeError): hash(ImmutableDict({1: []}))
def delitem(self): d = self.dict_class() d[1] = 2 Assert(d[1]) == 2 del d[1] with Assert.raises(KeyError): del d[1]