I need to monkeypatch some functions on a project I am writing tests for, but before it I created a simple project to try it out (it basically uses requests.get to call the ipify API to get my public IP, and I am trying to monkey patch the requests.get function OR the function on my own code that calls requests.get, in order to return a fixed value - "0.0.0.0" in this case).
The project structure looks like this:
- root directory
- ipify_api (my package)
- methods.py (here I have the function that return the public IP returned by the API)
- helpers.py (here I have the function that call the API and returns the response)
- tests
- test_ipify.py
- ipify_api (my package)
The project code is the following:
ipify_api/helpers.py
from requests import get
def request_ipify_api():
r = get("https://api.ipify.org/?format=raw")
return r
ipify_api/methods.py
from .helpers import *
def get_public_ip() -> str:
r = request_ipify_api()
return r.text
tests/test_ipify.py
import requests
import ipify_api
# import ipify_api.helpers
class FakeResponse:
text: str
class TestIpifyAPI:
@staticmethod
def __get_fake_response():
r = FakeResponse()
r.text = "0.0.0.0"
return r
def test_get_public_ip(self, monkeypatch):
"""Calling methods.get_public_ip() should return 0.0.0.0
"""
# monkeypatch.setattr(ipify_api.helpers, "request_ipify_api", self.__get_fake_response)
monkeypatch.setattr(requests, "get", self.__get_fake_response)
assert ipify_api.get_public_ip() == "0.0.0.0"
The problem is the real function keeps being called, so I do not get the expected "0.0.0.0" result, but my real IP instead (because the real requests.get get called). Patching the ipify_api.helpers.request_ipify_api() function of my own gives the same result.
As far as I understand, I am doing what the pytest documentation states for monkey patching functions: https://docs.pytest.org/en/latest/monkeypatch.html#simple-example-monkeypatching-functions
Aucun commentaire:
Enregistrer un commentaire