"""Test harness: CTFd's own test app with ctfd-cheaters loaded from this repo. CTFd is imported from CTFD_PATH (default: ../CTFd). The test app runs in CTFd's safe mode (no plugins loaded from CTFd/plugins), and this checkout is loaded as CTFd.plugins.ctfd_cheaters, the name other plugins import. """ import importlib.util import os import sys from pathlib import Path import pytest REPO = Path(__file__).resolve().parent.parent CTFD_PATH = Path(os.environ.get("CTFD_PATH", REPO.parent / "CTFd")).resolve() PLUGIN_MODULE = "CTFd.plugins.ctfd_cheaters" if not (CTFD_PATH / "CTFd" / "__init__.py").exists(): raise RuntimeError(f"CTFd not found at {CTFD_PATH}: set CTFD_PATH") sys.path.insert(0, str(CTFD_PATH)) import CTFd.plugins # noqa: E402,F401 (parent package of the plugin module) from tests.helpers import create_ctfd, destroy_ctfd, setup_ctfd # noqa: E402 def _import_plugin(): """Import the plugin (once). Like CTFd, only inside an app context.""" if PLUGIN_MODULE in sys.modules: return sys.modules[PLUGIN_MODULE] spec = importlib.util.spec_from_file_location( PLUGIN_MODULE, REPO / "__init__.py", submodule_search_locations=[str(REPO)] ) module = importlib.util.module_from_spec(spec) sys.modules[PLUGIN_MODULE] = module spec.loader.exec_module(module) return module def plugin(submodule=None): return sys.modules[PLUGIN_MODULE + (f".{submodule}" if submodule else "")] def _make_app(user_mode): app = create_ctfd(setup=False, user_mode=user_mode) with app.app_context(): _import_plugin().load(app) return setup_ctfd(app, user_mode=user_mode) @pytest.fixture def app(): app = _make_app("users") yield app destroy_ctfd(app) @pytest.fixture def teams_app(): app = _make_app("teams") yield app destroy_ctfd(app) def submit(client, challenge_id, submission, preview=False): url = "/api/v1/challenges/attempt" + ("?preview=true" if preview else "") r = client.post(url, json={"challenge_id": challenge_id, "submission": submission}) assert r.status_code == 200, r.get_json() return r.get_json()["data"]["status"] def reports(app): with app.app_context(): return [ (r.cheater_id, r.owner_id, r.flag_id) for r in plugin("models").CheatReport.query.all() ]