Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 395
Kurt Peek Avatar asked Jan 09 '18 23:01

Kurt Peek


2 Answers

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.

like image 101
Aaron Klein Avatar answered Oct 07 '22 00:10

Aaron Klein


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

like image 37
Stuart Dines Avatar answered Oct 07 '22 00:10

Stuart Dines