05-10-2021

  1. Run Django Tests In Vscode
  2. Run Django Server
  3. Django Run Tests For App
  4. Run Django Tests For Free
  5. Django Run Tests In Parallel

If you are just starting to set up unit tests, coverage can help offer suggestions on what should be tested. Coverage can also be used to turn testing into a game: I try to increase the percent of code covered by tests each day, for example. Django-discover-runner: helps locate tests if you organize them in a different way (e.g, outside of. Run tests that failed in the most recent test run. Similar to Python: Run Failed Tests on versions prior to 2021.9. Test: Rerun Last Run: Debug tests that were executed in the most recent test run. Test: Run All Tests: Run all discovered tests. Equivalent to Python: Run All Tests on versions prior to 2021.9. Test: Run Test at Cursor. The best base class for most tests is django.test.TestCase. This test class creates a clean database before its tests are run, and runs every test function in its own transaction. The class also owns a test Client that you can use to simulate a user interacting with the code at the view level.

Last post we talked about how to set up and use doc tests inside of Django.Today, in the second post of the series, we’ll be talking about how to usethe other testing framework that comes with Python, unittest. unittest is axUnit type of testing system (JUnit from the Java world is another example)implemented in Python. It is a much more robust solution for testing than Doctests, and allows for a lot more organization of code. We’ll get into that inthe next post in the series, comparing unit and doc tests.

Run Django Tests

So we’re going to assume that you are picking up after the previous post inthis series. If so, you should have a basic tests directory, with an__init__.py and a doctst.py file inside of it. Today we are going towrite some very basic unit tests, and figure out how to wire those into yourexisting test suite.

Writing your first unit test¶

Making a unit test is a lot like making a Python class. As per usual, theDjango docs have lots of great information and examples. They will showyou how to do some easy stuff with your Django models. This tutorial willmostly be about how to use unit tests inside Django, regardless of the dataat hand. So let’s start with a very basic unit test.:

This is a very basic unit test. You will notice it is just a normalPython class. You create a class that inherits from unittest.TestCase. Thistells unittest that it is a test file. Then you simply go in and define somefunctions (Note: they need to start with test so that unittest will runthem), in which you assert some conditions which are true. This allows you alot more flexibility in the tests.

Now if you try to run these tests, you will again not see them showingup in your output! You need to go into your __init__.py in your testsdirectory. It should now look like the following (assuming you followed part1 of this series):

Unit tests are a lot easier to import than doctests. You simply do a from<filename>import<testnames>. I named my unit test file unittst.py,and Python will import that from the current directory. You are importing thetest classes that you defined in your file. So I could have as easily putfromunittestimportTestBasic and it would work. Using the import*syntax allows us to add more tests to the file later and not have to edit it.

Run Django Tests In Vscode

You can go ahead and run your tests, and see if they’re being properlyimported.:

Awesome!

A couple neat features¶

There are some neat things you can do with basic unit tests. Below I’ll showan addition to the above file, which is another test class, with a bit morefunctionality.:

Here you see that you can define a docstring for the tests. These are usedwhen you are running the tests, so you have a human readable name. You’llalso notice that I’ve used some more assertions. The Python docs have afull list of assertions that you can make. The setUp and tearDownmethods are run before and after every test respectively. This allows you toset up a basic context or environment inside of each of your tests. This alsoinsures that each of your tests do not edit the data that other tests dependon. This is a basic tenet of testing, that each test should stand alone, andnot affect the others.

This also seems like a good time to explicitly say that all of your testclasses and files should start with test! If not, they will not be run! Ifyou have a test not running and everything else looks right, this is probablyyour problem. Also note that they cannot be named the same thing! These willoverwrite one another with the last one being imported into the file running.It is generally a good practice to name your tests something that is certainto be unique. I generally tend to follow whatever naming convention I’ve usedfor my named url patterns.

When you go ahead and run your tests, you should see one that fails (the lastone).:

You can see the value of unit tests here. Each test is run seperately, so youget a nice human readable error message when it breaks. You can go ahead andmake that test pass (self.assertFalse(self.a2)). You get an OK fromyour tests, and we can go on our merry way.

Now you can see for yourself that there are a lot of differences between Doctests and unit tests. They each serve their own purpose, and in the next postin this series I will talk about when you should use each. Unit tests requirea little bit more up front effort; you can’t just paste something out of yourPython shell and have it work. However, they give you a lot more flexibility.

Some developers regard writing tests as a lame checkbox task – but nothing could be farther from the truth. Done correctly, tests are one of your application’s most valuable assets.

The Django framework in particular offers your team the opportunity to create an efficient testing practice, based on the Python standard library unittest.

Proper tests in Django are fast to write, faster to run, and can offer you a seamless continuous integration solution for taking the pulse of your developing application.

Test

With comprehensive tests, developers have higher confidence when pushing changes. I’ve seen firsthand in my own teams that good tests can boost development velocity as a direct result of a better developer experience.

In this article, I’ll share my own experiences in building useful tests for Django applications, from the basics to the best possible execution. If you're using Django or building with it in your organization, you might like to read my Django series on Victoria.dev.

What to test

Tests are extremely important. Far beyond simply letting you know if a function works, tests can form the basis of your team’s understanding of how your application is intended to work.

Here’s the main goal: if you hit your head and forgot everything about how your application works tomorrow, you should be able to regain most of your understanding by reading and running the tests you write today.

Here are some questions that may be helpful to ask as you decide what to test:

  • What is your customer supposed to be able to do?
  • What is your customer not supposed to be able to do?
  • What should this method, view, or logical flow achieve?
  • When, how, or where is this feature supposed to execute?

Tests that make sense for your application can help build developer confidence.

With these sensible safeguards in place, developers make improvements more readily, and feel confident introducing innovative solutions to product needs. The result is an application that comes together faster, and features that are shipped often and with confidence.

Where to put tests

If you only have a few tests, you may organize your test files similarly to Django’s default app template by putting them all in a file called tests.py. This straightforward approach is best for smaller applications.

As your application grows, you may like to split your tests into different files, or test modules. One method is to use a directory to organize your files, such as projectroot/app/tests/. The name of each test file within that directory should begin with test, for example, test_models.py.

Besides being aptly named, Django will find these files using built-in test discovery based on the unittest module. All files in your application with names that begin with test will be collected into a test suite.

Run Django Server

This convenient test discovery allows you to place test files anywhere that makes sense for your application. As long as they’re correctly named, Django’s test utility can find and run them.

How to document a test

Use docstrings to explain what a test is intended to verify at a high level. For example:

These docstrings help you quickly understand what a test is supposed to be doing. Besides navigating the codebase, this helps to make it obvious when a test doesn’t verify what the docstring says it should.

Docstrings are also shown when the tests are being run, which can be helpful for logging and debugging.

What a test needs to work

Django Run Tests For App

Django tests can be quickly set up using data created in the setUpTestData() method. You can use various approaches to create your test data, such as utilizing external files, or even hard-coding silly phrases or the names of your staff.

Personally, I much prefer to use a fake-data-generation library, such as faker.

The proper set up of arbitrary testing data can help you ensure that you’re testing your application functionality instead of accidentally testing test data. Because generators like faker add some degree of unexpectedness to your inputs, it can be more representative of real-world use.

Here is an example set up for a test:

Tests pass or fail based on the outcome of the assertion methods. You can use Python’s unittest methods, and Django’s assertion methods.

For further guidance on writing tests, see Testing in Django.

Best possible execution for running your tests

Django’s test suite is manually run with:

Run Django Tests For Free

I rarely run my Django tests this way.

The best, or most efficient, testing practice is one that occurs without you or your developers ever thinking, “I need to run the tests first.”

The beauty of Django’s near-effortless test suite set up is that it can be seamlessly run as a part of regular developer activities. This could be in a pre-commit hook, or in a continuous integration or deployment workflow.

I’ve previously written about how to use pre-commit hooks to improve your developer ergonomics and save your team some brainpower. Django’s speedy tests can be run this way, and they become especially efficient if you can run tests in parallel.

Tests that run as part of a CI/CD workflow, for example, on pull requests with GitHub Actions, require no regular effort from your developers to remember to run tests at all. I’m not sure how plainly I can put it – this one’s literally a no-brainer.

Testing your way to a great Django application

Tests are extremely important, and under-appreciated. They can catch logical errors in your application. They can help explain and validate how concepts and features of your product actually function. Best of all, tests can boost developer confidence and development velocity as a result.

Django Run Tests In Parallel

The best tests are ones that are relevant, help to explain and define your application, and are run continuously without a second thought. I hope I’ve now shown you how testing in Django can help you to achieve these goals for your team!