Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django extract tests outside /src/project

I am trying to follow best practices which I often find in GitHub repositories: I would like to have a /src and a /test folder at the top level in a project. (random example https://github.com/bitcoin/bitcoin). I am not sure how to configure Django to accept that though.

In particular, Django is expecting tests to be inside the project folder, but ideally, these tests should be outside of /src/project_name and inside /test.

Any suggestions are greatly appreciated. Thank you so much!

project_root
  |-- src
  |   |-- project_name
  |       |-- app_name
  |       |   |-- views.py
  |       |   |-- serializers.py
  |       |   |-- etc...
  |       |-- manage.py
  |-- test
      |-- project_name
          |-- test_feature1.py
          |-- test_feature2.py
like image 221
Andrei Cioara Avatar asked Oct 25 '25 02:10

Andrei Cioara


1 Answers

I found an answer! Use the pytest-django module. They have some documentation about changing your test directory through the pythonpath environment variable here. All of your django tests should also be backwards compatible with pytest, so no changes to the individual tests should be required.

So to test from the /test directory,

  1. Install pytest-django: pip install pytest-django (also make sure to add pytest-django==4.5.2 to your requirements.txt file). This also installs the latest version of pytest.
  2. Move all tests from your /src/<app_name>/tests/ directories into /test. It should look like the following:
project_root
  |-- src
  |   |-- project_name
  |       |-- app_name
  |       |   |-- views.py
  |       |   |-- serializers.py
  |       |   |-- settings.py
  |       |   |-- etc...
  |       |-- manage.py
  |-- test
      |-- test_feature1.py
      |-- test_feature2.py
  1. Create a pytest.ini file in the root directory of your project. It must specify the DJANGO_SETTINGS_MODULE and pythonpath environment variables:
[pytest]
DJANGO_SETTINGS_MODULE = app_name.settings
pythonpath = src test  # adds /src and /test directories to the pythonpath
  1. Run pytest (or python -m pytest). This replaces python src/manage.py test src.

Hope this helps!

like image 107
Ethan Posner Avatar answered Oct 26 '25 16:10

Ethan Posner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!