2026-assignment2-Expense-Tracker-Pipeline 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of 2026-assignment2-Expense-Tracker-Pipeline might be problematic. Click here for more details.

@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: 2026_assignment2_Expense_Tracker_Pipeline
3
+ Version: 0.1.0
4
+ Summary: Track your expenses
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: Flask
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest; extra == "dev"
11
+ Dynamic: license-file
12
+
13
+ # ExpenseTracker
14
+
15
+ Small Flask + SQLite web app for tracking personal expenses. Add expenses with an amount, category, description and date, edit them in place, and delete entries. Categories you use are saved and suggested next time, and the page shows the total and per-category totals. A month dropdown filters the list and the totals.
16
+
17
+ ![Screenshot of the app](docs/screenshot.png)
18
+
19
+ ## Setup
20
+
21
+ ```bash
22
+ python3 -m venv .venv
23
+ source .venv/bin/activate
24
+ pip install -r requirements.txt
25
+ ```
26
+
27
+ ## Run
28
+
29
+ ```bash
30
+ python app.py
31
+ ```
32
+
33
+ Open http://localhost:5000. The SQLite database (`expenses.db`) is created next to the app on first run.
34
+
35
+ **Local use only:** there is no authentication or CSRF protection, and the app runs with `debug=True`. Don't expose it to a network or deploy it as is.
36
+
37
+ ## Tests
38
+
39
+ ```bash
40
+ pip install -r requirements-dev.txt
41
+ pytest
42
+ ```
43
+
44
+ Tests use a temporary database, so your real `expenses.db` is never touched.
45
+
46
+ ## Layout
47
+
48
+ - `app.py` – Flask app factory, routes and input validation
49
+ - `database.py` – SQLite access
50
+ - `templates/`, `static/` – HTML, CSS and two small scripts (category suggestions, keeping the scroll position when editing)
51
+ - `tests/` – pytest tests for validation, database functions and routes
52
+
53
+ ## About
54
+
55
+ The initial version was hand-coded as a practice project to remind myself of the tech behind a small web app. Development continues with Claude Code (security checks, polish, new features).
56
+
57
+ The original project was written before version control was set up, which is why the Git history starts on 20.10.2026.
58
+
59
+ Tech and concepts used:
60
+ - Flask routes and form handling
61
+ - Jinja templates
62
+ - Raw `sqlite3` with parameterized queries
63
+ - POST-redirect-GET pattern
64
+ - Server-side input validation
65
+ - Amounts stored as integer cents (parsed with `Decimal`) to avoid float rounding errors
66
+ - App factory (`create_app()`) so importing the app has no side effects
67
+ - Filtering with a query parameter (`?month=YYYY-MM`) and a parameterized `WHERE` clause
68
+
69
+ Ideas for later: CSV export.
70
+
71
+ ## License
72
+
73
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ app.py
4
+ database.py
5
+ pyproject.toml
6
+ 2026_assignment2_Expense_Tracker_Pipeline.egg-info/PKG-INFO
7
+ 2026_assignment2_Expense_Tracker_Pipeline.egg-info/SOURCES.txt
8
+ 2026_assignment2_Expense_Tracker_Pipeline.egg-info/dependency_links.txt
9
+ 2026_assignment2_Expense_Tracker_Pipeline.egg-info/requires.txt
10
+ 2026_assignment2_Expense_Tracker_Pipeline.egg-info/top_level.txt
11
+ tests/test_app.py
12
+ tests/test_database.py
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tomas Alivuotila
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: 2026_assignment2_Expense_Tracker_Pipeline
3
+ Version: 0.1.0
4
+ Summary: Track your expenses
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: Flask
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest; extra == "dev"
11
+ Dynamic: license-file
12
+
13
+ # ExpenseTracker
14
+
15
+ Small Flask + SQLite web app for tracking personal expenses. Add expenses with an amount, category, description and date, edit them in place, and delete entries. Categories you use are saved and suggested next time, and the page shows the total and per-category totals. A month dropdown filters the list and the totals.
16
+
17
+ ![Screenshot of the app](docs/screenshot.png)
18
+
19
+ ## Setup
20
+
21
+ ```bash
22
+ python3 -m venv .venv
23
+ source .venv/bin/activate
24
+ pip install -r requirements.txt
25
+ ```
26
+
27
+ ## Run
28
+
29
+ ```bash
30
+ python app.py
31
+ ```
32
+
33
+ Open http://localhost:5000. The SQLite database (`expenses.db`) is created next to the app on first run.
34
+
35
+ **Local use only:** there is no authentication or CSRF protection, and the app runs with `debug=True`. Don't expose it to a network or deploy it as is.
36
+
37
+ ## Tests
38
+
39
+ ```bash
40
+ pip install -r requirements-dev.txt
41
+ pytest
42
+ ```
43
+
44
+ Tests use a temporary database, so your real `expenses.db` is never touched.
45
+
46
+ ## Layout
47
+
48
+ - `app.py` – Flask app factory, routes and input validation
49
+ - `database.py` – SQLite access
50
+ - `templates/`, `static/` – HTML, CSS and two small scripts (category suggestions, keeping the scroll position when editing)
51
+ - `tests/` – pytest tests for validation, database functions and routes
52
+
53
+ ## About
54
+
55
+ The initial version was hand-coded as a practice project to remind myself of the tech behind a small web app. Development continues with Claude Code (security checks, polish, new features).
56
+
57
+ The original project was written before version control was set up, which is why the Git history starts on 20.10.2026.
58
+
59
+ Tech and concepts used:
60
+ - Flask routes and form handling
61
+ - Jinja templates
62
+ - Raw `sqlite3` with parameterized queries
63
+ - POST-redirect-GET pattern
64
+ - Server-side input validation
65
+ - Amounts stored as integer cents (parsed with `Decimal`) to avoid float rounding errors
66
+ - App factory (`create_app()`) so importing the app has no side effects
67
+ - Filtering with a query parameter (`?month=YYYY-MM`) and a parameterized `WHERE` clause
68
+
69
+ Ideas for later: CSV export.
70
+
71
+ ## License
72
+
73
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,61 @@
1
+ # ExpenseTracker
2
+
3
+ Small Flask + SQLite web app for tracking personal expenses. Add expenses with an amount, category, description and date, edit them in place, and delete entries. Categories you use are saved and suggested next time, and the page shows the total and per-category totals. A month dropdown filters the list and the totals.
4
+
5
+ ![Screenshot of the app](docs/screenshot.png)
6
+
7
+ ## Setup
8
+
9
+ ```bash
10
+ python3 -m venv .venv
11
+ source .venv/bin/activate
12
+ pip install -r requirements.txt
13
+ ```
14
+
15
+ ## Run
16
+
17
+ ```bash
18
+ python app.py
19
+ ```
20
+
21
+ Open http://localhost:5000. The SQLite database (`expenses.db`) is created next to the app on first run.
22
+
23
+ **Local use only:** there is no authentication or CSRF protection, and the app runs with `debug=True`. Don't expose it to a network or deploy it as is.
24
+
25
+ ## Tests
26
+
27
+ ```bash
28
+ pip install -r requirements-dev.txt
29
+ pytest
30
+ ```
31
+
32
+ Tests use a temporary database, so your real `expenses.db` is never touched.
33
+
34
+ ## Layout
35
+
36
+ - `app.py` – Flask app factory, routes and input validation
37
+ - `database.py` – SQLite access
38
+ - `templates/`, `static/` – HTML, CSS and two small scripts (category suggestions, keeping the scroll position when editing)
39
+ - `tests/` – pytest tests for validation, database functions and routes
40
+
41
+ ## About
42
+
43
+ The initial version was hand-coded as a practice project to remind myself of the tech behind a small web app. Development continues with Claude Code (security checks, polish, new features).
44
+
45
+ The original project was written before version control was set up, which is why the Git history starts on 20.10.2026.
46
+
47
+ Tech and concepts used:
48
+ - Flask routes and form handling
49
+ - Jinja templates
50
+ - Raw `sqlite3` with parameterized queries
51
+ - POST-redirect-GET pattern
52
+ - Server-side input validation
53
+ - Amounts stored as integer cents (parsed with `Decimal`) to avoid float rounding errors
54
+ - App factory (`create_app()`) so importing the app has no side effects
55
+ - Filtering with a query parameter (`?month=YYYY-MM`) and a parameterized `WHERE` clause
56
+
57
+ Ideas for later: CSV export.
58
+
59
+ ## License
60
+
61
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,142 @@
1
+ from datetime import date
2
+ from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
3
+
4
+ from flask import Flask, render_template, request, redirect, url_for
5
+
6
+ from database import (
7
+ add_expense, delete_expense, get_categories, get_expense, get_months,
8
+ get_total, get_total_by_category, init_db, get_expenses, update_expense,
9
+ )
10
+
11
+ MAX_CENTS = 10**12
12
+
13
+ def create_app():
14
+ app = Flask(__name__)
15
+ app.jinja_env.filters["money"] = format_cents
16
+ init_db()
17
+
18
+ @app.route("/")
19
+ def index():
20
+ month = parse_month(request.args.get("month"))
21
+ return render_index(month=month, edit_id=request.args.get("edit", type=int))
22
+
23
+ @app.route("/add", methods=["POST"])
24
+ def add():
25
+ month = parse_month(request.form.get("month"))
26
+ values, error = parse_expense_form()
27
+ if error:
28
+ return render_index(error, month=month)
29
+ add_expense(*values)
30
+ return redirect(url_for("index", month=month))
31
+
32
+ @app.route("/edit/<int:expense_id>", methods=["GET", "POST"])
33
+ def edit(expense_id):
34
+ if get_expense(expense_id) is None:
35
+ return redirect("/")
36
+
37
+ if request.method == "GET":
38
+ return redirect(url_for("index", edit=expense_id))
39
+
40
+ month = parse_month(request.form.get("month"))
41
+ values, error = parse_expense_form()
42
+ if error:
43
+ return render_index(error, month=month, edit_id=expense_id, edit_form=request.form)
44
+ update_expense(expense_id, *values)
45
+ return redirect(url_for("index", month=month))
46
+
47
+ @app.route("/delete", methods=["POST"])
48
+ def delete():
49
+ month = parse_month(request.form.get("month"))
50
+ try:
51
+ expense_id = int(request.form["expense_id"])
52
+ except (KeyError, ValueError):
53
+ return redirect(url_for("index", month=month))
54
+ delete_expense(expense_id)
55
+ return redirect(url_for("index", month=month))
56
+
57
+ return app
58
+
59
+ def parse_month(text):
60
+ if not text or len(text) != 7:
61
+ return None
62
+ try:
63
+ date.fromisoformat(text + "-01")
64
+ except ValueError:
65
+ return None
66
+ return text
67
+
68
+ def parse_cents(text):
69
+ try:
70
+ amount = Decimal(text)
71
+ if not amount.is_finite():
72
+ return None
73
+ return int((amount * 100).quantize(Decimal(1), rounding=ROUND_HALF_UP))
74
+ except InvalidOperation:
75
+ return None
76
+
77
+ def format_cents(cents):
78
+ sign = "-" if cents < 0 else ""
79
+ cents = abs(cents)
80
+ return f"{sign}{cents // 100}.{cents % 100:02d}"
81
+
82
+ def parse_expense_form():
83
+ amount = request.form["amount"].strip().replace(",",".")
84
+ category = request.form["category"].strip()
85
+ description = request.form["description"].strip()
86
+ date_text = request.form["date"] or None
87
+
88
+ cents = parse_cents(amount)
89
+ if cents is None:
90
+ return None, "Amount must be a number"
91
+
92
+ if cents <= 0:
93
+ return None, "Amount must be positive"
94
+
95
+ if cents > MAX_CENTS:
96
+ return None, "Amount is too large"
97
+
98
+ if not category:
99
+ return None, "Category can't be empty"
100
+
101
+ if not description:
102
+ return None, "Description can't be empty"
103
+
104
+ if date_text:
105
+ try:
106
+ date_text = date.fromisoformat(date_text).isoformat()
107
+ except ValueError:
108
+ return None, "Date must be YYYY-MM-DD"
109
+
110
+ return (cents, category, description, date_text), None
111
+
112
+ def render_index(error=None, edit_id=None, edit_form=None, month=None):
113
+ expenses = get_expenses(month)
114
+ if edit_id is not None and edit_form is None:
115
+ match = next((e for e in expenses if e[0] == edit_id), None)
116
+ if match:
117
+ _, amount_cents, category, description, date_text = match
118
+ edit_form = {
119
+ "amount": format_cents(amount_cents),
120
+ "category": category,
121
+ "description": description,
122
+ "date": date_text,
123
+ }
124
+ if edit_form is None:
125
+ edit_id = None
126
+ return render_template(
127
+ "index.html",
128
+ expenses=expenses,
129
+ total=get_total(month),
130
+ by_category=get_total_by_category(month),
131
+ categories=get_categories(),
132
+ months=get_months(),
133
+ month=month,
134
+ error=error,
135
+ edit_id=edit_id,
136
+ edit_form=edit_form,
137
+ )
138
+
139
+
140
+ if __name__ == "__main__":
141
+ create_app().run(debug=True)
142
+
@@ -0,0 +1,118 @@
1
+ import os
2
+ import sqlite3
3
+ from datetime import date
4
+
5
+ DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "expenses.db")
6
+
7
+ EXPENSES_COLUMNS = """(
8
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
9
+ amount_cents INTEGER NOT NULL,
10
+ category TEXT NOT NULL,
11
+ description TEXT,
12
+ date TEXT NOT NULL
13
+ )"""
14
+
15
+ def init_db():
16
+ conn = sqlite3.connect(DB_PATH)
17
+ cur = conn.cursor()
18
+ cur.execute("CREATE TABLE IF NOT EXISTS expenses " + EXPENSES_COLUMNS)
19
+ columns = [row[1] for row in cur.execute("PRAGMA table_info(expenses)")]
20
+ if "amount" in columns:
21
+ # Older databases stored the amount as a float in euros.
22
+ cur.execute("DROP TABLE IF EXISTS expenses_new")
23
+ cur.execute("CREATE TABLE expenses_new " + EXPENSES_COLUMNS)
24
+ cur.execute("""
25
+ INSERT INTO expenses_new (id, amount_cents, category, description, date)
26
+ SELECT id, CAST(ROUND(amount * 100) AS INTEGER), category, description, date FROM expenses
27
+ """)
28
+ cur.execute("DROP TABLE expenses")
29
+ cur.execute("ALTER TABLE expenses_new RENAME TO expenses")
30
+ cur.execute("CREATE TABLE IF NOT EXISTS categories (name TEXT PRIMARY KEY COLLATE NOCASE)")
31
+ cur.execute("INSERT OR IGNORE INTO categories (name) SELECT DISTINCT category FROM expenses")
32
+ conn.commit()
33
+ conn.close()
34
+
35
+ def month_filter(month):
36
+ if month:
37
+ return "WHERE substr(date, 1, 7) = ?", (month,)
38
+ return "", ()
39
+
40
+ def add_expense(amount_cents, category, description, date_text=None):
41
+ if date_text is None:
42
+ date_text = date.today().isoformat()
43
+ conn = sqlite3.connect(DB_PATH)
44
+ cur = conn.cursor()
45
+ cur.execute("INSERT OR IGNORE INTO categories (name) VALUES (?)", (category,))
46
+ cur.execute("INSERT INTO expenses (amount_cents, category, description, date) VALUES (?, ?, ?, ?)", (amount_cents, category, description, date_text))
47
+ conn.commit()
48
+ conn.close()
49
+
50
+ def get_expenses(month=None):
51
+ where, params = month_filter(month)
52
+ conn = sqlite3.connect(DB_PATH)
53
+ cur = conn.cursor()
54
+ cur.execute(f"SELECT id, amount_cents, category, description, date FROM expenses {where} ORDER BY date DESC, id DESC", params)
55
+ rows = cur.fetchall()
56
+ conn.close()
57
+ return rows
58
+
59
+ def get_expense(expense_id):
60
+ conn = sqlite3.connect(DB_PATH)
61
+ cur = conn.cursor()
62
+ cur.execute("SELECT id, amount_cents, category, description, date FROM expenses WHERE id = ?", (expense_id,))
63
+ row = cur.fetchone()
64
+ conn.close()
65
+ return row
66
+
67
+ def update_expense(expense_id, amount_cents, category, description, date_text=None):
68
+ conn = sqlite3.connect(DB_PATH)
69
+ cur = conn.cursor()
70
+ cur.execute("INSERT OR IGNORE INTO categories (name) VALUES (?)", (category,))
71
+ cur.execute(
72
+ "UPDATE expenses SET amount_cents = ?, category = ?, description = ?,"
73
+ "date = COALESCE(?, date) WHERE id = ?",
74
+ (amount_cents, category, description, date_text, expense_id),
75
+ )
76
+ conn.commit()
77
+ conn.close()
78
+
79
+ def delete_expense(expense_id):
80
+ conn = sqlite3.connect(DB_PATH)
81
+ cur = conn.cursor()
82
+ cur.execute("DELETE FROM expenses WHERE id = ?", (expense_id,))
83
+ conn.commit()
84
+ conn.close()
85
+
86
+ def get_categories():
87
+ conn = sqlite3.connect(DB_PATH)
88
+ cur = conn.cursor()
89
+ cur.execute("SELECT name FROM categories ORDER BY name")
90
+ rows = [row[0] for row in cur.fetchall()]
91
+ conn.close()
92
+ return rows
93
+
94
+ def get_total(month=None):
95
+ where, params = month_filter(month)
96
+ conn = sqlite3.connect(DB_PATH)
97
+ cur = conn.cursor()
98
+ cur.execute(f"SELECT SUM(amount_cents) FROM expenses {where}", params)
99
+ row = cur.fetchone()
100
+ conn.close()
101
+ return row[0] or 0
102
+
103
+ def get_total_by_category(month=None):
104
+ where, params = month_filter(month)
105
+ conn = sqlite3.connect(DB_PATH)
106
+ cur = conn.cursor()
107
+ cur.execute(f"SELECT category, SUM(amount_cents) FROM expenses {where} GROUP BY category", params)
108
+ rows = cur.fetchall()
109
+ conn.close()
110
+ return rows
111
+
112
+ def get_months():
113
+ conn = sqlite3.connect(DB_PATH)
114
+ cur = conn.cursor()
115
+ cur.execute("SELECT DISTINCT substr(date, 1, 7) FROM expenses ORDER BY 1 DESC")
116
+ rows = [row[0] for row in cur.fetchall()]
117
+ conn.close()
118
+ return rows
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "2026_assignment2_Expense_Tracker_Pipeline"
7
+ version = "0.1.0"
8
+ description = "Track your expenses"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ dependencies = ["Flask"]
12
+
13
+ [project.optional-dependencies]
14
+ dev = ["pytest"]
15
+
16
+ [tool.setuptools]
17
+ py-modules = ["app", "database"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,320 @@
1
+ import pytest
2
+
3
+
4
+ def add(client, **overrides):
5
+ data = {"amount": "10", "category": "Food", "description": "Lunch", "date": "2026-10-01"}
6
+ data.update(overrides)
7
+ return client.post("/add", data=data)
8
+
9
+
10
+ def test_index_ok(client):
11
+ assert client.get("/").status_code == 200
12
+
13
+
14
+ def test_add_redirects_and_saves(client, db):
15
+ response = add(client)
16
+ assert response.status_code == 302
17
+ assert db.get_expenses()[0][1] == 1000
18
+
19
+
20
+ def test_comma_decimal_accepted(client, db):
21
+ add(client, amount="12,50")
22
+ assert db.get_expenses()[0][1] == 1250
23
+
24
+
25
+ @pytest.mark.parametrize("amount", ["abc", "", "nan", "inf", "-inf", "1e999"])
26
+ def test_invalid_amount_rejected(client, db, amount):
27
+ response = add(client, amount=amount)
28
+ assert b"Amount must be a number" in response.data
29
+ assert db.get_expenses() == []
30
+
31
+
32
+ @pytest.mark.parametrize("amount", ["0", "-5"])
33
+ def test_non_positive_amount_rejected(client, db, amount):
34
+ response = add(client, amount=amount)
35
+ assert b"Amount must be positive" in response.data
36
+ assert db.get_expenses() == []
37
+
38
+
39
+ def test_empty_category_rejected(client, db):
40
+ assert b"Category can&#39;t be empty" in add(client, category=" ").data
41
+ assert db.get_expenses() == []
42
+
43
+
44
+ def test_empty_description_rejected(client, db):
45
+ assert b"Description can&#39;t be empty" in add(client, description="").data
46
+ assert db.get_expenses() == []
47
+
48
+
49
+ def test_bad_date_rejected(client, db):
50
+ assert b"Date must be YYYY-MM-DD" in add(client, date="not-a-date").data
51
+ assert db.get_expenses() == []
52
+
53
+
54
+ def test_date_normalized(client, db):
55
+ add(client, date="20261020")
56
+ assert db.get_expenses()[0][4] == "2026-10-20"
57
+
58
+
59
+ def test_blank_date_defaults_to_today(client, db):
60
+ from datetime import date
61
+
62
+ add(client, date="")
63
+ assert db.get_expenses()[0][4] == date.today().isoformat()
64
+
65
+
66
+ def test_delete(client, db):
67
+ add(client)
68
+ expense_id = db.get_expenses()[0][0]
69
+ assert client.post("/delete", data={"expense_id": expense_id}).status_code == 302
70
+ assert db.get_expenses() == []
71
+
72
+
73
+ def test_delete_bad_id_does_not_crash(client):
74
+ assert client.post("/delete", data={"expense_id": "x"}).status_code == 302
75
+ assert client.post("/delete", data={}).status_code == 302
76
+
77
+
78
+ def test_html_is_escaped(client):
79
+ add(client, description="<script>alert(1)</script>")
80
+ body = client.get("/").data
81
+ assert b"<script>alert(1)</script>" not in body
82
+ assert b"&lt;script&gt;" in body
83
+
84
+
85
+ def test_new_category_suggested_on_index(client):
86
+ add(client, category="Groceries")
87
+ assert b'<li role="option">Groceries</li>' in client.get("/").data
88
+
89
+
90
+ def test_category_suggestion_is_escaped(client):
91
+ add(client, category='"><script>')
92
+ data = client.get("/").data
93
+ assert b'"><script>' not in data
94
+ assert b"&#34;&gt;&lt;script&gt;" in data
95
+
96
+
97
+ def edit(client, expense_id, **overrides):
98
+ data = {"amount": "20", "category": "Rent", "description": "Flat", "date": "2026-11-01"}
99
+ data.update(overrides)
100
+ return client.post(f"/edit/{expense_id}", data=data)
101
+
102
+
103
+ def test_edit_row_prefilled_in_place(client, db):
104
+ add(client, amount="12,5", description="Lunch")
105
+ add(client, description="Other", date="2026-09-01")
106
+ expense_id = db.get_expenses()[0][0]
107
+ body = client.get(f"/?edit={expense_id}").data
108
+ assert b'action="/edit/%d"' % expense_id in body
109
+ assert b'value="12.50"' in body
110
+ assert b'value="Lunch"' in body
111
+ assert b'value="2026-10-01"' in body
112
+ assert body.count(b'class="editing"') == 1
113
+ assert b"Other" in body
114
+
115
+
116
+ def test_edit_unknown_id_shows_normal_page(client, db):
117
+ add(client)
118
+ assert b'class="editing"' not in client.get("/?edit=999").data
119
+ assert b'class="editing"' not in client.get("/?edit=abc").data
120
+
121
+
122
+ def test_edit_get_redirects_to_row(client, db):
123
+ add(client)
124
+ expense_id = db.get_expenses()[0][0]
125
+ response = client.get(f"/edit/{expense_id}")
126
+ assert response.status_code == 302
127
+ assert response.headers["Location"].endswith(f"/?edit={expense_id}")
128
+
129
+
130
+ def test_edit_saves_and_redirects(client, db):
131
+ add(client)
132
+ expense_id = db.get_expenses()[0][0]
133
+ assert edit(client, expense_id).status_code == 302
134
+ assert db.get_expense(expense_id) == (expense_id, 2000, "Rent", "Flat", "2026-11-01")
135
+
136
+
137
+ def test_edit_blank_date_keeps_existing(client, db):
138
+ add(client)
139
+ expense_id = db.get_expenses()[0][0]
140
+ edit(client, expense_id, date="")
141
+ assert db.get_expense(expense_id)[4] == "2026-10-01"
142
+
143
+
144
+ def test_edit_invalid_rejected_and_input_kept(client, db):
145
+ add(client)
146
+ expense_id = db.get_expenses()[0][0]
147
+ response = edit(client, expense_id, amount="abc", description="Changed")
148
+ assert b"Amount must be a number" in response.data
149
+ assert b'class="editing"' in response.data
150
+ assert b'value="Changed"' in response.data
151
+ assert db.get_expense(expense_id)[3] == "Lunch"
152
+
153
+
154
+ def test_edit_missing_expense_redirects(client):
155
+ assert client.get("/edit/999").status_code == 302
156
+ assert edit(client, 999).status_code == 302
157
+
158
+
159
+ def test_index_links_to_edit(client, db):
160
+ add(client)
161
+ expense_id = db.get_expenses()[0][0]
162
+ assert f'href="/?edit={expense_id}"'.encode() in client.get("/").data
163
+
164
+
165
+ def test_import_does_not_touch_database(tmp_path, monkeypatch):
166
+ import importlib
167
+
168
+ import app as app_module
169
+ import database
170
+
171
+ path = tmp_path / "untouched.db"
172
+ monkeypatch.setattr(database, "DB_PATH", str(path))
173
+ importlib.reload(app_module)
174
+ assert not path.exists()
175
+
176
+
177
+ @pytest.mark.parametrize("amount, cents", [("12.345", 1235), ("0.1", 10), ("5", 500), ("1,05", 105), ("0.005", 1)])
178
+ def test_amount_stored_as_whole_cents(client, db, amount, cents):
179
+ add(client, amount=amount)
180
+ assert db.get_expenses()[0][1] == cents
181
+
182
+
183
+ def test_amount_rounding_to_zero_rejected(client, db):
184
+ assert b"Amount must be positive" in add(client, amount="0.004").data
185
+ assert db.get_expenses() == []
186
+
187
+
188
+ def test_huge_amount_rejected(client, db):
189
+ assert b"Amount is too large" in add(client, amount="1e20").data
190
+ assert db.get_expenses() == []
191
+
192
+
193
+ def test_amounts_displayed_with_two_decimals(client):
194
+ add(client, amount="3")
195
+ add(client, amount="0,1", category="Snacks", description="dime")
196
+ body = client.get("/").data
197
+ assert body.count("3.00 €".encode()) == 2
198
+ assert body.count("0.10 €".encode()) == 2
199
+ assert b"3.10 \xe2\x82\xac" in body
200
+
201
+
202
+ def add_two_months(client):
203
+ add(client, description="oct expense", date="2026-10-05")
204
+ add(client, description="sep expense", date="2026-09-20", amount="5")
205
+
206
+
207
+ def test_index_filtered_by_month(client):
208
+ add_two_months(client)
209
+ body = client.get("/?month=2026-10").data
210
+ assert b"oct expense" in body
211
+ assert b"sep expense" not in body
212
+
213
+
214
+ def test_index_without_month_shows_everything(client):
215
+ add_two_months(client)
216
+ body = client.get("/").data
217
+ assert b"oct expense" in body
218
+ assert b"sep expense" in body
219
+
220
+
221
+ @pytest.mark.parametrize("month", ["garbage", "2026-13", "2026-1", "2026-10-05", "", "20261"])
222
+ def test_invalid_month_is_ignored(client, month):
223
+ add_two_months(client)
224
+ response = client.get("/", query_string={"month": month})
225
+ assert response.status_code == 200
226
+ assert b"oct expense" in response.data
227
+ assert b"sep expense" in response.data
228
+
229
+
230
+ def test_totals_follow_month_filter(client):
231
+ add_two_months(client)
232
+ body = client.get("/?month=2026-09").data
233
+ assert b"5.00 \xe2\x82\xac" in body
234
+ assert b"15.00 \xe2\x82\xac" not in body
235
+ assert "Total · 2026-09".encode() in body
236
+
237
+
238
+ def test_dropdown_lists_months_and_marks_selected(client):
239
+ add_two_months(client)
240
+ body = client.get("/?month=2026-09").data
241
+ assert b'<option value="2026-10">' in body
242
+ assert b'<option value="2026-09" selected>' in body
243
+ assert b'<option value="">All months</option>' in body
244
+
245
+
246
+ def test_empty_month_message(client):
247
+ add_two_months(client)
248
+ assert b"No expenses in 2026-01." in client.get("/?month=2026-01").data
249
+
250
+
251
+ def test_empty_database_message_without_filter(client):
252
+ assert b"No expenses yet." in client.get("/").data
253
+
254
+
255
+ def test_forms_carry_the_month(client, db):
256
+ add_two_months(client)
257
+ body = client.get("/?month=2026-10").data
258
+ assert body.count(b'name="month" value="2026-10"') >= 2
259
+ expense_id = db.get_expenses(month="2026-10")[0][0]
260
+ assert f'href="/?month=2026-10&amp;edit={expense_id}"'.encode() in body
261
+
262
+
263
+ def test_add_redirect_keeps_month(client, db):
264
+ response = add(client, month="2026-10")
265
+ assert response.headers["Location"].endswith("/?month=2026-10")
266
+
267
+
268
+ def test_add_redirect_without_month(client, db):
269
+ assert add(client).headers["Location"].endswith("/")
270
+ assert "month" not in add(client, month="garbage").headers["Location"]
271
+
272
+
273
+ def test_add_error_keeps_month(client, db):
274
+ add_two_months(client)
275
+ response = add(client, amount="abc", month="2026-09")
276
+ assert b"Amount must be a number" in response.data
277
+ assert b'<option value="2026-09" selected>' in response.data
278
+
279
+
280
+ def test_edit_redirect_keeps_month(client, db):
281
+ add(client)
282
+ expense_id = db.get_expenses()[0][0]
283
+ response = edit(client, expense_id, month="2026-10")
284
+ assert response.headers["Location"].endswith("/?month=2026-10")
285
+
286
+
287
+ def test_edit_error_keeps_month_and_edit_row(client, db):
288
+ add_two_months(client)
289
+ expense_id = db.get_expenses(month="2026-09")[0][0]
290
+ response = edit(client, expense_id, amount="abc", month="2026-09")
291
+ assert b"Amount must be a number" in response.data
292
+ assert b'class="editing"' in response.data
293
+ assert b'<option value="2026-09" selected>' in response.data
294
+ assert b"oct expense" not in response.data
295
+
296
+
297
+ def test_edit_row_shown_under_month_filter(client, db):
298
+ add_two_months(client)
299
+ expense_id = db.get_expenses(month="2026-09")[0][0]
300
+ body = client.get(f"/?month=2026-09&edit={expense_id}").data
301
+ assert b'class="editing"' in body
302
+ assert b'href="/?month=2026-09"' in body
303
+
304
+
305
+ def test_delete_redirect_keeps_month(client, db):
306
+ add(client)
307
+ expense_id = db.get_expenses()[0][0]
308
+ response = client.post("/delete", data={"expense_id": expense_id, "month": "2026-10"})
309
+ assert response.headers["Location"].endswith("/?month=2026-10")
310
+ assert db.get_expenses() == []
311
+
312
+
313
+ def test_delete_bad_id_keeps_month(client):
314
+ response = client.post("/delete", data={"expense_id": "x", "month": "2026-10"})
315
+ assert response.headers["Location"].endswith("/?month=2026-10")
316
+
317
+
318
+ def test_month_value_is_escaped_in_page(client):
319
+ body = client.get("/", query_string={"month": '"><script>alert(1)</script>'}).data
320
+ assert b"<script>alert(1)</script>" not in body
@@ -0,0 +1,186 @@
1
+ def test_add_and_get(db):
2
+ db.add_expense(1250, "Food", "Lunch", "2026-10-01")
3
+ rows = db.get_expenses()
4
+ assert len(rows) == 1
5
+ _, amount, category, description, date_text = rows[0]
6
+ assert (amount, category, description, date_text) == (1250, "Food", "Lunch", "2026-10-01")
7
+
8
+
9
+ def test_default_date_is_today(db):
10
+ from datetime import date
11
+
12
+ db.add_expense(1, "Food", "x")
13
+ assert db.get_expenses()[0][4] == date.today().isoformat()
14
+
15
+
16
+ def test_expenses_sorted_newest_first(db):
17
+ db.add_expense(1, "a", "old", "2026-01-01")
18
+ db.add_expense(1, "a", "new", "2026-06-01")
19
+ assert [r[3] for r in db.get_expenses()] == ["new", "old"]
20
+
21
+
22
+ def test_delete(db):
23
+ db.add_expense(1, "a", "x", "2026-01-01")
24
+ expense_id = db.get_expenses()[0][0]
25
+ db.delete_expense(expense_id)
26
+ assert db.get_expenses() == []
27
+
28
+
29
+ def test_totals(db):
30
+ db.add_expense(10, "Food", "a", "2026-01-01")
31
+ db.add_expense(5, "Food", "b", "2026-01-02")
32
+ db.add_expense(20, "Rent", "c", "2026-01-03")
33
+ assert db.get_total() == 35
34
+ assert dict(db.get_total_by_category()) == {"Food": 15, "Rent": 20}
35
+
36
+
37
+ def test_empty_total_is_zero(db):
38
+ assert db.get_total() == 0
39
+ assert db.get_total_by_category() == []
40
+
41
+
42
+ def test_categories_empty_on_fresh_db(db):
43
+ assert db.get_categories() == []
44
+
45
+
46
+ def test_add_expense_saves_category(db):
47
+ db.add_expense(1, "Food", "x", "2026-01-01")
48
+ db.add_expense(1, "Rent", "y", "2026-01-02")
49
+ assert db.get_categories() == ["Food", "Rent"]
50
+
51
+
52
+ def test_categories_deduplicated_case_insensitive(db):
53
+ db.add_expense(1, "Food", "x", "2026-01-01")
54
+ db.add_expense(1, "food", "y", "2026-01-02")
55
+ assert db.get_categories() == ["Food"]
56
+
57
+
58
+ def test_category_kept_after_expense_deleted(db):
59
+ db.add_expense(1, "Food", "x", "2026-01-01")
60
+ db.delete_expense(db.get_expenses()[0][0])
61
+ assert db.get_categories() == ["Food"]
62
+
63
+
64
+ def test_init_db_backfills_categories(db):
65
+ import sqlite3
66
+
67
+ conn = sqlite3.connect(db.DB_PATH)
68
+ conn.execute("INSERT INTO expenses (amount_cents, category, description, date) VALUES (1, 'Old', 'x', '2026-01-01')")
69
+ conn.commit()
70
+ conn.close()
71
+ db.init_db()
72
+ assert db.get_categories() == ["Old"]
73
+
74
+
75
+ def test_get_expense(db):
76
+ db.add_expense(5, "Food", "x", "2026-01-01")
77
+ expense_id = db.get_expenses()[0][0]
78
+ assert db.get_expense(expense_id) == (expense_id, 5, "Food", "x", "2026-01-01")
79
+ assert db.get_expense(999) is None
80
+
81
+
82
+ def test_update_expense(db):
83
+ db.add_expense(5, "Food", "x", "2026-01-01")
84
+ expense_id = db.get_expenses()[0][0]
85
+ db.update_expense(expense_id, 750, "Rent", "y", "2026-02-02")
86
+ assert db.get_expense(expense_id) == (expense_id, 750, "Rent", "y", "2026-02-02")
87
+ assert db.get_categories() == ["Food", "Rent"]
88
+
89
+
90
+ def test_update_expense_keeps_date_when_none(db):
91
+ db.add_expense(5, "Food", "x", "2026-01-01")
92
+ expense_id = db.get_expenses()[0][0]
93
+ db.update_expense(expense_id, 6, "Food", "x")
94
+ assert db.get_expense(expense_id)[4] == "2026-01-01"
95
+
96
+
97
+ def test_totals_are_exact_for_cents(db):
98
+ for _ in range(10):
99
+ db.add_expense(10, "Food", "dime", "2026-01-01")
100
+ db.add_expense(20, "Food", "x", "2026-01-01")
101
+ assert db.get_total() == 120
102
+
103
+
104
+ def test_init_db_migrates_float_amounts_to_cents(tmp_path, monkeypatch):
105
+ import sqlite3
106
+
107
+ import database
108
+
109
+ path = str(tmp_path / "old.db")
110
+ monkeypatch.setattr(database, "DB_PATH", path)
111
+ conn = sqlite3.connect(path)
112
+ conn.execute(
113
+ "CREATE TABLE expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, "
114
+ "amount REAL NOT NULL, category TEXT NOT NULL, description TEXT, date TEXT NOT NULL)"
115
+ )
116
+ conn.executemany(
117
+ "INSERT INTO expenses (amount, category, description, date) VALUES (?, ?, ?, ?)",
118
+ [(12.5, "Food", "a", "2026-01-01"), (0.1 + 0.2, "Rent", "b", "2026-01-02"), (980.75, "Food", "c", "2026-01-03")],
119
+ )
120
+ conn.commit()
121
+ conn.close()
122
+
123
+ database.init_db()
124
+ assert [(r[0], r[1]) for r in database.get_expenses()[::-1]] == [(1, 1250), (2, 30), (3, 98075)]
125
+
126
+ database.init_db()
127
+ assert database.get_total() == 1250 + 30 + 98075
128
+ database.add_expense(100, "Food", "new", "2026-01-04")
129
+ assert database.get_expenses()[0][0] == 4
130
+
131
+
132
+ def add_two_months(db):
133
+ db.add_expense(1000, "Food", "oct food", "2026-10-05")
134
+ db.add_expense(2000, "Rent", "oct rent", "2026-10-01")
135
+ db.add_expense(500, "Food", "sep food", "2026-09-20")
136
+
137
+
138
+ def test_get_expenses_filtered_by_month(db):
139
+ add_two_months(db)
140
+ assert [r[3] for r in db.get_expenses(month="2026-10")] == ["oct food", "oct rent"]
141
+ assert [r[3] for r in db.get_expenses(month="2026-09")] == ["sep food"]
142
+
143
+
144
+ def test_no_month_returns_everything(db):
145
+ add_two_months(db)
146
+ assert len(db.get_expenses()) == 3
147
+ assert len(db.get_expenses(month=None)) == 3
148
+ assert len(db.get_expenses(month="")) == 3
149
+ assert db.get_total() == 3500
150
+
151
+
152
+ def test_total_filtered_by_month(db):
153
+ add_two_months(db)
154
+ assert db.get_total(month="2026-10") == 3000
155
+ assert db.get_total(month="2026-09") == 500
156
+
157
+
158
+ def test_total_by_category_filtered_by_month(db):
159
+ add_two_months(db)
160
+ assert dict(db.get_total_by_category(month="2026-10")) == {"Food": 1000, "Rent": 2000}
161
+ assert dict(db.get_total_by_category(month="2026-09")) == {"Food": 500}
162
+
163
+
164
+ def test_month_without_expenses_is_empty(db):
165
+ add_two_months(db)
166
+ assert db.get_expenses(month="2026-01") == []
167
+ assert db.get_total(month="2026-01") == 0
168
+ assert db.get_total_by_category(month="2026-01") == []
169
+
170
+
171
+ def test_month_filter_does_not_match_other_years(db):
172
+ db.add_expense(100, "Food", "this year", "2026-10-05")
173
+ db.add_expense(100, "Food", "last year", "2025-10-05")
174
+ assert [r[3] for r in db.get_expenses(month="2026-10")] == ["this year"]
175
+
176
+
177
+ def test_month_filter_uses_parameter_not_sql_text(db):
178
+ add_two_months(db)
179
+ assert db.get_expenses(month="2026-10' OR '1'='1") == []
180
+
181
+
182
+ def test_get_months_newest_first_and_distinct(db):
183
+ assert db.get_months() == []
184
+ add_two_months(db)
185
+ db.add_expense(100, "Food", "older", "2025-12-31")
186
+ assert db.get_months() == ["2026-10", "2026-09", "2025-12"]