-
Notifications
You must be signed in to change notification settings - Fork 423
/
test_models.py
433 lines (321 loc) · 14.4 KB
/
test_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# coding: utf-8
from random import randint
import django_tables2 as tables
import pytest
from django.db.models.functions import Length
from django.utils import six
from django_tables2 import RequestConfig
from .app.models import Occupation, Person, PersonProxy, Player
from .utils import build_request
pytestmark = pytest.mark.django_db
request = build_request('/')
class PersonTable(tables.Table):
first_name = tables.Column()
last_name = tables.Column()
occupation = tables.Column()
def test_boundrows_iteration():
occupation = Occupation.objects.create(name='Programmer')
Person.objects.create(first_name='Bradley', last_name='Ayers', occupation=occupation)
Person.objects.create(first_name='Chris', last_name='Doble', occupation=occupation)
table = PersonTable(Person.objects.all())
records = [row.record for row in table.rows]
expecteds = Person.objects.all()
for expected, actual in six.moves.zip(expecteds, records):
assert expected == actual
def test_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
expected = ['id', 'name', 'region', 'boolean', 'boolean_with_choices']
assert expected == list(OccupationTable.base_columns.keys())
class OccupationTable2(tables.Table):
extra = tables.Column()
class Meta:
model = Occupation
expected.append('extra')
assert expected == list(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', on_delete=models.CASCADE)
m2m = models.ManyToManyField('self')
class Meta:
app_label = 'django_tables2_test'
class ComplexTable(tables.Table):
class Meta:
model = ComplexModel
assert ['id', 'char', 'fk'] == list(ComplexTable.base_columns.keys())
def test_mixins():
class TableMixin(tables.Table):
extra = tables.Column()
class OccupationTable(TableMixin, tables.Table):
extra2 = tables.Column()
class Meta:
model = Occupation
expected = ['extra', 'id', 'name', 'region', 'boolean', 'boolean_with_choices', 'extra2']
assert expected == list(OccupationTable.base_columns.keys())
def test_column_verbose_name():
'''
When using queryset data as input for a table, default to using model field
verbose names rather than an autogenerated string based on the column name.
However if a column does explicitly describe a verbose name, it should be
used.
'''
class PersonTable(tables.Table):
'''
The test_colX columns are to test that the accessor is used to
determine the field on the model, rather than the column name.
'''
first_name = tables.Column()
fn1 = tables.Column(accessor='first_name')
fn2 = tables.Column(accessor='first_name.upper')
fn3 = tables.Column(accessor='last_name', verbose_name='OVERRIDE')
fn4 = tables.Column(accessor='last_name', verbose_name='override')
last_name = tables.Column()
ln1 = tables.Column(accessor='last_name')
ln2 = tables.Column(accessor='last_name.upper')
ln3 = tables.Column(accessor='last_name', verbose_name='OVERRIDE')
region = tables.Column(accessor='occupation.region.name')
r1 = tables.Column(accessor='occupation.region.name')
r2 = tables.Column(accessor='occupation.region.name.upper')
r3 = tables.Column(accessor='occupation.region.name', verbose_name='OVERRIDE')
trans_test = tables.Column()
trans_test_lazy = tables.Column()
# The Person model has a ``first_name`` and ``last_name`` field, but only
# the ``last_name`` field has an explicit ``verbose_name`` set. This means
# that we should expect that the two columns that use the ``last_name``
# field should both use the model's ``last_name`` field's ``verbose_name``,
# however both fields that use the ``first_name`` field should just use a
# titlised version of the column name as the column header.
table = PersonTable(Person.objects.all())
# Should be generated (capitalized column name)
assert 'First Name' == table.columns['first_name'].verbose_name
assert 'First Name' == table.columns['fn1'].verbose_name
assert 'First Name' == table.columns['fn2'].verbose_name
assert 'OVERRIDE' == table.columns['fn3'].verbose_name
assert 'override' == table.columns['fn4'].verbose_name
# Should use the titlised model field's verbose_name
assert 'Surname' == table.columns['last_name'].verbose_name
assert 'Surname' == table.columns['ln1'].verbose_name
assert 'Surname' == table.columns['ln2'].verbose_name
assert 'OVERRIDE' == table.columns['ln3'].verbose_name
assert 'Name' == table.columns['region'].verbose_name
assert 'Name' == table.columns['r1'].verbose_name
assert 'Name' == table.columns['r2'].verbose_name
assert 'OVERRIDE' == table.columns['r3'].verbose_name
assert 'Translation Test' == table.columns['trans_test'].verbose_name
assert 'Translation Test Lazy' == table.columns['trans_test_lazy'].verbose_name
# -------------------------------------------------------------------------
# Now we'll try using a table with Meta.model
class PersonTable(tables.Table):
first_name = tables.Column(verbose_name='OVERRIDE')
class Meta:
model = Person
# Issue #16
table = PersonTable([])
assert 'Translation Test' == table.columns['trans_test'].verbose_name
assert 'Translation Test Lazy' == table.columns['trans_test_lazy'].verbose_name
assert 'Web Site' == table.columns['website'].verbose_name
assert 'Birthdate' == table.columns['birthdate'].verbose_name
assert 'OVERRIDE' == table.columns['first_name'].verbose_name
def test_data_verbose_name():
table = tables.Table(Person.objects.all())
assert table.data.verbose_name == 'person'
assert table.data.verbose_name_plural == 'people'
def test_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)
class Meta:
app_label = 'django_tables2_test'
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].get_cell('language')
assert 'Russian' == table.rows[1].get_cell('language')
def test_column_mapped_to_nonexistant_field():
'''
Issue #9 describes how if a Table has a column that has an accessor that
targets a non-existent field, a FieldDoesNotExist error is raised.
'''
class FaultyPersonTable(PersonTable):
missing = tables.Column()
table = FaultyPersonTable(Person.objects.all())
table.as_html(request) # the bug would cause this to raise FieldDoesNotExist
def test_should_support_rendering_multiple_times():
class MultiRenderTable(tables.Table):
name = tables.Column()
# test queryset data
table = MultiRenderTable(Person.objects.all())
assert table.as_html(request) == table.as_html(request)
def test_ordering():
class SimpleTable(tables.Table):
name = tables.Column(order_by=('first_name', 'last_name'))
table = SimpleTable(Person.objects.all(), order_by='name')
assert table.as_html(request)
def test_default_order():
'''
If orderable=False, do not sort queryset.
https://github.com/bradleyayers/django-tables2/issues/204
'''
table = PersonTable(PersonProxy.objects.all())
Person.objects.create(first_name='Foo', last_name='Bar')
Person.objects.create(first_name='Bradley', last_name='Ayers')
table.data.order_by([])
assert list(table.rows[0])[1] == 'Ayers'
def test_fields_should_implicitly_set_sequence():
class PersonTable(tables.Table):
extra = tables.Column()
class Meta:
model = Person
fields = ('last_name', 'first_name')
table = PersonTable(Person.objects.all())
assert table.columns.names() == ['last_name', 'first_name', 'extra']
def test_model_properties_should_be_useable_for_columns():
class PersonTable(tables.Table):
class Meta:
model = Person
fields = ('name', 'first_name')
Person.objects.create(first_name='Bradley', last_name='Ayers')
table = PersonTable(Person.objects.all())
assert list(table.rows[0]) == ['Bradley Ayers', 'Bradley']
def test_meta_fields_may_be_list():
class PersonTable(tables.Table):
class Meta:
model = Person
fields = ['name', 'first_name']
Person.objects.create(first_name='Bradley', last_name='Ayers')
table = PersonTable(Person.objects.all())
assert list(table.rows[0]) == ['Bradley Ayers', 'Bradley']
def test_column_with_delete_accessor_shouldnt_delete_records():
class PersonTable(tables.Table):
delete = tables.Column()
Person.objects.create(first_name='Bradley', last_name='Ayers')
table = PersonTable(Person.objects.all())
table.as_html(request)
assert Person.objects.get(first_name='Bradley')
def test_order_by_derived_from_queryset():
queryset = Person.objects.order_by('first_name', 'last_name', '-occupation__name')
class PersonTable(tables.Table):
name = tables.Column(order_by=('first_name', 'last_name'))
occupation = tables.Column(order_by=('occupation__name',))
assert PersonTable(
queryset.order_by('first_name', 'last_name', '-occupation__name')
).order_by == ('name', '-occupation')
class PersonTable(PersonTable):
class Meta:
order_by = ('occupation', )
assert PersonTable(queryset.all()).order_by == ('occupation', )
def test_queryset_table_data_supports_ordering():
class Table(tables.Table):
class Meta:
model = Person
for name in ('Bradley Ayers', 'Stevie Armstrong'):
first_name, last_name = name.split()
Person.objects.create(first_name=first_name, last_name=last_name)
table = Table(Person.objects.all())
assert table.rows[0].get_cell('first_name') == 'Bradley'
table.order_by = '-first_name'
assert table.rows[0].get_cell('first_name') == 'Stevie'
def test_queryset_table_data_supports_custom_ordering():
class Table(tables.Table):
class Meta:
model = Person
order_by = 'first_name'
def order_first_name(self, queryset, is_descending):
# annotate to order by length of first_name + last_name
queryset = queryset.annotate(
length=Length('first_name') + Length('last_name')
).order_by(('-' if is_descending else '') + 'length')
return (queryset, True)
for name in ('Bradley Ayers', 'Stevie Armstrong', 'VeryLongFirstName VeryLongLastName'):
first_name, last_name = name.split()
Person.objects.create(first_name=first_name, last_name=last_name)
table = Table(Person.objects.all())
# Shortest full names first
assert table.rows[0].get_cell('first_name') == 'Bradley'
# Longest full names first
table.order_by = '-first_name'
assert table.rows[0].get_cell('first_name') == 'VeryLongFirstName'
def test_doesnotexist_from_accessor_should_use_default():
class Table(tables.Table):
class Meta:
model = Person
default = 'abc'
fields = ('first_name', 'last_name', 'region')
Person.objects.create(first_name='Brad', last_name='Ayers')
table = Table(Person.objects.all())
assert table.rows[0].get_cell('first_name') == 'Brad'
assert table.rows[0].get_cell('region') == 'abc'
def test_unicode_field_names():
class Table(tables.Table):
class Meta:
model = Person
fields = (six.text_type('first_name'), )
Person.objects.create(first_name='Brad')
table = Table(Person.objects.all())
assert table.rows[0].get_cell('first_name') == 'Brad'
def test_foreign_key():
class PersonTable(tables.Table):
class Meta:
model = Person
fields = ('foreign_key', )
# TODO: implement
def test_fields_empty_list_means_no_fields():
class Table(tables.Table):
class Meta:
model = Person
fields = ()
table = Table(Person.objects.all())
assert len(table.columns.names()) == 0
def test_column_named_delete():
class DeleteTable(tables.Table):
delete = tables.TemplateColumn('[delete button]', verbose_name='')
class Meta:
model = Person
fields = ('name', 'delete')
person1 = Person.objects.create(first_name='Jan', last_name='Pieter')
person2 = Person.objects.create(first_name='John', last_name='Peter')
DeleteTable(Person.objects.all()).as_html(build_request())
assert Person.objects.get(pk=person1.pk) == person1
assert Person.objects.get(pk=person2.pk) == person2
def test_issue_361(per_page=5):
bob = Person.objects.create(first_name='Bob', last_name='Builder')
eve = Person.objects.create(first_name='Eve', last_name='Dropper')
for i in range(10):
Player.objects.create(person=bob, score=randint(0, 200))
Player.objects.create(person=eve, score=randint(200, 400))
Player.objects.create(person=bob, score=5)
Player.objects.create(person=eve, score=5)
class UserPlayerTable(tables.Table):
class Meta:
model = Player
fields = ('person.name', 'score',)
order_by = ['score', 'person.first_name']
orderable = False
queryset = Player.objects.filter(score=5)
table = UserPlayerTable(queryset)
RequestConfig(request, paginate={'per_page': per_page}).configure(table)
html = table.as_html(request)
# count the number of rows, subtract one for the header
assert (html.count('<tr') - 1) == per_page