Run a unit test which needs environment variables

Viewed 6345

Without environment variables, we know, the call is: python -m unittest tests.unit_test_1

But I need to pass environment variables as I need some values would be inserted in to the database whose creds are with me. I do not want to write it in a config/.py file, only pass them as environment variables. So if I pass the environment variables as:

python -m unittest tests.unit_test_1 $username $password

EDIT:

unit_test_1.py is somewhat as follows:

import unittest
from sys import argv
from os import environ

class database_helper_tests(unittest.TestCase):
    def fetch(this):
        x = connet_to_database(environ["username"], environ["password"])
        data = x.fetch_from_database(this)
        expected_output = ...
        self.assertEqual(expected_output, data)

if __name__ == "__main__":
    os["username"] = argv[1]
    os["password"] = argv[2]
    unittest.main()

The first test passes. And Then error I get is:

ModuleNotFoundError: No module named 'username"
ModuleNotFoundError: No module named 'password"

And finally I see this (although I am running just one test):

Ran 3 tests in 1.48s

What should I do so that I run only the test that is required?

Thank you in advance.

2 Answers
$ export username="user"
$ export password="secret"
$ python -m unittest tests.unit_test_1

and then access within your code like you did

os.environ["username"]

or

$ username="user" password="secret" python -m unittest tests

example env access

Realistically, your code should not depend on where the variables actually come from. For example, define a config.py

import os
config = {
  "user" : os.environ["username"], 
  "pass": os.environ["password"] 
}

Then change your test code to mock/define the config dictionary and your real methods to import the config module

Similarly, you should mock the database methods such that you don't really need authentication, unless you're explicitly trying to test that

Related