Project Workshop — CLI File Organizer
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
Python · argparse · pytest · logging
Expected effort: 5–8 focused hours · Minimum meaningful tests: 12What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | venv create/activate/deactivate (Win+Linux) produces the specified behavior inside pip & virtual environments | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | pip install/freeze/requirements.txt produces the specified behavior inside pip & virtual environments | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | pip-tools for deterministic deps produces the specified behavior inside pip & virtual environments | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | pyproject.toml and poetry commands produces the specified behavior inside Poetry & Pipenv | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | dependency groups (dev/test) produces the specified behavior inside Poetry & Pipenv | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | when to use Poetry vs venv+pip produces the specified behavior inside Poetry & Pipenv | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | fixtures (function/class/module/session scope) produces the specified behavior inside Testing with pytest | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | parametrize for data-driven tests produces the specified behavior inside Testing with pytest | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | mocking with unittest.mock + pytest-mock produces the specified behavior inside Testing with pytest | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | coverage with pytest-cov produces the specified behavior inside Testing with pytest | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | logging levels/handlers/formatters produces the specified behavior inside Logging | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | structured JSON logging produces the specified behavior inside Logging | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | rotating file handler produces the specified behavior inside Logging | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | loguru as modern alternative produces the specified behavior inside Logging | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | ArgumentParser: positional/optional/flags produces the specified behavior inside argparse & CLI tools | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | subcommands with subparsers produces the specified behavior inside argparse & CLI tools | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | click as alternative produces the specified behavior inside argparse & CLI tools | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.1 | 10 representative pytest cases produces the specified behavior inside Testing and packaging completeness | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.2 | editable install and src layout produces the specified behavior inside Testing and packaging completeness | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.3 | dependency locking vs constraints produces the specified behavior inside Testing and packaging completeness | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.4 | CI command sequence produces the specified behavior inside Testing and packaging completeness | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── src/3│ ├── __init__.py4│ ├── cli.py5│ ├── models.py6│ ├── services.py7│ ├── repository.py8│ └── errors.py9├── tests/{test_cli.py,test_services.py,test_repository.py}10├── pyproject.toml11├── README.md12└── .gitignoreBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | pip & virtual environments | venv create/activate/deactivate (Win+Linux); pip install/freeze/requirements.txt; pip-tools for deterministic deps | Demonstration plus focused tests |
| 2 | Poetry & Pipenv | pyproject.toml and poetry commands; dependency groups (dev/test); when to use Poetry vs venv+pip | Demonstration plus focused tests |
| 3 | Testing with pytest | fixtures (function/class/module/session scope); parametrize for data-driven tests; mocking with unittest.mock + pytest-mock | Demonstration plus focused tests |
| 4 | Logging | logging levels/handlers/formatters; structured JSON logging; rotating file handler | Demonstration plus focused tests |
| 5 | argparse & CLI tools | ArgumentParser: positional/optional/flags; subcommands with subparsers; click as alternative | Demonstration plus focused tests |
| 6 | Testing and packaging completeness | 10 representative pytest cases; editable install and src layout; dependency locking vs constraints | Demonstration plus focused tests |
| 7 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
1import argparse2import logging3from pathlib import Path4
5logger = logging.getLogger("organizer")6
7def target_for(file: Path) -> str:8 return {".jpg": "Images", ".pdf": "Docs"}.get(file.suffix.lower(), "Other")9
10def build_parser() -> argparse.ArgumentParser:11 parser = argparse.ArgumentParser()12 parser.add_argument("--src-dir", type=Path, required=True)13 parser.add_argument("--dry-run", action="store_true")14 return parser15
16def main(argv: list[str] | None = None) -> int:17 args = build_parser().parse_args(argv)18 for file in args.src_dir.iterdir():19 if file.is_file():20 logger.info("plan_move", extra={"file": str(file), "bucket": target_for(file)})21 return 0Expected result
1The command exits 0 and emits one structured plan event per file.Code reading
| Line | Code | Explanation | |
|---|---|---|---|
| 1 | import argparse | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 2 | import logging | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 3 | from pathlib import Path | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 5 | logger = logging.getLogger("organizer") | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 7 | def target_for(file: Path) -> str: | Defines a function; its parameters form the explicit input boundary. | |
| 8 | return {".jpg": "Images", ".pdf": "Docs"}.get(file.suffix.lower(), "Other") | Returns the observable result to the caller and ends this invocation. | |
| 10 | def build_parser() -> argparse.ArgumentParser: | Defines a function; its parameters form the explicit input boundary. | |
| 11 | parser = argparse.ArgumentParser() | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 12 | parser.add_argument("--src-dir", type=Path, required=True) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 13 | parser.add_argument("--dry-run", action="store_true") | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 14 | return parser | Returns the observable result to the caller and ends this invocation. | |
| 16 | `def main(argv: list[str] \ | None = None) -> int:` | Defines a function; its parameters form the explicit input boundary. |
| 17 | args = build_parser().parse_args(argv) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 18 | for file in args.src_dir.iterdir(): | Consumes the iterable one item at a time through the iterator protocol. | |
| 19 | if file.is_file(): | Evaluates the condition and enters this branch only when it is truthy. | |
| 20 | logger.info("plan_move", extra={"file": str(file), "bucket": target_for(file)}) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 21 | return 0 | Returns the observable result to the caller and ends this invocation. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| pip & virtual environments | pip freeze captures the current environment, including accidental packages; it is not always a clean dependency design. | Commit declarative dependencies and a deterministic lock appropriate to the tool. |
| Poetry & Pipenv | pip freeze captures the current environment, including accidental packages; it is not always a clean dependency design. | Commit declarative dependencies and a deterministic lock appropriate to the tool. |
| Testing with pytest | Coverage measures execution, not correctness; patching the wrong import path produces deceptive tests. | Prefer behavior-focused unit tests plus a smaller number of real integration tests. |
| Logging | Do not use logs as the only audit store or interpolate expensive messages before level checks. | Log stable event names and searchable fields, excluding secrets and high-cardinality noise. |
| argparse & CLI tools | Return meaningful exit codes and write diagnostics to stderr. | Separate parsing from business logic so handlers are independently testable. |
| Testing and packaging completeness | A pipeline that builds after tests but deploys from a second unverified build breaks artifact provenance. | Make the same commands available locally, fail quickly on cheap checks, and test the wheel rather than only the source tree. |
Engineering checklist for this stack
- To do: validate CLI inputs before domain operations
- To do: use explicit exit codes and deterministic output
- To do: close files, sessions, and network clients
- To do: separate domain logic from input/printing
- To do: measure large-input memory behavior
Test strategy
Implement at least 12 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 4 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1@pytest.mark.parametrize(2 ("value", "expected"),3 [("valid", "success"), ("", "validation-error"), ("duplicate", "same-result")],4)5def test_contract(value, expected, service):6 result = service.execute(value)7 assert result.status == expected8
9def test_failure_rolls_back(repository, service):10 repository.fail_next_write()11 with pytest.raises(RepositoryError):12 service.execute("valid")13 assert repository.visible_changes() == []Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?