Django - Run all tests inside of "test" sub-folder

Viewed 620

So I've been running tests using the command python manage.py test to run every test inside the test folder and I'd like to run all test in a subfolder of the test folder. So I tried python manage.py test <app name>.test.<sub-folder>(path to the test sub-folder), but it doesn't work. I created an __init__.py file inside <sub-folder> that imports all the test files in <sub-folder>, but that didn't work. Every time I run python manage.py test <app name>.test.<sub-folder> the terminal outputs Run 0 tests in <X number of seconds>s.

For example, typically in Django there's a root project folder then a test folder inside of that and then you can put folders with different test files in each folder. So I want to be able to run something like all the tests in folder project_folder/test/test_folder_A.

How do you run all tests inside of a sub-folder of the test folder in Django?

1 Answers

You may have reviewed it already, but the Django unit testing documentation provides some helpful information on how to run unit tests in a single package and/or module.

https://docs.djangoproject.com/en/3.2/topics/testing/overview/#running-tests

Based on your problem description, it sounds like you tried to create a package for your sub-folder and run the test command using that package path. If you tried creating a package and running the test command with that package path, but no tests were run, then my first thought is that it might be an issue with the package path that was supplied to the test command.

To resolve this issue, it might be helpful to first try and run the unit tests in a single python file/module. This can be done by passing the module name/path to the test command. Once you are able to get that working, then you could take the next step and try doing the same for an entire unit test folder/package.

EDIT: I was able to create a simple Django app and run only the unit tests in a specific sub-folder/package. My sample application code, along with brief repro steps, may be found on my GitHub page at the following link:

https://github.com/frederickm13/code-samples/tree/master/Django/unit-testing-django

Please review and compare what may be different between your project's structure and the structure of my sample application.

A few main points that I would like to note:

  • In order for the default Python unittest test runner to discover test files, the files must match the test*.py naming convention.
  • In order to run only the tests in a specific sub-folder/package, all folders in the Python package path must have an __init__.py file created within them. This signifies that those folders are Python packages. The full Python package path must then be passed to the test command as follows:

./manage.py test <parent_package>.<sub_package>.<sub_sub_package>

Related