I have troubles to test my function using the mock. This function take an url as parameter then return an GeoDataFrame. At first I have to stimulate the response of get request (Json format).
Function to test
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)
Test using Mock
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
You need to mock requests.get
, not the function you are actually testing.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.