Answer a question

I want to be able to set environment variables in my Django app for tests to be able to run. For instance, my views rely on several API keys.

There are ways to override settings during testing, but I don't want them defined in settings.py as that is a security issue.

I've tried in my setup function to set these environment variables, but that doesn't work to give the Django application the values.

class MyTests(TestCase):
    def setUp(self):
        os.environ['TEST'] = '123'  # doesn't propogate to app

When I test locally, I simply have an .env file I run with

foreman start -e .env web

which supplies os.environ with values. But in Django's unittest.TestCase it does not have a way (that I know) to set that.

How can I get around this?

Answers

As @schillingt noted in the comments, EnvironmentVarGuard was the correct way.

from test.test_support import EnvironmentVarGuard # Python(2.7 < 3)
from test.support import EnvironmentVarGuard # Python >=3
from django.test import TestCase

class MyTestCase(TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()
        self.env.set('VAR', 'value')

    def test_something(self):
        with self.env:
            # ... perform tests here ... #
            pass

This correctly sets environment variables for the duration of the context object with statement.

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐