test_login_background.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """登录界面自定义背景图接口(/api/v1/config/login-background)测试。
  2. 接口公开(无凭证可访问):
  3. - 运行目录存在 background.jpg / background.png 时返回对应图片二进制;
  4. - 两者同时存在时 jpg 优先;
  5. - 均不存在时返回 404 FILE_NOT_FOUND 标准错误体。
  6. """
  7. from __future__ import annotations
  8. import pytest
  9. # 最小合法 PNG 文件头(IHDR 数据块),仅用于让 send_file 返回二进制
  10. _PNG_BYTES = (
  11. b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
  12. b"\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00"
  13. )
  14. _JPEG_BYTES = b"\xff\xd8\xff\xe0\x00\x10JFIF"
  15. @pytest.fixture()
  16. def background_dir(flask_app, tmp_path):
  17. """把背景图查找目录指到临时目录,测试后还原。"""
  18. original = flask_app.config.get("DMS_LOGIN_BACKGROUND_DIR")
  19. flask_app.config["DMS_LOGIN_BACKGROUND_DIR"] = str(tmp_path)
  20. yield tmp_path
  21. if original is None:
  22. flask_app.config.pop("DMS_LOGIN_BACKGROUND_DIR", None)
  23. else:
  24. flask_app.config["DMS_LOGIN_BACKGROUND_DIR"] = original
  25. def test_login_background_returns_jpg_when_present(client, background_dir):
  26. (background_dir / "background.jpg").write_bytes(_JPEG_BYTES)
  27. response = client.get("/api/v1/config/login-background")
  28. assert response.status_code == 200
  29. assert response.mimetype == "image/jpeg"
  30. assert response.data == _JPEG_BYTES
  31. assert response.headers["X-Content-Type-Options"] == "nosniff"
  32. assert "max-age" in response.headers.get("Cache-Control", "")
  33. def test_login_background_returns_png_when_only_png_present(client, background_dir):
  34. (background_dir / "background.png").write_bytes(_PNG_BYTES)
  35. response = client.get("/api/v1/config/login-background")
  36. assert response.status_code == 200
  37. assert response.mimetype == "image/png"
  38. assert response.data == _PNG_BYTES
  39. def test_login_background_prefers_jpg_over_png(client, background_dir):
  40. (background_dir / "background.png").write_bytes(_PNG_BYTES)
  41. (background_dir / "background.jpg").write_bytes(_JPEG_BYTES)
  42. response = client.get("/api/v1/config/login-background")
  43. assert response.status_code == 200
  44. assert response.mimetype == "image/jpeg"
  45. assert response.data == _JPEG_BYTES
  46. def test_login_background_returns_404_when_absent(client, background_dir):
  47. response = client.get("/api/v1/config/login-background")
  48. assert response.status_code == 404
  49. body = response.get_json()
  50. assert body["code"] == "FILE_NOT_FOUND"
  51. assert body["requestId"]