I have an API that generates and returns a CSV file:
def getCSV():
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=export.csv'
writer = csv.writer(response, csv.excel)
# ... Write some CSV content ...
return response
This works fine when I call it from the browser, but I cannot figure out how to write a test that calls the API and check that the CSV contents are what they should be.
If I:
c = Client()
r = c.get('/my/export/api')
print(r.content)
That just prints three bytes and is most probably conceptually completely wrong.
How can I get the contents of the CSV file response in my test?
Open /catalog/tests/test_models.py.from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
The test client is a Python class that acts as a dummy web browser, allowing you to test your views and interact with your Django-powered application programmatically.
django-nose provides all the goodness of nose in your Django tests, like: Testing just your apps by default, not all the standard ones that happen to be in INSTALLED_APPS. Running the tests in one or more specific modules (or apps, or classes, or folders, or just running a specific test)
How to read a csv django http response
import csv
import io
def test_csv_export(self):
response = self.client.get('/my/export/api')
self.assertEqual(response.status_code, 200)
content = response.content.decode('utf-8')
cvs_reader = csv.reader(io.StringIO(content))
body = list(cvs_reader)
headers = body.pop(0)
print(body)
print(headers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With