【问题标题】:How do I get this simple pytest fixture to work correctly?如何让这个简单的 pytest 夹具正常工作?
【发布时间】:2022-01-02 15:02:44
【问题描述】:

我正在尝试让一个简单的 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"

我希望夹具提供应该可迭代返回的 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

【问题讨论】:

  • 您必须将夹具传递给测试功能。
  • 谢谢@MrBeanBremen 这是问题所在!

标签: pytest typeerror fixtures


【解决方案1】:

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

测试应该调用如下:

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2016-03-04
    • 1970-01-01
    • 2020-07-09
    • 2023-03-15
    • 1970-01-01
    • 2010-10-27
    • 2013-05-30
    相关资源
    最近更新 更多