1

I'm very much new to the pytest framework and while I was exploring I checked with few terms such as mocking, monkey patching, etc. I basically understood the definition of each of them but having issues in applying them to my functional code. The init class of my parent method reads a few environment variables and pass them to the methods.

I am having difficulty applying the mocking/monkey_patching those variables and passing those test cases with fake data. To be precise, check the below example

Scenario:

class sampleDB(object):
    
    config_keys = ["foo_env", "bar_env", "foo_pass", "bar_pass"]

    def __init__(self, database, conf=None):
    
    os.environ["foo_env"] = os.getenv("foo_env")
    os.environ["bar_env"] = os.getenv("bar_env") 
    os.environ["foo_pass"] = os.getenv("foo_pass")
    os.environ["bar_pass"] = os.getenv("bar_pass")

    if not isinstance(conf, AnalyticsConfig):
         if conf is None:
              conf = AnalyticsConfig(require_only=self.CONFIG_KEYS)
         else:
              raise TypeError("'conf' must be an AnalyticsConfig instance")

    self.foo_env= conf.foo_env
    self.bar_env= conf.bar_env
    self.foo_pass= conf.foo_pass
    self.bar_pass= conf.bar_pass
    self._conf = conf
    self.database = database

  def sample_run(x,y):
   
   """Sample function to read data from a database and and returns pandas.df"""
 
   result = read_data(self.foo_env, self.foo_pass, x, y) 
   
   return result

The above code works in a regular local test environment by requesting os.getenv variables. When I deploy this code with the test cases in the Azure pipeline, it is failing because there are no environment variables set up in the pipeline. Instead of keeping the variable in pipeline, I want to use the mocking/monkey patching concept here.

Can someone please help me out with the problem?

  • You can use the the `setenv` method of the [monkeypatch fixture](https://docs.pytest.org/en/stable/monkeypatch.html#monkeypatching-environment-variables), if you are using pytest. – MrBean Bremen Jan 05 '21 at 18:45

1 Answers1

1

Instead of keeping the variable in pipeline, I want to use the mocking/monkey patching concept here.

Since you do not want to keep the variable in pipeline, you could try to use the Mock to set environment variables in pytest:

import os
from unittest import mock

from example.settings import Colour, get_settings


@mock.patch.dict(os.environ, {"FROBNICATION_COLOUR": "ROUGE"})
def test_frobnication_colour():
    colour = get_settings().frobnication_colour
    assert colour == Colour.ROUGE

You could check following documents for some more details:

How to Mock Environment Variables in pytest

Python mock Patch os.environ and return value

Leo Liu
  • 71,098
  • 10
  • 114
  • 135
  • How to mock os.environ if environment var is accessed globally. like below USER = os.environ['USER'] def get_user(): return USER – Hasan Nov 22 '21 at 04:35