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
|
import json
import os
from datetime import date, datetime, time
from tempfile import NamedTemporaryFile
from unittest import skipIf
import pytz
import yaml
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import render
from django.test import TestCase
from openpyxl import load_workbook
import django_tables2 as tables
from django_tables2 import A
from django_tables2.config import RequestConfig
from .app.models import Occupation, Person, Region
from .utils import build_request
try:
from django_tables2.export.export import TableExport
from django_tables2.export.views import ExportMixin
except ImproperlyConfigured:
TableExport = None
NAMES = [("Yildiz", "van der Kuil"), ("Lindi", "Hakvoort"), ("Gerardo", "Castelein")]
NAMES_LIST_OF_DICTS = [
{"first_name": first_name, "last_name": last_name} for first_name, last_name in NAMES
]
CSV_SEP = "\r\n"
EXPECTED_CSV_DATA = tuple(",".join(name) for name in NAMES)
EXPECTED_CSV = CSV_SEP.join(("First name,Surname",) + EXPECTED_CSV_DATA) + CSV_SEP
EXPECTED_JSON = list(
[{"First name": first_name, "Surname": last_name} for first_name, last_name in NAMES]
)
class Table(tables.Table):
first_name = tables.Column()
last_name = tables.Column()
class AccessorTable(tables.Table):
given_name = tables.Column(accessor=A("first_name"), verbose_name="Given name")
surname = tables.Column(accessor=A("last_name"))
class View(ExportMixin, tables.SingleTableView):
table_class = Table
table_pagination = {"per_page": 1}
model = Person # required for ListView
template_name = "django_tables2/bootstrap.html"
@skipIf(TableExport is None, "Tablib is required to run the export tests")
class TableExportTest(TestCase):
"""
github issue #474: null/None values in exports
"""
def test_None_values(self):
table = Table(
[
{"first_name": "Yildiz", "last_name": "van der Kuil"},
{"first_name": "Jan", "last_name": None},
]
)
exporter = TableExport("csv", table)
expected = ("First name,Last name", "Yildiz,van der Kuil", "Jan,")
self.assertEqual(exporter.export(), CSV_SEP.join(expected) + CSV_SEP)
def test_null_values(self):
Person.objects.create(first_name="Jan", last_name="Coen")
class Table(tables.Table):
first_name = tables.Column()
last_name = tables.Column(verbose_name="Last name")
occupation = tables.Column(verbose_name="Occupation")
table = Table(Person.objects.all())
exporter = TableExport("csv", table)
expected = ("First name,Last name,Occupation", "Jan,Coen,")
self.assertEqual(exporter.export(), CSV_SEP.join(expected) + CSV_SEP)
def test_export_accessors_list_of_dicts(self):
table = AccessorTable(NAMES_LIST_OF_DICTS)
exporter = TableExport("csv", table)
expected = ("Given name,Surname",) + EXPECTED_CSV_DATA
self.assertEqual(exporter.export(), CSV_SEP.join(expected) + CSV_SEP)
def test_export_accessors_queryset(self):
programmer = Occupation.objects.create(name="Programmer")
for first_name, last_name in NAMES:
Person.objects.create(first_name=first_name, last_name=last_name, occupation=programmer)
class AccessorRelationTable(AccessorTable):
occupation = tables.Column(accessor=A("occupation__name"), verbose_name="Occupation")
table = AccessorRelationTable(Person.objects.all())
exporter = TableExport("csv", table)
expected = ("Given name,Surname,Occupation",) + tuple(
row + "," + programmer.name for row in EXPECTED_CSV_DATA
)
self.assertEqual(exporter.export(), CSV_SEP.join(expected) + CSV_SEP)
def test_export_dataset_kwargs(self):
table = Table(
[
{"first_name": "Yildiz", "last_name": "van der Kuil"},
{"first_name": "Jan", "last_name": None},
]
)
title = "My Custom Title"
exporter = TableExport("xlsx", table, dataset_kwargs={"title": title})
self.assertEqual(exporter.dataset.title, title)
def test_export_default_dataset_title(self):
class PersonTable(Table):
class Meta:
model = Person # provides default title
table = PersonTable(Person.objects.all())
exporter = TableExport("xlsx", table)
self.assertEqual(exporter.dataset.title, Person._meta.verbose_name_plural.title())
@skipIf(TableExport is None, "Tablib is required to run the export tests")
class ExportViewTest(TestCase):
def setUp(self):
for first_name, last_name in NAMES:
Person.objects.create(first_name=first_name, last_name=last_name)
def test_view_should_support_csv_export(self):
response = View.as_view()(build_request("/?_export=csv"))
self.assertEqual(response.getvalue().decode("utf8"), EXPECTED_CSV)
# should just render the normal table without the _export query
response = View.as_view()(build_request("/"))
html = response.render().rendered_content
self.assertIn("Yildiz", html)
self.assertNotIn("Lindy", html)
def test_should_raise_error_for_unsupported_file_type(self):
table = Table([])
with self.assertRaisesMessage(TypeError, 'Export format "exe" is not supported.'):
TableExport(table=table, export_format="exe")
def test_should_support_json_export(self):
response = View.as_view()(build_request("/?_export=json"))
self.assertEqual(json.loads(response.getvalue().decode("utf8")), EXPECTED_JSON)
def test_should_support_yaml_export(self):
response = View.as_view()(build_request("/?_export=yaml"))
self.assertEqual(
yaml.load(response.getvalue().decode("utf8"), Loader=yaml.FullLoader), EXPECTED_JSON
)
def test_should_support_custom_trigger_param(self):
class View(ExportMixin, tables.SingleTableView):
table_class = Table
export_trigger_param = "export_to"
model = Person # required for ListView
response = View.as_view()(build_request("/?export_to=json"))
self.assertEqual(json.loads(response.getvalue().decode("utf8")), EXPECTED_JSON)
def test_should_support_custom_filename(self):
class View(ExportMixin, tables.SingleTableView):
table_class = Table
export_name = "people"
model = Person # required for ListView
response = View.as_view()(build_request("/?_export=json"))
self.assertEqual(response["Content-Disposition"], 'attachment; filename="people.json"')
def test_function_view(self):
"""Test the code used in the docs."""
def table_view(request):
table = Table(Person.objects.all())
RequestConfig(request).configure(table)
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response(f"table.{export_format}")
return render(request, "django_tables2/table.html", {"table": table})
response = table_view(build_request("/?_export=csv"))
self.assertEqual(response.getvalue().decode("utf8"), EXPECTED_CSV)
# must also support the normal html table.
response = table_view(build_request("/"))
html = response.content.decode("utf8")
self.assertIn("Yildiz", html)
self.assertNotIn("Lindy", html)
# def test_should_support_custom_dataset_kwargs(self):
# title = "The Sheet Name"
#
# class View(ExportMixin, tables.SingleTableView):
# table_class = Table
# model = Person # required for ListView
# dataset_kwargs = {"title": title}
#
# response = View.as_view()(build_request("/?_export=xlsx"))
# self.assertEqual(response.status_code, 200)
#
# tmp = NamedTemporaryFile(suffix=".xlsx", delete=False)
# try:
# tmp.write(response.content)
# tmp.seek(0)
# wb = load_workbook(tmp.name)
# self.assertIn(title, wb.sheetnames)
# finally:
# tmp.close()
# os.unlink(tmp.name)
class OccupationTable(tables.Table):
name = tables.Column()
boolean = tables.Column()
region = tables.Column()
class OccupationView(ExportMixin, tables.SingleTableView):
model = Occupation
table_class = OccupationTable
table_pagination = {"per_page": 1}
template_name = "django_tables2/bootstrap.html"
@skipIf(TableExport is None, "Tablib is required to run the export tests")
class AdvancedExportViewTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
richard = Person.objects.create(first_name="Richard", last_name="Queener")
vlaanderen = Region.objects.create(name="Vlaanderen", mayor=richard)
Occupation.objects.create(name="Timmerman", boolean=True, region=vlaanderen)
Occupation.objects.create(name="Ecoloog", boolean=False, region=vlaanderen)
def test_should_work_with_foreign_keys(self):
response = OccupationView.as_view()(build_request("/?_export=xls"))
data = response.content
# binary data, so not possible to compare to an exact expectation
self.assertTrue(data.find(b"Vlaanderen"))
self.assertTrue(data.find(b"Ecoloog"))
self.assertTrue(data.find(b"Timmerman"))
def test_datetime_xls(self):
"""Verify datatime objects can be exported to xls."""
utc = pytz.timezone("UTC")
class Table(tables.Table):
date = tables.DateColumn()
time = tables.TimeColumn()
datetime = tables.DateTimeColumn()
class View(ExportMixin, tables.SingleTableView):
table_class = Table
table_pagination = {"per_page": 1}
template_name = "django_tables2/bootstrap.html"
def get_queryset(self):
return [
{
"date": date(2019, 7, 22),
"time": time(11, 11, 11),
"datetime": utc.localize(datetime(2019, 7, 22, 11, 11, 11)),
}
]
response = View.as_view()(build_request("/?_export=csv"))
data = response.getvalue().decode("utf8")
expected_csv = "Date,Time,Datetime\r\n07/22/2019,11:11 a.m.,07/22/2019 1:11 p.m.\r\n"
self.assertEqual(data, expected_csv)
response = View.as_view()(build_request("/?_export=xls"))
self.assertIn(b"07/22/2019 1:11 p.m.", response.content)
def test_export_invisible_columns(self):
"""Verify columns with visible=False *do* get exported."""
DATA = [{"name": "Bess W. Fletcher", "website": "teammonka.com"}]
class Table(tables.Table):
name = tables.Column()
website = tables.Column(visible=False)
class View(ExportMixin, tables.SingleTableView):
table_class = Table
table_pagination = {"per_page": 1}
template_name = "django_tables2/bootstrap.html"
def get_queryset(self):
return DATA
response = View.as_view()(build_request())
self.assertNotContains(response, "teammonka.com")
response = View.as_view()(build_request("/?_export=csv"))
data = response.getvalue().decode()
expected_csv = "\r\n".join(("Name,Website", "Bess W. Fletcher,teammonka.com", ""))
self.assertEqual(data, expected_csv)
def test_should_work_with_foreign_key_fields(self):
class OccupationWithForeignKeyFieldsTable(tables.Table):
name = tables.Column()
boolean = tables.Column()
region = tables.Column()
mayor = tables.Column(accessor="region__mayor__first_name")
class View(ExportMixin, tables.SingleTableView):
table_class = OccupationWithForeignKeyFieldsTable
table_pagination = {"per_page": 1}
model = Occupation
template_name = "django_tables2/bootstrap.html"
response = View.as_view()(build_request("/?_export=csv"))
data = response.getvalue().decode("utf8")
expected_csv = "\r\n".join(
(
"Name,Boolean,Region,First name",
"Timmerman,True,Vlaanderen,Richard",
"Ecoloog,False,Vlaanderen,Richard",
"",
)
)
self.assertEqual(data, expected_csv)
def test_should_allow_exclude_columns(self):
class OccupationExcludingView(ExportMixin, tables.SingleTableView):
table_class = OccupationTable
table_pagination = {"per_page": 1}
model = Occupation
template_name = "django_tables2/bootstrap.html"
exclude_columns = ("boolean",)
response = OccupationExcludingView.as_view()(build_request("/?_export=csv"))
data = response.getvalue().decode("utf8")
self.assertEqual(data.splitlines()[0], "Name,Region")
@skipIf(TableExport is None, "Tablib is required to run the export tests")
class UnicodeExportViewTest(TestCase):
def test_exporting_unicode_data(self):
unicode_name = "木匠"
Occupation.objects.create(name=unicode_name)
expected_csv = f"Name,Boolean,Region\r\n{unicode_name},,\r\n"
response = OccupationView.as_view()(build_request("/?_export=csv"))
self.assertEqual(response.getvalue().decode("utf8"), expected_csv)
# smoke tests, hard to test this binary format for string containment
response = OccupationView.as_view()(build_request("/?_export=xls"))
self.assertGreater(len(response.content), len(expected_csv))
response = OccupationView.as_view()(build_request("/?_export=xlsx"))
self.assertGreater(len(response.content), len(expected_csv))
def test_exporting_unicode_header(self):
unicode_header = "hé"
class Table(tables.Table):
name = tables.Column(verbose_name=unicode_header)
exporter = TableExport("csv", Table([]))
response = exporter.response()
self.assertEqual(response.getvalue().decode("utf8"), unicode_header + "\r\n")
exporter = TableExport("xls", Table([]))
# this would fail if the header contains unicode and string converstion is attempted.
exporter.export()
|