Python Forum

Full Version: Mocks with pytest
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi !
I am in the process of coding a small program with flask.
However I block on a test with mock. The goal is to simulate a return of an API locally.

This the function to test
def geolocalize(address):
    """function that returns information about
    a place based on an address
    """
    #construct the url based on the address
    urlBase = "https://maps.googleapis.com/maps/api/geocode/json?"
    url = urlBase + "address=" + address + "&key=" + geoApiKey

    #do the request
    r = requests.get(url)
    #if r.status_code != 200:
    #    return ('Error: the geolocalisation service failed.')
    return json.loads(r.content.decode('utf-8-sig'))
and the test function is:
def test_http_return(monkeypatch):

    response = {"results":
        [
            {"geometry":
                {"location":
                    {"lat": 5.3599517,
                     "lng": -4.0082563
                    }
                },
             "formatted_address": 'Abidjan, Côte d\'Ivoire'

            }
        ]
    }

    def mockreturn(request):
        return json.dumps(response)

    monkeypatch.setattr(requests, 'get', mockreturn)

    assert geolocalize('Abidjan') == response
but when I try to run the pytest, the console show this :
[Image: open?id=1u4ezQVznla5IJKkUKVVqGoVBA28HF3Pf]

please, I have done a lot to be able to solve this error; but in vain !
I ask you to get me out of three days of intense galleys Wall ...
Thank you in advance ...
Sorry !
I'll paste the traceback on a few moment