This document inventories the testing this project needs: what exists today, what's missing, and the specific test cases each module should have. The backend has a pytest suite, and the frontend uses Vitest with React Testing Library for its classification flow.
| Area | Test runner | Status |
|---|---|---|
Backend (backend/) |
pytest (installed, in requirements.txt) |
The deterministic classification contract is covered in test_recommendation_pipeline.py. Other modules also have tests, but the broader suite currently contains unrelated repo_fetcher failures and is not the CI gate for this flow. The live-network scripts remain excluded from collection. |
SDG inference (backend/services/inference.py, sdg_model.py) |
covered indirectly | No direct tests — loading real weights makes naive unit testing hard (see §7). zero_shot_scores is tested on both branches (in-process and MODEL_SERVICE_URL over HTTP), and the load path is pinned by a mocked import trace. |
Frontend (frontend/) |
Vitest + React Testing Library | test/classification-flow.test.tsx submits the form through a mocked API boundary and validates accepted prediction rendering. |
Run the classification contract suite with cd backend && pytest tests/test_recommendation_pipeline.py, and run the frontend flow with cd frontend && npm test. The broader backend suite currently has unrelated repo_fetcher failures and should not be described as green until those tests are reconciled with repository validation behavior.
Highest priority — this module is pure logic with a deliberate exception hierarchy, and needs no ML model or live network access if requests is mocked.
_sanitise_url: bytes input (valid UTF-8 and invalid), non-string types (None,int,list,dict), empty/whitespace-only string, missing scheme, non-http(s) scheme (ftp://,git://,ssh://), missing hostname._rewrite_github_pages: root*.github.io(no path),*.github.io/repo,*.github.io/repo/deep/path, non-Pages URLs pass through unchanged.- Provider
_parsemethods: validowner/repo, missing segments,.gitsuffix stripping, invalid characters (GitHub's segment regex), nested subgroups (GitLab),/wiki/path detection (Bitbucket). _raise_for_status: 200 (no raise), 404 →RepositoryNotFoundError, 429 →RateLimitError, 403 with "rate limit" in body →RateLimitError, 401 →FetchError, other 403 →FetchError, other status codes →FetchError.fetch_readme/fetch_topics/fetch_metaper provider (GitHub, GitLab, Codeberg, Bitbucket), with mocked HTTP responses — including the "repo has no README" case, which must return"", not raise._detect_engine: GitLab probe succeeds, Gitea/Forgejo probe succeeds, both fail →None, network exceptions during probing are swallowed rather than propagated.get_providerfactory: known domain resolves without a network call, unknown domain triggers engine detection, unsupported host raisesUnsupportedHostErrorwith the expected message, token is passed through to the provider.
Covered by backend/tests/test_embedding_url.py (24 tests, all passing). The checklist below is what that file implements; kept here for reference since it doubles as the coverage map.
fetch_repo_text: user-suppliedproject_descriptiontakes priority over the repo's own metadata description (the documented "CHANGE 2" behavior); provider errors onfetch_meta/fetch_topics/fetch_readmeare caught individually and don't abort the whole call.zero_shot_scores: score ordering matchesSDG_NAMES; raisesKeyErrorwhen the model's scores are missing expected keys; raisesTypeErroron an unexpectedscorestype; handles thepayload["data"]["scores"]nested-response shape. Both branches are covered — in-process (default) and remote overMODEL_SERVICE_URL.embedding_similarity_scores: output is clipped to[0, 1]viaCOSINE_LOW/COSINE_HIGH.ensemble_scores: weighted-average arithmetic is correct for variousalphavalues.classify_repo: empty extracted text raisesValueError; predictions abovethresholdare selected;predictionsis[]when nothing clears the threshold (see known gap above) — no best-effort fallback.main: scores are formatted to 3 decimal places in the output dict.
All of the above need requests, get_provider, summarize_for_sdg, and SentenceTransformer mocked — none of these are integration tests against a live model or network.
Table-driven tests against fixture Aurora API payloads:
sdgas a dict with acodefield → formatted as"SDG {code}: {name}".sdgpresent but missingcode→ falls back toname/label.sdgfield missing entirely → falls back topred.get("label")/pred.get("name")/pred.get("sdg_label").- Score at or below the
0.1cutoff is excluded fromsdg_predictions. requests.exceptions.RequestException→ returns the documented error dict, doesn't raise.- A generic
Exceptionduring processing → returns the documented error dict, doesn't raise.
_prepare_for_llm: code fences removed, badge/shield images stripped, generic markdown images collapsed to alt text, HTML comments and tags stripped, bare URLs stripped,max_charstruncation applied._validate_output: banned openers ("here is", "this project", "the repository", …) are stripped from the first line; output over 200 words is truncated at a sentence boundary._fallback_summary: assembles from whatever combination of name/description/topics/reason is present; returns""when all inputs are empty.summarize_for_sdg:- No
GROQ_API_KEY→ falls back immediately, no network call. - Groq returns HTTP 200 with an
"error"key in the body → falls back (this path is easy to miss sinceraise_for_status()alone won't catch it — worth its own explicit test). - Empty
choiceslist → falls back. requests.exceptions.Timeout/HTTPError/RequestException→ falls back in each case.- Malformed
choices[0]["message"]shape → falls back via theKeyError/IndexErrorbranch.
- No
Mock requests.post; no real Groq API calls in the unit suite.
Data-integrity checks rather than behavior:
len(SDG_NAMES) == len(SDG_DESCS) == len(SDG_LABELS) == 17.- Each entry in
SDG_NAMESandSDG_DESCSstarts with the correctSDG {n}number, in order. SDG_LABELS_DICThas exactly the keys"1"through"17".
Cheap to write, and catches silent data-entry drift if someone edits the SDG text by hand. (Note: the trailing SDGs = ["SDG 1", "SDG 2", "SDG 3"] at the bottom of the file looks like dead code left over from development — worth confirming with a maintainer and removing rather than testing.)
Integration-style tests using Flask's test client (no live server needed):
POST /api/classify_aurora: missingprojectDescription→400; happy path filters predictions to> 0.4; an exception fromaurora_classify→500with the documented error shape.POST /api/classify_st_url: missingprojectDescription→400; missingprojectUrl→200with emptypredictionsand an explanatorymessage; each ofInvalidURLError/UnsupportedHostError/ValueError→400,RepositoryNotFoundError→404,RateLimitError→429,FetchError/requests.exceptions.HTTPError→502, anything else →500. This status-code mapping is exactly the kind of thing that silently breaks during a refactor if it isn't pinned down by a test.- The ST route contract test also pins the p5.js regression: classifier-approved SDG 4 (
0.351) and SDG 9 (0.307) scores must reachpredictionswithout being subjected to Aurora's stricter cutoff. - No
/api/classify_st_descriptionroute exists, and no frontend code calls it anymore (see gap above) — nothing to test here unless the route is intentionally reintroduced later. - CORS headers are present on responses.
The hardest area to unit test conventionally: services/inference.py loads real weights from the Hugging Face Hub and builds tensors. Loading is now lazy and behind load()/is_loaded(), and score formatting lives in predict_scores() — both are seams a future test can use without a full weight load.
Recommended approach:
- Refactor first: extract the score→JSON formatting (rounding, threshold filtering in
/predict, min-max normalization in/similarities) into small pure functions so they're unit-testable without a loaded model. - Smoke/integration test for the model itself: start the service,
POSTa fixed known text, assert the response shape and that every score is in[0, 1]. Mark this slow/optional in CI — it needs to download model weights and doesn't need to run on every commit.
Vitest and React Testing Library are configured in frontend/vitest.config.ts.
Pure logic (no rendering required):
lib/utils.ts—cn()class merging/deduplication.components/editModal.tsx—parseSdgFromString(extracting number/name from strings like"SDG 3: Health"),getSdgNumber/getSdgName(string vs. objectsdgshape), duplicate-SDG rejection inaddNewSDG.components/results.tsx—isNoSdgs(null, empty array, empty object, all-zero-score object, mixed number/SDGValueshapes),getScore(number vs.SDGValuevs. undefined).components/mainScreen.tsx— the inline repo-URL validation regex (/^\/[^/]+\/[^/]+/): valid GitHub/GitLab path, bare domain with no path, malformed URL string.services/api.ts—classifyByModelswitch: each model type routes to the correct client method; an unknown type falls back to Aurora.
Component tests:
test/classification-flow.test.tsx— covered: form submission, API handoff, and accepted prediction rendering.mainScreen.tsx— every form-validation message branch ("Please fill in...", "valid repository URL").results.tsx— tab switching (handleTabChange) and its error path,handleDownload's JSON/blob generation.editModal.tsx— add/remove SDG flow end to end.
- Contract tests between
frontend/services/api.tsand the backend routes — would have caught the missingclassify_st_descriptionendpoint automatically instead of at runtime. - SSRF consideration:
fetch_repo_text/get_providertake a user-supplied URL and the server makes outbound requests to it._sanitise_urlcurrently only validates URL shape, not destination — it will happily route tohttp://localhost/...or an internal169.254.169.254/RFC1918 address if a domain-map or engine-detection match were ever added for one. Worth a test (and likely a fix) confirming internal/private hosts are rejected before any request is issued. - Rate-limit and timeout behavior against real forges (GitHub/GitLab/Codeberg/Bitbucket) isn't practical to unit test — track this as a documented manual/staging check instead.
- End-to-end smoke test: submit a real, known-good repository URL through the full stack and confirm a plausible SDG comes back. This is what
backend/tests/test_dpga_real_positives.pyalready does by hand. It belongs in a manual/nightly tier, not the automated unit suite, since it depends on live external services (the forge API, Groq, and Hugging Face for the model weights).
Install— done (pytestforbackend/test_repo_fetcher.py,test_embedding_url.py). Fix the failingclassify_repofallback test/behavior mismatch (see known gap above) before adding moreembedding_url.pycoverage on top of it. Install Jest/Vitest + RTL forfrontend/.— done, 72 tests.backend/services/repo_fetcher.pybackend/services/summariser.pyandbackend/aurora_api.py— both are mockable HTTP-boundary modules with well-defined fallback paths, still untested.backend/app.pyroute tests (theclassify_st_descriptiongap is already resolved, so this is unblocked).- Frontend pure-logic tests, then component tests.
- SDG inference — via
predict_scores()withload()stubbed, now that formatting is separated from loading.