Reputation: 60014
I want my package to be usable both with and without rapidjson
, so I have the following code:
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=(',',':'))
my question is: how can I test this file both with and without rapidjson
?
I would rather not do it manually like
$ 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. I am not actually sure that this is worth the effort, so I would accept an answer that tells me peremptorily to add python-rapidjson
to requirements.txt
and forget the whole thing. ;-)
Upvotes: 1
Views: 68
Reputation: 38116
With the mock library you can simulate that rapidjson is not installed in a specific test by patching the sys.modules
dict.
def test_with_import_error(self):
with mock.patch.dict('sys.modules', {'rapidjson': None}):
#test code with ImportError here
Upvotes: 1