File: test_templates.py

package info (click to toggle)
django-tables 2.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,752 kB
  • sloc: python: 7,120; makefile: 132; sh: 74
file content (383 lines) | stat: -rw-r--r-- 14,445 bytes parent folder | download
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
from django.template import Context, Template
from django.test import SimpleTestCase, TestCase, override_settings
from django.utils.translation import gettext_lazy, override as translation_override
from lxml import etree

import django_tables2 as tables
from django_tables2.config import RequestConfig

from .app.models import Person
from .utils import build_request, parse


class CountryTable(tables.Table):
    name = tables.Column()
    capital = tables.Column(orderable=False, verbose_name=gettext_lazy("Capital"))
    population = tables.Column(verbose_name="Population Size")
    currency = tables.Column(visible=False)
    tld = tables.Column(visible=False, verbose_name="Domain")
    calling_code = tables.Column(accessor="cc", verbose_name="Phone Ext.")


MEMORY_DATA = [
    {
        "name": "Germany",
        "capital": "Berlin",
        "population": 83,
        "currency": "Euro (€)",
        "tld": "de",
        "cc": 49,
    },
    {"name": "France", "population": 64, "currency": "Euro (€)", "tld": "fr", "cc": 33},
    {"name": "Netherlands", "capital": "Amsterdam", "cc": "31"},
    {"name": "Austria", "cc": 43, "currency": "Euro (€)", "population": 8},
]


class TemplateTest(TestCase):
    @override_settings(DJANGO_TABLES2_TEMPLATE="foo/bar.html")
    def test_template_override_in_settings(self):
        class Table(tables.Table):
            column = tables.Column()

        table = Table({})
        self.assertEqual(table.template_name, "foo/bar.html")

    def test_as_html(self):
        request = build_request("/")
        table = CountryTable(MEMORY_DATA)
        root = parse(table.as_html(request))
        self.assertEqual(len(root.findall(".//thead/tr")), 1)
        self.assertEqual(len(root.findall(".//thead/tr/th")), 4)
        self.assertEqual(len(root.findall(".//tbody/tr")), 4)
        self.assertEqual(len(root.findall(".//tbody/tr/td")), 16)

        # no data with no empty_text
        table = CountryTable([])
        root = parse(table.as_html(request))
        self.assertEqual(1, len(root.findall(".//thead/tr")))
        self.assertEqual(4, len(root.findall(".//thead/tr/th")))
        self.assertEqual(0, len(root.findall(".//tbody/tr")))

        # no data WITH empty_text
        table = CountryTable([], empty_text="this table is empty")
        root = parse(table.as_html(request))
        self.assertEqual(1, len(root.findall(".//thead/tr")))
        self.assertEqual(4, len(root.findall(".//thead/tr/th")))
        self.assertEqual(1, len(root.findall(".//tbody/tr")))
        self.assertEqual(1, len(root.findall(".//tbody/tr/td")))
        self.assertEqual(
            int(root.find(".//tbody/tr/td").get("colspan")), len(root.findall(".//thead/tr/th"))
        )
        self.assertEqual(root.find(".//tbody/tr/td").text, "this table is empty")

        # data without header
        table = CountryTable(MEMORY_DATA, show_header=False)
        root = parse(table.as_html(request))
        self.assertEqual(len(root.findall(".//thead")), 0)
        self.assertEqual(len(root.findall(".//tbody/tr")), 4)
        self.assertEqual(len(root.findall(".//tbody/tr/td")), 16)

        # with custom template
        table = CountryTable([], template_name="django_tables2/table.html")
        table.as_html(request)

    def test_custom_rendering(self):
        """For good measure, render some actual templates."""
        countries = CountryTable(MEMORY_DATA)
        context = Context({"countries": countries})

        # automatic and manual column verbose names
        template = Template(
            "{% for column in countries.columns %}{{ column }}/" "{{ column.name }} {% endfor %}"
        )
        result = "Name/name Capital/capital Population Size/population " "Phone Ext./calling_code "
        assert result == template.render(context)

        # row values
        template = Template(
            "{% for row in countries.rows %}{% for value in row %}"
            "{{ value }} {% endfor %}{% endfor %}"
        )
        result = "Germany Berlin 83 49 France — 64 33 Netherlands Amsterdam " "— 31 Austria — 8 43 "
        assert result == template.render(context)


class TestQueries(TestCase):
    def test_as_html_db_queries(self):
        class PersonTable(tables.Table):
            class Meta:
                model = Person

        request = build_request("/")

        with self.assertNumQueries(1):
            PersonTable(Person.objects.all()).as_html(request)

    def test_render_table_db_queries(self):
        """
        Paginated tables should result in two queries:
         - one query for pagination: .count()
         - one query for records on the current page: .all()[start:end]
        """
        Person.objects.create(first_name="brad", last_name="ayers")
        Person.objects.create(first_name="davina", last_name="adisusila")

        class PersonTable(tables.Table):
            class Meta:
                model = Person
                per_page = 1

        request = build_request("/")

        with self.assertNumQueries(2):
            request = build_request("/")
            table = PersonTable(Person.objects.all())
            RequestConfig(request).configure(table)
            html = Template("{% load django_tables2 %}{% render_table table %}").render(
                Context({"table": table, "request": request})
            )

            self.assertIn("brad", html)
            self.assertIn("ayers", html)


class TemplateLocalizeTest(TestCase):
    simple_test_data = [{"name": 1234.5}]
    expected_results = {None: "1234.5", False: "1234.5", True: "1 234,5"}  # non-breaking space

    def assert_cond_localized_table(self, localizeit=None, expected=None):
        """
        helper function for defining Table class conditionally
        """

        class TestTable(tables.Table):
            name = tables.Column(verbose_name="my column", localize=localizeit)

        self.assert_table_localization(TestTable, expected)

    def assert_table_localization(self, TestTable, expected):
        html = TestTable(self.simple_test_data).as_html(build_request())
        self.assertIn(f"<td >{self.expected_results[expected]}</td>", html)

    def test_localization_check(self):
        self.assert_cond_localized_table(None, None)
        # unlocalize
        self.assert_cond_localized_table(False, False)

    @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True)
    def test_localization_different_locale(self):
        with translation_override("pl"):
            # with default polish locales and enabled thousand separator
            # 1234.5 is formatted as "1 234,5" with nbsp
            self.assert_cond_localized_table(True, True)

            # with localize = False there should be no formatting
            self.assert_cond_localized_table(False, False)

            # with localize = None and USE_L10N = True
            # there should be the same formatting as with localize = True
            self.assert_cond_localized_table(None, True)

    def test_localization_check_in_meta(self):
        class TableNoLocalize(tables.Table):
            name = tables.Column(verbose_name="my column")

            class Meta:
                default = "---"

        self.assert_table_localization(TableNoLocalize, None)

    @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True)
    def test_localization_check_in_meta_different_locale(self):
        class TableNoLocalize(tables.Table):
            name = tables.Column(verbose_name="my column")

            class Meta:
                default = "---"

        class TableLocalize(tables.Table):
            name = tables.Column(verbose_name="my column")

            class Meta:
                default = "---"
                localize = ("name",)

        class TableUnlocalize(tables.Table):
            name = tables.Column(verbose_name="my column")

            class Meta:
                default = "---"
                unlocalize = ("name",)

        class TableLocalizePrecedence(tables.Table):
            name = tables.Column(verbose_name="my column")

            class Meta:
                default = "---"
                unlocalize = ("name",)
                localize = ("name",)

        with translation_override("pl"):
            # the same as in localization_check.
            # with localization and polish locale we get formatted output
            self.assert_table_localization(TableNoLocalize, True)

            # localize
            self.assert_table_localization(TableLocalize, True)

            # unlocalize
            self.assert_table_localization(TableUnlocalize, False)

            # test unlocalize has higher precedence
            self.assert_table_localization(TableLocalizePrecedence, False)

    def test_localization_of_pagination_strings(self):
        class Table(tables.Table):
            foo = tables.Column(verbose_name="my column")
            bar = tables.Column()

            class Meta:
                default = "---"

        table = Table(map(lambda x: [x, x + 100], range(40)))
        request = build_request("/?page=2")
        RequestConfig(request, paginate={"per_page": 10}).configure(table)

        with translation_override("en"):
            html = table.as_html(request)
            self.assertIn("previous", html)
            self.assertIn("next", html)

        with translation_override("nl"):
            html = table.as_html(request)
            self.assertIn("vorige", html)
            self.assertIn("volgende", html)

        with translation_override("fr"):
            html = table.as_html(request)
            self.assertIn("précédent", html)
            self.assertIn("suivant", html)


class BootstrapTable(CountryTable):
    class Meta:
        template_name = "django_tables2/bootstrap.html"
        prefix = "bootstrap-"
        per_page = 2


class BootstrapTemplateTest(SimpleTestCase):
    def test_bootstrap_template(self):
        table = BootstrapTable(MEMORY_DATA)
        request = build_request("/")
        RequestConfig(request).configure(table)

        template = Template("{% load django_tables2 %}{% render_table table %}")
        html = template.render(Context({"request": request, "table": table}))

        root = parse(html)
        self.assertEqual(root.find(".//table").attrib, {"class": "table"})

        self.assertEqual(len(root.findall(".//thead/tr")), 1)
        self.assertEqual(len(root.findall(".//thead/tr/th")), 4)
        self.assertEqual(len(root.findall(".//tbody/tr")), 2)
        self.assertEqual(len(root.findall(".//tbody/tr/td")), 8)

        self.assertEqual(root.find('.//ul[@class="pagination"]/li[2]/a').text.strip(), "2")
        # make sure the link is prefixed
        self.assertEqual(
            root.find('.//ul[@class="pagination"]/li[@class="next"]/a').get("href"),
            "?bootstrap-page=2",
        )

    def test_bootstrap_responsive_template(self):
        class BootstrapResponsiveTable(BootstrapTable):
            class Meta(BootstrapTable.Meta):
                template_name = "django_tables2/bootstrap-responsive.html"

        table = BootstrapResponsiveTable(MEMORY_DATA)
        request = build_request("/")
        RequestConfig(request).configure(table)

        template = Template("{% load django_tables2 %}{% render_table table %}")
        html = template.render(Context({"request": request, "table": table}))
        root = parse(html)
        self.assertEqual(len(root.findall(".//thead/tr")), 1)
        self.assertEqual(len(root.findall(".//thead/tr/th")), 4)
        self.assertEqual(len(root.findall(".//tbody/tr")), 2)
        self.assertEqual(len(root.findall(".//tbody/tr/td")), 8)

        self.assertEqual(root.find('.//ul[@class="pagination"]/li[2]/a').text.strip(), "2")


class SemanticTemplateTest(SimpleTestCase):
    def test_semantic_template(self):
        class SemanticTable(CountryTable):
            class Meta:
                template_name = "django_tables2/semantic.html"
                prefix = "semantic-"
                per_page = 2

        table = SemanticTable(MEMORY_DATA)
        request = build_request("/")
        RequestConfig(request).configure(table)

        template = Template("{% load django_tables2 %}{% render_table table %}")
        html = template.render(Context({"request": request, "table": table}))
        root = parse(html)
        self.assertEqual(len(root.findall(".//thead/tr")), 1)
        self.assertEqual(len(root.findall(".//thead/tr/th")), 4)
        self.assertEqual(len(root.findall(".//tbody/tr")), 2)
        self.assertEqual(len(root.findall(".//tbody/tr/td")), 8)

        # make sure the link is prefixed
        next_page = './/tfoot/tr/th/div[@class="ui right floated pagination menu"]/a[1]'
        self.assertEqual(root.find(next_page).get("href"), "?semantic-page=1")


class ValidHTMLTest(SimpleTestCase):
    template = """<!doctype html>
<html>
<head>
    <title>Basic html template to render a table</title>
</head>
<body>
    {% load django_tables2 %}{% render_table table %}
</body>
</html>
"""
    allowed_errors = {etree.ErrorTypes.HTML_UNKNOWN_TAG: ["Tag nav invalid"]}
    context_lines = 4

    def test_templates(self):
        parser = etree.HTMLParser()

        for name in ("table", "semantic", "bootstrap", "bootstrap4", "bootstrap5"):
            table = CountryTable(
                list([MEMORY_DATA] * 10), template_name=f"django_tables2/{name}.html"
            ).paginate(per_page=5)

            html = Template(self.template).render(
                Context({"request": build_request(), "table": table})
            )

            # will raise lxml.etree.XMLSyntaxError if markup is incorrect
            etree.fromstring(html, parser)

            for error in parser.error_log:
                if (
                    error.type in self.allowed_errors
                    and error.message in self.allowed_errors[error.type]
                ):
                    continue

                lines = html.splitlines()
                start, end = (
                    max(0, error.line - self.context_lines),
                    min(error.line + self.context_lines, len(lines)),
                )
                context = "\n".join(
                    [f"{i}: {line}" for i, line in zip(range(start + 1, end + 1), lines[start:end])]
                )
                raise AssertionError(f"template: {table.template_name}; {error} \n {context}")