使用python的mock来暂时从dict中删除一个对象

时间:2021-06-19 22:41:45

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:

我正在为一些检查os.environ中的值的代码编写测试(我知道这不是最佳的,但我必须使用它)。我想在测试期间从os.environ中删除一个条目。我不确定mock是否支持这个。我知道patch.dict可用于修改项目,但我希望删除键/值对。我想沿着这些方向做点什么:

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?

有没有办法执行这样的壮举?

2 个解决方案

#1


9  

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:

mock.patch.dict不像您的样本所需代码那样工作。 patch.dict是一个需要参数的函数。您可能想要像这样使用它:

>>> 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

#2


3  

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

#1


9  

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:

mock.patch.dict不像您的样本所需代码那样工作。 patch.dict是一个需要参数的函数。您可能想要像这样使用它:

>>> 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

#2


3  

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