test_error_handling.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import pytest
  2. import json
  3. from flexmeasures.auth import error_handling as auth_error_handling
  4. """
  5. Testing if errors are handled by the right handlers.
  6. First, test a JSON request, then a common one, which should lead to a rendered page.
  7. With Gone we are also testing an HTTPException which we currently do not explicitly support, so no explicit rendering
  8. of our base template. I was hoping registering for HTTPException would do this, but it does not.
  9. We also test unauth handling, whether flask security raises in its own way or we raise ourselves.
  10. """
  11. @pytest.mark.parametrize(
  12. "raising_url,status_code,expected_message",
  13. [
  14. ("/raise-error?type=server_error", 500, "InternalServerError Test Message"),
  15. ("/raise-error?type=bad_request", 400, "BadRequest Test Message"),
  16. ("/raise-error?type=gone", 410, "Gone Test Message"),
  17. ("/raise-error?type=unauthorized", 401, auth_error_handling.UNAUTH_MSG),
  18. ("/raise-error?type=forbidden", 403, auth_error_handling.FORBIDDEN_MSG),
  19. ("/non-existant-endpoint", 404, None),
  20. ("/protected-endpoint-only-for-admins", 403, auth_error_handling.FORBIDDEN_MSG),
  21. ],
  22. )
  23. def test_error_handling(
  24. client, error_endpoints, raising_url, status_code, expected_message
  25. ):
  26. """
  27. Make requests and check if the error comes back as expected.
  28. Try json as well as html content types.
  29. """
  30. res = client.get(raising_url, headers={"Content-Type": "application/json"})
  31. assert res.status_code == status_code
  32. assert "application/json" in res.content_type
  33. if expected_message:
  34. assert expected_message in json.loads(res.data)["message"]
  35. res = client.get(raising_url, headers={"Content-Type": "text/html"})
  36. print(f"Server responded with {res.data}")
  37. assert res.status_code == status_code
  38. assert "text/html" in res.content_type
  39. # test if we rendered the base template
  40. assert b"- FlexMeasures" in res.data
  41. if expected_message:
  42. assert expected_message.encode() in res.data