我正在使用 Httpretty 来模拟 Web API。
如果我使用
httpretty.enable(allow_net_connect=False)
(当allow_net_connect为False时,任何与未注册的uri的连接都会抛出httpretty.errors.UnmockedError),我会收到一个错误,因为pymysql无法通过套接字连接到本地数据库。
但是,当我使用
httpretty.enable(allow_net_connect=True)
时,我会因连接丢失而收到错误。
../../.virtualenvs/3.6espiga/lib/python3.6/site-packages/pymysql/__init__.py:90: in Connect
return Connection(*args, **kwargs)
../../.virtualenvs/3.6espiga/lib/python3.6/site-packages/pymysql/connections.py:699: in __init__
self.connect()
../../.virtualenvs/3.6espiga/lib/python3.6/site-packages/pymysql/connections.py:935: in connect
self._get_server_information()
../../.virtualenvs/3.6espiga/lib/python3.6/site-packages/pymysql/connections.py:1249: in _get_server_information
packet = self._read_packet()
../../.virtualenvs/3.6espiga/lib/python3.6/site-packages/pymysql/connections.py:991: in _read_packet
packet_header = self._read_bytes(4)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <pymysql.connections.Connection object at 0x7fefe1ad40f0>, num_bytes = 4
def _read_bytes(self, num_bytes):
self._sock.settimeout(self._read_timeout)
while True:
try:
data = self._rfile.read(num_bytes)
break
except (IOError, OSError) as e:
if e.errno == errno.EINTR:
continue
self._force_close()
raise err.OperationalError(
CR.CR_SERVER_LOST,
"Lost connection to MySQL server during query (%s)" % (e,))
if len(data) < num_bytes:
self._force_close()
raise err.OperationalError(
> CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
E pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
../../.virtualenvs/3.6espiga/lib/python3.6/site-packages/pymysql/connections.py:1037: OperationalError
如何让 Httpretty 模拟 Web API 并让数据库连接照常运行?
对于几年后发现这一点的人,我从 pytest-mock-resources 得到了
UnmockedError
,这让我意识到其他测试中的 httpretty 导致我的数据库测试失败。我发现的修复方法是在 pytest 中添加一个拆卸函数,该函数在每次测试后调用 httpretty.disable()
。例如
@pytest.fixture(autouse=True)
def stop_http_pretty():
yield
# Everything after the yield is run after each test as a "teardown".
# This is required to stop httpretty from intercepting calls to the
# mock db used by pytest-mock-resources
httpretty.disable()
这仅对我有用,因为我在相同的测试中没有使用 httpretty 和 db 连接,但我不确定它会如何工作。 pytest 开发人员显然普遍反对拆解,所以我不确定这是否是最佳实践,但它确实有效。