h2non/pook

Pook 1.0.1 Error of JSON module (Py2 only)

solomonxie opened this issue · 3 comments

Version: Pook==1.0.1
Environment: Python 2.7

Demo code

# demo.py
import pook, requests, json
pook.on()
pook.post('http://x.com', json={"a": "a"}, reply=300)
requests.post('http://x.com', data=json.dumps({"a": "a"}))
pook.off()

Error message:

=> Detailed matching errors:
JSONMatcher: 'module' object has no attribute 'dumps'

Error source code:

image

Debugging

After a bit of debugging at runtime console, I found out that the json module showed above was not actually builtin json but rather a "magic mock":

>>> json
<module 'pook.matchers.json' from '/Users/someone/virtualenv/venv2/lib/python2.7/site-packages/pook/matchers/json.pyc'>
>>> json.dumps
AttributeError: 'module' object has no attribute 'dumps'

>>> import ujson
>>> ujson.dumps({1:1})
'{"1":1}'
h2non commented

Python 2.x is no longer a supported version in pook v1+.
You can try with a version 0.1.x.

Anyway, the issue seems related to the import behavior of the package, that resolves it itself, perhaps because of some environment-specific misconfiguration that impacted the package import algorithm in Python.

Hi @h2non,
thanks for the quick reply. I've tried different versions in 0.1.x, but still have the same problem.
Sorry for that I know we shouldn't use Py2 anymore but we still have a project depends on the pook mocking.
Did some code review, realize that in the pook/matchers/json.py, it tries to import json which in the Py2 environment it imports itself that is having the same module name.

I'm not sure why it works in the Python 3 environment?

h2non commented

I suppose the import system in Python 2 is a bit flawed.

Try moving to Python 3 as Python 2 is officially obsolete for a while.