Compare commits
11
Commits
90713a05cb
...
bce8084306
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bce8084306 | ||
|
|
86c00ae3f9 | ||
|
|
26a9207daa | ||
|
|
9f76bf6c41 | ||
|
|
73d2a83250 | ||
|
|
1188b72263 | ||
|
|
bfcac9b9ee | ||
|
|
cea85baade | ||
|
|
ab905577b8 | ||
|
|
d2b92fc5a5 | ||
|
|
2029aa7e89 |
No files matched your search
@@ -1,2 +1,4 @@
|
||||
.aider*
|
||||
.env
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
@@ -8,3 +8,13 @@ dependencies = [
|
||||
"python-dotenv>=1.1.1",
|
||||
"requests>=2.32.4",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=9.2.0",
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["scripts"]
|
||||
addopts = "-v --tb=short"
|
||||
+32
-12
@@ -19,6 +19,7 @@ Optional environment variables
|
||||
--------------------------------
|
||||
STATE_FILE path to store last-run state (default: ~/.local/state/language_stats.json)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
@@ -137,7 +138,9 @@ def has_new_commits(current_timestamps: dict[str, str], saved_state: dict) -> bo
|
||||
return False
|
||||
|
||||
|
||||
def aggregate_language_bytes(session: requests.Session, repos: list[dict]) -> dict[str, int]:
|
||||
def aggregate_language_bytes(
|
||||
session: requests.Session, repos: list[dict]
|
||||
) -> dict[str, int]:
|
||||
"""Aggregate language byte counts across all repositories."""
|
||||
totals: dict[str, int] = defaultdict(int)
|
||||
|
||||
@@ -148,27 +151,43 @@ def aggregate_language_bytes(session: requests.Session, repos: list[dict]) -> di
|
||||
)
|
||||
if not resp.ok:
|
||||
# Skip repos we can't access (e.g., token scope limitations)
|
||||
print(f"Warning: Could not fetch languages for {repo['name']}: {resp.status_code}", file=sys.stderr)
|
||||
print(
|
||||
f"Warning: Could not fetch languages for {repo['name']}: {resp.status_code}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
langs = resp.json()
|
||||
# Skip error responses (e.g., {"message": "..."})
|
||||
if not isinstance(langs, dict) or "message" in langs:
|
||||
print(f"Warning: Unexpected response for {repo['name']}: {langs}", file=sys.stderr)
|
||||
print(
|
||||
f"Warning: Unexpected response for {repo['name']}: {langs}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
repo_bytes: dict[str, int] = {}
|
||||
for lang, bytes_ in langs.items():
|
||||
# Handle bytes as either int or string
|
||||
if isinstance(bytes_, int):
|
||||
totals[lang] += bytes_
|
||||
repo_bytes[lang] = bytes_
|
||||
elif isinstance(bytes_, str) and bytes_.isdigit():
|
||||
totals[lang] += int(bytes_)
|
||||
repo_bytes[lang] = int(bytes_)
|
||||
# Skip non-numeric values
|
||||
# Excluded files come off this repo's own bytes, so a repo that was
|
||||
# skipped above can't lower the totals of other repos.
|
||||
repo_bytes = subtract_excluded_files(session, repo["name"], repo_bytes)
|
||||
for lang, nbytes in repo_bytes.items():
|
||||
totals[lang] += nbytes
|
||||
|
||||
return dict(totals)
|
||||
|
||||
|
||||
def subtract_excluded_files(session: requests.Session, totals: dict[str, int]) -> dict[str, int]:
|
||||
"""Subtract byte counts for explicitly excluded files."""
|
||||
for repo_name, file_path, language in EXCLUDE_FILES:
|
||||
def subtract_excluded_files(
|
||||
session: requests.Session, repo_name: str, langs: dict[str, int]
|
||||
) -> dict[str, int]:
|
||||
"""Subtract byte counts for one repository's explicitly excluded files."""
|
||||
for excluded_repo, file_path, language in EXCLUDE_FILES:
|
||||
if excluded_repo != repo_name:
|
||||
continue
|
||||
try:
|
||||
meta = session.get(
|
||||
f"{BASE_URL}/api/v1/repos/{USERNAME}/{repo_name}/contents/{file_path}",
|
||||
@@ -176,11 +195,11 @@ def subtract_excluded_files(session: requests.Session, totals: dict[str, int]) -
|
||||
)
|
||||
if meta.ok:
|
||||
size = meta.json().get("size", 0)
|
||||
totals[language] = max(0, totals.get(language, 0) - size)
|
||||
langs[language] = max(0, langs.get(language, 0) - size)
|
||||
except requests.RequestException:
|
||||
# Ignore failures – continue with best-effort stats
|
||||
pass
|
||||
return totals
|
||||
return langs
|
||||
|
||||
|
||||
def generate_markdown(totals: dict[str, int]) -> str:
|
||||
@@ -189,7 +208,9 @@ def generate_markdown(totals: dict[str, int]) -> str:
|
||||
if total_bytes == 0:
|
||||
return ""
|
||||
|
||||
pairs = sorted(totals.items(), key=lambda x: x[1], reverse=True)
|
||||
# Languages whose bytes were all excluded would otherwise show as 0.0%
|
||||
nonzero = [(lang, nbytes) for lang, nbytes in totals.items() if nbytes > 0]
|
||||
pairs = sorted(nonzero, key=lambda x: x[1], reverse=True)
|
||||
|
||||
lang_lines = []
|
||||
for lang, nbytes in pairs:
|
||||
@@ -285,7 +306,6 @@ def main() -> int:
|
||||
|
||||
# Generate the stats
|
||||
totals = aggregate_language_bytes(session, repos)
|
||||
totals = subtract_excluded_files(session, totals)
|
||||
|
||||
if sum(totals.values()) == 0:
|
||||
sys.exit("No language data returned from API.")
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""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
|
||||
@@ -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"}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Running the whole script the way the Gitea Actions workflow does."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
import language_stats
|
||||
|
||||
REPOS_PAGE_1 = "https://gitea.test/api/v1/users/alice/repos?page=1&limit=50"
|
||||
REPOS_PAGE_2 = "https://gitea.test/api/v1/users/alice/repos?page=2&limit=50"
|
||||
README_URL = "https://gitea.test/api/v1/repos/alice/.profile/contents/README.md"
|
||||
WEBSITE_LANGS = "https://gitea.test/api/v1/repos/alice/website/languages"
|
||||
SCRIPTS_LANGS = "https://gitea.test/api/v1/repos/alice/scripts/languages"
|
||||
PROFILE_LANGS = "https://gitea.test/api/v1/repos/alice/.profile/languages"
|
||||
AFRAME_FILE = "https://gitea.test/api/v1/repos/alice/website/contents/static/aframe.js"
|
||||
|
||||
TIMESTAMPS = {"website": "2026-11-01T09:00:00Z", "scripts": "2026-11-05T14:30:00Z"}
|
||||
|
||||
# website: HTML 1500 + JavaScript 1000, minus the 500-byte excluded aframe.js
|
||||
# scripts: Python 2000
|
||||
# Total 4000 -> Python 50.0% (25 blocks), HTML 37.5% (18), JavaScript 12.5% (6)
|
||||
STATS = (
|
||||
"█" * 25
|
||||
+ " Python 50.0%\\\n"
|
||||
+ "█" * 18
|
||||
+ " HTML 37.5%\\\n"
|
||||
+ "█" * 6
|
||||
+ " JavaScript 12.5%"
|
||||
)
|
||||
OLD_README = (
|
||||
"# Hi there\n\n"
|
||||
"<!--LANG_STATS_START-->\nold stats\n<!--LANG_STATS_END-->\n\n"
|
||||
"Thanks for visiting\n"
|
||||
)
|
||||
NEW_README = (
|
||||
"# Hi there\n\n"
|
||||
"<!--LANG_STATS_START-->\n" + STATS + "\n<!--LANG_STATS_END-->\n\n"
|
||||
"Thanks for visiting\n"
|
||||
)
|
||||
|
||||
|
||||
def serve_account(gitea, monkeypatch, readme=OLD_README):
|
||||
"""Set up the fake server with two repos plus .profile."""
|
||||
monkeypatch.setattr(
|
||||
language_stats,
|
||||
"EXCLUDE_FILES",
|
||||
[("website", "static/aframe.js", "JavaScript")],
|
||||
)
|
||||
gitea.add(
|
||||
"GET",
|
||||
REPOS_PAGE_1,
|
||||
[
|
||||
{"name": "website", "updated_at": "2026-11-01T09:00:00Z"},
|
||||
{"name": "scripts", "updated_at": "2026-11-05T14:30:00Z"},
|
||||
{"name": ".profile", "updated_at": "2026-11-10T06:00:00Z"},
|
||||
],
|
||||
)
|
||||
gitea.add("GET", REPOS_PAGE_2, [])
|
||||
gitea.add("GET", WEBSITE_LANGS, {"HTML": 1500, "JavaScript": 1000})
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 2000})
|
||||
gitea.add("GET", PROFILE_LANGS, {})
|
||||
gitea.add("GET", AFRAME_FILE, {"size": 500})
|
||||
encoded = base64.b64encode(readme.encode("utf-8")).decode("ascii")
|
||||
gitea.add("GET", README_URL, {"content": encoded, "sha": "readme-sha"})
|
||||
gitea.add("PUT", README_URL, {})
|
||||
|
||||
|
||||
def save_timestamps(state_file):
|
||||
"""Pretend a previous run already saw the current repo timestamps."""
|
||||
state_file.parent.mkdir(parents=True)
|
||||
state_file.write_text(json.dumps({"repo_timestamps": TIMESTAMPS}))
|
||||
|
||||
|
||||
def run_main(monkeypatch, *args):
|
||||
monkeypatch.setattr(sys, "argv", ["language_stats.py", *args])
|
||||
return language_stats.main()
|
||||
|
||||
|
||||
def pushed_readme(gitea):
|
||||
return base64.b64decode(gitea.put_bodies[0]["content"]).decode("utf-8")
|
||||
|
||||
|
||||
def test_first_run_writes_the_stats_into_the_profile_readme(gitea, monkeypatch, capsys):
|
||||
serve_account(gitea, monkeypatch)
|
||||
assert run_main(monkeypatch) == 0
|
||||
assert len(gitea.put_bodies) == 1
|
||||
assert pushed_readme(gitea) == NEW_README
|
||||
assert gitea.put_bodies[0]["sha"] == "readme-sha"
|
||||
assert "README.md updated successfully." in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_excluded_file_in_a_skipped_repo_does_not_lower_other_repos(gitea, monkeypatch):
|
||||
# website (which holds the excluded aframe.js) can't be read, so none of
|
||||
# its bytes were counted and none should be subtracted.
|
||||
serve_account(gitea, monkeypatch)
|
||||
gitea.add("GET", WEBSITE_LANGS, {"message": "token scope is limited"}, status=403)
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 3000, "JavaScript": 1000})
|
||||
run_main(monkeypatch)
|
||||
# Total 4000 -> Python 75.0% (37 blocks), JavaScript 25.0% (12 blocks)
|
||||
assert pushed_readme(gitea) == (
|
||||
"# Hi there\n\n"
|
||||
"<!--LANG_STATS_START-->\n"
|
||||
+ "█" * 37
|
||||
+ " Python 75.0%\\\n"
|
||||
+ "█" * 12
|
||||
+ " JavaScript 25.0%\n"
|
||||
"<!--LANG_STATS_END-->\n\n"
|
||||
"Thanks for visiting\n"
|
||||
)
|
||||
|
||||
|
||||
def test_first_run_saves_repo_timestamps_without_the_profile_repo(
|
||||
gitea, monkeypatch, state_file
|
||||
):
|
||||
serve_account(gitea, monkeypatch)
|
||||
run_main(monkeypatch)
|
||||
assert json.loads(state_file.read_text()) == {"repo_timestamps": TIMESTAMPS}
|
||||
|
||||
|
||||
def test_every_request_sends_the_token(gitea, monkeypatch):
|
||||
serve_account(gitea, monkeypatch)
|
||||
run_main(monkeypatch)
|
||||
assert set(gitea.auth_headers) == {"token test-token"}
|
||||
|
||||
|
||||
def test_run_without_new_commits_only_lists_repos(
|
||||
gitea, monkeypatch, state_file, capsys
|
||||
):
|
||||
serve_account(gitea, monkeypatch)
|
||||
save_timestamps(state_file)
|
||||
assert run_main(monkeypatch) == 0
|
||||
assert gitea.requested == [f"GET {REPOS_PAGE_1}", f"GET {REPOS_PAGE_2}"]
|
||||
assert "No new commits detected. Skipping regeneration." in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_force_regenerates_even_without_new_commits(gitea, monkeypatch, state_file):
|
||||
serve_account(gitea, monkeypatch)
|
||||
save_timestamps(state_file)
|
||||
assert run_main(monkeypatch, "--force") == 0
|
||||
assert pushed_readme(gitea) == NEW_README
|
||||
|
||||
|
||||
def test_check_only_reports_new_commits_without_updating_or_saving_state(
|
||||
gitea, monkeypatch, state_file, capsys
|
||||
):
|
||||
# If --check-only saved state, the next real run would see "no new
|
||||
# commits" and never update the README.
|
||||
serve_account(gitea, monkeypatch)
|
||||
assert run_main(monkeypatch, "--check-only") == 0
|
||||
assert gitea.requested == [f"GET {REPOS_PAGE_1}", f"GET {REPOS_PAGE_2}"]
|
||||
assert not state_file.exists()
|
||||
assert "New commits detected." in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_unchanged_stats_skip_the_push_but_still_save_state(
|
||||
gitea, monkeypatch, state_file, capsys
|
||||
):
|
||||
serve_account(gitea, monkeypatch, readme=NEW_README)
|
||||
assert run_main(monkeypatch) == 0
|
||||
assert gitea.put_bodies == []
|
||||
assert json.loads(state_file.read_text()) == {"repo_timestamps": TIMESTAMPS}
|
||||
assert (
|
||||
"Language stats unchanged. Skipping README update." in capsys.readouterr().err
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("setting", ["BASE_URL", "TOKEN", "USERNAME"])
|
||||
def test_missing_setting_stops_the_run_before_any_request(gitea, monkeypatch, setting):
|
||||
monkeypatch.setattr(language_stats, setting, None)
|
||||
with pytest.raises(
|
||||
SystemExit, match="GITEA_BASE_URL, GITEA_TOKEN and GITEA_USERNAME must be set"
|
||||
):
|
||||
run_main(monkeypatch)
|
||||
assert gitea.requested == []
|
||||
|
||||
|
||||
def test_no_language_data_stops_the_run_without_touching_the_readme(
|
||||
gitea, monkeypatch, state_file
|
||||
):
|
||||
serve_account(gitea, monkeypatch)
|
||||
gitea.add("GET", WEBSITE_LANGS, {})
|
||||
gitea.add("GET", SCRIPTS_LANGS, {})
|
||||
with pytest.raises(SystemExit, match="No language data returned from API"):
|
||||
run_main(monkeypatch)
|
||||
assert gitea.put_bodies == []
|
||||
assert not state_file.exists()
|
||||
|
||||
|
||||
def test_readme_without_markers_stops_the_run_without_saving_state(
|
||||
gitea, monkeypatch, state_file
|
||||
):
|
||||
# Not saving state means the next run tries again once the markers exist.
|
||||
serve_account(gitea, monkeypatch, readme="# Hi there\n")
|
||||
with pytest.raises(ValueError, match="not found in README"):
|
||||
run_main(monkeypatch)
|
||||
assert gitea.put_bodies == []
|
||||
assert not state_file.exists()
|
||||
|
||||
|
||||
def test_rejected_push_does_not_save_state(gitea, monkeypatch, state_file):
|
||||
# Not saving state means the next run retries the push.
|
||||
serve_account(gitea, monkeypatch)
|
||||
gitea.add("PUT", README_URL, {"message": "sha does not match"}, status=409)
|
||||
with pytest.raises(requests.HTTPError):
|
||||
run_main(monkeypatch)
|
||||
assert not state_file.exists()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Reading, rewriting and pushing the .profile README."""
|
||||
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from language_stats import (
|
||||
fetch_readme,
|
||||
get_session,
|
||||
replace_between_markers,
|
||||
update_readme,
|
||||
)
|
||||
|
||||
README_URL = "https://gitea.test/api/v1/repos/alice/.profile/contents/README.md"
|
||||
|
||||
|
||||
def test_fetch_readme_decodes_the_content_and_returns_its_sha(gitea):
|
||||
encoded = base64.b64encode("# Hi 👋\n".encode("utf-8")).decode("ascii")
|
||||
gitea.add("GET", README_URL, {"content": encoded, "sha": "abc123"})
|
||||
assert fetch_readme(get_session()) == ("# Hi 👋\n", "abc123")
|
||||
|
||||
|
||||
def test_fetch_readme_raises_when_the_readme_is_missing(gitea):
|
||||
gitea.add("GET", README_URL, {"message": "not found"}, status=404)
|
||||
with pytest.raises(requests.HTTPError):
|
||||
fetch_readme(get_session())
|
||||
|
||||
|
||||
def test_text_between_the_markers_is_replaced_and_the_rest_is_kept():
|
||||
readme = (
|
||||
"# Hi\n"
|
||||
"<!--LANG_STATS_START-->\nold stats\n<!--LANG_STATS_END-->\n"
|
||||
"Thanks for visiting\n"
|
||||
)
|
||||
assert replace_between_markers(readme, "new stats") == (
|
||||
"# Hi\n"
|
||||
"<!--LANG_STATS_START-->\nnew stats\n<!--LANG_STATS_END-->\n"
|
||||
"Thanks for visiting\n"
|
||||
)
|
||||
|
||||
|
||||
def test_backslash_line_breaks_in_the_stats_survive_replacement():
|
||||
# re.sub gives backslashes in the replacement a special meaning, and the
|
||||
# chart uses a backslash at the end of each line as a markdown line break.
|
||||
stats = "## 📊 Languages\n██ Python 75.0%\\\n█ Lua 25.0%"
|
||||
readme = "<!--LANG_STATS_START--><!--LANG_STATS_END-->"
|
||||
assert replace_between_markers(readme, stats) == (
|
||||
"<!--LANG_STATS_START-->\n"
|
||||
"## 📊 Languages\n██ Python 75.0%\\\n█ Lua 25.0%\n"
|
||||
"<!--LANG_STATS_END-->"
|
||||
)
|
||||
|
||||
|
||||
def test_replacing_with_the_same_stats_leaves_the_readme_unchanged():
|
||||
# main() relies on this to skip pushing an identical README.
|
||||
readme = "<!--LANG_STATS_START-->\nsame stats\n<!--LANG_STATS_END-->\n"
|
||||
assert replace_between_markers(readme, "same stats") == (
|
||||
"<!--LANG_STATS_START-->\nsame stats\n<!--LANG_STATS_END-->\n"
|
||||
)
|
||||
|
||||
|
||||
def test_readme_without_markers_raises():
|
||||
with pytest.raises(ValueError, match="not found in README"):
|
||||
replace_between_markers("# Hi\nno markers here\n", "stats")
|
||||
|
||||
|
||||
def test_readme_with_only_the_start_marker_raises():
|
||||
with pytest.raises(ValueError, match="not found in README"):
|
||||
replace_between_markers("<!--LANG_STATS_START-->\nold stats\n", "stats")
|
||||
|
||||
|
||||
def test_update_readme_sends_base64_content_with_the_sha(gitea):
|
||||
gitea.add("PUT", README_URL, {})
|
||||
update_readme(get_session(), "# Hi 👋\n", "abc123")
|
||||
body = gitea.put_bodies[0]
|
||||
assert base64.b64decode(body["content"]).decode("utf-8") == "# Hi 👋\n"
|
||||
assert body["sha"] == "abc123"
|
||||
assert body["message"] == "Update language statistics"
|
||||
|
||||
|
||||
def test_update_readme_raises_when_gitea_rejects_the_push(gitea):
|
||||
# Gitea answers 409 when the sha is stale (README changed since we read it).
|
||||
gitea.add("PUT", README_URL, {"message": "sha does not match"}, status=409)
|
||||
with pytest.raises(requests.HTTPError):
|
||||
update_readme(get_session(), "# Hi\n", "old-sha")
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Fetching repos, adding up language bytes, and drawing the chart."""
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
import language_stats
|
||||
from language_stats import (
|
||||
aggregate_language_bytes,
|
||||
fetch_repos,
|
||||
generate_markdown,
|
||||
get_session,
|
||||
subtract_excluded_files,
|
||||
)
|
||||
|
||||
REPOS_PAGE = "https://gitea.test/api/v1/users/alice/repos?page={}&limit=50"
|
||||
WEBSITE_LANGS = "https://gitea.test/api/v1/repos/alice/website/languages"
|
||||
SCRIPTS_LANGS = "https://gitea.test/api/v1/repos/alice/scripts/languages"
|
||||
AFRAME_FILE = "https://gitea.test/api/v1/repos/alice/game/contents/static/aframe.js"
|
||||
VUE4_FILE = "https://gitea.test/api/v1/repos/alice/guide/contents/home/Vue3-v.4.html"
|
||||
VUE5_FILE = "https://gitea.test/api/v1/repos/alice/guide/contents/home/Vue3-v.5.html"
|
||||
|
||||
|
||||
# --- fetch_repos ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fetch_repos_follows_pages_until_an_empty_page(gitea):
|
||||
gitea.add("GET", REPOS_PAGE.format(1), [{"name": "website"}, {"name": "scripts"}])
|
||||
gitea.add("GET", REPOS_PAGE.format(2), [{"name": "notes"}])
|
||||
gitea.add("GET", REPOS_PAGE.format(3), [])
|
||||
assert fetch_repos(get_session()) == [
|
||||
{"name": "website"},
|
||||
{"name": "scripts"},
|
||||
{"name": "notes"},
|
||||
]
|
||||
|
||||
|
||||
def test_fetch_repos_raises_when_the_server_errors(gitea):
|
||||
gitea.add("GET", REPOS_PAGE.format(1), {"message": "internal error"}, status=500)
|
||||
with pytest.raises(requests.HTTPError):
|
||||
fetch_repos(get_session())
|
||||
|
||||
|
||||
# --- aggregate_language_bytes ---------------------------------------------
|
||||
|
||||
|
||||
def test_language_bytes_are_added_up_across_repos(gitea):
|
||||
gitea.add("GET", WEBSITE_LANGS, {"HTML": 1000, "JavaScript": 500})
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 2000, "JavaScript": 250})
|
||||
repos = [{"name": "website"}, {"name": "scripts"}]
|
||||
assert aggregate_language_bytes(get_session(), repos) == {
|
||||
"HTML": 1000,
|
||||
"JavaScript": 750,
|
||||
"Python": 2000,
|
||||
}
|
||||
|
||||
|
||||
def test_language_bytes_sent_as_strings_are_counted(gitea):
|
||||
# Regression test for d8f72b7: the API sometimes returns "2000", not 2000.
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": "2000", "Lua": 300})
|
||||
assert aggregate_language_bytes(get_session(), [{"name": "scripts"}]) == {
|
||||
"Python": 2000,
|
||||
"Lua": 300,
|
||||
}
|
||||
|
||||
|
||||
def test_non_numeric_language_bytes_are_skipped(gitea):
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 2000, "Lua": "lots", "Bash": None})
|
||||
assert aggregate_language_bytes(get_session(), [{"name": "scripts"}]) == {
|
||||
"Python": 2000
|
||||
}
|
||||
|
||||
|
||||
def test_repo_whose_languages_are_forbidden_is_skipped_with_a_warning(gitea, capsys):
|
||||
# Regression test for 2b4ef71: a limited token gets a 403 for private repos.
|
||||
gitea.add(
|
||||
"GET",
|
||||
WEBSITE_LANGS,
|
||||
{"message": "token scope is limited to public repos"},
|
||||
status=403,
|
||||
)
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 2000})
|
||||
repos = [{"name": "website"}, {"name": "scripts"}]
|
||||
assert aggregate_language_bytes(get_session(), repos) == {"Python": 2000}
|
||||
assert (
|
||||
"Warning: Could not fetch languages for website: 403" in capsys.readouterr().err
|
||||
)
|
||||
|
||||
|
||||
def test_repo_whose_languages_return_a_proxy_error_page_is_skipped(gitea, capsys):
|
||||
# A reverse proxy in front of Gitea answers a slow request with an HTML
|
||||
# page, not JSON; trying to parse it would crash the whole run.
|
||||
gitea.add("GET", WEBSITE_LANGS, b"<html><h1>504 Gateway Time-out</h1></html>", 504)
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 2000})
|
||||
repos = [{"name": "website"}, {"name": "scripts"}]
|
||||
assert aggregate_language_bytes(get_session(), repos) == {"Python": 2000}
|
||||
assert (
|
||||
"Warning: Could not fetch languages for website: 504" in capsys.readouterr().err
|
||||
)
|
||||
|
||||
|
||||
def test_error_message_inside_a_success_response_is_skipped_with_a_warning(
|
||||
gitea, capsys
|
||||
):
|
||||
gitea.add("GET", WEBSITE_LANGS, {"message": "token scope is limited"})
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 2000})
|
||||
repos = [{"name": "website"}, {"name": "scripts"}]
|
||||
assert aggregate_language_bytes(get_session(), repos) == {"Python": 2000}
|
||||
assert "Warning: Unexpected response for website" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_response_that_is_not_a_dict_is_skipped(gitea):
|
||||
gitea.add("GET", WEBSITE_LANGS, ["HTML", "JavaScript"])
|
||||
gitea.add("GET", SCRIPTS_LANGS, {"Python": 2000})
|
||||
repos = [{"name": "website"}, {"name": "scripts"}]
|
||||
assert aggregate_language_bytes(get_session(), repos) == {"Python": 2000}
|
||||
|
||||
|
||||
# --- subtract_excluded_files ------------------------------------------------
|
||||
|
||||
|
||||
def test_only_this_repos_excluded_files_are_subtracted(gitea, monkeypatch):
|
||||
# The game repo's aframe.js isn't registered with the fake server, so
|
||||
# fetching it while handling the guide repo would fail this test.
|
||||
monkeypatch.setattr(
|
||||
language_stats,
|
||||
"EXCLUDE_FILES",
|
||||
[
|
||||
("game", "static/aframe.js", "JavaScript"),
|
||||
("guide", "home/Vue3-v.4.html", "HTML"),
|
||||
("guide", "home/Vue3-v.5.html", "HTML"),
|
||||
],
|
||||
)
|
||||
gitea.add("GET", VUE4_FILE, {"size": 100})
|
||||
gitea.add("GET", VUE5_FILE, {"size": 150})
|
||||
langs = {"HTML": 500, "CSS": 400}
|
||||
assert subtract_excluded_files(get_session(), "guide", langs) == {
|
||||
"HTML": 250,
|
||||
"CSS": 400,
|
||||
}
|
||||
|
||||
|
||||
def test_subtracting_an_excluded_file_never_goes_below_zero(gitea, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
language_stats, "EXCLUDE_FILES", [("game", "static/aframe.js", "JavaScript")]
|
||||
)
|
||||
gitea.add("GET", AFRAME_FILE, {"size": 5000})
|
||||
langs = {"JavaScript": 1000, "CSS": 400}
|
||||
assert subtract_excluded_files(get_session(), "game", langs) == {
|
||||
"JavaScript": 0,
|
||||
"CSS": 400,
|
||||
}
|
||||
|
||||
|
||||
def test_excluded_file_that_no_longer_exists_is_ignored(gitea, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
language_stats, "EXCLUDE_FILES", [("game", "static/aframe.js", "JavaScript")]
|
||||
)
|
||||
gitea.add("GET", AFRAME_FILE, {"message": "not found"}, status=404)
|
||||
langs = {"JavaScript": 1000}
|
||||
assert subtract_excluded_files(get_session(), "game", langs) == {"JavaScript": 1000}
|
||||
|
||||
|
||||
def test_network_error_on_an_excluded_file_is_ignored(gitea, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
language_stats, "EXCLUDE_FILES", [("game", "static/aframe.js", "JavaScript")]
|
||||
)
|
||||
gitea.add_error("GET", AFRAME_FILE, requests.ConnectionError("connection reset"))
|
||||
langs = {"JavaScript": 1000}
|
||||
assert subtract_excluded_files(get_session(), "game", langs) == {"JavaScript": 1000}
|
||||
|
||||
|
||||
# --- generate_markdown --------------------------------------------------------
|
||||
|
||||
|
||||
def test_markdown_lists_languages_largest_first_with_bars_and_percentages():
|
||||
# Python 75% -> 75/2 = 37 bar blocks; JavaScript 25% -> 25/2 = 12 blocks.
|
||||
# Lines are joined with a backslash (a markdown line break) and the last
|
||||
# line has no trailing break (regression test for 57a5188).
|
||||
assert generate_markdown({"JavaScript": 250, "Python": 750}) == (
|
||||
"█" * 37 + " Python 75.0%\\\n" + "█" * 12 + " JavaScript 25.0%"
|
||||
)
|
||||
|
||||
|
||||
def test_markdown_percentages_are_rounded_to_one_decimal():
|
||||
# Python 2/3 = 66.67% -> 66.7, 33 blocks; Lua 1/3 = 33.33% -> 33.3, 16 blocks.
|
||||
assert generate_markdown({"Python": 2, "Lua": 1}) == (
|
||||
"█" * 33 + " Python 66.7%\\\n" + "█" * 16 + " Lua 33.3%"
|
||||
)
|
||||
|
||||
|
||||
def test_markdown_leaves_out_languages_with_zero_bytes():
|
||||
# e.g. every HTML byte came from excluded files
|
||||
assert generate_markdown({"Python": 750, "JavaScript": 250, "HTML": 0}) == (
|
||||
"█" * 37 + " Python 75.0%\\\n" + "█" * 12 + " JavaScript 25.0%"
|
||||
)
|
||||
|
||||
|
||||
def test_markdown_is_empty_when_there_are_no_languages():
|
||||
assert generate_markdown({}) == ""
|
||||
|
||||
|
||||
def test_markdown_is_empty_when_every_language_has_zero_bytes():
|
||||
assert generate_markdown({"Python": 0, "Lua": 0}) == ""
|
||||
@@ -1,5 +1,5 @@
|
||||
version = 1
|
||||
revision = 5
|
||||
revision = 3
|
||||
requires-python = ">=3.13"
|
||||
|
||||
[[package]]
|
||||
@@ -126,6 +126,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "colorama"
|
||||
version = "0.4.6"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "3.20"
|
||||
@@ -135,6 +144,33 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iniconfig"
|
||||
version = "2.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "packaging"
|
||||
version = "26.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pluggy"
|
||||
version = "1.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "profile-stats"
|
||||
version = "0.1.0"
|
||||
@@ -144,12 +180,45 @@ dependencies = [
|
||||
{ name = "requests" },
|
||||
]
|
||||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
{ name = "pytest" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "python-dotenv", specifier = ">=1.1.1" },
|
||||
{ name = "requests", specifier = ">=2.32.4" },
|
||||
]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [{ name = "pytest", specifier = ">=9.2.0" }]
|
||||
|
||||
[[package]]
|
||||
name = "pygments"
|
||||
version = "2.21.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest"
|
||||
version = "9.2.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
{ name = "iniconfig" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pluggy" },
|
||||
{ name = "pygments" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dotenv"
|
||||
version = "1.2.4"
|
||||
|
||||
Reference in new issue
Block a user