使用pytest测试使用请求库的功能

时间:2019-11-22 17:39:32

标签: python python-3.x python-requests pytest

我有一个python函数,可以使用request函数调用API。我想测试200条路径,然后测试500条错误。在查看requests-mock文档时,我似乎无法弄清楚该怎么做。

这是我要测试的内容。

def get_sku_data(sku: str):
    """
    Retrieve a single product from api
    """
    uri = app.config["SKU_URI"]
    url = f"{uri}/{sku}"
    headers = {
        "content-type": "application/json",
        "cache-control": "no-cache",
        "accept": "application/json",
    }
    try:
        retry_times = 3
        response = retry_session(retries=retry_times).get(url, headers=headers)
        return response.json()
    except ConnectionError as ex:
        raise Exception(f"Could not connect to sku api at {uri}. {ex}.")
    except requests.exceptions.RetryError:
        raise Exception(f"Attempted to connect to {uri} {retry_times} times.")

def retry_session(
    retries, backoff_factor=0.3, status_forcelist=(500, 502, 503, 504)
) -> requests.Session:
    """
    Performs a retry
    """
    session = requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

这是我要尝试的测试存根

# These test use pytest https://pytest.readthedocs.io/en/latest/

# Note: client is a pytest fixture that is dependency injected from src/tests/conftest.py

import json
import pytest
from src.app import create_app
import requests
import requests_mock


@pytest.fixture
def app():
    app = create_app()
    return app


def test():
    session = requests.Session()
    adapter = requests_mock.Adapter()
    session.mount("mock", adapter)
    adapter.register_uri("GET", "mock://12", text="data")
    resp = session.get("mock://12")
    assert resp.status_code == 200
    assert resp.text == "data"

我对python测试有点陌生,因此非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我对它是如何工作的看法是错误的。 我注册了要测试的URI,实际上没有调用session.get,而是调用了受测试的函数。