Reputation: 31
I'm having a hard time mocking os.environ.get
hoping you can help.
I have a BaseClass that is imported. I'm trying to mock the os.environ.get call in that base_class file when import the BaseClass method into the sub_class module.
project.data.base_class.py
import os
class BaseClass(object):
VAR1 = os.environ.get('something')
VAR2 = os.environ.get('something')
def __init__(self):
pass
def get(self):
return BaseClass.VAR1
project.data.sub_class.py
from project.data.base_class import BaseClass
class SubClass(BaseClass):
def __init__(self):
def run(self):
return self.get()
I want to test the SubClass.run
method, but when I try mocking, I can't seem to get the right mock set up for os.environ. Here is what I've tried:
from mock import patch
@patch('base_class.os.environ')
def test_sub_class_run(self, mock_base):
mock_base.get.side_effect = ['var1', 'var2']
from sub_class import sub_class
self.assertEqual(sub_class.SubClass.run(), 'var1')
from mock import patch
and
@patch('sub_class.base_class.os.environ')
def test_sub_class_run(self, mock_base):
mock_base.get.side_effect = ['var1', 'var2']
from sub_class import sub_class
self.assertEqual(sub_class.SubClass.run(), 'var1')
I feel like because of when I am using os.environ, i'm not mocking properly. I'm not really sure what the appropriate way to structure the mock is to get it to mock that os call. properly.
That's my pseudo code more or less.
Upvotes: 2
Views: 429
Reputation: 31
I didn't solve the problem. I did have to refactor my code and the reason was because, and I think this is true but please someone correct this if I'm wrong!
It looks like when you try to patch a library, the patching library seems to actually run the script or module you are importing. So in my case, I was trying to mock an OS call, but the OS call of the thing I was trying to patch was at the outermost layer of my script. When I would try to patch it, my environment variable didn't exist. I had to move that environment variable retrieval into my class and then try to patch.
This could be wrong and I misinterpreted what I did, but that's how I solved my problem.
Upvotes: 1