Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pytest monkeypatch

# contents of test_app.py, a simple test for our API retrieval
# import requests for the purposes of monkeypatching
import requests

# our app.py that includes the get_json() function
# this is the previous code block example
import app

def get_json(url):
    """Takes a URL, and returns the JSON."""
    r = requests.get(url)
    return r.json()

# custom class to be the mock return value
# will override the requests.Response returned from requests.get
class MockResponse:

    # mock json() method always returns a specific testing dictionary
    @staticmethod
    def json():
        return {"mock_key": "mock_response"}


def test_get_json(monkeypatch):

    # Any arguments may be passed and mock_get() will always return our
    # mocked object, which only has the .json() method.
    def mock_get(*args, **kwargs):
        return MockResponse()

    # apply the monkeypatch for requests.get to mock_get
    monkeypatch.setattr(requests, "get", mock_get)

    # app.get_json, which contains requests.get, uses the monkeypatch
    result = app.get_json("https://fakeurl")
    assert result["mock_key"] == "mock_response"
Comment

PREVIOUS NEXT
Code Example
Python :: pyspark on colab 
Python :: torch.utils.data.random_split(dataset, lengths) 
Python :: any all in python 
Python :: shape of variable python 
Python :: what is data normalization 
Python :: how to index lists in python 
Python :: lambda functions python 
Python :: how to print second largest number in python 
Python :: flow of control in python 
Python :: set intersection 
Python :: bitbucket rest api python example 
Python :: list dataframe to numpy array 
Python :: can we use else without if in python 
Python :: how to use djoser signals 
Python :: how to use the sleep function in python 
Python :: Yield Expressions in python 
Python :: python in 
Python :: argparse one argument or without argument 
Python :: python iterator 
Python :: python takes 2 positional arguments but 3 were given 
Python :: python tuple operations 
Python :: Python NumPy concatenate Function Syntax 
Python :: python read array line by line 
Python :: problem solving with python 
Python :: for loop in django template css 
Python :: python pandas how to check in what columns there are empty values(NaN) 
Python :: python how to loop 
Python :: Python - How To Pad String With Spaces 
Python :: python pprint on file 
Python :: py 2 exe 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =