Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test file response in Django?

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?

like image 813
user2061057 Avatar asked Dec 13 '16 13:12

user2061057


People also ask

How do I run a test file in Django?

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.

How do I test a Django project?

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.

What is Django test client?

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.

What is Django nose?

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)


1 Answers

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)
like image 198
Jefe Avatar answered Sep 22 '22 04:09

Jefe