How to run django-pytest on a project which imports settings from environment variables defined in manage.py
Asked Answered
E

2

5

I'm working on a Django project in which settings such as SECRET_KEY are defined in a .env file, and manage.py sets the environment variable using python-dotenv as follows:

from dotenv import load_dotenv, find_dotenv

if __name__ == "__main__":
    load_dotenv(find_dotenv())
    # usual manage.py code

Then settings.py simply defines module-level settings from environment variables, for example,

SECRET_KEY = os.environ['SECRET_KEY']

I'm now in the process of switching to pytest-django for unit testing. The problem, however, is that without running python manage.py first, the environment variables don't get set, so I end up with

E   KeyError: 'SECRET_KEY'

The way I'm now thinking of working around this is to define a custom action to register with manage.py to run pytest (following https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/). This seems a bit like using a sledgehammer to crack a nut, though. Any suggestions of more elegant ways to go about this problem?

Electrostatic answered 9/1, 2018 at 23:33 Comment(0)
E
2

Another approach could be to create a test runner for Django as described at https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-use-manage-py-test-with-pytest-django

Endoergic answered 10/1, 2018 at 0:30 Comment(0)
S
4

You could use os.getenv('SECRET_KEY'), which will return None if there is no such environment variable. That's equivalent to os.environ.get('SECRET_KEY') and similarly allows an optional second argument for a default value (e.g. os.getenv('SECRET_KEY', 'my-default-key').

This is the approach that most of the projects I've worked on have taken, both for testing and for local development reasons.

Socialize answered 10/1, 2018 at 0:35 Comment(0)
E
2

Another approach could be to create a test runner for Django as described at https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-use-manage-py-test-with-pytest-django

Endoergic answered 10/1, 2018 at 0:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.