Files

210 lines
7.4 KiB
Python

"""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()