the_works/tests/unit/test_unit_genre.py
2025-07-25 09:19:20 +02:00

60 lines
2.0 KiB
Python

from the_works.models import Genre
import pytest
def test_genre_all(client, mocker):
"""Test view all() from genre.py."""
# mock database function
# Note: The original method returns an sqlalchemy.engine.Result.ScalarResult, not a list, but the template code
# uses the return value in a way that works for both ScalarResult and list
# mocker.patch("the_works.database.db.session.scalars", return_value=[
mocker.patch("flask_sqlalchemy.SQLAlchemy.session.scalars", return_value=[
Genre(ID=4, Genre="bla"),
Genre(ID=26, Genre="blubb")
])
# test case: get request
response = client.get("/genre")
assert response.status_code == 200
assert response.data.count(b'<tr id="genre-') == 2
# test case: post request
response = client.post("/genre")
assert response.status_code == 405
def test_genre_create(client, mocker):
"""Test view create() from genre.py."""
# mock database function
mocker.patch("flask_sqlalchemy.SQLAlchemy.session.add")
# test a POST request with good data
response = client.post("/genre/create", data={"form_Genre": "Testname"}, follow_redirects=True)
# exactly 1 redirect
assert len(response.history) == 1
# redirect to the right page
assert response.request.path == "/genre/all"
assert response.status_code == 200
# test a POST request with no form data
with pytest.raises(ValueError) as excinfo:
response = client.post("/genre/create", data={})
assert "value can't be empty" in str(excinfo.value)
# test a POST request with bad form data
with pytest.raises(ValueError) as excinfo:
response = client.post("/genre/create", data={"wrong_key": "Genrename"})
assert "value can't be empty" in str(excinfo.value)
# test a POST request with empty form data
with pytest.raises(ValueError) as excinfo:
response = client.post("/genre/create", data={"form_genre": ""})
assert "value can't be empty" in str(excinfo.value)
# test a GET request
response = client.get("/genre/create", query_string={"form_Genre": "GET-Genre"})
assert response.status_code == 405