2

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?)

Phil Brockman
  • 310
  • 3
  • 17

1 Answers1

0

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")
    ```
mrvol
  • 2,575
  • 18
  • 21
  • Yes this does work for `test_inside_test`, but is there a way to apply os.environ["INSIDE_TEST"] to *every* test? – Phil Brockman Nov 04 '21 at 18:04
  • 1
    Please don't be confused about adding a short decorator to all needed tests. It is OK. Every developer/tester who reads a code of a test will be understanding that behaviour was changed by a decorator. It's short - just copy/paste it. – mrvol Nov 04 '21 at 18:08
  • Understood. I am looking for a DRY solution – Phil Brockman Nov 04 '21 at 19:11
  • 1
    DRY principle is not for testing. Testing principle is repeating, hardcoding, avoiding any logic and complicity. – mrvol Nov 04 '21 at 19:15
  • Good news! It is possible to implement DRY principles during testing. This solution worked for me: https://stackoverflow.com/a/66384229/3869506 – Phil Brockman Nov 06 '21 at 03:12