【发布时间】: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 这是问题所在!