Python mocking os.environ返回,str应为not dict

Python mocking os.environ返回,str应为not dict,python,python-unittest,Python,Python Unittest,执行此代码将导致: 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_di

执行此代码将导致:

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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/usr/local/ceral/python/3.7.0/Frameworks/python.framework/Versions/3.7/lib/python3.7/unittest/mock.py”,第1630行,输入__
self.\u patch\u dict()
文件“/usr/local/ceral/python/3.7.0/Frameworks/python.framework/Versions/3.7/lib/python3.7/unittest/mock.py”,第1652行,在补丁中
目录更新(值)
文件“/Users///venv/bin/./lib/python3.7/_collections\u abc.py”,第841行,在更新中
自[键]=其他[键]
文件“/Users///venv/bin/./lib/python3.7/os.py”,第683行,在_setitem中__
值=自身。编码值(值)
文件“/Users///venv/bin/./lib/python3.7/os.py”,第753行,编码
raise TypeError(“应为str,而不是%s”%type(value)。\uuuu name\uuuu)
TypeError:应为str,而不是int

您正试图使用导致问题的
键传递dict

有关进一步的方法,请参阅

请尝试以下代码:

import os
import unittest
from mock import patch
with patch.dict('os.environ',{"devUrl":"https://devurl.com","testUrl":"https://testurl.com"}):
     print(os.environ['devUrl'])
     print(os.environ['testUrl'])

您发布的内容在语法上无效。此外,该环境被表示为字符串字典,因此您的测试双精度与它所替换的东西不匹配。我认为您试图通过在dict中将两个URL称为dev和test来传递它们,但这不是正确的方式。请不要发布代码图片。必须编写测试用例的代码中包含URL。因此,我无法删除它。如果我删除URL,我不会得到上面提到的错误。但是我需要一个URL,你不能在
path.dict
中那样使用字典。所以,为了访问它,您需要删除URL,并为您的测试用例寻找解决方法。