Add fake Gitea fixture and change-detection tests
This commit is contained in:
1 parent
2029aa7e89
commit
d2b92fc5a5
2 files changed
+176
No files matched your search
@@ -0,0 +1,88 @@
|
||||
"""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."""
|
||||
resp = requests.Response()
|
||||
resp.status_code = status
|
||||
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
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Deciding whether anything changed since the last run."""
|
||||
|
||||
import json
|
||||
|
||||
from language_stats import get_repo_timestamps, has_new_commits, load_state, save_state
|
||||
|
||||
SAVED = {
|
||||
"repo_timestamps": {
|
||||
"website": "2026-11-01T09:00:00Z",
|
||||
"scripts": "2026-11-05T14:30:00Z",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def test_repo_timestamps_map_each_repo_to_its_updated_at():
|
||||
repos = [
|
||||
{"name": "website", "updated_at": "2026-11-01T09:00:00Z"},
|
||||
{"name": "scripts", "updated_at": "2026-11-05T14:30:00Z"},
|
||||
]
|
||||
assert get_repo_timestamps(repos) == {
|
||||
"website": "2026-11-01T09:00:00Z",
|
||||
"scripts": "2026-11-05T14:30:00Z",
|
||||
}
|
||||
|
||||
|
||||
def test_repo_timestamps_leave_out_the_profile_repo():
|
||||
# Each README push updates .profile, so counting it would make every
|
||||
# run look like it has new commits.
|
||||
repos = [
|
||||
{"name": ".profile", "updated_at": "2026-11-10T06:00:00Z"},
|
||||
{"name": "website", "updated_at": "2026-11-01T09:00:00Z"},
|
||||
]
|
||||
assert get_repo_timestamps(repos) == {"website": "2026-11-01T09:00:00Z"}
|
||||
|
||||
|
||||
def test_repo_without_updated_at_gets_an_empty_timestamp():
|
||||
assert get_repo_timestamps([{"name": "website"}]) == {"website": ""}
|
||||
|
||||
|
||||
def test_no_new_commits_when_every_timestamp_matches():
|
||||
current = {"website": "2026-11-01T09:00:00Z", "scripts": "2026-11-05T14:30:00Z"}
|
||||
assert has_new_commits(current, SAVED) is False
|
||||
|
||||
|
||||
def test_new_commits_when_a_repo_was_updated():
|
||||
current = {"website": "2026-11-01T09:00:00Z", "scripts": "2026-11-11T08:00:00Z"}
|
||||
assert has_new_commits(current, SAVED) is True
|
||||
|
||||
|
||||
def test_new_commits_when_a_repo_was_added():
|
||||
current = {
|
||||
"website": "2026-11-01T09:00:00Z",
|
||||
"scripts": "2026-11-05T14:30:00Z",
|
||||
"new-tool": "2026-11-11T08:00:00Z",
|
||||
}
|
||||
assert has_new_commits(current, SAVED) is True
|
||||
|
||||
|
||||
def test_new_commits_when_a_repo_was_deleted():
|
||||
current = {"website": "2026-11-01T09:00:00Z"}
|
||||
assert has_new_commits(current, SAVED) is True
|
||||
|
||||
|
||||
def test_first_run_without_saved_state_counts_as_new_commits():
|
||||
assert has_new_commits({"website": "2026-11-01T09:00:00Z"}, {}) is True
|
||||
|
||||
|
||||
def test_load_state_returns_empty_dict_when_no_file_exists():
|
||||
assert load_state() == {}
|
||||
|
||||
|
||||
def test_load_state_reads_the_saved_json(state_file):
|
||||
state_file.parent.mkdir(parents=True)
|
||||
state_file.write_text('{"repo_timestamps": {"website": "2026-11-01T09:00:00Z"}}')
|
||||
assert load_state() == {"repo_timestamps": {"website": "2026-11-01T09:00:00Z"}}
|
||||
|
||||
|
||||
def test_load_state_treats_a_corrupt_file_as_empty(state_file):
|
||||
state_file.parent.mkdir(parents=True)
|
||||
state_file.write_text("{not valid json")
|
||||
assert load_state() == {}
|
||||
|
||||
|
||||
def test_save_state_creates_missing_folders_and_writes_json(state_file):
|
||||
save_state({"repo_timestamps": {"website": "2026-11-01T09:00:00Z"}})
|
||||
assert json.loads(state_file.read_text()) == {
|
||||
"repo_timestamps": {"website": "2026-11-01T09:00:00Z"}
|
||||
}
|
||||
Reference in new issue
Block a user