简体   繁体   English

Monkeypatching requests.get() 函数

[英]Monkeypatching a requests.get() function

I am testing my code, so far so good.我正在测试我的代码,到目前为止一切顺利。 But now I have to test a function using requests.get() to make an API call.但是现在我必须使用 requests.get() 测试一个函数来进行 API 调用。 As far as I understand, I have to 'mock' this function in my test.据我所知,我必须在我的测试中“模拟”这个功能。

My function calls Google Maps API, and in my test I added the wanted output:我的函数调用 Google Maps API,在我的测试中我添加了想要的输出:

     result = 

            {
                    "candidates":[
                        {
                            "geometry":{
                                "location":{
                                "lat":-34.5453062,
                                "lng":-58.44977489999999
                                }
                                },
                             "name":"Stade Monumental Antonio Vespucio Liberti",
                             "place_id":"ChIJ340B5jq0vJURijD6W6dgfz0"
                        }
                                ]
             }

    return json.dumps(result)

This the function I am testing:这是我正在测试的功能:

def get_lat_lng (self):
        self.input_api = '%20'.join(self.parsed_question)
        self.input_api = ' '.join(self.parsed_question)
        self.google_api_url = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={}&inputtype=textquery&fields=geometry,name,place_id&types=point_of_interest&key={}'.format (self.input_api, api_key)     
        self.r = requests.get (url = self.google_api_url)        
        self.data = self.r.json()                    
        self.name = self.data['candidates'][0]['name']       
        self.place_id = self.data['candidates'][0]['place_id']              
        self.lat = self.data['candidates'][0]['geometry']['location']['lat']        
        self.lng = self.data['candidates'][0]['geometry']['location']['lng']                
        return (self.lat, self.lng, self.place_id)

And my test so far:到目前为止我的测试:

def test_get_lat_lng (monkeypatch):    

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

This is the error code I get when trying to run the test:这是我在尝试运行测试时得到的错误代码:

 self.r = requests.get (url = self.google_api_url)
>       self.data = self.r.json()
E       AttributeError: 'str' object has no attribute 'json'

I don't understand since I use json.dumps() on my desired output to "mock" an answer from requests.get(), how can it be a 'str' object?我不明白,因为我在我想要的输出上使用 json.dumps() 来“模拟”来自 requests.get() 的答案,它怎么可能是一个“str”对象? Looking for the type of self.r I get <class 'requests.models.Response'> .寻找self.r的类型,我得到<class 'requests.models.Response'>

Making mock_get_lat_lng() a class did the trick.使 mock_get_lat_lng() 成为一个类就可以了。 Here is my final working test:这是我的最终工作测试:

class mock_get_lat_lng():

    def __init__(self, url):
        pass

    def json(self):
        result = {
                "candidates": [
                    {
                        "geometry": {
                            "location": {
                                "lat": -34.5453062,
                                "lng": -58.44977489
                            }
                        },
                        "name": "Stade Monumental Antonio Vespucio Liberti",
                        "place_id": "ChIJ340B5jq0vJURijD6W6dgfz0"
                    }
                ]
                }
        return result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM