Why does the simplest requests_mock example fail with pytest?

2024/11/16 0:03:48

I have a peculiar problem with requests_mock. I want to use it with pytest to test my API wrapper library.

I've tried to use the first example in the requests_mock docs, except I put it in a test_mock()-function and added an assert-statement for pytest to discover it.

The following code fails:

# tests/test_mock.pyimport requests
import requests_mockwith requests_mock.Mocker() as m:def test_mock():m.get('http://test.com', text='resp')assert requests.get('http://test.com').text == 'resp'

However, when running the following example in ipython, it works as expected. This is the exact code from the example:

with requests_mock.Mocker() as m:m.get('http://test.com', text='resp')print(requests.get('http://test.com').text)# prints 'resp'

Because I can make requests_mock work from ipython, I assume the issue is with pytest, but I might be wrong.

It seems like the adapter isn't used at all, so that requests sends a real http request to the target url instead of using the mocked object.


I'm using Python 3.6.3 (Anaconda3), requests_mock 1.3.0 and pytest 3.3.0

Output from running the code that fails:

C:\dev\mylib>pytest -v
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.3.0, py-1.5.2, pluggy-0.6.0 -- e:\anaconda3\envs\benv\python.exe
cachedir: .cache
rootdir: C:\dev\mylib, inifile: setup.cfg
collected 1 itemtests/test_mocks.py::test_mock FAILED                                    [100%]================================== FAILURES ===================================
__________________________________ test_mock __________________________________def test_mock():m.get('http://test.com', text='resp')
>       assert requests.get('http://test.com').text == 'resp'
E       assert '<!DOCTYPE ht...y>\n</html>\n' == 'resp'
E         + resp
E         - <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
E         - <html>
E         - <head>
E         - <title>Client Validation</title>
E         - <script type="text/javascript">
E         - function setCookie(c_name, value, expiredays) {...
E
E         ...Full output truncated (26 lines hidden), use '-vv' to showtests\test_mocks.py:9: AssertionError
------------------------------ Captured log call ------------------------------
connectionpool.py          208 DEBUG    Starting new HTTP connection (1): test.com
connectionpool.py          396 DEBUG    http://test.com:80 "GET / HTTP/1.1" 302 161
connectionpool.py          824 DEBUG    Starting new HTTPS connection (1): www.test.com
connectionpool.py          396 DEBUG    https://www.test.com:443 "GET / HTTP/1.1" 200 None
========================== 1 failed in 2.05 seconds ===========================
Answer

Why it works in IPython seems like a mystery to me. To fix the issue just swap the lines of the function definition with the opening of the context manager.

# tests/test_mock.pyimport requests
import requests_mockdef test_mock():with requests_mock.Mocker() as m:m.get('http://test.com', text='resp')assert requests.get('http://test.com').text == 'resp'
https://en.xdnf.cn/q/71412.html

Related Q&A

Error installing PyCurl

I tried installing pycurl via pip. it didnt work and instead it gives me this error.running installrunning buildrunning build_pyrunning build_extbuilding pycurl extensiongcc-4.2 -fno-strict-aliasing -f…

Serializing objects containing django querysets

Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)?I want to serialize the following dictionar…

How do I list my scheduled queries via the Python google client API?

I have set up my service account and I can run queries on bigQuery using client.query(). I could just write all my scheduled queries into this new client.query() format but I already have many schedule…

What does conda env do under the hood?

After searching and not finding, I must ask here:How does conda env work under the hood, meaning, how does anaconda handle environments?To clarify, I would like an answer or a reference to questions l…

Numpy array larger than RAM: write to disk or out-of-core solution?

I have the following workflow, whereby I append data to an empty pandas Series object. (This empty array could also be a NumPy array, or even a basic list.)in_memory_array = pd.Series([])for df in list…

Pandas DataFrame styler - How to style pandas dataframe as excel table?

How to style the pandas dataframe as an excel table (alternate row colour)? Sample style:Sample data: import pandas as pd import seaborn as snsdf = sns.load_dataset("tips")

Remove namespace with xmltodict in Python

xmltodict converts XML to a Python dictionary. It supports namespaces. I can follow the example on the homepage and successfully remove a namespace. However, I cannot remove the namespace from my XM…

Groupby count only when a certain value is present in one of the column in pandas

I have a dataframe similar to the below mentioned database:+------------+-----+--------+| time | id | status |+------------+-----+--------+| 1451606400 | id1 | Yes || 1451606400 | id1 | Yes …

how to save tensorflow model to pickle file

I want to save a Tensorflow model and then later use it for deployment purposes. I dont want to use model.save() to save it because my purpose is to somehow pickle it and use it in a different system w…

PySide2 Qt3D mesh does not show up

Im diving into Qt3D framework and have decided to replicate a simplified version of this c++ exampleUnfortunately, I dont see a torus mesh on application start. Ive created all required entities and e…