我正在尝试在os.environ
的Python单元测试中模拟unittest.mock.patch.dict
。但是,当我尝试执行测试时,我得到TypeError: str expected, not int
。
大致上,我有以下内容:
import os
from unittest.mock import patch
with patch.dict('os.environ', values={"foo": 3, "bar": "hello"}, clear=True):
print(os.environ["foo"])
print(os.environ["bar"])
执行此代码将产生以下堆栈跟踪:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 1630, in __enter__
self._patch_dict()
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 1652, in _patch_dict
in_dict.update(values)
File "/Users/<redacted>/<redeacted>/<redacted>/venv/bin/../lib/python3.7/_collections_abc.py", line 841, in update
self[key] = other[key]
File "/Users/<redacted>/<redacted>/<redacted>/venv/bin/../lib/python3.7/os.py", line 683, in __setitem__
value = self.encodevalue(value)
File "/Users/<redacted>/<redacted>/<redacted>/venv/bin/../lib/python3.7/os.py", line 753, in encode
raise TypeError("str expected, not %s" % type(value).__name__)
TypeError: str expected, not int
我在做什么错?我查看了文档,看来这是使用unittest.mock.patch
模拟字典的正确方法。我正在MacOS High Sierra(版本10.13.5)上运行Python 3.7.0。
答案 0 :(得分:0)
事实证明,os.environ
checks可以看到您所设置的值是str
类型。就我而言,将values
更改为{"foo": "3", "bar": "hello"}
可解决问题。