嘲笑os.environ返回,str不应该是dict

时间:2019-02-27 07:37:18

标签: python python-unittest

enter image description here

执行此代码将导致:

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 个答案:

答案 0 :(得分:0)

您正试图通过key URL来传递字典,这会导致问题。

有关更多方法,请参见this documentation

尝试以下代码:

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'])