How do I change an environment variable only during tests in Django?

Viewed 261

I have a class that extends the root TestCase. I would like to set an environment variable in each of the tests that extend this class so that I don't cycles on unnecessary API queries.

When I place the patch decorator outside of the class, it appears to have no effect.

When I place the patch decorator just above the setUp, the patch appears to only last through the duration of the setUp.

import mock, os
from django.test import TestCase


#patching here seems to have no effect
class TCommerceTestCase(TestCase):

  @mock.patch.dict(os.environ, {
    "INSIDE_TEST": "True"
  })
  def setUp(self):
    self.assertEqual(os.environ["INSIDE_TEST"], "True") # works!

  def test_inside_test(self):
    self.assertEqual(os.environ["INSIDE_TEST"], "True") # Fails!

How do I patch an environment variable in a Django test (without manually patching to every function?)

1 Answers

Try this in that way:

import mock, os
from django.test import TestCase

class TCommerceTestCase(TestCase):

  @mock.patch.dict(os.environ, {
    "INSIDE_TEST": "True"
  })
  def test_inside_test(self):
    self.assertEqual(os.environ["INSIDE_TEST"], "True")
    ```
Related