2

I am trying to add env variables to pytest. I have successfully managed to add env and configure for regular python scripts but i am unable to use env vars for pytest.

 somefile.env 
 KEY = "12345"

 Config.py
 import os
 headers = {"Key": os.environ.get("KEY"), "content_Type": "application/json"}

Above are the values given in .env and config file. I can access headers value in python script, but i am unable to access this header value inside pytest. Eg this is my code in pytest

 import os
 from config import headers

  print(headers) #---> as this works as expected and prints key value

  #Pytests starts
  def test_one():
  print(headers) # prints key as None

When i call headers in pytest i am getting key value as None

user29496
  • 187
  • 1
  • 3
  • 10
  • Can you update your question and add the code that you've tried? I mean you can access environment variables through `os` module in Python: `os.environ.get("CUSTOM_ENV_VARIABLE")` What seems to be the problem then? – pavelsaman Jun 17 '20 at 16:55
  • updated question – user29496 Jun 17 '20 at 17:22
  • I think you can add them in a `pytest.ini` file. – Games Brainiac Jun 17 '20 at 19:20
  • Tried it but no luck. Entered the following code in pytest.ini [pytest] env = HOME=~/tmp RUN_ENV=1234 as1234 is my key. I am not sure if i am doing it in right way – user29496 Jun 17 '20 at 19:59
  • Does this answer your question? [How to pass environment variables to pytest](https://stackoverflow.com/questions/36141024/how-to-pass-environment-variables-to-pytest) – gold_cy Jun 17 '20 at 20:08
  • none of the approaches are working – user29496 Jun 18 '20 at 00:23

1 Answers1

8

The solution here is as described by @user29496

# contents of pytest.ini
[pytest]
env =
    D:RUN_ENV=1234

This will silently fail/not work unless you install pytest-env

pip install pytest-env

At this point, the RUN_ENV should be correctly passed. See also How to pass environment variables to pytest

jandom
  • 111
  • 1
  • 7
  • Hi, I have tried above solution and unable to pass/read environment variables. I'm using Pycharm as IDE and Python 3.9 version. Here is what i have tried # pytest.ini [pytest] env = D:RUN_ENV=1234 # testfile.py import os print(os.environ.get('RUN_ENV')) When i run the testfile.py I'm getting NONE – user29496 Aug 08 '21 at 18:01
  • [python-dotenv](https://github.com/theskumar/python-dotenv) is a more active project these days. – sourcream Apr 18 '22 at 22:19