Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,41 @@ jobs:

- name: Run application tests
run: python -m unittest discover -s tests -v

# The same tests on PostgreSQL, which the live site uses: schema upgrades,
# case-insensitive search and date handling can differ from SQLite.
postgres:
runs-on: ubuntu-latest

services:
postgres:
image: postgres:16
env:
POSTGRES_USER: classfind
POSTGRES_PASSWORD: classfind
POSTGRES_DB: classfind_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U classfind"
--health-interval 5s
--health-timeout 5s
--health-retries 10

env:
TEST_DATABASE_URL: postgresql://classfind:classfind@localhost:5432/classfind_test

steps:
- name: Check out repository
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"

- name: Install dependencies
run: pip install -r requirements.txt

- name: Run application tests on PostgreSQL
run: python -m unittest discover -s tests -v
314 changes: 188 additions & 126 deletions README.md

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions campus.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ def _aliases():
ALIASES = _aliases()
# A word like this after a place belongs to it: "computer science lab" is one place.
TRAILING = r"(?:\s+(?:lab|labs|department|dept|block|room|building|hall|area|side))?"
# Things people lose whose names contain a place word.
NOT_PLACES = ("power bank", "powerbank", "piggy bank", "bank card", "bank passbook", "passbook",
"atm card", "atm pin", "debit card", "credit card", "tree charm", "gate pass")
# A loose match may not start or end on one of these, so "near canteen" is not
# read as a misspelt "main canteen".
FILLER = {"the", "a", "an", "near", "at", "in", "on", "by", "to", "and", "of", "my", "i", "inside",
Expand Down Expand Up @@ -100,6 +103,10 @@ def find_places(text):
clean = normalise(text)
if not clean:
return []
# Item names that contain a place word, like "power bank", are blanked out
# (keeping positions) so the bank in the Main Block is not matched.
for phrase in NOT_PLACES:
clean = re.sub(rf"(?<!\w){re.escape(phrase)}(?!\w)", lambda m: " " * len(m.group()), clean)
found = []
for alias, ids in ALIASES:
for match in re.finditer(rf"(?<!\w){re.escape(alias)}{TRAILING}(?!\w)", clean):
Expand Down
Binary file modified docs/screenshots/classfind_home.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed docs/screenshots/classfind_item.png
Binary file not shown.
Binary file removed docs/screenshots/classfind_matches.png
Binary file not shown.
Binary file added docs/screenshots/classfind_place.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
106 changes: 98 additions & 8 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
from datetime import datetime, timedelta
from io import BytesIO

os.environ["DATABASE_URL"] = "sqlite:///:memory:"
# CI also runs these against PostgreSQL, the database the live site uses.
os.environ["DATABASE_URL"] = os.environ.get("TEST_DATABASE_URL", "sqlite:///:memory:")
os.environ["SECRET_KEY"] = "test-secret"

import app as app_module
Expand Down Expand Up @@ -43,7 +44,17 @@


class ClassFindTestCase(unittest.TestCase):
# Settings that would reach real services or change which one is asked. A
# developer's own keys must never make a test call Groq or Gemini.
OUTSIDE_SETTINGS = ("GEMINI_API_KEY", "GROQ_API_KEY", "CEREBRAS_API_KEY", "LLM_MODEL", "AI_ORDER",
"GEMINI_MODEL", "GROQ_MODEL", "CEREBRAS_MODEL", "GEMINI_AUDIO_MODEL", "WHISPER_MODEL",
"SES_SENDER", "PHOTO_LABELS", "THUMBNAILS", "ADMIN_EMAIL", "STAFF_EMAILS")

def setUp(self):
saved = {name: os.environ.pop(name) for name in self.OUTSIDE_SETTINGS if name in os.environ}
self.addCleanup(os.environ.update, saved)
app_module._cooling_until.clear()
app_module._found_models.clear()
app.config.update(TESTING=True, WTF_CSRF_ENABLED=False, RATE_LIMITS_ENABLED=False)
self.upload_dir = tempfile.mkdtemp()
app.config["UPLOAD_FOLDER"] = self.upload_dir
Expand Down Expand Up @@ -118,7 +129,8 @@ def test_csrf_protection_and_security_headers(self):
response = self.client.get("/health")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json()["database"], "ok")
self.assertEqual(response.get_json()["engine"], "sqlite")
with app.app_context():
self.assertEqual(response.get_json()["engine"], db.engine.dialect.name)
self.assertEqual(response.headers["X-Content-Type-Options"], "nosniff")
self.assertEqual(response.headers["X-Frame-Options"], "DENY")
self.assertIn("frame-ancestors 'none'", response.headers["Content-Security-Policy"])
Expand Down Expand Up @@ -1047,16 +1059,18 @@ def test_desk_columns_are_added_to_an_older_database(self):
"""A database from before the desk gets its columns, and found items count as held."""
with app.app_context():
db.drop_all()
# Both databases accept this; INTEGER PRIMARY KEY only numbers rows by itself in SQLite.
key = "INTEGER PRIMARY KEY" if db.engine.dialect.name == "sqlite" else "SERIAL PRIMARY KEY"
for statement in (
'CREATE TABLE "user" (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, '
f'CREATE TABLE "user" (id {key}, name VARCHAR(100) NOT NULL, '
"email VARCHAR(160) NOT NULL, password_hash VARCHAR(255) NOT NULL, "
"is_admin BOOLEAN NOT NULL, created_at DATETIME NOT NULL)",
"CREATE TABLE item (id INTEGER PRIMARY KEY, title VARCHAR(120) NOT NULL, "
"is_admin BOOLEAN NOT NULL, created_at TIMESTAMP NOT NULL)",
f"CREATE TABLE item (id {key}, title VARCHAR(120) NOT NULL, "
"description TEXT NOT NULL, category VARCHAR(60) NOT NULL, location VARCHAR(120) NOT NULL, "
"status VARCHAR(20) NOT NULL, reporter_name VARCHAR(100) NOT NULL, contact VARCHAR(160) NOT NULL, "
"image_url VARCHAR(500), owner_id INTEGER, created_at DATETIME NOT NULL)",
"CREATE TABLE claim (id INTEGER PRIMARY KEY, item_id INTEGER NOT NULL, claimant_id INTEGER NOT NULL, "
"message TEXT NOT NULL, status VARCHAR(20) NOT NULL, created_at DATETIME NOT NULL, decided_at DATETIME)",
"image_url VARCHAR(500), owner_id INTEGER, created_at TIMESTAMP NOT NULL)",
f"CREATE TABLE claim (id {key}, item_id INTEGER NOT NULL, claimant_id INTEGER NOT NULL, "
"message TEXT NOT NULL, status VARCHAR(20) NOT NULL, created_at TIMESTAMP NOT NULL, decided_at TIMESTAMP)",
"INSERT INTO item (title, description, category, location, status, reporter_name, contact, created_at) "
"VALUES ('Old bottle', 'Steel bottle', 'Other', 'Gym', 'Found', 'X', 'x@example.com', '2026-09-01')",
):
Expand Down Expand Up @@ -1145,6 +1159,82 @@ def test_ordinary_items_and_recent_valuables_stay_at_the_desk(self):
self.assertEqual(escalate_unclaimed_valuables(), 0)
self.assertEqual(Item.query.filter_by(custody="office").count(), 0)

# The tests below cover what mutation testing (tools/mutate.py) showed no test noticed.

def test_a_valuable_with_an_approved_claim_stays_at_the_desk(self):
item_id = self.found_item("Grey phone", category="Electronics")
self.register("Owner", "owner@example.com")
self.claim(item_id, "IMEI ends in 4471 and the lock screen is a beach photo.")
self.logout()
self.register_staff()
self.post(f"/desk/item/{item_id}/received", follow_redirects=True)
with app.app_context():
claim_id = Claim.query.one().id
self.post(f"/claims/{claim_id}/accept", follow_redirects=True)
with app.app_context():
for event in db.session.get(Item, item_id).events:
event.created_at = datetime.utcnow() - timedelta(hours=100)
db.session.commit()
# The owner is on the way with a code: the phone must not move to the office.
self.assertEqual(escalate_unclaimed_valuables(), 0)
self.assertEqual(db.session.get(Item, item_id).custody, "held")

def test_collecting_an_item_closes_the_other_claims_on_it(self):
item_id = self.found_item()
self.register("Owner", "owner@example.com")
self.claim(item_id)
self.logout()
self.register("Other", "other@example.com")
self.claim(item_id, "Mine too, it has a scratch on the lid and my initials.")
self.logout()
self.register("Third", "third@example.com")
self.report("Red cap", "Cotton", "Clothing", "Gym", "Found")
self.logout()
self.register_staff()
with app.app_context():
owner_claim = Claim.query.join(User, Claim.claimant_id == User.id).filter(
User.email == "owner@example.com").one().id
cap_id = Item.query.filter_by(title="Red cap").one().id
self.post(f"/desk/item/{item_id}/received", follow_redirects=True)
self.post(f"/claims/{owner_claim}/accept", follow_redirects=True)
self.post("/desk/handover", data={"code": self.code_for(owner_claim)}, follow_redirects=True)
with app.app_context():
statuses = {c.claimant.email: c.status for c in Claim.query.filter_by(item_id=item_id)}
self.assertEqual(statuses, {"owner@example.com": "Collected", "other@example.com": "Rejected"})
self.assertEqual(db.session.get(Item, cap_id).status, "Found")

def test_retrace_ranks_where_you_went_above_what_you_passed(self):
self.register()
self.found_at("Wallet A", "canteen counter", "canteen")
self.found_at("Wallet B", "outside the main block", "main-block", "outside")
since = (datetime.utcnow() - timedelta(hours=6)).isoformat() + "Z"
items = self.client.get("/api/retrace", query_string={
"stops": "canteen", "passed": "main-block", "since": since}).get_json()["items"]
self.assertEqual([i["title"] for i in items], ["Wallet A", "Wallet B"])
self.assertEqual(items[0]["why"], "at Canteen, where you went")
self.assertEqual(items[1]["why"], "outside Main Block, which you passed")

def test_retrace_counts_what_the_photo_shows(self):
self.register()
self.found_at("Grey item", "canteen", "canteen")
self.found_at("Other item", "canteen", "canteen")
with app.app_context():
Item.query.filter_by(title="Grey item").one().image_labels = "Bottle,Tumbler"
db.session.commit()
since = (datetime.utcnow() - timedelta(hours=6)).isoformat() + "Z"
items = self.client.get("/api/retrace", query_string={
"stops": "canteen", "since": since, "q": "bottle"}).get_json()["items"]
self.assertEqual(items[0]["title"], "Grey item")
self.assertGreater(items[0]["score"], items[1]["score"])

def test_a_path_place_picked_on_the_map_is_always_outside(self):
self.register()
self.post("/report", data={"title": "Keys", "description": "Bike keys", "category": "Keys",
"location": "on the way in", "status": "Found",
"place": "road-main", "place_side": "inside"})
with app.app_context():
self.assertEqual(Item.query.one().place_side, "outside")

def test_dashboard_insights_count_what_happened(self):
item_id = self.found_item("Grey phone", category="Electronics")
self.register("Owner", "owner@example.com")
Expand Down
28 changes: 28 additions & 0 deletions tests/test_campus.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,21 @@ def test_misheard_and_misspelt_places_still_match(self):
self.assertEqual(self.place("mechnical parkin"), "mech-parking")
self.assertEqual(self.place("kalashetra"), "kalakshetra")

def test_loose_matches_of_one_two_and_three_words(self):
# Mutation testing showed only two-word misspellings were covered.
self.assertEqual(self.place("workshps"), "workshops")
self.assertEqual(self.place("kalakshtra"), "kalakshetra")
self.assertEqual(self.place("internet of thngs"), "main-block")
# Five letters is long enough to match loosely, typed or as the place's own name.
self.assertEqual(self.place("garge"), "mech-parking")
self.assertEqual(campus.resolve_place("xeroox")["candidates"], ["xerox-mech", "xerox-canteen"])

def test_a_loose_match_is_cut_out_of_the_search_exactly(self):
self.assertEqual(campus.split_search("mesh parking umbrella"), (["mech-parking"], "umbrella"))
self.assertEqual(campus.split_search("red umbrella mesh parking"), (["mech-parking"], "red umbrella"))
self.assertEqual(campus.split_search("black bag near workshps"), (["workshops"], "black bag"))
self.assertEqual(campus.resolve_place("black bag near workshps")["side"], "outside")

def test_words_shared_by_several_places_are_not_guessed(self):
canteen = campus.resolve_place("near the canteen")
self.assertIsNone(canteen["place"])
Expand All @@ -59,6 +74,19 @@ def test_kannada_and_hindi_words(self):
self.assertEqual(campus.resolve_place("ಕ್ಯಾಂಟೀನ್ ಹತ್ತಿರ")["candidates"], ["canteen", "puff-shop", "nandini"])
self.assertEqual(self.place("लाइब्रेरी में"), "main-block")

def test_everyday_items_are_not_places(self):
# Mutation testing found "power bank" landing on the bank in the Main Block.
items = ("my pen", "blue cap", "phone case", "lunch box", "id card", "black bag", "water bottle",
"steel tiffin", "grey hoodie", "spectacles", "calculator", "earphones", "umbrella",
"laptop charger", "house keys", "notebook", "helmet", "power bank", "bus pass", "watch",
"pencil box", "textbook", "purse", "wallet", "airpods", "pendrive", "ATM card",
"debit card", "bank passbook")
for text in items:
self.assertEqual(campus.find_places(text), [], text)
self.assertEqual(campus.split_search("power bank in the canteen"),
(["canteen", "puff-shop", "nandini"], "power bank"))
self.assertEqual(self.place("lost my ATM card at the ATM"), "atm")

def test_unknown_places_and_item_words_match_nothing(self):
for text in ("Hostel", "Black Milton bottle", "my bag", ""):
self.assertEqual(campus.resolve_place(text)["candidates"], [], text)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_quality.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import unittest
from pathlib import Path

os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("DATABASE_URL", os.environ.get("TEST_DATABASE_URL", "sqlite:///:memory:"))
os.environ.setdefault("SECRET_KEY", "test-secret")

from app import app
Expand Down
Loading
Loading