"""Shared test setup. Every test runs against a fake Gitea server instead of the network, with fake credentials and a state file inside pytest's temporary directory, so no test can touch the real Gitea account or ~/.local/state. """ import json import pytest import requests import language_stats def make_response(status, payload): """Build a real requests.Response so .ok, .json() and .raise_for_status() behave exactly as they do against a live server. A bytes payload is sent as-is (e.g. an HTML error page from a proxy); anything else is sent as JSON. """ resp = requests.Response() resp.status_code = status if isinstance(payload, bytes): resp._content = payload else: resp._content = json.dumps(payload).encode("utf-8") return resp class FakeGitea: """Answers only the requests a test has registered with add(). Any other request fails the test, so a wrong URL in the script shows up as a test failure instead of a silent miss. """ def __init__(self): self.routes = {} self.requested = [] # "GET https://..." for every request made self.auth_headers = [] # Authorization header sent with each request self.put_bodies = [] # JSON body of every PUT def add(self, method, url, payload, status=200): self.routes[f"{method} {url}"] = make_response(status, payload) def add_error(self, method, url, error): """Make a request raise a network error, e.g. requests.ConnectionError.""" self.routes[f"{method} {url}"] = error def handle(self, method, session, url, params=None, body=None): full_url = requests.Request(method, url, params=params).prepare().url key = f"{method} {full_url}" self.requested.append(key) self.auth_headers.append(session.headers.get("Authorization")) if body is not None: self.put_bodies.append(body) if key not in self.routes: raise AssertionError(f"Unexpected request: {key}") answer = self.routes[key] if isinstance(answer, Exception): raise answer return answer @pytest.fixture def state_file(tmp_path): """Where the script keeps its last-run state during a test.""" return tmp_path / "state" / "language_stats.json" @pytest.fixture(autouse=True) def gitea(monkeypatch, state_file): """Runs for every test: fake settings, and the network replaced by FakeGitea. Tests that need to register responses ask for `gitea` by name. """ monkeypatch.setattr(language_stats, "BASE_URL", "https://gitea.test") monkeypatch.setattr(language_stats, "TOKEN", "test-token") monkeypatch.setattr(language_stats, "USERNAME", "alice") monkeypatch.setattr(language_stats, "STATE_FILE", state_file) monkeypatch.setattr(language_stats, "EXCLUDE_FILES", []) fake = FakeGitea() def fake_get(session, url, params=None, timeout=None): return fake.handle("GET", session, url, params=params) def fake_put(session, url, json=None, timeout=None): return fake.handle("PUT", session, url, body=json) monkeypatch.setattr(requests.Session, "get", fake_get) monkeypatch.setattr(requests.Session, "put", fake_put) return fake