Exemplo n.º 1
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()
Exemplo n.º 2
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)
Exemplo n.º 3
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']
Exemplo n.º 4
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]
Exemplo n.º 5
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
Exemplo n.º 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]
Exemplo n.º 7
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]
Exemplo n.º 8
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'
Exemplo n.º 9
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'
Exemplo n.º 10
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'
Exemplo n.º 11
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)
Exemplo n.º 12
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]
Exemplo n.º 13
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())) == []
Exemplo n.º 14
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']
Exemplo n.º 15
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
Exemplo n.º 16
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
Exemplo n.º 17
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)
Exemplo n.º 18
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)
Exemplo n.º 19
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)
Exemplo n.º 20
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">'
    ]
Exemplo n.º 21
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]
Exemplo n.º 22
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'}
Exemplo n.º 23
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)
Exemplo n.º 24
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'}
Exemplo n.º 25
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)
Exemplo n.º 26
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']
Exemplo n.º 27
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))
Exemplo n.º 28
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
Exemplo n.º 29
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
Exemplo n.º 30
0
def field_choices_used_to_translated_value():
    """
    When a model field uses the ``choices`` option, a table should render the
    "pretty" value rather than the database value.

    See issue #30 for details.
    """
    LANGUAGES = (
        ('en', 'English'),
        ('ru', 'Russian'),
    )

    from django.db import models

    class Article(models.Model):
        name = models.CharField(max_length=200)
        language = models.CharField(max_length=200, choices=LANGUAGES)

        def __unicode__(self):
            return self.name

    class ArticleTable(tables.Table):
        class Meta:
            model = Article

    table = ArticleTable([
        Article(name='English article', language='en'),
        Article(name='Russian article', language='ru')
    ])

    Assert('English') == table.rows[0]['language']
    Assert('Russian') == table.rows[1]['language']