I am writing a test for some code that checks for a value in os.environ
(I know this isn't optimal, but I have to go with it). I would like to remove an entry from os.environ for the duration of the test. I am not sure if mock supports this. I know patch.dict
can be used to modify an item, but I want the key/value pair removed. I would like something along these lines:
print os.environ
{ ... , 'MY_THING': 'foo', ... }
with mock.patch.dict.delete('os.environ', 'MY_THING'):
# run the test
# ( 'MY_THING' in os.environ ) should return False
# everything back to normal now
print os.environ
{ ... , 'MY_THING': 'foo', ... }
Is there a way to perform such a feat?
Python has in-built clear () method to delete a dictionary in Python. The clear () method deletes all the key-value pairs present in the dict and returns an empty dict. The following techniques can be used to delete a key-value pair from a dictionary: 1. Using pop () method
A Python mock object contains data about its usage that you can inspect such as: Understanding what a mock object does is the first step to learning how to use one. Now, you’ll see how to use Python mock objects. The Python mock object library is unittest.mock. It provides an easy way to introduce mocks into your tests.
For example, if you are mocking the json library and your program calls dumps (), then your Python mock object must also contain dumps (). Next, you’ll see how Mock deals with this challenge. A Mock must simulate any object that it replaces. To achieve such flexibility, it creates its attributes when you access them:
As mentioned before, if you change a class or function definition or you misspell a Python mock object’s attribute, you can cause problems with your tests. These problems occur because Mock creates attributes and methods when you access them.
mock.patch.dict
doesn't quite work like your sample desired code. patch.dict
is a function which requires an argument. You probably want to use it like this:
>>> import os
>>> import mock
>>> with mock.patch.dict('os.environ'):
... del os.environ['PATH']
... print 'PATH' in os.environ
...
False
>>> print 'PATH' in os.environ
True
For deleting the item, you can simply use:
my_thing = os.environ['MY_THING'] # Gotta store it to restore it later
del os.environ['MY_THING']
And then restore it with:
os.environ['MY_THING'] = my_thing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With