How do I debug my tests? For example, I POST to create an entry and expect it to validate and return a particular page. It works in the browser and in the shell, but the test is the only thing that fails (ironically!). I would like to print the response to the console or something so I could read errors or what have you. But I can only see things that I print
in e.g. the view.
Not sure it's necessary, but here's the test code in question from tests.py
:
resp = self.client.post('/meal/invite/', {'summary': 'Test munch', 'when': now(), 'max_diners': '1', 'description': 'Munchies'}, follow=True) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'Test munch', 1) self.assertContains(resp, 'You are hosting this meal', 1)
The final assertion is incorrect. If I change it to a value present in the original form page showing 'field required' errors, it passes. I just can't see what I'm missing.
I have a few other tests working, but I just don't know how to debug this.
How is it done?
To debug a failed test case you should: check that the input data is correct (open the test case to view and/or update the base level attribute values) check that the expected results are correct (in the Test Report, click on the expected result to view and/or update the expected results for that attribute)
The debug mode (DEBUG=True) is turned on by default in the Django framework. It provides a detailed traceback with the local variables to find out the error with the line numbers. The error can be triggered from the view page by setting the value of assert to False in the view file.
Starting with Django 1.11 you can use --debug-mode to set the DEBUG setting to True prior to running tests. Show activity on this post. The accepted answer didn't work for me. I use Selenium for testing, and setting @override_settings(DEBUG=True) makes the test browser always display 404 error on every page.
You can drop in a pdb
and inspect everything.
If you're using nose
i believe you have to run your tests with -s
-s, --nocapture Don't capture stdout (any stdout output will be printed immediately) [NOSE_NOCAPTURE]
This is what keeps you from seeing output immediately.
To run the test under pdb:
python -m pdb manage.py test yourapp
I agree with Alasdair, the print response.content (and printing stuff in general) is a great help. The output gets mixed up with the normal test runner output, and should be removed once you find the problem and fix it, but it can help you narrow down the problem.
Also, if the code works in the browser and the shell but not the unit test, remember that the unit test makes a new (empty) database. Ensure that your setUp puts in any data that is required for your test.
(Updated the code part from Patrick's suggestion, thanks Patrick)
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