Lukich
Lukich

Reputation: 726

Testing Django view with environment variables

I am starting to write tests for a Django app, which relies on several environment variables. When I am testing it in the shell, I can import os and specify the variables and my tests work just fine. However, when I put them into tests.py, I still get a key error because those variables are not found. here's what my test looks like:

from django.utils import unittest
from django.test.utils import setup_test_environment
from django.test.client import Client
import os

os.environ['a'] = 'a'
os.environ['b'] = 'b'


class ViewTests(unittest.TestCase):
    def setUp(self):
        setup_test_environment()

    def test_login_returning_right_template(self):
        """ get / should return login.html template """
        c = Client()
        resp = c.get('/')
        self.assertEqual(resp.templates[0].name, 'login.html')

Is this the wrong place to initialize those variables? I tried to do it on setUp, but with the same result - they are not found. Any suggestions on how to initialize environment variables before running a test suite? Thanks! Luka

Upvotes: 2

Views: 5276

Answers (1)

Tomasz Wysocki
Tomasz Wysocki

Reputation: 11568

You should not relay on os.envior in your views. If you have to, do It in your settings.py

MY_CUSTOM_SETTING = os.environ.get('a', 'default_value')

And in views use settings variable:

from django.conf.settings import MY_CUSTOM_SETTING
print MY_CUSTOM_SETTING

Then in your test you can set this setting:

from django.test import TestCase

class MyTestCase(TestCase):

    def test_something(self):
        with self.settings(MY_CUSTOM_SETTING='a'):
            c = Client()
            resp = c.get('/')
            self.assertEqual(resp.templates[0].name, 'login.html')

Upvotes: 5

Related Questions