模拟调用使用 Python 获取的函数的一部分



我使用模拟测试我的函数时遇到麻烦。此函数将 url 作为参数,然后返回地理数据帧。首先,我必须刺激get请求(Json格式(的响应。

要测试的功能

def download_stations_from_url(url):
response = requests.get(url)
data = response.json()
gdf = gpd.GeoDataFrame.from_features(data['features'])
gdf.crs = {'init': 'epsg:32188'}
return gdf.to_crs(epsg=4326)

使用模拟进行测试

from py_process.app import download_stations_from_url
@patch('py_process.app.download_stations_from_url')
def test_download_stations_from_url(self, mock_requests_json):
mock_requests_json.return_value.status_code = 200
mock_requests_json.return_value.json.return_value = {
"features": [{
"geometry": {
"coordinates": [
299266.0160258789,
5039428.849663065
],
"type": "Point"
},
"type": "Feature",
"properties": {
"valide_a": 99999999,
"MUNIC": "Montreal",
"X": 299266.016026,
"xlong": -73.5708055439,
"Parking": 0,
"Y": 5039428.84966,
"NOM": "Gare Lucien-L'Allier",
"ylat": 45.4947606844
}
}]
}
response = download_stations_from_url('http://www.123.com')
assert response.status_code == 200

你需要模拟requests.get,而不是你实际测试的函数。

from py_process.app import download_stations_from_url
@patch('py_process.app.requests.get')
def test_download_stations_from_url(self, mock_requests_json):
mock_requests_json.return_value.status_code = 200
mock_requests_json.return_value.json.return_value = {
"features": [{
"geometry": {
"coordinates": [
299266.0160258789,
5039428.849663065
],
"type": "Point"
},
"type": "Feature",
"properties": {
"valide_a": 99999999,
"MUNIC": "Montreal",
"X": 299266.016026,
"xlong": -73.5708055439,
"Parking": 0,
"Y": 5039428.84966,
"NOM": "Gare Lucien-L'Allier",
"ylat": 45.4947606844
}
}]
}
df = download_stations_from_url('http://www.123.com')
# Wrong:
#     assert response.status_code == 200
# Right:
#     Make assertions about the DataFrame you get back.

最新更新