如何使这个简单的pytest夹具正确工作



我正在尝试让一个简单的pytest夹具工作。

@pytest.fixture
def two_cities_wind():
    return {'bristol': [7, 7, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 9, 9, 8, 8, 8, 8, 8, 8, 9, 8, 8, 8],
            'bath': [14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 16, 16, 16, 16, 16, 15, 16, 16, 16, 16, 15, 15, 15]}

我的测试是

def test_city_with_high_wind_of_week():
    windy_city = weather.city_with_high_wind_of_week(two_cities_wind)
    assert windy_city == "bath"

我希望fixture提供应该可迭代返回的dict,但测试抛出了一个异常。

        windy_city = ""
        wind_speed = 0
>       for city in cities_weather:
E       TypeError: 'function' object is not iterable
src/weather.py:52: TypeError
========================================================== short test summary info ===========================================================
FAILED tests/test_zweather.py::test_city_with_high_wind_of_week - TypeError: 'function' object is not iterable
======================================================== 1 failed, 10 passed in 0.49s ========================================================

测试中的功能是

def city_with_high_wind_of_week(cities_weather) -> str:
    windy_city = ""
    wind_speed = 0
    for city in cities_weather:
        highest_speed = cities_weather[city].sort()[-1]
        if highest_speed > wind_speed:
            windy_city = city
            wind_speed = highest_speed
    return windy_city

我尝试这样做的方式看起来与这些示例相当
https://docs.pytest.org/en/latest/explanation/fixtures.html
https://levelup.gitconnected.com/how-to-make-your-pytest-tests-as-dry-as-bone-e9c1c35ddcb4

@MrBeanRemen提供的答案
我需要将夹具传递给测试函数。

测试应按以下方式调用:

def test_city_with_high_wind_of_week(two_cities_wind):
    windy_city = weather.city_with_high_wind_of_week(two_cities_wind)
    assert windy_city == "bath"

最新更新