|
| 1 | +import io |
| 2 | + |
| 3 | +import pytest |
| 4 | +from openpyxl.reader.excel import load_workbook |
| 5 | +from rest_framework.test import APIClient |
| 6 | + |
| 7 | +from tests.testapp.models import ExampleModel |
| 8 | + |
| 9 | +@pytest.fixture |
| 10 | +def api_client(): |
| 11 | + return APIClient() |
| 12 | + |
| 13 | + |
| 14 | +@pytest.mark.django_db |
| 15 | +def test_simple_viewset_model(api_client): |
| 16 | + ExampleModel.objects.create(title="test 1", description="This is a test") |
| 17 | + ExampleModel.objects.create(title="test 2", description="Another test") |
| 18 | + ExampleModel.objects.create(title="test 3", description="Testing this out") |
| 19 | + |
| 20 | + response = api_client.get("/examples/") |
| 21 | + |
| 22 | + assert response.status_code == 200 |
| 23 | + assert response.headers["Content-Type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8" |
| 24 | + assert response.headers["content-disposition"] == "attachment; filename=my_export.xlsx" |
| 25 | + |
| 26 | + workbook_buffer = io.BytesIO(response.content) |
| 27 | + workbook = load_workbook(workbook_buffer, read_only=True) |
| 28 | + |
| 29 | + assert len(workbook.worksheets) == 1 |
| 30 | + sheet = workbook.worksheets[0] |
| 31 | + rows = list(sheet.rows) |
| 32 | + assert len(rows) == 4 |
| 33 | + r0, r1, r2, r3 = rows |
| 34 | + |
| 35 | + assert len(r0) == 2 |
| 36 | + assert r0[0].value == "title" |
| 37 | + assert r0[1].value == "description" |
| 38 | + |
| 39 | + assert len(r1) == 2 |
| 40 | + assert r1[0].value == "test 1" |
| 41 | + assert r1[1].value == "This is a test" |
| 42 | + |
| 43 | + assert len(r2) == 2 |
| 44 | + assert r2[0].value == "test 2" |
| 45 | + assert r2[1].value == "Another test" |
| 46 | + |
| 47 | + assert len(r3) == 2 |
| 48 | + assert r3[0].value == "test 3" |
| 49 | + assert r3[1].value == "Testing this out" |
0 commit comments