Mocking global variables in Python tests
I attempted to test global variables in Python, specifically for a script that contains global variables. After struggling to do so, I found a simple solution that I can share with you.
🏃 The quick solution
Now, let’s go to the test file.
ENVS variable will be mocked in your
✏️ Solution with description
To simplify the process, I recommend using the
pytest-mock library: https://pypi.org/project/pytest-mock/
What I was trying to do?
Firstly, suppose you have a file called
demo_file.py with the following content (where the global variable is located):
If you try to execute
simple_method, it will print the dictionary with
Next, we have the following test file.
I know the test seems simple, but it’s important to make sure that it returns a zero value after printing the values of the ENV variable.
👾 Mocking the Variable
However, as you can see, we are calling environment variables on the current computer. If you write your tests to expect those variables on your CI/CD server, the tests will fail. How can we avoid this and tell our test server (or test pipeline) that we want specific fixed values?
If you have installed the package mentioned in the requirements section, it is easy to start mocking values. We only need to add a single line.
Your tests will not execute the real ENVS variable and, therefore, will not call