2

How can I specify environment variable in PyCharm for all runs. Can I do it without extension from this answer Set the same environment variables for all configurations in PyCharm

I know that I can set environment variables for one test when I want to run anoter test with environmet variable I have to set env variable again)

Open the Run Configuration  --> Edit Configurations --> Environment Variables --> Set variable

enter image description here

How can I set environment variable in PyCharm one time for all tests (use one run configuration for all tests)?

Alex
  • 562
  • 1
  • 6
  • 25
  • Relatedly, I can click on the "arrow" in the left hand gutter to start one unit test, but how do I make sure the right environment variables are set for that one test? – Ben May 25 '22 at 18:23

1 Answers1

0

There may be a better way to do this, but this seems to work for me.

I set up a child class of unittest.TestCase.

class GRTestCase(unittest.TestCase):
    """
    Setting up a generic way for us to store env vars before running unit tests
    """
    def __init__(self, *args, **kwargs):
        super(GRTestCase, self).__init__(*args, **kwargs)
        os.environ['TESTVAR'] = 'TEST value'

Then, use this child class GRTestCase in your tests, rather than unittest.TestCase. You can test this by running the method test_env_var in the next class (right click on the green arrow in the left gutter):

class tests(GRTestCase):
    
    def test_env_var(self):
        tmpvar = os.getenv('TESTVAR')
        print(tmpvar)
        self.assertEqual(tmpvar, 'TEST value')

You should see that your test passes and TEST value gets printed to the console. One advantage here could be that this should work even if you're not in PyCharm.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Ben
  • 4,798
  • 3
  • 21
  • 35