Exemple #1
0
def request(method: str,
            url: str,
            access_token: str = None,
            user_agent: str = None,
            ids: Union[str, List] = None,
            params: Dict = None,
            headers: Dict = None,
            **kwargs) -> requests.Response:
    """Wrapper around :py:func:`requests.request` that supports dry-run mode and
    adds appropriate headers.

    Args:
        method: HTTP method
        url: Request URL
        access_token: access_token: the access token, as returned by :func:`get_access_token()`
        user_agent: a user-agent string that will be passed to iNaturalist
        ids: One or more integer IDs used as REST resource(s) to request
        params: Requests parameters
        headers: Request headers

    Returns:
        API response
    """
    # Set user agent and authentication headers, if specified
    headers = headers or {}
    headers["Accept"] = "application/json"
    headers["User-Agent"] = user_agent or pyinaturalist.user_agent
    if access_token:
        headers["Authorization"] = "Bearer %s" % access_token

    params = preprocess_request_params(params)

    # If one or more REST resources are requested, update the request URL accordignly
    if ids:
        url = url.rstrip("/") + "/" + validate_ids(ids)

    # Run either real request or mock request depending on settings
    if is_dry_run_enabled(method):
        logger.debug("Dry-run mode enabled; mocking request")
        log_request(method, url, params=params, headers=headers, **kwargs)
        return MOCK_RESPONSE
    else:
        return requests.request(method,
                                url,
                                params=params,
                                headers=headers,
                                **kwargs)
def test_validate_ids__invalid():
    with pytest.raises(ValueError):
        validate_ids('not a number')
def test_validate_ids(value, expected):
    assert validate_ids(value) == expected