diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4651e57..600b931 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,12 +1,3 @@ -# DEMO TODO (Module 3 - DevOps): this CI workflow is intentionally incomplete. -# Use Copilot to finish the steps so the pipeline installs dependencies and runs pytest. -# -# Suggested goals for the live demo: -# - check out the repository -# - set up Python 3.13 -# - install dependencies from requirements-test.txt -# - run pytest with coverage - name: CI on: @@ -15,6 +6,9 @@ on: pull_request: branches: [ main ] +permissions: + contents: read + jobs: test: runs-on: ubuntu-latest @@ -22,8 +16,15 @@ jobs: - name: Checkout uses: actions/checkout@v4 - # TODO: set up Python 3.13 with actions/setup-python + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.13' + cache: pip + cache-dependency-path: requirements-test.txt - # TODO: install dependencies from requirements-test.txt + - name: Install dependencies + run: python -m pip install -r requirements-test.txt - # TODO: run pytest + - name: Run tests + run: python -m pytest diff --git a/CHANGELOG.md b/CHANGELOG.md index b8283d3..e2687f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] ### Added +- Added a top-five merchants-by-spend section to the monthly report, excluding + income and sorting ties deterministically by merchant name. +- Added table workflow and application report/entry-point tests, bringing the + configured total coverage above 90% without changing application behavior. +- Implemented expense forecasting, over-budget checks, transaction sorting, + normalized category spending alerts, and expense totals by merchant. +- Added validated, path-confined atomic CSV export and clear CSV row errors. +- Added regression tests for feature boundaries, CSV validation, and export safety. +- Added security regression tests for path containment and atomic report writes. - Revamped the repository into **Budget Buddy**, a working Personal Budget & Expense Tracker demo app for GH-300 delivery. - Added sample transaction data in [data/sample_transactions.csv](data/sample_transactions.csv). - Added a sparse starter pytest suite designed to begin around 30% coverage. @@ -15,6 +24,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - Added reusable Copilot Skills under [.github/skills](.github/skills). ### Changed +- Documented calculator public methods, including existing zero-division behavior; + retained their existing parameter and return type hints without behavior changes. +- Refactored category grouping into a single-pass aggregation with one category + normalization per expense, preserving input data and expense-only totals. +- Completed Docker and GitHub Actions setup, including dependency installation + and the existing pytest coverage gate. CI uses pip caching and read-only + repository permissions; the image copies app/data without local environments + or Git metadata. Updated demo completion notes. +- Confined CSV/JSON reads and report writes to `base_path`, rejecting absolute, + drive-qualified, and escaping paths, including existing symlink/junction targets. +- Write JSON reports through same-directory temporary files with atomic + replacement and cleanup, preserving existing reports when writes fail. +- Updated security demo documentation; unrelated intentional issues remain. - Simplified console logging to show report messages without timestamp, logger name, or level prefixes. - Replaced arithmetic-only calculator examples with budget calculation helpers. - Replaced generic data processing examples with transaction processing helpers. @@ -24,6 +46,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Intentional Demo Gaps - Coverage is intentionally low at the start of the demo. -- Several TODOs and bugs are intentionally present for Copilot-assisted implementation. -- File handling intentionally includes a path traversal risk for security review demos. +- Original code TODOs are complete; unrelated calculator bugs and permissive + transaction-processor validation remain for Copilot-assisted exercises. +- CSV handling and path traversal are now fixed + subject to a trusted filesystem (concurrent link replacement remains a risk). - Transaction processing intentionally includes O(n^2) logic for refactoring demos. \ No newline at end of file diff --git a/DEMO_SCRIPT.md b/DEMO_SCRIPT.md index 235e551..99cbad9 100644 --- a/DEMO_SCRIPT.md +++ b/DEMO_SCRIPT.md @@ -363,7 +363,8 @@ Add concise docstrings and type hints to the public methods in calculator.py. ### 3e. DevOps snippets -The repo ships a `Dockerfile` and a CI workflow with intentional TODOs. Ask: +The Dockerfile and CI workflow are now complete. Review their implementations +using the original exercise prompt: ```text Complete the Dockerfile to run Budget Buddy, then finish the GitHub Actions workflow to install deps and run pytest. @@ -626,21 +627,20 @@ If live generation runs long, implement one narrow slice end to end: ## Annex A — DevOps files (`Dockerfile` and CI workflow) -Module 3e references these two files, but they ship **intentionally incomplete** -so you can complete them live with Copilot. This annex is a self-contained, +Module 3e references these two files, which are now complete. The original +generation prompts below can be used to review the result. This annex is a self-contained, optional deep-dive you can run any time you want a DevOps beat. Neither file is exercised by `pytest`, so finishing them won't affect the coverage journey. -### Starting state +### Completed state -| File | What's missing | +| File | What's implemented | | --- | --- | -| [Dockerfile](Dockerfile) | `WORKDIR`, dependency install, app copy, and the run command are TODO stubs. | -| [.github/workflows/ci.yml](.github/workflows/ci.yml) | Python setup, dependency install, and the pytest step are TODO stubs. | +| [Dockerfile](Dockerfile) | Python 3.13 slim, `WORKDIR`, dependencies, explicit app/data copy, and `python main.py`. | +| [.github/workflows/ci.yml](.github/workflows/ci.yml) | Python 3.13 setup, pip caching, dependency install, and pytest. | -> Talking point: both files carry guiding TODO comments. This mirrors a real -> onboarding task — "finish the pipeline" — and shows Copilot turning intent in -> comments into working DevOps config. +> Talking point: review the completed configuration, manifest-before-source +> Docker layer caching, and the shared local/CI coverage gate in `pytest.ini`. ### A1. Complete the Dockerfile @@ -661,7 +661,8 @@ docker build -t budget-buddy . docker run --rm budget-buddy ``` -> Presenter note: if Docker isn't installed, just review the generated file and +> Presenter note: Docker Desktop's Linux engine must be running. If Docker is +> unavailable, just review the generated file and > explain the layer-caching order (manifest before source). No build required to > make the teaching point. diff --git a/Dockerfile b/Dockerfile index b53b62d..153a63c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,20 +1,13 @@ # Budget Buddy container image -# DEMO TODO (Module 3 - DevOps): this Dockerfile is intentionally incomplete. -# Use Copilot to finish it so the app runs in a container. -# -# Suggested goals for the live demo: -# - choose a slim Python base image -# - set a working directory -# - install dependencies from requirements-test.txt (or a runtime requirements file) -# - copy the application code -# - set the default command to run the app FROM python:3.13-slim -# TODO: set WORKDIR +WORKDIR /app -# TODO: copy dependency manifests and install them +COPY requirements-test.txt ./ +RUN python -m pip install --no-cache-dir -r requirements-test.txt -# TODO: copy the rest of the application +COPY *.py ./ +COPY data/ ./data/ -# TODO: define the container entrypoint/command, e.g. python main.py +CMD ["python", "main.py"] diff --git a/INTENTIONAL_ISSUES.md b/INTENTIONAL_ISSUES.md index a37e2a4..3c7b0a8 100644 --- a/INTENTIONAL_ISSUES.md +++ b/INTENTIONAL_ISSUES.md @@ -20,12 +20,12 @@ Budget Buddy starts from a realistic but incomplete codebase. These issues are d | 3 | [data_processor.py](data_processor.py) | Category grouping mutates a list while using nested loops | Replace with one-pass aggregation | | 3 | [data_processor.py](data_processor.py) | Duplicate detection is O(n^2) | Use a tuple key and dictionary/set | -## DevOps TODOs (Module 3) +## Completed DevOps Work (Module 3) -| File | Issue | Suggested Improvement | +| File | Completed behavior | Verification | | --- | --- | --- | -| [Dockerfile](Dockerfile) | Image build steps are stubbed with TODOs | Complete so `python main.py` runs in a container | -| [.github/workflows/ci.yml](.github/workflows/ci.yml) | CI steps are stubbed with TODOs | Install deps and run pytest on push/PR | +| [Dockerfile](Dockerfile) | Python 3.13 slim image, dependencies, app/data copy, and `python main.py` | Build and run with Docker Desktop's Linux engine running | +| [.github/workflows/ci.yml](.github/workflows/ci.yml) | Python 3.13 setup, dependency install, and pytest with the existing coverage gate | Push or open a PR targeting main | ## TODOs For Feature Generation diff --git a/README.md b/README.md index 011a1b0..870ca75 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Budget Buddy reads sample transactions from [data/sample_transactions.csv](data/ - savings rate - largest expense - spending by category +- top five merchants by expense total - a paginated transaction table ## Main Files diff --git a/calculator.py b/calculator.py index d357212..a51450d 100644 --- a/calculator.py +++ b/calculator.py @@ -2,7 +2,7 @@ Financial calculation helpers for the Budget Buddy demo app. This module is intentionally starter-quality for GitHub Copilot demos. Some -methods work on the happy path, while selected edge cases and TODOs are left for +methods work on the happy path, while selected edge cases are left for learners to fix with Copilot. """ @@ -15,51 +15,70 @@ class BudgetCalculator: def __init__(self) -> None: + """Initialize an empty calculation history.""" self.history: List[str] = [] def total_income(self, transactions: List[Transaction]) -> float: + """Return the sum of income transaction amounts.""" total = sum(float(item["amount"]) for item in transactions if item.get("type") == "income") self.history.append(f"total_income = {total}") return total def total_expenses(self, transactions: List[Transaction]) -> float: + """Return the sum of expense transaction amounts.""" total = sum(float(item["amount"]) for item in transactions if item.get("type") == "expense") self.history.append(f"total_expenses = {total}") return total def net_cash_flow(self, transactions: List[Transaction]) -> float: + """Return total income minus total expenses.""" result = self.total_income(transactions) - self.total_expenses(transactions) self.history.append(f"net_cash_flow = {result}") return result def remaining_budget(self, monthly_budget: float, transactions: List[Transaction]) -> float: + """Return the monthly budget minus total expenses.""" result = monthly_budget - self.total_expenses(transactions) self.history.append(f"remaining_budget({monthly_budget}) = {result}") return result def average_expense(self, transactions: List[Transaction]) -> float: + """Return mean expense amount; raise ZeroDivisionError if no expenses exist.""" expenses = [float(item["amount"]) for item in transactions if item.get("type") == "expense"] result = sum(expenses) / len(expenses) self.history.append(f"average_expense = {result}") return result def category_percentage(self, category_total: float, total_expenses: float) -> float: + """Return category share as a percentage; raise ZeroDivisionError for a zero total.""" result = (category_total / total_expenses) * 100 self.history.append(f"category_percentage = {result}") return result def savings_rate(self, income: float, expenses: float) -> float: - result = ((income - expenses) / income) * 100 + """Return savings as a percentage of income, or 0.0 for zero income.""" + result = 0.0 if income == 0 else ((income - expenses) / income) * 100 self.history.append(f"savings_rate = {result}") return result - # TODO: Implement forecast_month_end_spend(transactions, days_elapsed, days_in_month) - # It should estimate month-end spending from current month-to-date expenses. + def forecast_month_end_spend( + self, transactions: List[Transaction], days_elapsed: int, days_in_month: int + ) -> float: + """Project month-to-date expenses over a valid elapsed day range.""" + if days_in_month <= 0 or not 1 <= days_elapsed <= days_in_month: + raise ValueError("Days must satisfy 1 <= days_elapsed <= days_in_month") + result = self.total_expenses(transactions) / days_elapsed * days_in_month + self.history.append(f"forecast_month_end_spend = {result}") + return result - # TODO: Implement is_over_budget(monthly_budget, transactions) - # It should return True when expenses exceed the monthly budget. + def is_over_budget(self, monthly_budget: float, transactions: List[Transaction]) -> bool: + """Return whether expenses strictly exceed the monthly budget.""" + result = self.total_expenses(transactions) > monthly_budget + self.history.append(f"is_over_budget({monthly_budget}) = {result}") + return result def get_history(self) -> List[str]: + """Return a copy of the recorded calculation history.""" return self.history.copy() diff --git a/data_processor.py b/data_processor.py index 8d11ff2..034edcc 100644 --- a/data_processor.py +++ b/data_processor.py @@ -1,8 +1,8 @@ """ Transaction processing helpers for the Budget Buddy demo app. -This starter module intentionally includes inefficient logic, permissive -validation, and TODOs so GitHub Copilot can improve it during the workshop. +This module intentionally retains inefficient logic and permissive validation +so GitHub Copilot can improve it during the workshop. """ from collections import defaultdict @@ -35,22 +35,14 @@ def expenses_only(self, transactions: List[Transaction]) -> List[Transaction]: return [item for item in transactions if item.get("type") == "expense"] def group_expenses_by_category(self, transactions: List[Transaction]) -> Dict[str, float]: - """Return expense totals grouped by category.""" + """Return normalized expense totals with a single pass over transactions.""" self.processed_count += 1 totals: Dict[str, float] = defaultdict(float) - expenses = self.expenses_only(transactions) - - # PERFORMANCE ISSUE: This nested loop is easy to refactor with one pass. - for expense in expenses: + for expense in transactions: + if expense.get("type") != "expense": + continue category = self.normalize_category(str(expense.get("category", ""))) - for candidate in expenses: - candidate_category = self.normalize_category(str(candidate.get("category", ""))) - if candidate_category == category: - totals[category] += float(candidate.get("amount", 0)) - expenses = [ - item for item in expenses - if self.normalize_category(str(item.get("category", ""))) != category - ] + totals[category] += float(expense.get("amount", 0)) return dict(totals) @@ -86,14 +78,54 @@ def validate_transaction(self, transaction: Transaction) -> bool: return True - # TODO: Create sort_transactions(transactions, field, descending=False) - # It should sort by date, merchant, category, or amount and reject unknown fields. - - # TODO: Create spending_alerts(transactions, category_limits) - # It should return categories where spending is above the configured limit. + def sort_transactions( + self, transactions: List[Transaction], field: str, descending: bool = False + ) -> List[Transaction]: + """Return a sorted copy, using numeric comparison for amounts.""" + if field not in ("date", "merchant", "category", "amount"): + raise ValueError(f"Unsupported sort field: {field}") + self.processed_count += 1 + if field == "amount": + return sorted(transactions, key=lambda item: float(item[field]), reverse=descending) + return sorted(transactions, key=lambda item: str(item[field]), reverse=descending) + + def spending_alerts( + self, transactions: List[Transaction], category_limits: Dict[str, float] + ) -> Dict[str, float]: + """Return normalized categories and spending totals above their limits.""" + self.processed_count += 1 + totals: Dict[str, float] = defaultdict(float) + for item in self.expenses_only(transactions): + category = self.normalize_category(str(item.get("category", ""))) + totals[category] += float(item["amount"]) + limits = {self.normalize_category(category): limit + for category, limit in category_limits.items()} + return {category: total for category, total in totals.items() + if category in limits and total > limits[category]} + + def summarize_by_merchant(self, transactions: List[Transaction]) -> Dict[str, float]: + """Return expense totals by merchant, excluding income.""" + self.processed_count += 1 + totals: Dict[str, float] = defaultdict(float) + for item in self.expenses_only(transactions): + totals[str(item["merchant"])] += float(item["amount"]) + return dict(totals) - # TODO: Create summarize_by_merchant(transactions) - # It should return total spending by merchant. + def top_merchants( + self, transactions: List[Transaction], limit: int = 5 + ) -> List[Transaction]: + """Return the highest-spend merchants, ordered by spend then name.""" + if limit < 0: + raise ValueError("limit must be nonnegative") + merchant_totals = self.summarize_by_merchant(transactions) + ranked = sorted( + merchant_totals.items(), + key=lambda item: (-item[1], item[0].casefold(), item[0]), + ) + return [ + {"merchant": merchant, "amount": amount} + for merchant, amount in ranked[:limit] + ] def get_processed_count(self) -> int: """Return the number of processing operations performed.""" diff --git a/file_handler.py b/file_handler.py index 2c81277..81c2975 100644 --- a/file_handler.py +++ b/file_handler.py @@ -1,17 +1,22 @@ -""" -File loading helpers for the Budget Buddy demo app. +"""File loading helpers with confined paths and atomic report writes. -This module intentionally starts with simple file handling and a path traversal -gap so Copilot can demonstrate secure refactoring and test generation. +The base directory must not be writable by untrusted users: path validation +does not prevent concurrent symlink or junction replacement. """ import csv +from datetime import date import json +import math +import ntpath import os +from pathlib import Path +import tempfile from typing import Dict, List Transaction = Dict[str, object] +CSV_FIELDS = ("date", "merchant", "category", "amount", "type") class BudgetFileHandler: @@ -22,54 +27,123 @@ def __init__(self, base_path: str = ".") -> None: self.base_path = base_path self.files_processed: List[str] = [] + def _resolve_safe_path(self, filename: str) -> Path: + """Resolve a relative filename inside base_path, following links.""" + if ( + not filename + or Path(filename).is_absolute() + or ntpath.isabs(filename) + or ntpath.splitdrive(filename)[0] + ): + raise ValueError("Filename must be a nonempty relative path") + + base = Path(self.base_path).resolve() + # Treat both Windows and POSIX separators as path separators. + target = (base / filename.replace("\\", "/")).resolve() + try: + target.relative_to(base) + except ValueError as exc: + raise ValueError("Filename must remain inside base_path") from exc + + if target == base: + raise ValueError("Filename must identify a file") + return target + def read_transactions_csv(self, filename: str) -> List[Transaction]: """Read transactions from a CSV file.""" - filepath = os.path.join(self.base_path, filename) + filepath = self._resolve_safe_path(filename) transactions: List[Transaction] = [] with open(filepath, "r", encoding="utf-8", newline="") as file: - reader = csv.DictReader(file) - for row in reader: - transactions.append( - { - "date": row["date"], - "merchant": row["merchant"], - "category": row["category"], - "amount": float(row["amount"]), - "type": row["type"], - } - ) + reader = csv.DictReader(file, strict=True) + try: + if reader.fieldnames is None or sorted(reader.fieldnames) != sorted(CSV_FIELDS): + raise ValueError("CSV header must contain date, merchant, category, amount, type") + for row in reader: + transactions.append(self._validate_csv_row(row, reader.line_num)) + except csv.Error as exc: + raise ValueError(f"CSV row {reader.line_num}: {exc}") from exc self.files_processed.append(filename) return transactions + def _validate_csv_row(self, row: Transaction, line_number: int) -> Transaction: + try: + if set(row) != set(CSV_FIELDS): + raise ValueError("incorrect number of columns") + for field in CSV_FIELDS: + if row[field] is None or not str(row[field]).strip(): + raise ValueError(f"missing {field}") + date.fromisoformat(str(row["date"])) + amount = float(row["amount"]) + if not math.isfinite(amount) or amount < 0: + raise ValueError("amount must be finite and nonnegative") + if row["type"] not in ("income", "expense"): + raise ValueError("type must be income or expense") + except (KeyError, TypeError, ValueError, OverflowError) as exc: + raise ValueError(f"CSV row {line_number}: {exc}") from exc + return {**row, "amount": amount} + + def write_transactions_csv(self, filename: str, transactions: List[Transaction]) -> None: + """Atomically export transactions using the reader's CSV columns.""" + filepath = self._resolve_safe_path(filename) + temporary_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", newline="", dir=filepath.parent, + prefix=".budget-transactions-", suffix=".tmp", delete=False, + ) as file: + temporary_path = Path(file.name) + writer = csv.DictWriter(file, fieldnames=CSV_FIELDS) + writer.writeheader() + for line_number, transaction in enumerate(transactions, start=2): + writer.writerow(self._validate_csv_row(transaction, line_number)) + file.flush() + os.fsync(file.fileno()) + os.replace(temporary_path, filepath) + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + self.files_processed.append(filename) + def read_transactions_json(self, filename: str) -> List[Transaction]: """Read transactions from a JSON file.""" - filepath = os.path.join(self.base_path, filename) + filepath = self._resolve_safe_path(filename) with open(filepath, "r", encoding="utf-8") as file: data = json.load(file) self.files_processed.append(filename) return data def write_report_json(self, filename: str, report: Dict[str, object]) -> None: - """Write a summary report as JSON.""" - filepath = os.path.join(self.base_path, filename) - with open(filepath, "w", encoding="utf-8") as file: - json.dump(report, file, indent=2) + """Atomically replace a summary report inside base_path.""" + filepath = self._resolve_safe_path(filename) + temporary_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=filepath.parent, + prefix=".budget-report-", + suffix=".tmp", + delete=False, + ) as file: + temporary_path = Path(file.name) + json.dump(report, file, indent=2) + file.flush() + os.fsync(file.fileno()) + + # Close the temporary file before replacement for Windows support. + os.replace(temporary_path, filepath) + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + self.files_processed.append(filename) def get_processed_files(self) -> List[str]: """Return processed files.""" return self.files_processed.copy() - # TODO: Create write_transactions_csv(filename, transactions) - # It should preserve the same CSV headers used by read_transactions_csv. - - # TODO: Create _resolve_safe_path(filename) - # It should block absolute paths and traversal outside base_path. - - # TODO: Improve read_transactions_csv to reject malformed rows with clear errors. - # Backward-compatible alias used by older demo prompts. FileHandler = BudgetFileHandler \ No newline at end of file diff --git a/main.py b/main.py index 1b9c57c..22fb1a5 100644 --- a/main.py +++ b/main.py @@ -20,6 +20,7 @@ def build_report(monthly_budget: float, transactions: list[dict[str, object]]) - expenses = calculator.total_expenses(transactions) income = calculator.total_income(transactions) category_totals = processor.group_expenses_by_category(transactions) + top_merchants = processor.top_merchants(transactions) return { "monthly_budget": monthly_budget, @@ -30,6 +31,7 @@ def build_report(monthly_budget: float, transactions: list[dict[str, object]]) - "savings_rate": calculator.savings_rate(income, expenses), "largest_expense": processor.largest_expense(transactions), "category_totals": category_totals, + "top_merchants": top_merchants, } @@ -54,6 +56,24 @@ def show_transactions(transactions: list[dict[str, object]]) -> None: ) +def show_top_merchants(merchants: list[dict[str, object]]) -> None: + """Log the highest-spend merchants as a compact table.""" + logger.info("Top merchants by spend") + if not merchants: + logger.info("No expense transactions.") + return + + columns = [ + ColumnDefinition("merchant", "Merchant"), + ColumnDefinition("amount", "Amount", formatter=format_currency), + ] + table = DataTable(merchants, columns, rows_per_page=5) + logger.info("Merchant | Amount") + logger.info("----------------------|----------") + for item in table.get_current_page(): + logger.info(f"{item['merchant']:<20} | {format_currency(item['amount']):>8}") + + def main() -> None: """Run the Budget Buddy demo app.""" monthly_budget = 3200.00 @@ -73,6 +93,7 @@ def main() -> None: logger.info(f"Savings rate: {report['savings_rate']:.1f}%") logger.info(f"Largest expense: {report['largest_expense']}") logger.info(f"Category totals: {report['category_totals']}") + show_top_merchants(report["top_merchants"]) logger.info("Demo-start app completed. Now use Copilot to harden it.") diff --git a/pytest.ini b/pytest.ini index 79dc735..aa56878 100644 --- a/pytest.ini +++ b/pytest.ini @@ -23,7 +23,7 @@ addopts = --cov-report=term-missing --cov-report=html # Demo-start coverage threshold. The workshop goal is to use Copilot to reach 90%+. - --cov-fail-under=30 + --cov-fail-under=90 # Show warnings -W default @@ -45,7 +45,7 @@ omit = [coverage:report] # Demo-start minimum; trainers raise this to 90 after generating tests. -fail_under = 30 +fail_under = 90 # Show missing lines show_missing = True # Skip covered files in report diff --git a/tests/test_data_table.py b/tests/test_data_table.py new file mode 100644 index 0000000..ddb66d4 --- /dev/null +++ b/tests/test_data_table.py @@ -0,0 +1,135 @@ +from types import SimpleNamespace + +import pytest + +from data_table import ( + ColumnDefinition, DataTable, apply_search, get_paginated_data, + process_table_data, sort_data, +) + + +@pytest.fixture +def columns() -> list[ColumnDefinition]: + return [ColumnDefinition("name", "Name"), ColumnDefinition("age", "Age")] + + +@pytest.fixture +def rows() -> list[dict[str, object]]: + return [{"name": "Charlie", "age": 30}, {"name": "Alice", "age": 20}, + {"name": "Bob", "age": 25}] + + +def test_table_pagination_and_metadata(rows, columns) -> None: + table = DataTable(rows, columns, rows_per_page=2) + assert table.get_columns() == columns + assert table.get_current_page() == rows[:2] + assert not table.is_empty() + assert table.get_page_info() == { + "current_page": 1, "total_pages": 2, "total_rows": 3, + "start_row": 1, "end_row": 2, "has_prev": False, "has_next": True, + } + table.set_page(2) + assert table.get_current_page() == rows[2:] + assert table.get_page_info() == { + "current_page": 2, "total_pages": 2, "total_rows": 3, + "start_row": 3, "end_row": 3, "has_prev": True, "has_next": False, + } + for page in (0, 3): + with pytest.raises(ValueError, match="Page must be between"): + table.set_page(page) + + +def test_table_empty_state_and_invalid_page_size(columns) -> None: + table = DataTable([], columns) + assert table.is_empty() + assert table.get_current_page() == [] + assert table.get_total_pages() == 1 + assert table.get_page_info() == { + "current_page": 1, "total_pages": 1, "total_rows": 0, + "start_row": 0, "end_row": 0, "has_prev": False, "has_next": False, + } + table.set_page(1) + with pytest.raises(ValueError, match="rows_per_page"): + DataTable([], columns, rows_per_page=0) + + +def test_search_sort_and_reset(rows, columns) -> None: + original = [row.copy() for row in rows] + table = DataTable(rows, columns, rows_per_page=1) + table.set_page(2) + table.search(" ALI ") + assert table.get_search_query() == "ali" + assert table.get_current_page() == [rows[1]] + assert table.get_page_info()["current_page"] == 1 + table.search("not found") + assert table.is_empty() + table.search(" ") + assert table.get_total_rows() == 3 + table.sort("age", ascending=False) + assert table.get_current_page() == [rows[0]] + assert table.get_sort_state() == {"column": "age", "ascending": False} + table.sort("name") + assert table.get_current_page() == [rows[1]] + table.reset() + assert table.get_current_page() == rows[:1] + assert table.get_search_query() == "" + assert table.get_sort_state() == {"column": None, "ascending": True} + assert rows == original + + +def test_sort_rejects_unknown_and_unsortable_columns(rows) -> None: + table = DataTable(rows, [ColumnDefinition("name", "Name", sortable=False)]) + with pytest.raises(ValueError, match="not found"): + table.sort("missing") + with pytest.raises(ValueError, match="not sortable"): + table.sort("name") + + +def test_object_rows_missing_values_and_formatters(columns) -> None: + item = SimpleNamespace(name="Alice", age=20) + table = DataTable([item, SimpleNamespace()], columns) + table.search("20") + assert table.get_current_page() == [item] + assert table.format_cell(item, columns[0]) == "Alice" + assert table.format_cell(item, ColumnDefinition("missing", "Missing")) == "" + assert table.format_cell(item, ColumnDefinition("age", "Age", formatter=lambda value: f"{value} years")) == "20 years" + + +def test_pure_search_and_sort_support_objects_and_missing_values(columns) -> None: + objects = [SimpleNamespace(name="Bob"), SimpleNamespace(name="Alice"), SimpleNamespace()] + assert apply_search(objects, columns, " ALI ") == [objects[1]] + assert apply_search(objects, columns, "nothing") == [] + assert apply_search(objects, columns, " ") == objects + assert sort_data(objects, "name") == [objects[2], objects[1], objects[0]] + rows = [{"name": "Bob"}, {"name": "Alice"}, {}] + original = rows.copy() + assert sort_data(rows, "name", ascending=False) == [rows[0], rows[1], rows[2]] + assert rows == original + + +@pytest.mark.parametrize("page,size", [(0, 2), (1, 0), (1, -1)]) +def test_pure_pagination_rejects_invalid_input(page: int, size: int) -> None: + with pytest.raises(ValueError): + get_paginated_data([1, 2, 3], page, size) + + +def test_pure_pagination_slices_without_mutation() -> None: + rows = [1, 2, 3] + assert get_paginated_data(rows, 2, 2) == [3] + assert get_paginated_data(rows, 3, 2) == [] + assert rows == [1, 2, 3] + + +def test_combined_processing_and_page_clamping(rows, columns) -> None: + result = process_table_data(rows, columns, search_query="a", sort_column="age", + sort_ascending=False, page=99, rows_per_page=1) + assert result == { + "rows": [rows[1]], "total_rows": 2, "total_pages": 2, + "current_page": 2, "has_prev": True, "has_next": False, + "start_row": 2, "end_row": 2, + } + assert process_table_data(rows, columns, page=0)["current_page"] == 1 + assert process_table_data([], columns, page=9) == { + "rows": [], "total_rows": 0, "total_pages": 1, "current_page": 1, + "has_prev": False, "has_next": False, "start_row": 0, "end_row": 0, + } \ No newline at end of file diff --git a/tests/test_file_handler_security.py b/tests/test_file_handler_security.py new file mode 100644 index 0000000..36e1144 --- /dev/null +++ b/tests/test_file_handler_security.py @@ -0,0 +1,154 @@ +"""Regression tests for confined paths and atomic report writes.""" + +import json +from pathlib import Path + +import pytest + +from file_handler import BudgetFileHandler + + +OPERATIONS = [ + "read_transactions_csv", + "read_transactions_json", + "write_report_json", +] + + +def _perform(handler: BudgetFileHandler, operation: str, filename: str) -> None: + method = getattr(handler, operation) + if operation == "write_report_json": + method(filename, {"total": 25}) + else: + method(filename) + + +@pytest.mark.parametrize("operation", OPERATIONS) +@pytest.mark.parametrize( + "filename", + [ + "../outside.json", + r"..\outside.json", + "../base-sibling/outside.json", + r"C:\outside.json", + "C:outside.json", + r"\outside.json", + r"\\server\share\outside.json", + "", + ".", + ], +) +def test_rejects_unsafe_paths( + tmp_path: Path, operation: str, filename: str +) -> None: + base = tmp_path / "base" + base.mkdir() + handler = BudgetFileHandler(str(base)) + + with pytest.raises(ValueError): + _perform(handler, operation, filename) + + assert handler.get_processed_files() == [] + assert list(base.iterdir()) == [] + + +@pytest.mark.parametrize("operation", OPERATIONS) +def test_rejects_absolute_paths(tmp_path: Path, operation: str) -> None: + handler = BudgetFileHandler(str(tmp_path)) + + with pytest.raises(ValueError): + _perform(handler, operation, str(tmp_path / "outside.json")) + + assert handler.get_processed_files() == [] + + +@pytest.mark.parametrize("operation", OPERATIONS) +def test_rejects_posix_absolute_paths(tmp_path: Path, operation: str) -> None: + handler = BudgetFileHandler(str(tmp_path)) + + with pytest.raises(ValueError): + _perform(handler, operation, "/tmp/outside.json") + + assert handler.get_processed_files() == [] + + +@pytest.mark.parametrize("operation", OPERATIONS) +def test_rejects_symlink_escape(tmp_path: Path, operation: str) -> None: + base = tmp_path / "base" + base.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + try: + (base / "link").symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Symlink creation requires platform support and permissions") + + handler = BudgetFileHandler(str(base)) + with pytest.raises(ValueError): + _perform(handler, operation, "link/report.json") + + assert handler.get_processed_files() == [] + assert list(outside.iterdir()) == [] + + +def test_valid_nested_files(tmp_path: Path) -> None: + nested = tmp_path / "nested" + nested.mkdir() + transactions = [{"merchant": "Grocery", "amount": 12.5}] + (nested / "transactions.json").write_text( + json.dumps(transactions), encoding="utf-8" + ) + (nested / "transactions.csv").write_text( + "date,merchant,category,amount,type\n" + "2026-06-02,Grocery,Groceries,12.5,expense\n", + encoding="utf-8", + ) + handler = BudgetFileHandler(str(tmp_path)) + + assert handler.read_transactions_json("nested/transactions.json") == transactions + assert handler.read_transactions_csv("nested/transactions.csv")[0]["amount"] == 12.5 + destination = nested / "report.json" + destination.write_text('{"old": true}', encoding="utf-8") + handler.write_report_json("nested/report.json", {"total": 12.5}) + + assert json.loads(destination.read_text(encoding="utf-8")) == {"total": 12.5} + assert handler.get_processed_files() == [ + "nested/transactions.json", "nested/transactions.csv", "nested/report.json" + ] + assert sorted(path.name for path in nested.iterdir()) == [ + "report.json", "transactions.csv", "transactions.json" + ] + + +def test_failed_serialization_preserves_report(tmp_path: Path) -> None: + destination = tmp_path / "report.json" + original = '{"original": true}' + destination.write_text(original, encoding="utf-8") + handler = BudgetFileHandler(str(tmp_path)) + + with pytest.raises(TypeError): + handler.write_report_json("report.json", {"invalid": object()}) + + assert destination.read_text(encoding="utf-8") == original + assert list(tmp_path.iterdir()) == [destination] + assert handler.get_processed_files() == [] + + +def test_failed_replace_preserves_report( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + destination = tmp_path / "report.json" + original = '{"original": true}' + destination.write_text(original, encoding="utf-8") + handler = BudgetFileHandler(str(tmp_path)) + + def fail_replace(source: Path, target: Path) -> None: + raise PermissionError("Replacement denied") + + monkeypatch.setattr("file_handler.os.replace", fail_replace) + with pytest.raises(PermissionError): + handler.write_report_json("report.json", {"total": 25}) + + assert destination.read_text(encoding="utf-8") == original + assert list(tmp_path.iterdir()) == [destination] + assert handler.get_processed_files() == [] diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..3fe18cb --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,110 @@ +import runpy +from pathlib import Path + +import pytest + +import main as app + + +def test_build_report_calculates_totals(sample_transactions) -> None: + report = app.build_report(1000.0, sample_transactions) + assert report == { + "monthly_budget": 1000.0, "income": 5000.0, "expenses": 160.0, + "remaining_budget": 840.0, "net_cash_flow": 4840.0, + "savings_rate": pytest.approx(96.8), + "largest_expense": sample_transactions[1], + "category_totals": {"Groceries": 120.0, "Transport": 40.0}, + "top_merchants": [ + {"merchant": "Grocery", "amount": 120.0}, + {"merchant": "Transit", "amount": 40.0}, + ], + } + + +def test_build_report_without_transactions() -> None: + assert app.build_report(1000.0, []) == { + "monthly_budget": 1000.0, "income": 0, "expenses": 0, + "remaining_budget": 1000.0, "net_cash_flow": 0, + "savings_rate": 0.0, "largest_expense": None, "category_totals": {}, + "top_merchants": [], + } + + +def test_show_top_merchants_formats_table(monkeypatch) -> None: + messages = [] + monkeypatch.setattr(app.logger, "info", messages.append) + app.show_top_merchants([ + {"merchant": "Grocery", "amount": 120.5}, + {"merchant": "Transit", "amount": 40.0}, + ]) + assert messages == [ + "Top merchants by spend", "Merchant | Amount", + "----------------------|----------", "Grocery | $120.50", + "Transit | $40.00", + ] + + +def test_show_top_merchants_handles_empty_input(monkeypatch) -> None: + messages = [] + monkeypatch.setattr(app.logger, "info", messages.append) + app.show_top_merchants([]) + assert messages == ["Top merchants by spend", "No expense transactions."] + + +@pytest.mark.parametrize("value,expected", [ + (1234.5, "$1,234.50"), (0, "$0.00"), (-12.5, "$-12.50"), ("2.5", "$2.50"), +]) +def test_format_currency(value: object, expected: str) -> None: + assert app.format_currency(value) == expected + + +def test_format_currency_rejects_invalid_values() -> None: + with pytest.raises(ValueError): + app.format_currency("invalid") + with pytest.raises(TypeError): + app.format_currency(None) + + +def test_show_transactions_limits_output_to_first_page(monkeypatch, sample_transactions) -> None: + messages = [] + monkeypatch.setattr(app.logger, "info", messages.append) + transactions = [{**sample_transactions[1], "merchant": f"Shop {index}"} + for index in range(7)] + app.show_transactions(transactions) + assert messages[0] == "Recent transactions" + assert len(messages) == 9 + assert "Shop 0" in messages[3] + assert "$120.00" in messages[3] + assert "Shop 5" in messages[-1] + assert not any("Shop 6" in message for message in messages) + + +@pytest.mark.parametrize("as_script", [False, True]) +def test_entry_point_reads_temporary_data( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, as_script: bool +) -> None: + data = tmp_path / "data" + data.mkdir() + (data / "sample_transactions.csv").write_text( + "date,merchant,category,amount,type\n" + "2026-06-01,Payroll,Income,1000,income\n" + "2026-06-02,Shop,Food,100,expense\n", + encoding="utf-8", + ) + messages = [] + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(app.logger, "info", messages.append) + if as_script: + runpy.run_module("main", run_name="__main__") + else: + app.main() + assert "Budget Buddy - GitHub Copilot Demo App" in messages + assert "Monthly budget: $3,200.00" in messages + assert "Income: $1,000.00" in messages + assert "Expenses: $100.00" in messages + assert "Remaining budget: $3,100.00" in messages + assert "Net cash flow: $900.00" in messages + assert "Savings rate: 90.0%" in messages + assert "Category totals: {'Food': 100.0}" in messages + assert "Top merchants by spend" in messages + assert "Shop | $100.00" in messages \ No newline at end of file diff --git a/tests/test_savings_rate_demo.py b/tests/test_savings_rate_demo.py new file mode 100644 index 0000000..574d754 --- /dev/null +++ b/tests/test_savings_rate_demo.py @@ -0,0 +1,15 @@ +import pytest + +from calculator import BudgetCalculator + + +def test_savings_rate_with_zero_income_and_zero_expenses() -> None: + assert BudgetCalculator().savings_rate(0.0, 0.0) == 0.0 + + +def test_savings_rate_with_zero_income_and_positive_expenses() -> None: + assert BudgetCalculator().savings_rate(0.0, 100.0) == 0.0 + + +def test_savings_rate_with_positive_income() -> None: + assert BudgetCalculator().savings_rate(1000.0, 800.0) == pytest.approx(20.0) \ No newline at end of file diff --git a/tests/test_transaction_processor.py b/tests/test_transaction_processor.py index 8757e97..c89bc2c 100644 --- a/tests/test_transaction_processor.py +++ b/tests/test_transaction_processor.py @@ -1,5 +1,9 @@ """Starter tests for TransactionProcessor.""" +import pytest + +from data_processor import TransactionProcessor + def test_filter_by_month(processor, sample_transactions): """Filter transactions by a YYYY-MM prefix.""" @@ -14,4 +18,126 @@ def test_largest_expense(processor, sample_transactions): def test_validate_transaction_accepts_required_fields(processor, sample_transactions): """Validate a complete happy-path transaction.""" - assert processor.validate_transaction(sample_transactions[0]) is True \ No newline at end of file + assert processor.validate_transaction(sample_transactions[0]) is True + + +def test_group_expenses_normalizes_categories_and_preserves_input(processor) -> None: + transactions = [ + {"type": "expense", "category": " food ", "amount": "10.5"}, + {"type": "income", "category": "Food", "amount": 1000}, + {"type": "expense", "category": "FOOD", "amount": 2.5}, + {"type": "expense", "category": "Travel", "amount": 5}, + {"type": "expense"}, + {"category": "Food", "amount": 100}, + ] + original = [item.copy() for item in transactions] + assert processor.group_expenses_by_category(transactions) == { + "Food": 13.0, "Travel": 5.0, "": 0.0, + } + assert transactions == original + assert processor.group_expenses_by_category([]) == {} + + +def test_empty_expense_selection(processor) -> None: + transactions = [{"type": "income", "amount": 100}] + assert processor.expenses_only(transactions) == [] + assert processor.largest_expense(transactions) is None + assert processor.largest_expense([]) is None + + +def test_duplicate_detection_uses_date_amount_and_merchant(processor) -> None: + first = {"date": "2026-06-02", "amount": 10, "merchant": "Shop", "category": "Food"} + matching = {**first, "category": "Other"} + transactions = [first, first.copy(), matching, + {**first, "date": "2026-06-03"}, + {**first, "amount": 11}, {**first, "merchant": "Cafe"}] + original = [item.copy() for item in transactions] + assert processor.find_duplicate_transactions(transactions) == [first, matching] + assert transactions == original + assert processor.find_duplicate_transactions([]) == [] + assert processor.find_duplicate_transactions([first]) == [] + + +@pytest.mark.parametrize("field", ["date", "merchant", "category", "amount", "type"]) +def test_validation_rejects_missing_fields(processor, sample_transactions, field: str) -> None: + transaction = sample_transactions[0].copy() + del transaction[field] + assert processor.validate_transaction(transaction) is False + + +@pytest.mark.parametrize("field", ["date", "merchant", "category", "amount"]) +@pytest.mark.parametrize("descending", [False, True]) +def test_sort_transactions_preserves_input( + processor, sample_transactions, field: str, descending: bool +) -> None: + original = sample_transactions.copy() + result = processor.sort_transactions(sample_transactions, field, descending) + assert result == sorted(original, key=lambda item: item[field], reverse=descending) + assert result is not sample_transactions + assert sample_transactions == original + + +def test_sort_amounts_numerically_and_reject_invalid_input(processor) -> None: + transactions = [{"amount": "100"}, {"amount": "20"}] + assert processor.sort_transactions(transactions, "amount") == transactions[::-1] + assert processor.sort_transactions([], "date") == [] + with pytest.raises(ValueError, match="Unsupported sort field"): + processor.sort_transactions([], "type") + with pytest.raises(ValueError): + processor.sort_transactions([{"amount": "invalid"}], "amount") + with pytest.raises(KeyError, match="amount"): + processor.sort_transactions([{}], "amount") + + +def test_spending_alerts_normalize_categories_and_apply_strict_limits(processor) -> None: + transactions = [ + {"type": "expense", "category": " food ", "amount": "10"}, + {"type": "expense", "category": "FOOD", "amount": 15}, + {"type": "expense", "category": "Travel", "amount": 20}, + {"type": "expense", "category": "Other", "amount": 100}, + {"type": "income", "category": "Food", "amount": 1000}, + ] + assert processor.spending_alerts(transactions, {"food": 20, " Travel ": 20}) == {"Food": 25} + assert processor.spending_alerts(transactions, {}) == {} + assert processor.spending_alerts([], {"Food": 0}) == {} + + +def test_summarize_by_merchant_excludes_income(processor) -> None: + transactions = [ + {"type": "expense", "merchant": "Shop", "amount": "10"}, + {"type": "expense", "merchant": "Shop", "amount": 15}, + {"type": "expense", "merchant": "Cafe", "amount": 5}, + {"type": "income", "merchant": "Shop", "amount": 1000}, + ] + assert processor.summarize_by_merchant(transactions) == {"Shop": 25, "Cafe": 5} + assert processor.summarize_by_merchant([]) == {} + + +def test_top_merchants_ranks_expenses_with_stable_ties(processor) -> None: + transactions = [ + {"type": "expense", "merchant": "Zeta", "amount": 30}, + {"type": "expense", "merchant": "Beta", "amount": 50}, + {"type": "expense", "merchant": "Alpha", "amount": 50}, + {"type": "expense", "merchant": "Zeta", "amount": 25}, + {"type": "income", "merchant": "Payroll", "amount": 1000}, + ] + assert processor.top_merchants(transactions, limit=2) == [ + {"merchant": "Zeta", "amount": 55.0}, + {"merchant": "Alpha", "amount": 50.0}, + ] + assert processor.top_merchants(transactions) == [ + {"merchant": "Zeta", "amount": 55.0}, + {"merchant": "Alpha", "amount": 50.0}, + {"merchant": "Beta", "amount": 50.0}, + ] + assert processor.top_merchants([], limit=5) == [] + assert processor.top_merchants(transactions, limit=0) == [] + with pytest.raises(ValueError, match="limit"): + processor.top_merchants(transactions, limit=-1) + + +def test_processed_count_tracks_operations() -> None: + processor = TransactionProcessor() + assert processor.get_processed_count() == 0 + assert processor.normalize_category(" food ") == "Food" + assert processor.get_processed_count() == 1 \ No newline at end of file