在os.environ上使用unittest.mock.patch.dict会导致TypeError

时间:2018-08-14 17:26:33

标签: python python-3.x unit-testing

我正在尝试在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。

1 个答案:

答案 0 :(得分:0)

事实证明,os.environ checks可以看到您所设置的值是str类型。就我而言,将values更改为{"foo": "3", "bar": "hello"}可解决问题。