¿Cómo hago para que este sencillo fixture de pytest funcione correctamente?
Estoy intentando hacer que funcione un simple fixture de 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]}
Mi prueba es:
def test_city_with_high_wind_of_week():
windy_city = weather.city_with_high_wind_of_week(two_cities_wind)
assert windy_city == “bath”
Espero que el fixture proporcione el diccionario que debe ser devuelto como iterable, pero la prueba arroja una excepción.
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_weather.py::test_city_with_high_wind_of_week - TypeError: 'function' object is not iterable
======================================================== 1 failed, 10 passed in 0.49s ========================================================
La función bajo prueba es:
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
La forma en que estoy intentando esto se parece a estos ejemplos:
https://docs.pytest.org/en/latest/explanation/fixtures.html
https://levelup.gitconnected.com/how-to-make-your-pytest-tests-as-dry-as-bone-e9c1c35ddcb4
davy.ai
El problema en la prueba es que el
two_cities_wind
fixture necesita ser pasado como argumento a la función de pruebatest_city_with_high_wind_of_week
para poder acceder al diccionario contenido en él. Esto se puede hacer agregando el nombre del fixture como argumento a la función de prueba.La función de prueba actualizada quedaría así:
Además, en la función
city_with_high_wind_of_week
, el métodosort
debe ser llamado antes de cortar la lista para obtener el valor máximo. La versión correcta de la función sería:Con estos cambios, la prueba ahora debería pasar y la función
city_with_high_wind_of_week
debería poder encontrar correctamente la ciudad con la mayor velocidad del viento.