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 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 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 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 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 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 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 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 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 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 equality(): """Assert() == and !=""" Assert(1) == 1 Assert(1) != 0 with Assert.raises(AssertionError): Assert(1) == 0 with Assert.raises(AssertionError): Assert(1) != 1
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_issubclass(): """Assert.not_issubclass""" with Assert.raises(AssertionError) as error: Assert.not_issubclass(int, (int, float)) error.__str__() == "issubclass(int, (int, float))" with Assert.raises(AssertionError) as error: Assert.not_issubclass(int, int) error.__str__() == "issubclass(int, int)" Assert.not_issubclass(int, str)
def issubclass(): """Assert.issubclass""" with Assert.raises(AssertionError) as error: Assert.issubclass(str, (int, float)) error.__str__() == "not issubclass(str, (int, float))" with Assert.raises(AssertionError) as error: Assert.issubclass(str, int) error.__str__() == "not issubclass(str, int)" Assert.issubclass(str, str)
def not_isinstance(): """Assert.not_isinstance""" with Assert.raises(AssertionError) as error: Assert.not_isinstance(1, (int, float)) error.__str__() == "isinstance(1, (int, float))" with Assert.raises(AssertionError) as error: Assert.not_isinstance(1, int) error.__str__() == "isinstance(1, int)" Assert.not_isinstance("hello", int)
def isinstance(): """Assert.isinstance""" with Assert.raises(AssertionError) as error: Assert.isinstance("hello", (int, float)) error.__str__() == "not isinstance('hello', (int, float))" with Assert.raises(AssertionError) as error: Assert.isinstance("hello", int) error.__str__() == "not isinstance('hello', int)" Assert.isinstance("hello", basestring)
def arguments_mixed_positional_arbitary_keyword_arguments(self): sig = Signature.from_function(lambda a, b, **kwargs: None) Assert(sig.bind_arguments((1, 2))) == dict(a=1, b=2, kwargs={}) Assert(sig.bind_arguments((1, 2), {'c': 3})) == dict(a=1, b=2, kwargs=dict(c=3)) Assert(sig.bind_arguments((), dict(a=1, b=2))) == dict(a=1, b=2, kwargs={}) with Assert.raises(ValueError): sig.bind_arguments() with Assert.raises(ValueError): sig.bind_arguments((1, 2), {'a': 3})
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 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 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]
def basic_creation(): q = quantum.now() Assert(q.tz) == None Assert.isinstance(q.as_utc(), datetime) with Assert.raises(quantum.QuantumException): Assert.isinstance(q.as_local(), datetime) q = quantum.parse('2013-06-27T12:27:54', timezone='UTC') Assert(q.tz) == pytz.utc Assert.isinstance(q.as_utc(), datetime) Assert(q.as_utc()) == datetime(2013, 6, 27, 12, 27, 54) Assert(q.as_local()) == datetime(2013, 6, 27, 12, 27, 54) q = quantum.parse('2013-06-27T12:27:54', timezone='Pacific/Auckland') Assert(q.tz) == pytz.timezone('Pacific/Auckland') Assert.isinstance(q.dt, datetime) Assert(q.as_utc()) == datetime(2013, 6, 27, 0, 27, 54) Assert(q.as_local()) == datetime(2013, 6, 27, 12, 27, 54) q = quantum.parse('2013-06-26 3:27pm', timezone='UTC', relaxed=True) Assert(q.tz) == pytz.utc Assert.isinstance(q.dt, datetime) Assert(q.as_utc()) == datetime(2013, 6, 26, 15, 27, 0) Assert(q.as_local()) == datetime(2013, 6, 26, 15, 27, 0) q = quantum.parse('2013-06-26 3:27pm', relaxed=True, timezone='Pacific/Auckland') Assert(q.tz) == pytz.timezone('Pacific/Auckland') Assert.isinstance(q.dt, datetime) Assert(q.as_utc()) == datetime(2013, 6, 26, 3, 27, 0) Assert(q.as_local()) == datetime(2013, 6, 26, 15, 27, 0)
def should_raise_exception_if_session_middleware_not_used(): class Step1(forms.Form): name = forms.CharField() class Step2(forms.Form): name = forms.CharField() class StepsWizardView(WizardView): # pylint: ignore=W0223 storage = 'formwizard.storage.SessionStorage' steps = ( ("Step 1", Step1), ("Step 2", Step2), ) template_name = 'simple.html' view = StepsWizardView.as_view() request = factory.get('/') with Assert.raises(ImproperlyConfigured): view(request) # use session middleware and no exceptions should be raised middleware = SessionMiddleware() request = factory.get('/') middleware.process_request(request) view(request)
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 _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 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 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 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 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 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 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 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 inplace_update(self): old = s = OrderedSet() with Assert.raises(TypeError): s |= 'abc' s |= OrderedSet('abc') Assert(s) == OrderedSet('abc') Assert(s).is_(old)
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 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 arbitary_keyword_arguments(self): func = curried(lambda a, b, c, **kwargs: (a, b, c, kwargs)) Assert(func(1, 2, 3)) == (1, 2, 3, {}) with Assert.raises(TypeError): func(1, 2)(3, c=4) Assert(func(1, 2, 3, foo=4)) == (1, 2, 3, dict(foo=4)) Assert(func(1)(2, 3, foo=4)) == (1, 2, 3, dict(foo=4)) Assert(func(1, 2)(3, foo=4)) == (1, 2, 3, dict(foo=4))
def quickfix_reporter(): """QuickFixReporter""" with attest.capture_output() as (out, err): with Assert.raises(SystemExit): _meta.suite.run(attest.QuickFixReporter) assert out == ['%s:%d: TestFailure' % (SOURCEFILE, LINENO)]