我希望我的包在有或没有 rapidjson
的情况下都可以使用,所以我有以下代码:
try:
import rapidjson as json # https://github.com/python-rapidjson/python-rapidjson
def pp_json(x, fd):
"Pretty-print object to stream as JSON."
return json.dump(x, fd, sort_keys=True, indent=1)
except ImportError:
import json # https://docs.python.org/3/library/json.html
def pp_json(x, fd):
"Pretty-print object to stream as JSON."
return json.dump(x,fd,sort_keys=True,indent=1,separators=(',',':'))
我的问题是:如何在使用和不使用rapidjson
的情况下测试此文件?
我不想像这样手动完成
$ coverage3 run --source=pyapp -m unittest discover --pattern *_test.py
$ pip3 uninstall python-rapidjson
$ coverage3 run --source=pyapp -m unittest discover --pattern *_test.py
$ pip3 install python-rapidjson
PS。我实际上不确定这是否值得付出努力,所以我会接受一个答案,它告诉我强行将 python-rapidjson
添加到 requirements.txt
并忘记整个事情。 ;-)
最佳答案
与 mock library您可以通过修补 sys.modules 字典来模拟在特定测试中未安装rapidjson。
def test_with_import_error(self):
with mock.patch.dict('sys.modules', {'rapidjson': None}):
#test code with ImportError here
关于python - 使用和不使用包依赖项进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51200093/