簡體   English   中英

使用 pytest 測試使用請求庫的 function

[英]Using pytest to test a function that uses request library

我有一個 python function 調用一個 API 使用請求 ZC1C425268E68385D1AB5Z44FZ 我想測試一個 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 測試有點陌生,所以非常感謝任何幫助。

我對它如何工作的看法是錯誤的。 我注冊了我正在測試的 URI,而不是調用 session.get,我實際上調用了正在測試的 function。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM