【问题标题】:mocking os.environ returns, str expected not dict模拟 os.environ 返回,str 预期不是 dict
【发布时间】:2019-02-27 07:37:18
【问题描述】:

执行此代码会导致:

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

【问题讨论】:

  • 您发布的内容在语法上无效。此外,环境表示为 strings 的字典,因此您的测试替身与它要替换的内容不匹配。
  • 我认为您试图通过将两个 url 提及为 dev 并在 dict 中进行测试来传递它们,但这不是正确的方法。
  • 请勿发代码图片。

标签: python python-unittest


【解决方案1】:

您正在尝试使用导致问题的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'])

【讨论】:

  • 必须编写测试用例的代码中包含 URL。所以,我无法删除它。如果我删除 URL,我不会收到上述错误。但我需要其中的网址
  • 您不能在path.dict 中那样使用字典。因此,为了访问它,您需要删除 URL 并为您的测试用例寻找解决方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
相关资源
最近更新 更多