Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python's mock to temporarily delete an object from a dict

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?

like image 788
Wisco crew Avatar asked Mar 24 '15 21:03

Wisco crew


People also ask

How to delete a dictionary in Python with clear () method?

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

What is a Python mock object?

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.

How does Python mock handle dumps?

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:

What happens if you misspell a Python mock object’s attribute?

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.


Video Answer


2 Answers

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
like image 107
bmhkim Avatar answered Sep 27 '22 02:09

bmhkim


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
like image 24
Spice Avatar answered Sep 23 '22 02:09

Spice