繁体   English   中英

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

[英]Mock a part of function that calls get using Python

我无法使用模拟来测试我的功能。 此函数以url作为参数,然后返回GeoDataFrame。 首先,我必须刺激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.

暂无
暂无

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

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