conftest.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import os
  2. import re
  3. from pathlib import Path
  4. from collections.abc import Iterable
  5. import pytest
  6. from pytest import CaptureFixture
  7. from gemini_antenna.URLHelper import URLHelper
  8. from gemini_antenna.db import AntennaDB
  9. from gemini_antenna.cgi import customFilters
  10. def pytest_configure():
  11. pytest.filter_script_name = "/~antenna/cgi-bin/filter"
  12. pytest.filter_redirect = re.compile(
  13. rf"30 {pytest.filter_script_name}/([a-zA-Z]{{32}})\r\n"
  14. )
  15. def write_blocklist(directory: Path, rules: Iterable[str]) -> str:
  16. """
  17. Write blocklist.txt file.
  18. :param directory: Parent directory for the blocklist.txt file.
  19. :param rules: URL prefixes to block.
  20. :returns: Path to the blocklist.txt file.
  21. """
  22. blocklist = directory / "blocklist.txt"
  23. with open(blocklist, "w") as blockfile:
  24. blockfile.write("\n".join(rules))
  25. return blocklist
  26. @pytest.fixture
  27. def url_helper(request: pytest.FixtureRequest, tmp_path: Path) -> URLHelper:
  28. marker = request.node.get_closest_marker("blocklist_rules")
  29. if marker is None:
  30. return URLHelper
  31. blocklist = write_blocklist(tmp_path, marker.args)
  32. return URLHelper(blocklist)
  33. @pytest.fixture
  34. def db(request: pytest.FixtureRequest, tmp_path: Path) -> AntennaDB:
  35. os.environ['ANTENNA_DATAROOT'] = str(tmp_path)
  36. marker = request.node.get_closest_marker("blocklist_rules")
  37. if marker is not None:
  38. write_blocklist(tmp_path, marker.args)
  39. antennaDB = AntennaDB(tmp_path / "antenna.sqlite")
  40. antennaDB.createDB()
  41. return antennaDB
  42. @pytest.fixture
  43. def filter_name(db: AntennaDB, capfd: CaptureFixture[str]) -> str:
  44. """
  45. Create a new filter.
  46. :returns: Filter's name (32 random characters).
  47. """
  48. os.environ['SCRIPT_NAME'] = pytest.filter_script_name
  49. os.environ['QUERY_STRING'] = "y"
  50. customFilters.main()
  51. out = capfd.readouterr().out
  52. return pytest.filter_redirect.match(out).group(1)