Example #1
0
 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']
Example #2
0
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'}
Example #3
0
 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()
Example #4
0
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']
Example #5
0
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']
Example #6
0
 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]
Example #7
0
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()
Example #8
0
 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
Example #9
0
 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
Example #10
0
 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'
Example #11
0
 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'
Example #12
0
 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'
Example #13
0
 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)
Example #14
0
    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]
Example #15
0
 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))
Example #16
0
    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())) == []
Example #17
0
 def inplace_update(self):
     old = s = OrderedSet()
     with Assert.raises(TypeError):
         s |= 'abc'
     s |= OrderedSet('abc')
     Assert(s) == OrderedSet('abc')
     Assert(s).is_(old)
Example #18
0
 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])
Example #19
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)
Example #20
0
    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
Example #21
0
    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)
Example #22
0
    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']
Example #23
0
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'}
Example #24
0
 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)
Example #25
0
 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
Example #26
0
    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'"
Example #27
0
 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'
Example #28
0
    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
Example #29
0
 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)
Example #30
0
 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
Example #31
0
 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]
Example #32
0
 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]
Example #33
0
 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]
Example #34
0
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">'
    ]
Example #35
0
 def inplace_multiply(self):
     old = a = LazyList(self._genrange(10))
     b = range(10)
     a *= 5
     b *= 5
     Assert(a) == b
     Assert(a).is_(old)
Example #36
0
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', )]
Example #37
0
 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
Example #38
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()
Example #39
0
 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)
Example #40
0
def equality():
    """Assert() == and !="""

    Assert(1) == 1
    Assert(1) != 0

    with Assert.raises(AssertionError):
        Assert(1) == 0

    with Assert.raises(AssertionError):
        Assert(1) != 1
Example #41
0
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')
Example #42
0
    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)
Example #43
0
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)
Example #44
0
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")
Example #45
0
    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')
Example #46
0
    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
Example #47
0
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']
Example #48
0
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])
Example #49
0
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)
Example #50
0
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
Example #51
0
    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())
Example #52
0
 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
Example #53
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: []}))
Example #54
0
 def delitem(self):
     d = self.dict_class()
     d[1] = 2
     Assert(d[1]) == 2
     del d[1]
     with Assert.raises(KeyError):
         del d[1]