diff --git a/.github/workflows/template-security-scan.yml b/.github/workflows/template-security-scan.yml index d5682cd9..faaf6c1d 100644 --- a/.github/workflows/template-security-scan.yml +++ b/.github/workflows/template-security-scan.yml @@ -88,6 +88,7 @@ jobs: templates = [] total_vulnerabilities = 0 affected_templates = [] + failed_templates = [] for name in template_names: audit_file = os.path.join(temp_dir, f"{name}.json") @@ -119,13 +120,24 @@ jobs: else: print(f"❌ pip-audit failed for {name}: {entry['error']}") + if "error" in entry: + failed_templates.append(name) + templates.append(entry) + scan_total = len(template_names) + failed_count = len(failed_templates) + scanned_ok = scan_total - failed_count + results = { "scan_date": scan_date, "templates": templates, "total_vulnerabilities": total_vulnerabilities, "affected_templates": " ".join(affected_templates), + "scan_total": scan_total, + "scanned_ok": scanned_ok, + "failed_count": failed_count, + "failed_templates": " ".join(failed_templates), } with open(results_file, "w") as rf: @@ -136,6 +148,10 @@ jobs: with open(github_output, "a") as gh: gh.write(f"total_vulnerabilities={total_vulnerabilities}\n") gh.write(f"affected_templates={' '.join(affected_templates)}\n") + gh.write(f"scan_total={scan_total}\n") + gh.write(f"scanned_ok={scanned_ok}\n") + gh.write(f"failed_count={failed_count}\n") + gh.write(f"failed_templates={' '.join(failed_templates)}\n") PYEOF - name: Upload scan results @@ -160,6 +176,11 @@ jobs: try { const results = JSON.parse(fs.readFileSync('security_scan_results.json', 'utf8')); + issueBody += `**Scanned:** ${results.scanned_ok}/${results.scan_total} templates\n\n`; + if (results.failed_count > 0) { + issueBody += `> ⚠️ **Incomplete scan:** pip-audit failed for ${results.failed_count} template(s): ${results.failed_templates}\n\n`; + } + results.templates.forEach(template => { if (template.error) { issueBody += `### ❌ ${template.template}\n\n`; @@ -215,16 +236,59 @@ jobs: - name: Report Summary if: always() + env: + TOTAL_VULNERABILITIES: ${{ steps.scan.outputs.total_vulnerabilities }} + AFFECTED_TEMPLATES: ${{ steps.scan.outputs.affected_templates }} + SCAN_TOTAL: ${{ steps.scan.outputs.scan_total }} + SCANNED_OK: ${{ steps.scan.outputs.scanned_ok }} + FAILED_TEMPLATES: ${{ steps.scan.outputs.failed_templates }} run: | echo "## 🔒 Security Scan Summary" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY + echo "Scanned: ${SCANNED_OK:-0}/${SCAN_TOTAL:-0} templates" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + + if [ -z "$SCAN_TOTAL" ] || [ "$SCAN_TOTAL" = "0" ]; then + echo "❌ **No templates were scanned (scan did not run or no templates were discovered). The result is incomplete.**" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + elif [ "$SCANNED_OK" != "$SCAN_TOTAL" ]; then + echo "❌ **Some scans failed, so the result is incomplete.**" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "Failed templates: $FAILED_TEMPLATES" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + fi - if [ "${{ steps.scan.outputs.total_vulnerabilities }}" = "0" ]; then - echo "✅ **No vulnerabilities found in any template!**" >> $GITHUB_STEP_SUMMARY - else - echo "⚠️ **Found ${{ steps.scan.outputs.total_vulnerabilities }} vulnerabilities**" >> $GITHUB_STEP_SUMMARY + if [ "$TOTAL_VULNERABILITIES" = "0" ]; then + if [ -n "$SCAN_TOTAL" ] && [ "$SCAN_TOTAL" != "0" ] && [ "$SCANNED_OK" = "$SCAN_TOTAL" ]; then + echo "✅ **No vulnerabilities found in any template!**" >> $GITHUB_STEP_SUMMARY + else + echo "No vulnerabilities found in the templates that were scanned." >> $GITHUB_STEP_SUMMARY + fi + elif [ -n "$TOTAL_VULNERABILITIES" ]; then + echo "⚠️ **Found $TOTAL_VULNERABILITIES vulnerabilities**" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - echo "Affected templates: ${{ steps.scan.outputs.affected_templates }}" >> $GITHUB_STEP_SUMMARY + echo "Affected templates: $AFFECTED_TEMPLATES" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "A GitHub Issue has been created with detailed information." >> $GITHUB_STEP_SUMMARY fi + + - name: Fail if any scan did not complete + if: always() + env: + SCAN_OUTCOME: ${{ steps.scan.outcome }} + SCAN_TOTAL: ${{ steps.scan.outputs.scan_total }} + SCANNED_OK: ${{ steps.scan.outputs.scanned_ok }} + FAILED_TEMPLATES: ${{ steps.scan.outputs.failed_templates }} + run: | + if [ "$SCAN_OUTCOME" != "success" ]; then + echo "::error::Scan step did not complete successfully (outcome: $SCAN_OUTCOME)" + exit 1 + fi + if [ -z "$SCAN_TOTAL" ] || [ "$SCAN_TOTAL" = "0" ]; then + echo "::error::No templates were discovered to scan" + exit 1 + fi + if [ "$SCANNED_OK" != "$SCAN_TOTAL" ]; then + echo "::error::Scan incomplete ($SCANNED_OK/$SCAN_TOTAL). Failed templates: $FAILED_TEMPLATES" + exit 1 + fi diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c2fc2144..32b243bd 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,14 +10,32 @@ on: jobs: test-fastapi-fastkit-sources: - runs-on: ubuntu-latest + name: test (${{ matrix.os }}, py${{ matrix.python-version }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 30 strategy: + fail-fast: false matrix: + os: + - ubuntu-latest python-version: - - "3.12" # the only supported version (requires-python = ">=3.12") + - "3.12" # the oldest supported version (requires-python = ">=3.12") - "3.13" - "3.14" - fail-fast: false + include: + # Windows: the oldest and the newest supported Python. + - os: windows-latest + python-version: "3.12" + - os: windows-latest + python-version: "3.14" + defaults: + run: + shell: bash + env: + # Hard links from the uv cache fail across drives on Windows runners. + UV_LINK_MODE: copy + # PYTHONUTF8 / PYTHONIOENCODING are deliberately not set: the Windows + # runner's cp1252 console is part of what these jobs test. steps: - name: Checkout code uses: actions/checkout@v4 @@ -40,10 +58,16 @@ jobs: run: pdm install -G dev - name: Run tests with coverage + if: runner.os == 'Linux' run: | pdm run pytest --cov=src/fastapi_fastkit --cov-report=term-missing --cov-report=xml --cov-fail-under=70 + - name: Run tests + if: runner.os != 'Linux' + run: pdm run pytest + - name: Upload coverage to Codecov + if: runner.os == 'Linux' uses: codecov/codecov-action@v4 with: file: ./coverage.xml @@ -51,3 +75,51 @@ jobs: name: codecov-umbrella fail_ci_if_error: false token: ${{ secrets.CODECOV_TOKEN }} + + # Windows runners use cp1252; this job covers what they cannot: implicit + # locale encodings (EncodingWarning) and a non-UTF-8 C locale, which is how + # cp949 / cp932 / cp936 machines read files that lack an explicit encoding. + encoding-guard: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + UV_LINK_MODE: copy + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Setup PDM + uses: pdm-project/setup-pdm@v4 + + - name: Install package managers for tests + run: | + pip install uv + pip install poetry + + - name: Install dependencies + run: pdm install -G dev + + - name: Fail on implicit text encodings in fastapi_fastkit + env: + PYTHONWARNDEFAULTENCODING: "1" + # An ini-style filter (-o) matches the module as a prefix, so it + # covers every fastapi_fastkit submodule; -W would only match the + # top-level package name exactly. + run: | + pdm run pytest -q -o "filterwarnings=error::EncodingWarning:fastapi_fastkit" + + - name: Run tests under a non-UTF-8 C locale + env: + LC_ALL: C + LANG: C + PYTHONCOERCECLOCALE: "0" + PYTHONUTF8: "0" + # Keeps pytest's own output readable; file reads still use the + # C locale's ASCII codec unless fastkit passes an encoding. + PYTHONIOENCODING: utf-8 + run: pdm run pytest -q -m "not extended" diff --git a/CHANGELOG.md b/CHANGELOG.md index cf38bf80..bd6fc5f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,96 +1,184 @@ # Changelog +## v1.5.2 (2026-12-01) + +### Security + +- Templates ship `.env.example` instead of `.env` (template authors: `.env-tpl` is now `.env.example-tpl`). `init` and `startdemo` create the local `.env` from it with a freshly generated `SECRET_KEY`, so projects no longer share the public example key. An existing `.env` is never overwritten, and the generated key is never printed. +- Every template's `.gitignore` now ignores `.env` and `.env.*` and keeps `.env.example`; before, most templates did not ignore `.env`, and `fastapi-mcp` had no `.gitignore` at all. +- `fastapi-auth-jwt`, `fastapi-llm-agent`, `fastapi-domain-starter` and `fastapi-sqlmodel` refuse to start with `ENVIRONMENT=production` and an example `SECRET_KEY`. `fastapi-mcp` also refuses a missing `SECRET_KEY` or `ENABLE_DEMO_USERS=true` in production. Templates with `src/core/config.py` already rejected `changethis` outside `development`. +- `fastapi-mcp`: the MCP endpoint had no authentication, and `MCP_API_KEY` had no effect. It now requires `Authorization: Bearer ` when `MCP_API_KEY` is set, and a valid JWT access token otherwise. +- `fastapi-mcp`: the demo accounts (`user1`, `user2`, `admin`) exist only with the new `ENABLE_DEMO_USERS=true` (default `false`), and the default `SECRET_KEY` is a random per-process key instead of a fixed string. +- `fastapi-auth-jwt`: refresh-token rotation runs in one transaction, so a refresh token can be used only once even under concurrent requests, and its stored expiry is checked. `RefreshTokenRepository.revoke(record)` is replaced by `revoke_if_active(jti)`. +- `fastkit init` with the CORS utility no longer allows every origin with credentials: CORS is enabled only for the origins in `BACKEND_CORS_ORIGINS`, and `*` turns credentials off. +- `fastkit init` auth modules (JWT, OAuth2, Session-based) no longer ship a default secret. They sign with `SECRET_KEY` from `.env` and refuse to start with a missing or example key in production. `SESSION_SECRET_KEY` is no longer read. + +### Templates + +- `fastapi-mcp`: new `ENVIRONMENT` setting; `MCP_MOUNT_PATH` is now honoured (the server always mounted at `/mcp`); `BACKEND_CORS_ORIGINS` accepts a comma-separated value. Known limitation: in `MCP_API_KEY` mode, tools that call JWT-protected endpoints return `401` (see the template README). +- `fastapi-custom-response`: `.gitignore` no longer hides the project's `scripts/` directory. +- Every template ships a `.gitattributes` that keeps LF in shell scripts, Dockerfiles, compose files, `Makefile` and `.env` files, even with `core.autocrlf=true`. +- `uvloop` is no longer installed on Windows, which it does not support. +- `fastapi-auth-jwt`, `fastapi-domain-starter`, `fastapi-llm-agent`, `fastapi-mcp` and `fastapi-sqlmodel` ship tests for the production guard, and `fastapi-auth-jwt` for refresh-token rotation. + +### CLI + +- `fastkit init --config ` never prompts and always creates `.//`. An unusable config, an existing project directory or a generation failure now exits with status 1 instead of 0. `--yes` has no effect with `--config`. +- Plain and `--interactive` `init` exit with status 1 on an invalid project name, an existing project directory or a generation failure. Declining a confirmation still exits 0; `startdemo` exit statuses are unchanged. +- In-place deployment that would overwrite files now refuses to run without a terminal (CI, piped input) unless `--yes` is given; `init` then exits with status 1 and `startdemo` with 0. +- Config files with a UTF-8 BOM now load; UTF-16 and UTF-32 files fail with an error that explains how to re-save them. `--save-config` writes LF line endings. +- uv, PDM and Poetry no longer replace the template's `pyproject.toml` with a fixed skeleton: fastkit edits only the dependency and build sections it owns and keeps everything else, including `requires-python`. If it cannot edit the file safely, it stops with an error; an invalid `pyproject.toml` is kept as `pyproject.toml.bak`. +- `--package-manager pip` now works when fastkit itself was installed with `uv tool install` or pipx, instead of silently switching to uv. A `requirements.txt` is written whenever the manager actually used is not pip. +- `fastkit addroute` no longer drops an import whose text is part of an existing one (`user` next to `users`), which caused a `NameError` at runtime. +- Generated tooling passes its own checks: `.pre-commit-config.yaml` no longer requires `python3.12` on `PATH`, ruff no longer flags FastAPI's `Depends` / `Query` defaults (B008), and injected imports are sorted. This was checked by hand; there is no automated end-to-end test yet. +- With `classic-layered` and `domain-starter`, Pagination no longer generates an example router that replaced the template's items list (`GET /api/v1/items`). It adds `add_pagination(app)` to `main.py` with a comment on how to paginate the existing endpoint. `minimal` and `single-module` keep the example router. +- Projects with a SQL database (PostgreSQL, MySQL or SQLite) now depend on `sqlalchemy[asyncio]`. Plain `sqlalchemy` could install without `greenlet`, and the app or Alembic then failed at import. +- `fastkit init` projects with Prometheus monitoring (`minimal`, `single-module`) no longer crash at startup. + +### Windows / Portability + +- fastkit reads and writes every file as UTF-8, writes generated files with LF, and keeps the existing line endings when it edits a file in place. +- Console output on non-UTF-8 consoles and pipes no longer crashes, and `list-templates` and interactive template selection work on non-UTF-8 locales. +- `list-templates` and the other info tables no longer split template names across lines on an 80-column console (79 usable columns on a Windows console); long descriptions wrap instead. +- `deleteproject`, rollback, `runserver`, package-manager calls, prompts and the template inspector now handle Windows paths, read-only files, `.cmd` / `.bat` shims and Git Bash. +- The debug log falls back to `~/.fastapi-fastkit/logs` when the package directory is not writable. +- Windows behaviour is covered by tests that simulate Windows and by the new `windows-latest` CI job; it has not been verified by hand on a Windows machine. Generated projects' `scripts/*.sh` still need Git Bash or WSL. + +### Documentation + +- The English docs cover the changes above: the generated `.env` / `.env.example`, `init --config` and exit statuses, Windows notes, how package managers keep `pyproject.toml`, Pagination per preset, the MCP security defaults and the new template-authoring rules. +- The translated locales (ko/ja/zh/es/fr/de) are not re-synced in this release; `reference/translation-status` lists the affected pages. Where a translation disagrees with English, English applies. + +### Maintenance + +- CI tests on `windows-latest` and adds an `encoding-guard` job. Check names change to `test (, py)`; update required status checks accordingly. +- The template security scan now fails when a template could not be scanned, instead of reporting a clean result. + +### Upgrade notes for existing projects + +These apply to projects generated with v1.5.1 or earlier. Upgrading fastkit does not change an existing project. + +1. **If `.env` was committed:** add these rules to `.gitignore`, run `git rm --cached .env`, commit, and keep a copy without real values as `.env.example`. + + ```gitignore + .env + .env.* + !.env.example + ``` + + The old file stays in Git history, so rotate every secret it contained (`SECRET_KEY`, database passwords, `ANTHROPIC_API_KEY` / `LLM_AUTH_TOKEN`, `MCP_API_KEY`, `FIRST_SUPERUSER_PASSWORD`, ...). Rewrite history only if the old values must also disappear from the repository. + +2. **Replace the example `SECRET_KEY`** (`changethis` or another `changethis-...` value) with a key from `python -c "import secrets; print(secrets.token_urlsafe(32))"`. Users have to log in again afterwards. + +3. **`fastapi-mcp`:** in `src/mcp_server/router.py`, pass `auth_config=AuthConfig(dependencies=[Depends(verify_mcp_access)])` to `FastApiMCP(...)`, and compare the key with `secrets.compare_digest` in `verify_mcp_access`. Remove the hard-coded demo users from `src/api/routes/auth.py` or put them behind `ENABLE_DEMO_USERS`. A newly generated project shows the full change. + +4. **`fastapi-auth-jwt`:** compare `src/app/domains/auth/repository.py` and `service.py` with a newly generated project to get transactional rotation; code that calls `revoke(record)` must move to `revoke_if_active(jti)` inside `atomic()`. + +5. **SQL database in a `fastkit init` project:** change `sqlalchemy` to `sqlalchemy[asyncio]` (or add `greenlet`) in `pyproject.toml` and `requirements.txt`, then reinstall. + +6. **Prometheus in a `fastkit init` project:** move `Instrumentator().instrument(app).expose(app)` out of `lifespan` to the line after `app = FastAPI(...)`. + +7. **CORS in a `fastkit init` project:** replace `allow_origins=["*"]` with your frontend origins, or set `allow_credentials=False`. + +8. **JWT, OAuth2 or Session-based auth in a `fastkit init` project:** remove the default `"your-secret-key-here-change-in-production"` / `"change-me-in-production"` from the auth module and set a unique `SECRET_KEY` in `.env` and in the deployment environment. + +9. **Pagination with `classic-layered` or `domain-starter`:** delete `features/pagination.py` and its import and `include_router` line in `main.py`. + +10. **Scripts and CI that call `fastkit init`:** `init` can now exit with status 1, and `init --config` no longer asks whether to create a project folder; it always creates `.//` and ignores `--yes`, so adjust piped answers and paths. + +### Notes + +- New projects get a `.env` that Git ignores. Commit `.env.example` and keep real values in `.env` or in the deployment environment. +- An in-place deployment keeps an existing `.env`; check that its `SECRET_KEY` is not an example value. + ## v1.5.1 (2026-10-27) ### Security -- Templates: `black` pinned to 26.10.1 in 11 templates and the `black>=26.10.1` floor applied to every `pyproject.toml-tpl` and the `fastapi-mcp` `setup.cfg-tpl` (GHSA-cg8m-r9f2-5wm2); `certifi` 2026.10.23 in 9 templates (GHSA-6q48-6c7w-9gw2, critical); `fastapi-dockerized` pins `setuptools==84.2.1` (GHSA-xmj3-9gf7-h52w); `fastapi-mcp` pins `mcp==1.30.0` with constraint `mcp>=1.30.0,<2.0.0` (GHSA-84m7-p3x7-pcfv). `pip-audit` reports no known vulnerabilities for all 12 template `requirements.txt-tpl` files (#86, #88, #90). -- Workspace: 40 open Dependabot alerts resolved (#90). Docs group floor `certifi>=2026.10.19` (GHSA-6q48-6c7w-9gw2, critical, transitive via `requests`); dev extra floors `black>=26.10.1`, `virtualenv>=21.14.9` (GHSA-8rjx-v5ww-45pp, GHSA-c947-3pg5-gm8q, GHSA-5vjq-rrrf-7h2q, GHSA-vxj4-q4g9-crj7 and 12 related advisories, transitive via `pre-commit`) and new `filelock>=4.2.1` (GHSA-v4x8-3wr5-3wq8 plus two related advisories, transitive via `virtualenv`). `uv.lock`, `pdm.lock`, `requirements.txt`, and `requirements-docs.txt` relocked on certifi 2026.10.23, black 26.10.1, virtualenv 21.14.13, filelock 4.2.4; `distlib`, `packaging`, and `python-discovery` moved as `virtualenv` requirements. +- Templates: `black` (GHSA-cg8m-r9f2-5wm2), `certifi` (GHSA-6q48-6c7w-9gw2, critical), `setuptools` in `fastapi-dockerized` (GHSA-xmj3-9gf7-h52w) and `mcp` in `fastapi-mcp` (GHSA-84m7-p3x7-pcfv) upgraded. `pip-audit` reports no known vulnerabilities in any template (#86, #88, #90). +- Workspace: 40 open Dependabot alerts resolved by raising `certifi`, `black`, `virtualenv` and `filelock` (GHSA-6q48-6c7w-9gw2, GHSA-8rjx-v5ww-45pp and 18 more) (#90). ### Maintenance -- `scripts/update_nav_translations.py` moved its AI fallback from `gpt-4` (retired by OpenAI on 2026-10-23) to `gpt-5.6-sol`, using `max_completion_tokens=1000` and dropping `temperature`, which reasoning models reject (contributed by @brunobuddy, #89). +- `scripts/update_nav_translations.py` moved its AI fallback from the retired `gpt-4` to `gpt-5.6-sol` (contributed by @brunobuddy, #89). ### Notes -- `mcp` 1.30.0 changes some defaults in generated `fastapi-mcp` projects: HTTP clients follow redirects only within the same origin, idle Streamable HTTP sessions close after 30 minutes (`FastMCP(session_idle_timeout=None, max_sessions=None)` disables this), and the OAuth client validates the authorization server's `issuer`. The template's own tests pass unchanged. +- `mcp` 1.30.0 changes some defaults in `fastapi-mcp` projects: redirects are followed only within the same origin, idle Streamable HTTP sessions close after 30 minutes, and the OAuth client validates the authorization server's `issuer`. ## v1.5.0 (2026-10-14) ### Features -- `fastkit addroute --layout classic-layer|domain` (contributed by @vastimofeev, #83). Without the option, the layout is resolved from `[tool.fastapi-fastkit]`: `preset = "domain-starter"` selects `domain`, other presets keep `classic-layer`; when no preset is recorded (`startdemo`, older `init` projects), a `template = "fastapi-domain-starter"` entry selects `domain`. The resolved layout is shown in the confirmation table. -- `domain` layout generates `domains//` with `models.py`, `schemas.py`, `repository.py`, `service.py`, `router.py`, and a re-exporting `__init__.py`; class names are derived from the route (`health_checks` → `HealthChecksService`). The example is a typed CRUD API backed by a thread-safe in-memory repository (process-local, lost on restart) with a `reset_store()` hook, and is registered in the shared API router with `prefix="/"` and `tags=[""]`. -- Re-running `addroute` is idempotent for both layouts: existing files are kept, existing `include_router` registrations (positional or `router=` keyword form) are not duplicated, and custom prefix/options on an existing registration are preserved with an info message. An unparsable router module falls back to text insertion, and import aliases (`_router`, `_2`, …) let same-named modules from different layouts coexist. +- `fastkit addroute --layout classic-layer|domain` (contributed by @vastimofeev, #83). Without the option, `domain-starter` projects get the `domain` layout and others keep `classic-layer`; the chosen layout is shown before generation. +- The `domain` layout generates `domains//` with models, schemas, repository, service and router, an in-memory CRUD example, and registers it in the API router. +- Re-running `addroute` is safe: existing files and router registrations are kept, not duplicated. ### Templates -- `fastapi-domain-starter`: the shipped `items` domain now follows the same convention (`APIRouter()` in the domain, `prefix="/items", tags=["items"]` on `include_router`; endpoints unchanged), and `tests/conftest.py` resets the in-memory store of every domain that exposes `service.reset_store()` before and after each test, so generated domains stay isolated (#83). +- `fastapi-domain-starter`: the `items` domain follows the same convention, and tests reset each domain's in-memory store so generated domains stay isolated (#83). ### Security -- `PyJWT` floor raised to 2.15.1 in `fastapi-auth-jwt` and `fastapi-mcp` (PYSEC-2026-4140 ~ 4152); `fastapi-mcp` pins `urllib3==2.8.0` (PYSEC-2026-4175 ~ 4177). -- Workspace security floors `urllib3>=2.8.0` (GHSA-gh4c-6fx4-qh6g) and `anyio>=4.14.2` (GHSA-82r6-8w77-94w6, GHSA-5p39-cfhj-2xmp) added to `pyproject.toml`; `uv.lock` (anyio 4.14.2, urllib3 2.8.0), `pdm.lock` (anyio 4.15.1, urllib3 2.8.0), and `requirements-docs.txt` (urllib3 2.8.0) relocked (#80, #82). -- Dev extra floor `virtualenv>=21.7.13` (transitive via `pre-commit`) closes GHSA-p58f-9548-mpm2 (bash/fish activation scripts execute commands embedded in paths), GHSA-x78j-v8h9-3j2q (command injection via `--prompt` in `activate.bat`), GHSA-94p9-xgh2-xp45 (seed wheels not integrity-checked) and GHSA-9h9j-4vrj-gf7g (`pyvenv.cfg` prompt injection); `requirements.txt` pinned to 21.7.16 and `uv.lock` / `pdm.lock` relocked (virtualenv 21.7.9 → 21.7.16, no other packages moved). +- `PyJWT` raised to 2.15.1 in `fastapi-auth-jwt` and `fastapi-mcp` (PYSEC-2026-4140 ~ 4152); `fastapi-mcp` pins `urllib3==2.8.0` (PYSEC-2026-4175 ~ 4177). +- Workspace floors `urllib3>=2.8.0` (GHSA-gh4c-6fx4-qh6g) and `anyio>=4.14.2` (GHSA-82r6-8w77-94w6, GHSA-5p39-cfhj-2xmp) (#80, #82). +- Dev floor `virtualenv>=21.7.13` closes GHSA-p58f-9548-mpm2, GHSA-x78j-v8h9-3j2q, GHSA-94p9-xgh2-xp45 and GHSA-9h9j-4vrj-gf7g. ### Documentation -- Docs landing pages (root and every locale) now load the logo from `img/fastkit_general_logo.png` instead of the repo-only `.github/` path (#81). -- English: `adding-routes`, `cli-reference`, and the domain-starter tutorial document `--layout` and the domain layout (#83); the MCP tutorial's `dependencies.py` snippet gains the missing `import jwt`; `development-setup` says "see above" instead of "see below". -- All six translated locales (ko/ja/zh/es/fr/de) brought to parity with English: the `auth-jwt`, `sqlmodel`, and `llm-agent` tutorials translated, drifted pages (`index`, `development-setup`, `template-creation-guide`, `preset-feature-matrix`, `template-quality-assurance`, `cli-reference`, `creating-projects`, `choosing-a-starter`, `mcp-integration`) re-synced, and the translation-status page updated (#84). The three pages changed by #83 (domain-starter tutorial, `adding-routes`, `cli-reference`) are re-synced in every locale in this release. +- Landing pages load the logo from a path that works on the docs site (#81). +- English: `adding-routes`, `cli-reference` and the domain-starter tutorial document `--layout` (#83); small fixes to the MCP tutorial and `development-setup`. +- All six translated locales (ko/ja/zh/es/fr/de) brought to parity with English, including the pages changed by #83 (#84). ### Maintenance -- `addroute` generation moved into `backend/route_generators.py` (`ClassicLayeredRouteGenerator`, `DomainRouteGenerator`, `resolve_route_layout`) and `backend/route_wiring.py` (`register_router`, `router_alias`); `add_new_route()` gained an optional `layout` argument. Suite size: **1047 tests passing**. +- `addroute` generation moved into separate modules; `add_new_route()` gained an optional `layout` argument. ### Breaking Changes -- `addroute` in a `domain-starter` project (or a project generated from `fastapi-domain-starter` without a recorded preset) now generates the domain layout instead of `api/routes` / `crud` / `schemas` modules; pass `--layout classic-layer` to keep the old output. +- `addroute` in a `domain-starter` project now generates the domain layout; pass `--layout classic-layer` to keep the old output. ## v1.4.1 (2026-09-10) ### Security -- `python-jose` → `PyJWT[crypto]` in the JWT / FastAPI-Users catalog entries and the `fastapi-mcp` template (drops the unpatched `ecdsa` CVE-2024-23342); docs dependency floors raised for Dependabot advisories (mkdocs-material ≥ 9.7.7, pymdown-extensions ≥ 11.0.1, idna ≥ 3.15; urllib3 / virtualenv / filelock refreshed in lock files). -- `passlib[bcrypt]` → `pwdlib[argon2]` in the JWT / FastAPI-Users catalog entries and the `fastapi-mcp` template (passlib is unmaintained and pinned bcrypt to 4.0.1; generated projects now hash with argon2id like `fastapi-auth-jwt`). +- `python-jose` replaced by `PyJWT[crypto]` in the JWT / FastAPI-Users options and `fastapi-mcp` (drops the unpatched `ecdsa` CVE-2024-23342); docs dependencies raised for Dependabot advisories. +- `passlib[bcrypt]` replaced by `pwdlib[argon2]` in the same places; generated projects now hash passwords with argon2id. ### Fixes -- Template inspector's compile check no longer writes bytecode and runs before the Docker test step (fixes the weekly `fastapi-psql-orm` PermissionError); Docker strategy reclaims bind-mount ownership after container runs; CI pins PDM's interpreter to 3.12; security-scan workflow now builds a valid JSON report and counts vulnerabilities correctly. -- Template inspector parses every `docker-compose ps --format json` shape (single JSON array on Compose < 2.21, NDJSON on newer releases) and falls back to the `docker compose` plugin when the standalone binary is missing. -- Docker-backed templates are smoke-tested against the container's published port instead of requiring a host virtualenv (the weekly `fastapi-psql-orm` run now reaches and passes the smoke step). -- `startdemo` / `init` normalize copied text files to LF and keep executable bits, and a new `.gitattributes` pins template line endings, so shell scripts generated on Windows or with `core.autocrlf=true` no longer fail with `bash\r: No such file or directory`. `fastapi-psql-orm` `.env` now sets `ENVIRONMENT=development`. +- Template inspector and CI fixes: the weekly `fastapi-psql-orm` inspection passes again, every `docker-compose ps` output format is parsed with a fallback to the `docker compose` plugin, Docker templates are smoke-tested on the container's port, and the security-scan report counts vulnerabilities correctly. +- `startdemo` / `init` write text files with LF and keep executable bits, so shell scripts no longer fail with `bash\r: No such file or directory`. `fastapi-psql-orm` `.env` now sets `ENVIRONMENT=development`. ## v1.4.0 (2026-09-04) ### Features -- `fastkit init --config ` (JSON/TOML/YAML) for prompt-free, reproducible generation, plus `--save-config` to capture an interactive session. Configs are normalized and schema-validated. -- `--dry-run`, `--no-venv`, `--no-install`, and `--yes` for `init` and `startdemo`. -- Generated projects record a `[tool.fastapi-fastkit]` metadata block (`template`, `preset`, `package_manager`, `app_module`, `features`); `runserver` and `addroute` use it instead of guessing the layout. -- Interactive builder now generates working code for every catalog choice (Celery/Dramatiq, Redis cache, WebSocket, Pagination, OpenTelemetry, OAuth2, Session auth) and adds three axes: `migrations` (Alembic), `tooling` (ruff, pre-commit, GitHub Actions, devcontainer, Makefile), `logging` (structured JSON). `/health` and `/ready` are always generated. -- `# fastkit:imports` / `# fastkit:routes` anchors in templates; `addroute` falls back to AST-based insertion. -- Package-manager subprocesses are bounded by timeouts (`FASTKIT_SUBPROCESS_TIMEOUT`); auto-detection prefers `uv`. +- `fastkit init --config ` (JSON/TOML/YAML) for prompt-free, reproducible generation, and `--save-config` to save an interactive session. +- `--dry-run`, `--no-venv`, `--no-install` and `--yes` for `init` and `startdemo`. +- Generated projects record a `[tool.fastapi-fastkit]` block that `runserver` and `addroute` use instead of guessing the layout. +- The interactive builder generates working code for every option and adds `migrations` (Alembic), `tooling` (ruff, pre-commit, GitHub Actions, devcontainer, Makefile) and `logging` (structured JSON). `/health` and `/ready` are always generated. +- Templates carry `# fastkit:imports` / `# fastkit:routes` anchors for `addroute`. +- Package-manager commands time out (`FASTKIT_SUBPROCESS_TIMEOUT`); auto-detection prefers `uv`. ### Templates -- New: `fastapi-auth-jwt` (refresh-token rotation, argon2, scopes), `fastapi-sqlmodel` (async SQLModel + Alembic + generic CRUD), `fastapi-llm-agent` (Claude SSE streaming with tool loop). +- New: `fastapi-auth-jwt`, `fastapi-sqlmodel` and `fastapi-llm-agent`. - Deprecated: `fastapi-dockerized`, `fastapi-async-crud` (still shipped). -- All templates aligned on Python 3.12, `setup.py-tpl` removed, self-dependency on `FastAPI-fastkit` removed, dependency pins refreshed, `fastapi-mcp` package renamed to `mcp_server` to stop shadowing the `mcp` library. +- All templates target Python 3.12, drop `setup.py-tpl` and the `FastAPI-fastkit` dependency; the `fastapi-mcp` package is renamed to `mcp_server`. ### Fixes -- Rollback on a failed run no longer deletes a project directory that existed before the run; `startdemo` refuses an existing target. -- In-place deployment only substitutes placeholders in files it copied and asks before overwriting. -- Quotes and backslashes in project name/author/description no longer break `pyproject.toml` or generated Python. +- A failed run no longer deletes a project directory that existed before it; `startdemo` refuses an existing target. +- In-place deployment asks before overwriting and only edits files it copied. +- Quotes and backslashes in the project name, author or description no longer break generated files. - Rewriting the `[tool.fastapi-fastkit]` block no longer corrupts arrays in it. ### Maintenance -- Interactive code generation moved from string concatenation to Jinja2 fragments (`src/fastapi_fastkit/fragments/`); generated apps use `lifespan` and `python:3.12-slim`. `jinja2` is the only new runtime dependency. -- Template inspector split into `fastapi_fastkit.backend.inspection` with real smoke tests (boots uvicorn, probes `/docs` and `/health`), config-consistency, dependency-drift, and placeholder-residue checks. `scripts/inspect-templates.py` gained `--offline`, `--no-smoke`, `--mypy`. -- `cli.init` orchestration extracted into `backend/scaffolder.py`; package managers share one checked-run helper. -- Docs: tutorials for the three new templates, CLI reference and starter guide updated (EN/KO). Suite size: **781 tests passing**. +- Interactive code generation uses Jinja2 templates; generated apps use `lifespan` and `python:3.12-slim`. `jinja2` is the only new runtime dependency. +- The template inspector runs real smoke tests and more consistency checks; `scripts/inspect-templates.py` gained `--offline`, `--no-smoke` and `--mypy`. +- Docs: tutorials for the new templates; CLI reference and starter guide updated (EN/KO). ### Breaking Changes @@ -98,254 +186,143 @@ - Generated projects no longer list `FastAPI-fastkit` as a runtime dependency. - `pip` is no longer auto-upgraded during environment setup. - Auto-detection prefers `uv` over `pip`; pass `--package-manager pip` to keep the old behaviour. -- `TemplateInspector` / `inspect_fastapi_template` take an `InspectionOptions` argument; check functions moved to `fastapi_fastkit.backend.inspection`. +- `TemplateInspector` / `inspect_fastapi_template` take an `InspectionOptions` argument. ## v1.3.0 (2026-05-06) ### Features -- **Architecture preset selection in interactive init** - - `fastkit init --interactive` now includes an `Architecture Preset` step with `minimal`, `single-module`, `classic-layered`, and `domain-starter`. - - The selected preset is saved in the interactive config and shown in the final summary. - - CLI help and interactive docs were updated to match the new flow. -- **Preset-aware project generation** - - Interactive generation now selects a different base template for each preset. - - `minimal` and `single-module` continue to use generated `main.py`, while `classic-layered` and `domain-starter` preserve the template-shipped entrypoint. - - Database/auth config output paths, compatibility warnings, and app module resolution are now preset-aware. - - `fastkit runserver` and generated Dockerfiles now resolve the correct app module for non-default layouts such as `src/app/main.py`. +- `fastkit init --interactive` adds an `Architecture Preset` step: `minimal`, `single-module`, `classic-layered` and `domain-starter`. +- Each preset uses its own base template; `classic-layered` and `domain-starter` keep the template's entrypoint, and `runserver` and generated Dockerfiles find the app module in layouts such as `src/app/main.py`. ### Templates -- **Add `fastapi-domain-starter` template** - - New pyproject-first, domain-oriented starter for medium-sized FastAPI APIs. - - Includes a built-in `/api/v1/health` endpoint and an example `items` domain. - - Ships with FastAPI-fastkit identity markers in `pyproject.toml`. -- Improve template metadata/path handling for the domain-oriented layout. -- Update template README titles so `fastkit list-templates` shows readable descriptions. +- New `fastapi-domain-starter` template: a domain-oriented starter with `/api/v1/health` and an example `items` domain. +- Template READMEs have titles that `fastkit list-templates` shows as descriptions. ### Documentation -- Add `Choosing a Starter` guide for template and preset selection. -- Add `Preset Feature Matrix` reference docs for preset-specific generation behavior. -- Add `fastapi-domain-starter` tutorial and generated project walkthrough. -- Add translation status and source-of-truth policy docs, plus translation status notices on the English and Korean landing pages. -- Refresh CLI examples and fix the Korean `init --interactive` walkthrough so docs match the current flow. +- New `Choosing a Starter` guide, `Preset Feature Matrix` reference, `fastapi-domain-starter` tutorial, and translation status and source-of-truth pages. +- CLI examples refreshed; the Korean `init --interactive` walkthrough fixed. ### Tests -- Add end-to-end coverage for architecture presets and `fastapi-domain-starter`. -- Add regression tests for preset layout decisions, app module derivation, and interactive summary rendering. -- Add package-manager compatibility coverage for `fastapi-domain-starter`, including the `pip` path. -- Suite size: **612 tests passing** at the close of v1.3.0. +- End-to-end and regression tests for the presets and `fastapi-domain-starter`, including the `pip` path. ### Maintenances -- **Modernize template contract to be pyproject-first** - - Template inspection now accepts `pyproject.toml-tpl` as a primary metadata source. - - Dependency inspection and `read_template_stack` now support `pyproject.toml-tpl` alongside existing files. - - Template authoring and QA docs were updated for the new contract. -- **Add pyproject-aware project identity detection** - - `is_fastkit_project()` now detects FastAPI-fastkit-managed projects from `pyproject.toml` as well as legacy `setup.py`. - - Standardize the FastAPI-fastkit description marker and `[tool.fastapi-fastkit] managed = true` metadata across shipped pyproject templates. -- Add `requirements.txt-tpl` to `fastapi-domain-starter` for full package-manager compatibility, including `pip`. +- Templates are pyproject-first: inspection and project detection read `pyproject.toml`. +- `fastapi-domain-starter` ships `requirements.txt-tpl` so it works with `pip`. ## v1.2.1 (2026-04-17) ### Fixes -- **`fastkit init` failure no longer wipes the user workspace** - - Introduced `_cleanup_failed_project` helper; the previous `shutil.rmtree(project_dir)` on error could delete the entire workspace when `create_project_folder=False` (in-place deploy). Cleanup now refuses to remove the workspace and only deletes freshly created project folders. -- **Single-module template (`fastapi-single-module`) now renders the project name** - - `inject_project_metadata()` was not substituting `` placeholders that live directly in `main.py`. Added `_process_main_file` so single-module templates come out with the correct title/name. -- **Generated test configuration written to `pytest.ini`, not `tests/conftest.py`** - - Interactive init used to dump INI-format content into a Python module, breaking the generated project's test suite immediately. Test config now lands in `pytest.ini` at the project root. -- **Poetry dependency generation now handles the full PEP 508 spec** - - `PoetryManager.generate_dependency_file` previously only split on `==`. Any other specifier (`>=`, `~=`, `<=`, `!=`, `===`), environment marker (e.g. `; sys_platform != 'win32'`), or `extras + version` combination was emitted as part of the TOML key, producing an invalid `pyproject.toml` that `poetry install` could not parse. Added `_parse_pip_requirement` to split name, extras, version specifier, and marker, emitting inline tables when needed. -- **SQLite stack now installs `aiosqlite`** - - `core/settings.py` catalog previously omitted the async driver, so SQLite projects failed at runtime when the generated code used async sessions. -- **Dockerfile `CMD` uses exec form with double-quoted JSON array** - - The previous single-quoted form was interpreted as shell form by some Docker versions and bypassed signal handling (no graceful shutdown on `SIGTERM`). +- A failed `fastkit init` with in-place deployment could delete the whole working directory; cleanup now removes only a project folder it created. +- `fastapi-single-module` projects now get the project name in `main.py`. +- Interactive init writes test configuration to `pytest.ini` instead of `tests/conftest.py`, which broke the generated test suite. +- Poetry projects get a valid `pyproject.toml` for any version specifier, marker or extra, not just `==`. +- SQLite projects now install `aiosqlite`. +- The generated Dockerfile `CMD` uses exec form, so the app shuts down gracefully on `SIGTERM`. ### Security -Addressed open Dependabot advisories by bumping minimum versions: - -- `pytest >= 9.0.3` — tmpdir handling advisory (GHSA) -- `black >= 26.3.1` — arbitrary file writes via cache file name -- `pygments >= 2.20.0` — ReDoS in GUID regex (transitive via `rich`) -- `requests >= 2.33.0` — insecure temp file reuse in `extract_zipped_paths` -- `pymdown-extensions >= 10.17.2` — required to run on `pygments` 2.20+ (prevents `html.escape(None)` crash during docs build) +- Minimum versions raised for Dependabot advisories: `pytest>=9.0.3`, `black>=26.3.1`, `pygments>=2.20.0`, `requests>=2.33.0` (and `pymdown-extensions>=10.17.2` to keep the docs building). ### Documentation -- **FAQ (`docs/en/reference/faq.md`)**: the "interactive mode automatically generates" bullets now accurately describe what is generated conditionally — database/auth files only when the selected option supports code generation, Docker files only for the selected deployment option, and coverage config only when `Coverage` or `Advanced` testing is selected. -- Contributing and development-setup guides updated; `fastkit --version` example refreshed to 1.2.1. +- FAQ: the interactive mode section now says which files are generated only for certain options. +- Contributing and development-setup guides updated. ### Maintenances -- Added regression tests for every fix above, plus targeted tests to close Codecov patch-coverage gaps (`_process_main_file` error handling, `_cleanup_failed_project` edge cases, interactive init failure branch). -- Cleaned up Ruff warnings in `src/fastapi_fastkit/cli.py` (E402 import ordering for `__version__`, four stray F541 `f""` prefixes). -- Refreshed `requirements.txt`, `requirements-docs.txt`, `pdm.lock`, and `uv.lock` to the new security floors. +- Regression tests for every fix above, Ruff warnings cleaned up in the CLI, and lock files refreshed to the new security floors. ## v1.2.0 (2025-11-27) ### Features -- **(Breaking Change) Add `fastkit init --interactive` feature**: Revolutionary feature-by-feature project builder - - `fastkit init --interactive` now provides guided project setup with intelligent feature selection - - Always uses Empty project (fastapi-empty template) as base template to prevent conflicts with DynamicConfigGenerator - - Interactive project configuration with validation and compatibility warnings - - Real-time dependency collection based on selected features - - Confirmation summary before project creation - -- **Dynamic Code Generation**: Intelligent code generation based on feature selections - - Integrated DynamicConfigGenerator for automatic code scaffolding - - Generates `main.py` with selected features (auth, database, monitoring, etc.) - - Creates database configuration files for PostgreSQL, MySQL, MongoDB, SQLite - - Generates authentication setup for JWT, OAuth2, FastAPI-Users - - Auto-generates test configuration (pytest with optional coverage) - - Docker deployment files (Dockerfile, docker-compose.yml) generation - -- **Enhanced Dependency Management**: Multi-format dependency file generation - - Automatically generates both package-manager-specific files AND requirements.txt - - Ensures pip compatibility regardless of selected package manager - - Dependencies correctly reflect all selected stack features - - Smart dependency deduplication and version management +- **(Breaking Change) `fastkit init --interactive`**: a guided, feature-by-feature project builder on top of the `fastapi-empty` template, with compatibility warnings and a summary before creation. +- Generates `main.py`, database, authentication, test and Docker files for the selected features. +- Writes the package manager's dependency file and a `requirements.txt` with the dependencies of every selected feature. ### Improvements -- **Interactive CLI Experience**: - - Step-by-step feature selection with descriptions. Each selection step proceeds in the following order below: - - Database selection (PostgreSQL, MySQL, MongoDB, Redis, SQLite) - - Authentication options (JWT, OAuth2, FastAPI-Users, Session-based) - - Background tasks (Celery, Dramatiq) - - Caching layer (Redis, fastapi-cache2) - - Monitoring integration (Loguru, OpenTelemetry, Prometheus) - - Testing framework (Basic, Coverage, Advanced) - - Utilities (CORS, Rate-Limiting, Pagination, WebSocket) - - Deployment configuration (Docker, docker-compose) - - Package manager selection (pip, uv, pdm, poetry) - - Custom package addition support +- Interactive steps: database, authentication, background tasks, caching, monitoring, testing, utilities, deployment, package manager and custom packages. ### Technical -- **Interactive Backend Architecture**: - - `InteractiveConfigBuilder`: Orchestrates full interactive flow - - `DynamicConfigGenerator`: Generates feature-specific code - - `DependencyCollector`: Intelligently collects stack dependencies - - Input validators with comprehensive error handling - - Multi-select prompts for utilities and deployment options - - Feature compatibility validation system +- The interactive backend is split into a config builder, a code generator and a dependency collector, with input validation and compatibility checks. ### Documentation -- Add AI translation support of user guides(docs/ folder sources that mkdocs renders) +- AI translation support for the user guides. ## v1.1.5 (2025-09-14) ### Improvements -- **Adaptive Console Sizing**: Enhanced terminal output display - - Console width is 80% of terminal width, capped at 120 characters - - Console height is terminal height minus buffer (5 lines) - - Automatic terminal size detection with fallback to default sizes (80x24) - - Dynamic sizing based on actual terminal dimensions +- Console output adapts to the terminal size (80% of its width, up to 120 characters). ### Fixes -- **Text Truncation Prevention**: Completely eliminated text truncation in CLI output - - Template names and descriptions are now fully displayed without "..." truncation - - Table columns automatically adjust to content length to prevent text cutting - - Added `overflow="fold"` and `no_wrap=False` settings to Rich tables - - Template listing now shows complete template names (e.g., `fastapi-custom-response` instead of `fastapi-custom-respo...`) -- **Fixing the object `console` not found error** - - this critical error was occurred every version before this version. - - this error was occurred because of the mismatched logic between distribute github actions workflow and the top `__init__.py` file of fastkit project package. - - This issue was discovered during the development of version 1.1.2, and I spent a lot of time troubleshooting it. I believe this was due to my lack of development experience. I sincerely apologize. +- CLI tables no longer truncate template names and descriptions. +- Fixed the `console` not found error that affected every earlier version. ## v1.1.4 (deprecated) -this version was hotfix build, but it is deprecated. - -The issues that were being addressed during the development of this version remained unresolved and were fixed in version v1.1.5. - -For more details, please refer to the CHANGELOG.md file for v1.1.5. +This hotfix build is deprecated; its issues were fixed in v1.1.5. ## v1.1.3 (2025-09-13) ### Templates - add `fastapi-single-module` template -- update `fastapi-psql-orm` template : fix dockerfile & docker-compose.yml scripts errors +- fix the Dockerfile and `docker-compose.yml` of `fastapi-psql-orm` ## v1.1.2 (2025-09-05) ### Improvements -- add a feature of `fastkit init`, `fastkit startdemo` command to define to make a new project folder at current working directory -- add `setuptools` package at `fastapi-empty` template's dependency list. -- add a feature of `fastkit addroute`command to recognize current working project (with cmd option `.`). +- `fastkit init` and `fastkit startdemo` can create the project in the current directory instead of a new folder. +- `fastapi-empty` lists `setuptools` as a dependency. +- `fastkit addroute` accepts `.` for the current project. ## v1.1.1 (2025-08-15) ### Improvements -- fix template inspection workflow & script - - fixing uv supportation compatibility - - for now, template inspection is running with `uv` package manager +- Template inspection workflow fixed; it now runs with `uv`. ## v1.1.0 (2025-08-08) ### Features -- **Package Manager Support**: Add comprehensive support for multiple Python package managers - - Support for UV (default), PDM, Poetry, and PIP package managers - - Interactive package manager selection in `fastkit init` and `fastkit startdemo` commands - - `--package-manager` CLI option for non-interactive usage - - Automatic generation of appropriate dependency files (`pyproject.toml` for UV/PDM/Poetry, `requirements.txt` for PIP) - - PEP 621 compliant project metadata for modern package managers - -- **Automated Template Testing System**: Revolutionary zero-configuration template testing - - Dynamic template discovery - new templates are automatically tested - - Comprehensive end-to-end testing with actual project creation - - Multi-package manager compatibility testing - - Virtual environment creation and dependency installation validation - - Project structure and FastAPI integration verification - - Parameterized testing with pytest for scalable test execution +- Support for the uv (default), PDM, Poetry and pip package managers: a selection step in `fastkit init` and `fastkit startdemo`, the `--package-manager` option, and the matching dependency files. +- Templates are tested automatically end to end with every package manager; new templates need no test configuration. ### Improvements -- **Enhanced CLI Experience**: Package manager selection with interactive prompts and helpful descriptions -- **Better Template Quality Assurance**: Multi-layer quality assurance with static inspection and dynamic testing -- **Improved Developer Experience**: Zero boilerplate test configuration for template contributors -- **Cross-Platform Compatibility**: Enhanced support for different package manager workflows +- Package manager prompts with descriptions, and template quality checks that combine static inspection with these tests. ### Documentation -- Updated all user guides with package manager selection examples -- Enhanced CLI reference with comprehensive package manager documentation -- Updated contributing guidelines with new automated testing system -- Improved template creation guide with zero-configuration testing instructions -- Enhanced template quality assurance documentation +- User guides, CLI reference, contributing guide and template guides updated for package managers and automated template testing. ### Technical -- Implemented BasePackageManager abstract class with concrete implementations -- Added PackageManagerFactory for dynamic package manager instantiation -- Enhanced project metadata injection for all package managers -- Improved test infrastructure with dynamic template discovery -- Updated CI/CD pipelines for multi-package manager testing +- Package managers share a common base class and factory; CI tests every package manager. ### Breaking Changes -- **Default Package Manager**: Changed from PIP to UV for better performance -- **CLI Prompts**: Added package manager selection step in interactive commands +- **Default Package Manager**: changed from pip to uv. +- **CLI Prompts**: interactive commands ask for a package manager. ## v1.0.2 (2025-07-02) ### Features -- add logging feature at `--debug` mode option : debugging log will be stored at package directory +- `--debug` mode writes a debug log to the package directory. ### Maintenances @@ -363,7 +340,7 @@ For more details, please refer to the CHANGELOG.md file for v1.1.5. ### Maintenances -- add a test case : test_cli_extended.py +- add CLI test cases ## v1.0.0 (2025-03-01) @@ -371,9 +348,7 @@ official release version ### Features -- rename some `fastkit` commands: - - `fastkit startup` -> `fastkit startdemo` - - `fastkit startproject` -> `fastkit init` +- rename `fastkit startup` to `fastkit startdemo` and `fastkit startproject` to `fastkit init` - add `fastkit addroute` command : for adding a route to project - add `fastkit runserver` command : for running FastAPI server @@ -403,15 +378,7 @@ initial release : pre-release version ### Features -- add `fastkit` command line base structure : `fastkit ` - - add `fastkit --help` command : for more information about fastkit command - - add `fastkit --version` command : for version information - - add `fastkit --debug` command : for debugging information - - add `fastkit echo` command : for echo test - - add `fastkit list-templates` command : for listing available templates - - add `fastkit startup` command : for starting project with template - - add `fastkit startproject`command : for starting empty FastAPI project - - add `fastkit deleteproject` command : for deleting project +- add the `fastkit` CLI with `--help`, `--version`, `--debug`, `echo`, `list-templates`, `startup`, `startproject` and `deleteproject` ### Maintenances diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be9d12ca..b7933cd6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -244,24 +244,30 @@ template-name/ │ └── utils/ ├── tests/ ├── scripts/ +├── pyproject.toml-tpl ├── requirements.txt-tpl -├── setup.py-tpl -└── README.md-tpl +├── README.md-tpl +├── .env.example-tpl +├── .gitattributes-tpl +└── .gitignore-tpl ``` 2. File Extensions: - All Python source files must use `.py-tpl` extension - - Template files must include proper configuration files (.env-tpl, etc.) + - Template files must include proper configuration files (`.env.example-tpl`, `.gitignore-tpl`, `.gitattributes-tpl`, etc.), never `.env-tpl` (fastkit generates `.env`) + - `.gitignore-tpl` must ignore `.env` and `.env.*` and keep `!.env.example` 3. Dependencies: - - Include `fastapi-fastkit` in setup.py + - Declare dependencies in `pyproject.toml-tpl` (`requires-python = ">=3.12"`); no `setup.py-tpl`, no `FastAPI-fastkit` dependency - Specify version numbers in requirements.txt - Use latest stable versions of dependencies +See [Template Creation Guide](docs/en/contributing/template-creation-guide.md) for the full rules. + ### Security Requirements 1. Implementation Requirements: - - Environment variables management (.env) + - Environment variables management (`.env.example` committed, `.env` git-ignored) - Basic authentication system - CORS configuration - Exception handling and logging diff --git a/docs/en/contributing/template-creation-guide.md b/docs/en/contributing/template-creation-guide.md index 923ea5aa..3aeb6914 100644 --- a/docs/en/contributing/template-creation-guide.md +++ b/docs/en/contributing/template-creation-guide.md @@ -101,8 +101,9 @@ fastapi-{template-name}/ ├── requirements.txt-tpl # 🟡 Optional when pyproject declares deps ├── setup.cfg-tpl # Development tools configuration ├── README.md-tpl # ✅ Project documentation (required) -├── .env-tpl # Environment variables template -└── .gitignore-tpl # Git ignore file +├── .env.example-tpl # Shareable environment variables (fastkit creates .env from it) +├── .gitattributes-tpl # Line-ending policy (LF for scripts, Docker, env files) +└── .gitignore-tpl # Git ignore file (must ignore .env) ``` **Minimum required files.** A template must provide: @@ -124,7 +125,22 @@ out-of-tree templates keep working, but it is a legacy path. **Target Python 3.12 consistently**: `requires-python = ">=3.12"`, black `target-version = ["py312"]`, mypy `python_version = "3.12"`, and `python:3.12-slim` for any Docker base image. Inspection checks that the -three pins agree. +three pins agree. fastkit keeps the template's `requires-python` in the +generated project. + +**Environment and Git files:** + +- Ship `.env.example-tpl` with placeholder values, never `.env-tpl`; fastkit + creates the project's `.env` from it with a unique `SECRET_KEY`. +- `.gitignore-tpl` must ignore `.env` and `.env.*`, re-include + `!.env.example`, and not ignore files the template ships (a bare + `[Ss]cripts` rule hides `scripts/`). +- Ship a `.gitattributes-tpl` that pins LF for shell scripts, Docker files, + `Makefile` and env files; copy one from an existing template. +- If the settings read `SECRET_KEY`, refuse to start with + `ENVIRONMENT=production` and an example key (see + `KNOWN_EXAMPLE_SECRET_KEYS` in `fastapi-auth-jwt`'s + `src/app/core/config.py-tpl`). **Never declare `FastAPI-fastkit` as a runtime dependency** of a generated project. The CLI is a development tool; a template's dependency list should @@ -233,6 +249,10 @@ build-backend = "hatchling.build" Optional when `pyproject.toml-tpl` declares `[project].dependencies`. Still useful for templates that prefer `pip`-only workflows. +Packages that do not install on every platform need an environment marker. +`uvloop` does not support Windows, so templates pin it as +`uvloop==0.22.1; sys_platform != "win32"`. + ```txt # FastAPI core dependencies (required) fastapi==0.104.1 diff --git a/docs/en/reference/preset-feature-matrix.md b/docs/en/reference/preset-feature-matrix.md index 3f9cb8cd..0aa02ad5 100644 --- a/docs/en/reference/preset-feature-matrix.md +++ b/docs/en/reference/preset-feature-matrix.md @@ -37,15 +37,15 @@ also wires them up automatically. | Feature | `minimal` / `single-module` | `classic-layered` / `domain-starter` | |---|---|---| | **Database** (PostgreSQL, MySQL, SQLite, MongoDB) | Generates the config module **and** stubs `await init_db()` calls in the regenerated `main.py`. | Generates the config module at the preset's path. The shipped `main.py` is **preserved**, so wire `get_db()` into routers manually. | -| **Authentication** (JWT, FastAPI-Users, OAuth2, Session-based) | Generates the auth config module; JWT imports `HTTPBearer`, OAuth2 and Session-based also add their `main.py` middleware setup. | Generates the auth config module at the preset's path. No imports added to `main.py` — wire dependencies manually. | -| **Background tasks** (Celery, Dramatiq) | Generates `worker.py` and `features/tasks.py`, and mounts the task router in the regenerated `main.py`. | Generates `worker.py` and `features/tasks.py`, but the shipped `main.py` is **preserved** — mount the router manually. | +| **Authentication** (JWT, FastAPI-Users, OAuth2, Session-based) | Generates the auth config module; JWT imports `HTTPBearer`, OAuth2 and Session-based also add their `main.py` middleware setup. JWT, OAuth2 and Session-based refuse to start with a missing or example `SECRET_KEY` when `ENVIRONMENT=production`. | Generates the auth config module at the preset's path. No imports added to `main.py` — wire dependencies manually. | +| **Background tasks** (Celery, Dramatiq) | Generates `worker.py` and `features/tasks.py`, and mounts the task router in the regenerated `main.py`. | Generates `worker.py` and `features/tasks.py` and mounts the task router through the `# fastkit:imports` / `# fastkit:routes` anchors of the shipped `main.py`. | | **Caching** (Redis) | Generates `features/cache.py` and mounts/initializes it in the regenerated `main.py`. | Generates `features/cache.py`; mount it manually. | -| **Utilities: Pagination / WebSocket** | Generates `features/pagination.py` / `features/websocket.py` and mounts the router in the regenerated `main.py`. | Generates the same module; mount it manually. | +| **Utilities: Pagination / WebSocket** | Generates `features/pagination.py` (a paginated demo list on `GET /api/v1/items`) / `features/websocket.py` and mounts the router in the regenerated `main.py`. | WebSocket: generates `features/websocket.py` and mounts it below the `# fastkit:routes` anchor. Pagination: no demo router, because both templates already serve an items list (`GET /items`, `GET /api/v1/items`); `add_pagination(app)` is appended to `main.py` with a comment on paginating that endpoint. | | **Monitoring: OpenTelemetry** | No standalone file — tracing setup is added directly to the regenerated `main.py`. | No standalone file. The shipped `main.py` is preserved, so tracing is **not wired** — add the setup manually. | | **Migrations** (Alembic) | Generates `alembic.ini`, `alembic/env.py`, a baseline revision and `scripts/migrate.sh` for any SQL database selection — independent of the `main.py` overlay. | Same — Alembic generation does not depend on whether `main.py` is preserved. | | **Tooling** (ruff, pre-commit, github-actions, devcontainer, makefile) | Generates the matching config file(s), independent of the `main.py` overlay. | Same. | | **Logging** (structured) | Generates `logging_config.py` and wires the request-id middleware into the regenerated `main.py`. | Generates `logging_config.py`; the shipped `main.py` is preserved, so wire the middleware manually. | -| **CORS** (utility) | `CORSMiddleware` added to the regenerated `main.py` with `allow_origins=['*']`. | **Already wired** in the shipped `main.py` (conditional on `settings.all_cors_origins`). Activate by setting `BACKEND_CORS_ORIGINS` in `.env` — no code edits required. | +| **CORS** (utility) | `CORSMiddleware` is added only when `BACKEND_CORS_ORIGINS` lists origins (comma-separated); `*` turns credentials off. | **Already wired** in the shipped `main.py` (conditional on `settings.all_cors_origins`). Activate by setting `BACKEND_CORS_ORIGINS` in `.env` — no code edits required. | | **Testing** (Basic / Coverage / Advanced) | `pytest.ini` is generated at the project root; Advanced also adds `tests/factories.py` and `tests/test_factories.py`. | Same. | | **Deployment** (Docker, docker-compose) | `Dockerfile` and/or `docker-compose.yml` written at the project root. | Same. | | **`/health` / `/ready`** | Always present in the regenerated `main.py`. | Already present in the preserved, template-shipped `main.py`. | @@ -61,11 +61,12 @@ which selections need manual wiring: |---|---| | `CORS` (utility) | ❌ — already wired in the shipped `main.py`. Just populate `BACKEND_CORS_ORIGINS` in `.env`. | | `Rate-Limiting` (utility) | ✅ — `slowapi` limiter setup is not added | -| `Pagination` / `WebSocket` (utility) | ✅ — the generated router (`features/pagination.py` / `features/websocket.py`) is not mounted | -| `Celery` / `Dramatiq` (async_tasks) | ✅ — the generated `worker.py` / `features/tasks.py` router is not mounted | +| `Pagination` / `WebSocket` (utility) | ❌ — WebSocket is mounted through `# fastkit:routes`; Pagination wires only `add_pagination(app)` and prints an info line. | +| `Celery` / `Dramatiq` (async_tasks) | ❌ — the `features/tasks.py` router is mounted through the `# fastkit:routes` anchor | | `Redis` (caching) | ✅ — the generated `features/cache.py` is not mounted or initialized | -| `Prometheus` / `OpenTelemetry` (monitoring) | ✅ — instrumentation setup is not added to `main.py` | +| `Prometheus` / `OpenTelemetry` (monitoring) | ✅ — instrumentation setup is not added to `main.py`. For Prometheus the warning shows the line to add after `app = FastAPI(...)`. | | `structured` (logging) | ✅ — `logging_config.py` is generated, but the request-id middleware is not added to `main.py` | +| `OAuth2` / `Session-based` (authentication) | ✅ — the `SessionMiddleware` setup and the auth router are not added to `main.py` | | `Alembic` (migrations), `tooling` selections | ❌ — these files are generated and usable regardless of preset; nothing depends on `main.py` | | Any database / auth selection | ⚠️ — config files are generated, but you must `Depends()` them into your routers | @@ -74,9 +75,11 @@ handles every axis above automatically; no warnings fire. ## Unsupported combinations (stay safe) -The strategist deliberately **does not** attempt to splice generated code -into a template-shipped `main.py`. Doing so would risk producing broken -imports or duplicating routers. The contract is: +The strategist changes a template-shipped `main.py` only for the +background task and WebSocket routers (through the `# fastkit:imports` / +`# fastkit:routes` anchors) and `add_pagination(app)`. Middleware, lifespan +hooks and instrumentation are never spliced in, to avoid broken imports or +duplicate setup. The contract is: - Selected packages are always installed (so `pip freeze` matches the user's intent). diff --git a/docs/en/reference/translation-status.md b/docs/en/reference/translation-status.md index e06fcce8..4b87787a 100644 --- a/docs/en/reference/translation-status.md +++ b/docs/en/reference/translation-status.md @@ -41,6 +41,13 @@ next section explains). | 🇫🇷 French (`fr`) | ✅ Complete | 29 / 29 | Phases 1-3 complete. Re-synced with the v1.5.0 English sources on 2026-10-14: the three v1.4.0 tutorials (`tutorial/auth-jwt.md`, `tutorial/sqlmodel.md`, `tutorial/llm-agent.md`) are translated and pages that had drifted since their original translation were brought back in line. `docs/fr/changelog.md` intentionally reuses the canonical English `CHANGELOG.md`. | | 🇩🇪 German (`de`) | ✅ Complete | 29 / 29 | Phases 1-3 complete. Re-synced with the v1.5.0 English sources on 2026-10-14: the three v1.4.0 tutorials (`tutorial/auth-jwt.md`, `tutorial/sqlmodel.md`, `tutorial/llm-agent.md`) are translated and pages that had drifted since their original translation were brought back in line. `docs/de/changelog.md` intentionally reuses the canonical English `CHANGELOG.md`. | +**Not yet re-synced after v1.5.2.** In all six locales these pages still +describe v1.5.1; follow the English pages until they are updated: + +- `user-guide/`: `cli-reference`, `creating-projects`, `using-templates`, `installation` +- `tutorial/`: `auth-jwt`, `domain-starter`, `llm-agent`, `sqlmodel`, `mcp-integration`, `docker-deployment` +- `contributing/template-creation-guide`, `reference/preset-feature-matrix` + *Snapshot verified 2026-10-14, after the v1.5.0 release. All six translated locales were brought to parity with the English sources: the three tutorials added in v1.4.0 were translated and every page that had drifted since its diff --git a/docs/en/tutorial/auth-jwt.md b/docs/en/tutorial/auth-jwt.md index 5174b7e8..d091fbfa 100644 --- a/docs/en/tutorial/auth-jwt.md +++ b/docs/en/tutorial/auth-jwt.md @@ -61,7 +61,8 @@ accounts-api/ ├── requirements.txt ├── alembic.ini ├── Dockerfile -├── .env # SECRET_KEY, DATABASE_URL, token lifetimes +├── .env # SECRET_KEY, DATABASE_URL, token lifetimes (git-ignored) +├── .env.example # shareable copy with placeholder values ├── scripts/ │ ├── format.sh lint.sh run-server.sh test.sh ├── src/ @@ -142,6 +143,10 @@ into the database: ```python def issue_token_pair(self, user: User) -> TokenPair: + with self.refresh_tokens.atomic(): + return self._stage_token_pair(user) + +def _stage_token_pair(self, user: User) -> TokenPair: scopes = user.scope_list access_token, _, _ = create_access_token(str(user.id), scopes) refresh_token, jti, expires_at = create_refresh_token(str(user.id), scopes) @@ -149,20 +154,33 @@ def issue_token_pair(self, user: User) -> TokenPair: return TokenPair(access_token=access_token, refresh_token=refresh_token) ``` -On refresh, the presented token is revoked **before** the new pair is -issued: +On refresh, the presented token is revoked and its successor is stored in +**one transaction** (`atomic()` commits once or rolls everything back): ```python def rotate(self, refresh_token: str) -> TokenPair: payload = decode_token(refresh_token, REFRESH_TOKEN_TYPE) - record = self.refresh_tokens.get_by_jti(str(payload.get("jti"))) - if record is None or record.revoked: - raise TokenError("refresh token is no longer valid") - ... - self.refresh_tokens.revoke(record) - return self.issue_token_pair(user) + jti = str(payload.get("jti")) + + with self.refresh_tokens.atomic(): + record = self.refresh_tokens.get_by_jti(jti) + if record is None or record.revoked: + raise TokenError("refresh token is no longer valid") + if _as_utc(record.expires_at) <= datetime.now(timezone.utc): + raise TokenError("refresh token has expired") + ... + # The read above is only a fast path; this is the real guard. + if not self.refresh_tokens.revoke_if_active(jti): + raise TokenError("refresh token is no longer valid") + + return self._stage_token_pair(user) ``` +`revoke_if_active(jti)` is a conditional `UPDATE ... WHERE jti = :jti AND +revoked = false`, so when two requests present the same refresh token, only +one gets a new pair. If storing the successor fails, the transaction rolls +back and the presented token stays valid. + Try it: refresh once, then send the *old* refresh token again. ```console @@ -263,10 +281,13 @@ $ alembic revision --autogenerate -m "add profile fields" Two settings in `.env` decide whether this is a demo or a real service: -- **`SECRET_KEY`** signs every token. Leave it unset and a random key is - generated per process — which logs everyone out on every restart, and - makes multiple workers disagree about which tokens are valid. Generate - one and pin it: +- **`SECRET_KEY`** signs every token. The generated `.env` already has a + unique key. Leave `SECRET_KEY` unset and a random + key is generated per process — which logs everyone out on every restart, + and makes multiple workers disagree about which tokens are valid. With + `ENVIRONMENT=production` the app refuses to start with an example key + such as the placeholder in `.env.example`. For a deployment, generate a + key and pin it: ```console $ python -c "import secrets; print(secrets.token_urlsafe(32))" diff --git a/docs/en/tutorial/docker-deployment.md b/docs/en/tutorial/docker-deployment.md index 04d872c7..6507afee 100644 --- a/docs/en/tutorial/docker-deployment.md +++ b/docs/en/tutorial/docker-deployment.md @@ -823,6 +823,11 @@ CORS_ORIGINS=["https://your-frontend.com"] SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id ``` +!!! warning "Keep `.env.prod` out of Git" + The generated `.gitignore` already ignores `.env.prod` (every `.env.*` + file except `.env.example`). Keep real values out of `.env.example`, or + use your platform's secret store instead of a file. + ### Production deployment command
diff --git a/docs/en/tutorial/domain-starter.md b/docs/en/tutorial/domain-starter.md index 1ca71442..3c498883 100644 --- a/docs/en/tutorial/domain-starter.md +++ b/docs/en/tutorial/domain-starter.md @@ -53,7 +53,9 @@ orders-api/ ├── README.md ├── pyproject.toml # PEP 621 metadata + [tool.fastapi-fastkit] ├── requirements.txt # pinned deps (template ships both files; you maintain them as you add packages) -├── .env # SECRET_KEY, ENVIRONMENT +├── .env # local settings, git-ignored (generated with a unique SECRET_KEY) +├── .env.example # shareable copy with placeholder values; commit this one +├── .gitattributes # LF for scripts and env files ├── .gitignore ├── scripts/ │ ├── format.sh # black + isort @@ -123,6 +125,10 @@ settings = Settings() `main.py` reads `settings.PROJECT_NAME`, `settings.API_V1_PREFIX`, and `settings.all_cors_origins` to wire the FastAPI app. +The shipped code does not read `SECRET_KEY`; it is there for signing +features you add. With `ENVIRONMENT=production` the app refuses to start +while it is an example value such as `changethis`. + **When to add to `core/`:** anything not specific to one domain — global settings, structured logging, custom middleware, security helpers, etc. diff --git a/docs/en/tutorial/llm-agent.md b/docs/en/tutorial/llm-agent.md index 999b1b50..3b33fc1d 100644 --- a/docs/en/tutorial/llm-agent.md +++ b/docs/en/tutorial/llm-agent.md @@ -36,7 +36,8 @@ Select package manager (pip, uv, pdm, poetry) [uv]: uv Do you want to proceed with project creation? [y/N]: y ``` -Put your key in `.env` before the first run: +Put your key in the generated `.env` (git-ignored, never in +`.env.example`) before the first run: ```bash ANTHROPIC_API_KEY=sk-ant-... @@ -68,7 +69,8 @@ support-agent/ ├── pyproject.toml # PEP 621 metadata + [tool.fastapi-fastkit] ├── requirements.txt ├── Dockerfile -├── .env +├── .env # local settings, git-ignored +├── .env.example # shareable copy with placeholder values ├── scripts/ │ ├── chat.sh # send one message to a running server │ ├── format.sh lint.sh run-server.sh test.sh diff --git a/docs/en/tutorial/mcp-integration.md b/docs/en/tutorial/mcp-integration.md index c1a0f358..b232efc3 100644 --- a/docs/en/tutorial/mcp-integration.md +++ b/docs/en/tutorial/mcp-integration.md @@ -82,6 +82,22 @@ Do you want to proceed with project creation? [y/N]: y
+!!! note "Security defaults of the generated project" + The generated `fastapi-mcp` project already applies these defaults + (its `README.md` has the details): + + - The MCP endpoint requires `Authorization: Bearer ` when + `MCP_API_KEY` is set, and a JWT access token from + `/api/v1/auth/login` otherwise. It is never open. + - The demo users (`user1`, `user2`, `admin`) exist only with + `ENABLE_DEMO_USERS=true`. + - With `ENVIRONMENT=production` the app refuses to start with a missing + or example `SECRET_KEY`, or with `ENABLE_DEMO_USERS=true`. + - `MCP_MOUNT_PATH` (default `/mcp`) sets where the MCP server is mounted. + + In `MCP_API_KEY` mode, tools that call JWT-protected endpoints return + `401`. + ## Step 2: Project Structure Analysis Let's examine the structure of the generated project: @@ -1463,7 +1479,8 @@ $ cd ai-integrated-api $ fastkit runserver Starting FastAPI server at 127.0.0.1:8000... -# User login +# User login (in a generated fastapi-mcp project, admin/admin123 needs +# ENABLE_DEMO_USERS=true) $ curl -X POST "http://localhost:8000/auth/login" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=admin&password=admin123" diff --git a/docs/en/tutorial/sqlmodel.md b/docs/en/tutorial/sqlmodel.md index 9ffafb4b..b04517cb 100644 --- a/docs/en/tutorial/sqlmodel.md +++ b/docs/en/tutorial/sqlmodel.md @@ -55,7 +55,8 @@ catalog-api/ ├── requirements.txt ├── alembic.ini ├── Dockerfile -├── .env +├── .env # local settings, git-ignored +├── .env.example # shareable copy with placeholder values ├── scripts/ │ ├── format.sh lint.sh migrate.sh run-server.sh test.sh ├── src/ diff --git a/docs/en/user-guide/cli-reference.md b/docs/en/user-guide/cli-reference.md index 22be0fdf..81dea8a3 100644 --- a/docs/en/user-guide/cli-reference.md +++ b/docs/en/user-guide/cli-reference.md @@ -61,7 +61,7 @@ $ fastkit init [OPTIONS] | Option | Description | Default | |--------|-------------|---------| | `--interactive` | Guided setup: architecture preset, then feature selection | off | -| `--config ` | Create the project from a saved configuration file, with no prompts | - | +| `--config ` | Create the project from a saved configuration file in a new `.//` folder, with no prompts | - | | `--save-config ` | With `--interactive`, write the answered configuration to this path | - | | `--project-name` | Project name (prompted when omitted) | - | | `--author` | Author name (prompted when omitted) | - | @@ -71,9 +71,13 @@ $ fastkit init [OPTIONS] | `--dry-run` | Show the files and packages that would be created, without writing anything | off | | `--no-venv` | Skip virtual environment creation (implies `--no-install`) | off | | `--no-install` | Skip dependency installation | off | -| `--yes` / `-y` | Do not ask for confirmation before overwriting existing files when deploying the project in place | off | +| `--yes` / `-y` | Do not ask for confirmation before overwriting existing files when deploying the project in place; required when there is no terminal. Ignored with `--config` | off | | `--help` | Show command help | - | +`init` exits with status 1 when the project name is invalid, the project +directory already exists, or generation fails. Declining a confirmation +prompt is not a failure and exits with status 0. + #### Configuration files (`--config` / `--save-config`) An interactive session's answers are a plain mapping, and that mapping can @@ -93,6 +97,12 @@ asks whether to save the selections and where to put them. That prompt only appears when a human is at the terminal — piped or CI runs stay silent and opt in with the flag instead. +`--config` never prompts: it always creates `.//` (no +in-place deployment, so `--yes` has no effect). It exits with status 1 when +the file is unusable (unreadable, invalid, missing `project_name`, or +rejected by the schema below), when the folder already exists, or when +generation fails. + **Supported formats** are chosen from the file extension: | Extension | Availability | @@ -101,6 +111,10 @@ opt in with the flag instead. | `.toml` | Always (standard library) | | `.yaml` / `.yml` | Only when PyYAML is installed — fastkit does not add it as a runtime dependency | +Config files must be UTF-8; a UTF-8 byte order mark is accepted. UTF-16 +and UTF-32 files (PowerShell 5's `>` default) are rejected; re-save them as +UTF-8. + A loaded file must contain a mapping at its top level with at least `project_name`, `author` and `author_email`. It is then validated with the same rules the interactive prompts use (project name shape, email format, @@ -211,8 +225,22 @@ replacing any file that already exists. `--yes` (or its short form `-y`) skips that confirmation and proceeds with the overwrite. It does not affect the separate "Do you want to proceed with project creation?" prompt, which is still shown. In a non-interactive environment (stdin is not a TTY, as in -CI or a piped run), the overwrite confirmation is skipped automatically -even without `--yes`. +CI or a piped run), fastkit refuses to overwrite anything unless `--yes` +is given: `init` exits with status 1 before writing any file (`startdemo` +exits with status 0). An existing `.env` is never overwritten (see +[Generated `.env` file](#generated-env-file)). + +#### Generated `.env` file + +Templates ship a shareable `.env.example`. fastkit creates the project's +`.env` from it with a fresh random `SECRET_KEY`, so no two projects share a +signing key; the key is not printed, and an existing `.env` is kept. +Feature selections add the variables they read to `.env.example` (for +example `ENVIRONMENT` for JWT, OAuth2 or Session-based auth). + +The generated `.gitignore` ignores `.env` and every `.env.*` file except +`.env.example`: commit `.env.example`, and keep real values in `.env` or in +the deployment environment. #### Interactive Prompts @@ -264,15 +292,15 @@ warnings) differ. | Axis | Choices | Installed packages | Generated files | |---|---|---|---| -| `database` | PostgreSQL, MySQL, MongoDB, Redis, SQLite, None | PostgreSQL: `asyncpg`, `sqlalchemy` · MySQL: `aiomysql`, `sqlalchemy` · MongoDB: `motor` · Redis: `redis[hiredis]` · SQLite: `sqlalchemy`, `aiosqlite` | A database config module at the preset's path (e.g. `src/config/database.py`) | +| `database` | PostgreSQL, MySQL, MongoDB, Redis, SQLite, None | PostgreSQL: `asyncpg`, `sqlalchemy[asyncio]` · MySQL: `aiomysql`, `sqlalchemy[asyncio]` · MongoDB: `motor` · Redis: `redis[hiredis]` · SQLite: `sqlalchemy[asyncio]`, `aiosqlite` | A database config module at the preset's path (e.g. `src/config/database.py`) | | `authentication` | JWT, OAuth2, FastAPI-Users, Session-based, None | JWT: `pyjwt[crypto]`, `pwdlib[argon2]` · OAuth2: `authlib`, `itsdangerous`, `httpx` · FastAPI-Users: `fastapi-users[sqlalchemy]`, `pyjwt[crypto]`, `pwdlib[argon2]` · Session-based: `itsdangerous` | An auth config module at the preset's path; OAuth2 and Session-based also add `main.py` middleware setup | | `async_tasks` | Celery, Dramatiq, None | Celery: `celery[redis]`, `redis[hiredis]` · Dramatiq: `dramatiq[redis]`, `redis[hiredis]` | `/worker.py` (background worker) + `/features/tasks.py` (task routes) | | `testing` | Basic, Coverage, Advanced, None | Basic: `pytest`, `pytest-asyncio`, `httpx` · Coverage: + `pytest-cov` · Advanced: + `faker`, `factory-boy` | `pytest.ini`; Advanced also adds `tests/factories.py` and `tests/test_factories.py` | | `caching` | Redis, None | Redis: `redis[hiredis]`, `fastapi-cache2`, `jinja2` | `/features/cache.py` (cached endpoints) | -| `monitoring` | Loguru, OpenTelemetry, Prometheus, None | Loguru: `loguru` · OpenTelemetry: `opentelemetry-api`, `opentelemetry-sdk`, `opentelemetry-instrumentation-fastapi`, `opentelemetry-exporter-otlp-proto-http` · Prometheus: `prometheus-client`, `prometheus-fastapi-instrumentator` | No standalone file — wired directly into `main.py` (import / lifespan / setup) | -| `utilities` (multi-select) | CORS, Rate-Limiting, Pagination, WebSocket, None | CORS: none (built into FastAPI) · Rate-Limiting: `slowapi` · Pagination: `fastapi-pagination` · WebSocket: `websockets` | CORS and Rate-Limiting wire into `main.py` directly; Pagination adds `/features/pagination.py`, WebSocket adds `/features/websocket.py` | +| `monitoring` | Loguru, OpenTelemetry, Prometheus, None | Loguru: `loguru` · OpenTelemetry: `opentelemetry-api`, `opentelemetry-sdk`, `opentelemetry-instrumentation-fastapi`, `opentelemetry-exporter-otlp-proto-http` · Prometheus: `prometheus-client`, `prometheus-fastapi-instrumentator` | No standalone file — wired directly into `main.py` (import / setup) | +| `utilities` (multi-select) | CORS, Rate-Limiting, Pagination, WebSocket, None | CORS: none (built into FastAPI) · Rate-Limiting: `slowapi` · Pagination: `fastapi-pagination` · WebSocket: `websockets` | CORS and Rate-Limiting wire into `main.py` directly (CORS stays off until `BACKEND_CORS_ORIGINS` is set); Pagination adds `/features/pagination.py` (a demo list on `GET /api/v1/items`), or only `add_pagination(app)` with `classic-layered` / `domain-starter`; WebSocket adds `/features/websocket.py` | | `migrations` | Alembic, None | Alembic: `alembic` | `alembic.ini`, `alembic/env.py`, `alembic/script.py.mako`, a baseline `alembic/versions/_initial.py`, `scripts/migrate.sh` — only when the database axis is a SQL database | -| `tooling` (multi-select) | ruff, pre-commit, github-actions, devcontainer, makefile, None | ruff: `ruff` · pre-commit: `pre-commit` · github-actions / devcontainer / makefile: none | ruff merges a `[tool.ruff]` block into `pyproject.toml` (or writes `ruff.toml` for `pip` projects); pre-commit writes `.pre-commit-config.yaml`; github-actions writes `.github/workflows/test.yml`; devcontainer writes `.devcontainer/devcontainer.json`; makefile writes `Makefile` | +| `tooling` (multi-select) | ruff, pre-commit, github-actions, devcontainer, makefile, None | ruff: `ruff` · pre-commit: `pre-commit` · github-actions / devcontainer / makefile: none | ruff merges a `[tool.ruff]` block into `pyproject.toml` (or writes `ruff.toml` for `pip` projects) that allows FastAPI's `Depends`, `Query`, ... defaults (B008); pre-commit writes `.pre-commit-config.yaml` without pinning a Python interpreter (without ruff, it also adds a missing `[tool.black]` table); github-actions writes `.github/workflows/test.yml`; devcontainer writes `.devcontainer/devcontainer.json`; makefile writes `Makefile` | | `logging` | structured, None | None (stdlib `logging` + `json` only) | `/logging_config.py` (structured JSON logging + request-id middleware), wired into `main.py` | Regardless of selection, every generated project gets `/health` and @@ -461,8 +489,11 @@ api_router.include_router(health.router) # fastkit:routes ``` -Keep those comments in place when you edit the file — `addroute` inserts -directly below `# fastkit:imports` and `# fastkit:routes`. A project that +Keep those comments in place when you edit the file. `addroute` registers +the router below `# fastkit:routes` and adds the import in sorted position +below `# fastkit:imports` (or in its isort section higher up), so ruff stays +clean. An import is skipped only when the same names are already imported. +A project that lost them (or was generated before the anchors existed) still works: fastkit falls back to an AST-based insertion that finds the import block and the router registrations itself. The anchors simply make the result predictable. @@ -499,7 +530,8 @@ $ fastkit startdemo [OPTIONS] Like `init`, `startdemo` refuses to run when the target project directory already exists (`Error: Project '{name}' already exists.`). `--dry-run` is the exception: since it never writes to disk, it is still allowed to target -a name that already has a directory. See +a name that already has a directory. Unlike `init`, `startdemo` still exits +with status 0 when it refuses or when generation fails. See [In-place deployment and overwrite confirmation](#in-place-deployment-and-overwrite-confirmation-yes-y) above for what `--yes` does when deploying into the current workspace. @@ -1025,6 +1057,17 @@ FastAPI-fastkit supports multiple Python package managers, allowing you to choos | **Poetry** | Python dependency management and packaging | `pyproject.toml` | Poetry-based workflows | | **PIP** | Standard Python package manager | `requirements.txt` | Traditional Python development | +Every template ships a complete `pyproject.toml`. With uv, PDM or Poetry, +`init` edits only the dependency and build sections the package manager +owns and keeps everything else, including the template's `requires-python`, +dependency groups, other `[tool.*]` tables and comments. If fastkit cannot +edit the file safely, it stops with an error; a `pyproject.toml` that is not +valid TOML is kept as `pyproject.toml.bak` and replaced. These projects +also get a `requirements.txt` with the same dependencies. + +`--package-manager pip` also works when fastkit itself runs from +`uv tool install` or pipx. + ### Specifying Package Manager #### Global Configuration diff --git a/docs/en/user-guide/creating-projects.md b/docs/en/user-guide/creating-projects.md index a2e5ab7b..c8151928 100644 --- a/docs/en/user-guide/creating-projects.md +++ b/docs/en/user-guide/creating-projects.md @@ -284,7 +284,8 @@ Contains all your application source code following the **src layout** pattern, - **config.py**: Application settings, environment variables, and configuration - Centralizes all configuration management -- Supports `.env` file for environment-specific settings +- Supports `.env` file for environment-specific settings (generated from + `.env.example`, git-ignored) #### `api/` Module @@ -420,9 +421,11 @@ INFO: Uvicorn running on http://127.0.0.1:8000 ### Environment Variables -Your project supports environment-based configuration through `.env` files: +Your project supports environment-based configuration through `.env` files. -Create a `.env` file in your project root: +fastkit generates `.env` from the template's `.env.example` with a unique +`SECRET_KEY`. `.env` is git-ignored: commit `.env.example` with placeholders +only (see [Generated `.env` file](cli-reference.md#generated-env-file)). A `.env` looks like this: ```env # .env @@ -510,7 +513,8 @@ $ git commit -m "Initial commit - FastAPI project setup" - Use `.env` files for local development - Use environment variables for production -- Never commit sensitive data to version control +- Never commit sensitive data to version control: commit `.env.example`, + not `.env` ### 4. Testing diff --git a/docs/en/user-guide/installation.md b/docs/en/user-guide/installation.md index f9050fc5..05b8fccb 100644 --- a/docs/en/user-guide/installation.md +++ b/docs/en/user-guide/installation.md @@ -9,6 +9,20 @@ To use FastAPI-fastkit, you need to meet the following requirements: - **Python**: 3.12 or higher - **Operating System**: Windows, macOS, Linux supported +### Notes for Windows + +- fastkit writes files as UTF-8 with LF line endings whatever the system + locale; characters the console cannot show are replaced with `?`. +- Generated projects include a `.gitattributes` that keeps scripts, Docker + and env files on LF with `core.autocrlf=true`. +- The generated `scripts/*.sh` need Git Bash or WSL; otherwise run + `uvicorn` or `pytest` directly. +- `uvloop` is not installed on Windows. +- If the package directory is not writable, the debug log goes to + `~/.fastapi-fastkit/logs`. + +The test suite runs on `windows-latest` in CI with Python 3.12 and 3.14. + ## Installation Methods ### Install with pip (Recommended) diff --git a/docs/en/user-guide/using-templates.md b/docs/en/user-guide/using-templates.md index 16b01dd4..27c93b96 100644 --- a/docs/en/user-guide/using-templates.md +++ b/docs/en/user-guide/using-templates.md @@ -415,7 +415,9 @@ settings = Settings() ### 3. Add Environment Variables -Create a `.env` file in your project root: +fastkit already created a git-ignored `.env` from the template's +`.env.example` (see [Generated `.env` file](cli-reference.md#generated-env-file)). Add your +own settings to `.env`: ```env # .env @@ -524,7 +526,8 @@ $ docker-compose up -d ### 2. Environment Management - Always use `.env` files for configuration -- Never commit sensitive data to version control +- Never commit sensitive data to version control: commit `.env.example`, + not `.env` - Use different environments for development/production ### 3. Customization Strategy diff --git a/src/fastapi_fastkit/backend/inspection/checks.py b/src/fastapi_fastkit/backend/inspection/checks.py index 2d564e5e..0330926e 100644 --- a/src/fastapi_fastkit/backend/inspection/checks.py +++ b/src/fastapi_fastkit/backend/inspection/checks.py @@ -319,6 +319,7 @@ def check_no_placeholder_residue(ctx: InspectionContext) -> bool: ".json", ".sh", ".env", + ".example", ".ini", } residue: List[str] = [] diff --git a/src/fastapi_fastkit/backend/inspection/context.py b/src/fastapi_fastkit/backend/inspection/context.py index 1e956bc1..8aa61c54 100644 --- a/src/fastapi_fastkit/backend/inspection/context.py +++ b/src/fastapi_fastkit/backend/inspection/context.py @@ -13,6 +13,7 @@ from typing import Any, Dict, List, Optional from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.platform import venv_python @dataclass @@ -66,6 +67,4 @@ def python_executable(self) -> Optional[str]: """Return the interpreter of the inspection venv, if one was created.""" if not self.venv_path: return None - if os.name == "nt": # pragma: no cover - Windows-only branch - return os.path.join(self.venv_path, "Scripts", "python") - return os.path.join(self.venv_path, "bin", "python") + return venv_python(self.venv_path) diff --git a/src/fastapi_fastkit/backend/inspection/docker.py b/src/fastapi_fastkit/backend/inspection/docker.py index c07ccd8c..3a492394 100644 --- a/src/fastapi_fastkit/backend/inspection/docker.py +++ b/src/fastapi_fastkit/backend/inspection/docker.py @@ -44,6 +44,8 @@ def _run( cwd=self.project_dir, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=timeout, ) except (subprocess.TimeoutExpired, OSError) as e: @@ -68,7 +70,12 @@ def _probe(command: Sequence[str]) -> bool: """Return whether ``command`` exits successfully.""" try: result = subprocess.run( - list(command), capture_output=True, text=True, timeout=SHORT_TIMEOUT + list(command), + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=SHORT_TIMEOUT, ) except (subprocess.TimeoutExpired, OSError): return False diff --git a/src/fastapi_fastkit/backend/inspection/fsutils.py b/src/fastapi_fastkit/backend/inspection/fsutils.py index 53ce7748..5b3162c0 100644 --- a/src/fastapi_fastkit/backend/inspection/fsutils.py +++ b/src/fastapi_fastkit/backend/inspection/fsutils.py @@ -6,12 +6,12 @@ # @author bnbong # -------------------------------------------------------------------------- import os -import shutil import stat import subprocess import time from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.platform import is_windows, rmtree_force CLEANUP_MAX_RETRIES = 5 @@ -83,7 +83,7 @@ def force_cleanup_directory(directory_path: str) -> None: """Remove ``directory_path`` using progressively more forceful strategies.""" for attempt in range(CLEANUP_MAX_RETRIES): try: - shutil.rmtree(directory_path) + rmtree_force(directory_path) debug_log( f"Successfully cleaned up temp directory: {directory_path}", "info" ) @@ -98,7 +98,7 @@ def force_cleanup_directory(directory_path: str) -> None: try: fix_directory_permissions(directory_path) - shutil.rmtree(directory_path) + rmtree_force(directory_path) debug_log( "Successfully cleaned up temp directory after permission fix: " f"{directory_path}", @@ -128,10 +128,10 @@ def force_cleanup_directory(directory_path: str) -> None: "warning", ) try: - if os.name == "nt": # pragma: no cover - Windows-only branch - subprocess.run( - ["rmdir", "/s", "/q", directory_path], check=False, shell=True - ) + if is_windows(): + # No shell-out: ``rmdir /s /q`` through ``shell=True`` would hand + # the path to cmd.exe for parsing. + rmtree_force(directory_path, ignore_errors=True) else: subprocess.run(["rm", "-rf", directory_path], check=False) debug_log(f"Force cleanup completed for: {directory_path}", "info") diff --git a/src/fastapi_fastkit/backend/inspection/lint.py b/src/fastapi_fastkit/backend/inspection/lint.py index e4acf57a..fc8a35ec 100644 --- a/src/fastapi_fastkit/backend/inspection/lint.py +++ b/src/fastapi_fastkit/backend/inspection/lint.py @@ -85,6 +85,8 @@ def check_mypy(ctx: InspectionContext) -> bool: cwd=ctx.temp_dir, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=MYPY_TIMEOUT, ) except subprocess.TimeoutExpired: diff --git a/src/fastapi_fastkit/backend/inspection/smoke.py b/src/fastapi_fastkit/backend/inspection/smoke.py index 653dada6..2255e4bf 100644 --- a/src/fastapi_fastkit/backend/inspection/smoke.py +++ b/src/fastapi_fastkit/backend/inspection/smoke.py @@ -198,7 +198,10 @@ def _terminate(process: "subprocess.Popen[bytes]") -> None: except subprocess.TimeoutExpired: pass - if not _signal_group(process, signal.SIGKILL): + # Windows has no SIGKILL (nor process groups to signal); kill() is + # TerminateProcess there. + sigkill = getattr(signal, "SIGKILL", None) + if sigkill is None or not _signal_group(process, sigkill): process.kill() try: process.wait(timeout=SHUTDOWN_TIMEOUT) diff --git a/src/fastapi_fastkit/backend/inspection/strategies.py b/src/fastapi_fastkit/backend/inspection/strategies.py index 814e3723..fbb2c1c1 100644 --- a/src/fastapi_fastkit/backend/inspection/strategies.py +++ b/src/fastapi_fastkit/backend/inspection/strategies.py @@ -9,12 +9,15 @@ # @author bnbong # -------------------------------------------------------------------------- import os +import shutil import subprocess from abc import ABC, abstractmethod -from typing import Any, Dict, List +from typing import Any, Dict, List, Optional from fastapi_fastkit.backend.main import create_venv, install_dependencies_with_manager from fastapi_fastkit.utils.logging import debug_log +from fastapi_fastkit.utils.platform import is_windows, venv_bin_dir +from fastapi_fastkit.utils.textio import write_generated_text from . import smoke from .context import InspectionContext @@ -25,6 +28,28 @@ DEFAULT_TEST_COMMAND = "pytest tests/ -v" +def windows_bash() -> Optional[str]: + """Return a bash that can run a template's ``scripts/test.sh`` on Windows. + + ``C:\\Windows\\System32\\bash.exe`` is the WSL launcher: it runs the + script inside a Linux distribution that cannot see the Windows venv, so + it is not accepted. Git for Windows' bash is. + """ + bash = shutil.which("bash") + if not bash: + return None + system_root = os.environ.get("SystemRoot") or os.environ.get("SYSTEMROOT") + if system_root: + try: + if os.path.commonpath( + [os.path.normcase(bash), os.path.normcase(system_root)] + ) == os.path.normcase(system_root): + return None + except ValueError: # different drives + pass + return bash + + def detect_package_manager(project_dir: str) -> str: """Pick the package manager that fits the project's dependency files.""" if os.path.exists(os.path.join(project_dir, "pyproject.toml")): @@ -111,11 +136,7 @@ def run(self) -> bool: assert venv_path is not None # prepare_environment guarantees this env = self.environment() - bin_dir = "Scripts" if os.name == "nt" else "bin" - separator = ";" if os.name == "nt" else ":" - env["PATH"] = ( - f"{os.path.join(venv_path, bin_dir)}{separator}{env.get('PATH', '')}" - ) + env["PATH"] = os.pathsep.join([venv_bin_dir(venv_path), env.get("PATH", "")]) test_script_path = self.ctx.temp_path("scripts", "test.sh") try: @@ -143,14 +164,33 @@ def run(self) -> bool: def _run_test_script( self, test_script_path: str, env: Dict[str, str] ) -> subprocess.CompletedProcess[str]: - """Run the template's own test script.""" + """Run the template's own test script. + + Windows cannot execute a shell script directly (WinError 193): it is + run through Git Bash when one is installed, and replaced by the + plain pytest invocation otherwise. + """ fix_script_line_endings(test_script_path) - os.chmod(test_script_path, 0o755) + if is_windows(): + bash = windows_bash() + if bash is None: + debug_log( + "No usable bash on Windows; running pytest instead of " + "scripts/test.sh", + "info", + ) + return self._run_pytest(env) + command = [bash, test_script_path] + else: + os.chmod(test_script_path, 0o755) + command = [test_script_path] return subprocess.run( - [test_script_path], + command, cwd=self.ctx.temp_dir, capture_output=True, text=True, + encoding="utf-8", + errors="replace", env=env, timeout=TEST_TIMEOUT, ) @@ -164,6 +204,8 @@ def _run_pytest(self, env: Dict[str, str]) -> subprocess.CompletedProcess[str]: cwd=self.ctx.temp_dir, capture_output=True, text=True, + encoding="utf-8", + errors="replace", env=env, timeout=TEST_TIMEOUT, ) @@ -231,9 +273,10 @@ def _setup_test_environment(self) -> None: debug_log(f"Error reading existing .env file: {e}", "warning") final_vars = {**env_defaults, **existing_vars} - with open(env_file_path, "w", encoding="utf-8") as f: - for key, value in final_vars.items(): - f.write(f"{key}={value}\n") + write_generated_text( + env_file_path, + "".join(f"{key}={value}\n" for key, value in final_vars.items()), + ) debug_log( f"Set up environment file: {env_file_path} " diff --git a/src/fastapi_fastkit/backend/interactive/prompts.py b/src/fastapi_fastkit/backend/interactive/prompts.py index 5224d95a..eeaf840e 100644 --- a/src/fastapi_fastkit/backend/interactive/prompts.py +++ b/src/fastapi_fastkit/backend/interactive/prompts.py @@ -156,7 +156,9 @@ def prompt_template_selection(settings: Any) -> Optional[str]: readme_path = os.path.join(template_dir, template, "README.md-tpl") description = "No description" if os.path.exists(readme_path): - with open(readme_path, "r") as f: + # Template READMEs are UTF-8; the locale codec (cp949, cp1252, + # ASCII) must never be able to crash template selection. + with open(readme_path, "r", encoding="utf-8", errors="replace") as f: first_line = f.readline().strip() if first_line.startswith("# "): description = first_line[2:] diff --git a/src/fastapi_fastkit/backend/main.py b/src/fastapi_fastkit/backend/main.py index 0008c7f9..70b710aa 100644 --- a/src/fastapi_fastkit/backend/main.py +++ b/src/fastapi_fastkit/backend/main.py @@ -8,6 +8,8 @@ import json import os import re +import secrets +import sys import tokenize import tomllib from typing import Any, Dict, Iterable, List, Optional @@ -15,6 +17,10 @@ import click from fastapi_fastkit.backend.package_managers import PackageManagerFactory +from fastapi_fastkit.backend.package_managers.pyproject import ( + PyprojectMergeError, + replace_project_dependencies, +) from fastapi_fastkit.backend.project_builder.preset_layout import ( app_module_from_main_path, ) @@ -36,6 +42,11 @@ print_warning, read_fastkit_metadata, ) +from fastapi_fastkit.utils.textio import ( + read_text_preserving_newlines, + write_generated_text, + write_text_preserving_newlines, +) # Explicit insertion points templates may declare so ``addroute`` never has # to guess where generated code belongs. See the route anchor contract in @@ -51,6 +62,18 @@ # ------------------------------------------------------------ +def _project_file(project_dir: str, *relative: str) -> str: + """ + Join ``project_dir`` with ``/``-separated template-relative paths. + + ``settings.TEMPLATE_PATHS`` spells paths POSIX-style (``src/main.py``); + splitting them keeps the result on the native separator, so Windows gets + ``...\\src\\main.py`` instead of a mixed ``...\\src/main.py``. + """ + parts = [part for rel in relative for part in rel.split("/") if part] + return os.path.join(project_dir, *parts) + + def find_template_core_modules(project_dir: str) -> Dict[str, str]: """ Find core module files in the template project structure. @@ -64,21 +87,21 @@ def find_template_core_modules(project_dir: str) -> Dict[str, str]: # Find main.py for main_path in template_paths["main"]: - full_path = os.path.join(project_dir, main_path) + full_path = _project_file(project_dir, main_path) if os.path.exists(full_path): core_modules["main"] = full_path break # Find setup.py for setup_path in template_paths["setup"]: - full_path = os.path.join(project_dir, setup_path) + full_path = _project_file(project_dir, setup_path) if os.path.exists(full_path): core_modules["setup"] = full_path break # Find pyproject.toml for pyproject_path in template_paths["pyproject"]: - full_path = os.path.join(project_dir, pyproject_path) + full_path = _project_file(project_dir, pyproject_path) if os.path.exists(full_path): core_modules["pyproject"] = full_path break @@ -88,7 +111,7 @@ def find_template_core_modules(project_dir: str) -> Dict[str, str]: if isinstance(config_info, dict): for config_path in config_info["paths"]: for config_file in config_info["files"]: - full_path = os.path.join(project_dir, config_path, config_file) + full_path = _project_file(project_dir, config_path, config_file) if os.path.exists(full_path): core_modules["config"] = full_path break @@ -387,8 +410,7 @@ def replace_placeholders_in_project( for file_path in _substitution_targets(project_dir, files): try: - with open(file_path, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(file_path) except (OSError, UnicodeDecodeError) as e: debug_log(f"Skipping {file_path} during substitution: {e}", "debug") continue @@ -399,8 +421,7 @@ def replace_placeholders_in_project( continue try: - with open(file_path, "w", encoding="utf-8") as f: - f.write(updated) + write_text_preserving_newlines(file_path, updated, newline) except OSError as e: debug_log(f"Failed to write substituted file {file_path}: {e}", "error") raise BackendExceptions(f"Failed to substitute placeholders: {e}") @@ -513,6 +534,86 @@ def inject_project_metadata( raise BackendExceptions("Failed to inject project metadata") +#: The shareable environment file templates ship (``.env.example-tpl``), and +#: the local, git-ignored file generated from it. +ENV_EXAMPLE_FILE = ".env.example" +ENV_FILE = ".env" + +# A non-commented ``SECRET_KEY=`` assignment, optionally ``export``-prefixed. +_SECRET_KEY_LINE = re.compile(r"^([ \t]*(?:export[ \t]+)?SECRET_KEY[ \t]*=).*$", re.M) + + +def render_local_env(example_content: str) -> str: + """ + Build the content of a local ``.env`` from a ``.env.example``. + + Line endings are normalised to ``\\n`` and the value of every + ``SECRET_KEY=`` line is replaced with a fresh random key, so no two + generated projects share a signing key and the example value never + reaches a running app. Everything else is kept verbatim. + + :param example_content: Text of the project's ``.env.example`` + :return: Text for the project's ``.env`` + """ + content = example_content.replace("\r\n", "\n").replace("\r", "\n") + return _SECRET_KEY_LINE.sub( + lambda match: match.group(1) + secrets.token_urlsafe(32), content + ) + + +def create_local_env_file(project_dir: str) -> Optional[str]: + """ + Create the project's local ``.env`` from its ``.env.example``. + + Templates ship only ``.env.example`` (the shareable, committed file); the + ``.env`` an app actually reads is generated here with a unique + ``SECRET_KEY`` and is ignored by the template's ``.gitignore``. An + existing ``.env`` - an in-place deployment into a directory the user + already works in - is never overwritten. The generated key is never + printed. + + :param project_dir: Path to the generated project + :return: Absolute path of the ``.env`` that was written, or None when the + project has no ``.env.example`` or already has a ``.env`` + :raises BackendExceptions: If the file cannot be read or written + """ + example_path = os.path.join(project_dir, ENV_EXAMPLE_FILE) + env_path = os.path.join(project_dir, ENV_FILE) + + if not os.path.isfile(example_path): + return None + if os.path.lexists(env_path): + print_info(f"Keeping the existing {ENV_FILE}; it was not regenerated.") + return None + + try: + with open(example_path, "r", encoding="utf-8", newline="") as f: + example_content = f.read() + except (OSError, UnicodeDecodeError) as e: + raise BackendExceptions(f"Failed to read {ENV_EXAMPLE_FILE}: {e}") from e + + content = render_local_env(example_content) + + try: + # "x" refuses to clobber a .env that appeared since the check above. + with open(env_path, "x", encoding="utf-8", newline="\n") as f: + f.write(content) + except FileExistsError: + print_info(f"Keeping the existing {ENV_FILE}; it was not regenerated.") + return None + except OSError as e: + raise BackendExceptions(f"Failed to create {ENV_FILE}: {e}") from e + + if _SECRET_KEY_LINE.search(content): + print_success( + f"Created {ENV_FILE} from {ENV_EXAMPLE_FILE} with a unique SECRET_KEY " + f"(git-ignored; share {ENV_EXAMPLE_FILE} instead)" + ) + else: + print_success(f"Created {ENV_FILE} from {ENV_EXAMPLE_FILE}") + return env_path + + def _process_setup_file( setup_py: str, project_name: str, author: str, author_email: str, description: str ) -> None: @@ -529,8 +630,7 @@ def _process_setup_file( return try: - with open(setup_py, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(setup_py) # Replace placeholders replacements = { @@ -542,8 +642,7 @@ def _process_setup_file( content = _apply_escaped_replacements(content, replacements, setup_py) - with open(setup_py, "w", encoding="utf-8") as f: - f.write(content) + write_text_preserving_newlines(setup_py, content, newline) debug_log("Injected metadata into setup.py", "info") print_info("Injected metadata into setup.py") @@ -568,8 +667,7 @@ def _process_main_file(main_py: str, project_name: str) -> None: return try: - with open(main_py, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(main_py) if "" not in content: return @@ -578,8 +676,7 @@ def _process_main_file(main_py: str, project_name: str) -> None: "", escape_placeholder_value(project_name, main_py) ) - with open(main_py, "w", encoding="utf-8") as f: - f.write(content) + write_text_preserving_newlines(main_py, content, newline) debug_log("Injected project name into main.py", "info") print_info("Injected project name into main.py") @@ -600,16 +697,14 @@ def _process_config_file(config_py: str, project_name: str) -> None: return try: - with open(config_py, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(config_py) # Replace project name placeholder content = content.replace( "", escape_placeholder_value(project_name, config_py) ) - with open(config_py, "w", encoding="utf-8") as f: - f.write(content) + write_text_preserving_newlines(config_py, content, newline) debug_log("Injected project name into config file", "info") print_info("Injected project name into config file") @@ -639,8 +734,7 @@ def _process_pyproject_file( return try: - with open(pyproject_toml, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(pyproject_toml) # Replace placeholders replacements = { @@ -654,8 +748,7 @@ def _process_pyproject_file( content = _ensure_pyproject_fastkit_markers(content) - with open(pyproject_toml, "w", encoding="utf-8") as f: - f.write(content) + write_text_preserving_newlines(pyproject_toml, content, newline) debug_log("Injected metadata into pyproject.toml", "info") print_info("Injected metadata into pyproject.toml") @@ -824,13 +917,11 @@ def write_fastkit_metadata(project_dir: str, metadata: Dict[str, Any]) -> None: return try: - with open(pyproject_path, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(pyproject_path) content = _ensure_pyproject_fastkit_markers(content, metadata) - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(content) + write_text_preserving_newlines(pyproject_path, content, newline) debug_log("Wrote FastAPI-fastkit metadata into pyproject.toml", "info") @@ -839,73 +930,44 @@ def write_fastkit_metadata(project_dir: str, metadata: Dict[str, Any]) -> None: print_warning(f"Could not write fastkit metadata: {e}") -def _render_dependency_array(dependencies: List[str]) -> str: - """Render a PEP 621 ``dependencies`` array as multi-line TOML.""" - if not dependencies: - return "[]" - body = "\n".join(f' "{dep}",' for dep in dependencies) - return f"[\n{body}\n]" - - def _update_pyproject_dependencies( pyproject_path: str, dependencies: List[str] ) -> bool: """ Replace ``[project].dependencies`` in a pyproject.toml file. - The array is located by bracket matching rather than a lazy regex so - requirement strings carrying extras (``redis[hiredis]``) don't truncate - the match. + See :func:`replace_project_dependencies` for how the array is located. + Nothing is written unless the result passes its semantic check (valid + TOML, nothing but ``dependencies`` changed). A leading UTF-8 BOM is + dropped. :param pyproject_path: Path to the project's pyproject.toml :param dependencies: Dependency specifications to write :return: True when the file was rewritten, False when no array was found + or it could not be replaced safely (the file is then left unchanged) """ try: - with open(pyproject_path, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(pyproject_path) except (OSError, UnicodeDecodeError) as e: debug_log(f"Error reading pyproject.toml dependencies: {e}", "error") return False - project_match = re.search(r"^\[project\]\s*$", content, re.MULTILINE) - if not project_match: - return False - - section_start = project_match.end() - next_table = re.search(r"^\[", content[section_start:], re.MULTILINE) - section_end = section_start + next_table.start() if next_table else len(content) - section = content[section_start:section_end] - - deps_match = re.search(r"^dependencies\s*=\s*\[", section, re.MULTILINE) - if not deps_match: + try: + new_content = replace_project_dependencies( + content.removeprefix("\ufeff"), dependencies + ) + except PyprojectMergeError as e: + debug_log(f"Leaving pyproject.toml unchanged: {e}", "warning") + print_warning( + f"Could not update dependencies in {pyproject_path} safely ({e}); " + "the file was left unchanged." + ) return False - - array_start = section.rindex("[", deps_match.start(), deps_match.end()) - depth = 0 - array_end = -1 - for index in range(array_start, len(section)): - char = section[index] - if char == "[": - depth += 1 - elif char == "]": - depth -= 1 - if depth == 0: - array_end = index + 1 - break - if array_end == -1: + if new_content is None: return False - new_section = ( - section[: deps_match.start()] - + f"dependencies = {_render_dependency_array(dependencies)}" - + section[array_end:] - ) - new_content = content[:section_start] + new_section + content[section_end:] - try: - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(new_content) + write_text_preserving_newlines(pyproject_path, new_content, newline) except OSError as e: debug_log(f"Error writing pyproject.toml dependencies: {e}", "error") return False @@ -950,8 +1012,7 @@ def update_setup_py_dependencies(project_dir: str, dependencies: List[str]) -> N return try: - with open(setup_py_path, "r", encoding="utf-8") as f: - content = f.read() + content, newline = read_text_preserving_newlines(setup_py_path) # Build the new install_requires list deps_str = ",\n ".join(f'"{dep}"' for dep in dependencies) @@ -984,8 +1045,7 @@ def update_setup_py_dependencies(project_dir: str, dependencies: List[str]) -> N return # Write updated content - with open(setup_py_path, "w", encoding="utf-8") as f: - f.write(content) + write_text_preserving_newlines(setup_py_path, content, newline) print_info(f"Updated setup.py with {len(dependencies)} dependencies") @@ -1092,15 +1152,18 @@ def generate_dependency_file_with_manager( dependencies, project_name, author, author_email, description ) - # Also generate requirements.txt for pip compatibility (if not using pip) - if manager_type != "pip": + # Also generate requirements.txt for pip compatibility. Decided by the + # manager actually in use: auto-detection may have replaced the + # requested one, and a stale template requirements.txt would then + # disagree with pyproject.toml. + if package_manager.get_dependency_file_name() != "requirements.txt": from pathlib import Path requirements_path = Path(project_dir) / "requirements.txt" try: - with open(requirements_path, "w", encoding="utf-8") as f: - for dep in dependencies: - f.write(f"{dep}\n") + write_generated_text( + requirements_path, "".join(f"{dep}\n" for dep in dependencies) + ) debug_log("Generated requirements.txt for pip compatibility", "info") except (OSError, UnicodeEncodeError) as e: debug_log( @@ -1178,11 +1241,26 @@ def resolve_project_layout(project_dir: str) -> Dict[str, str]: def _dotted_module(project_dir: str, path: str) -> str: - """Convert a path inside the project into a dotted module prefix.""" - relative = os.path.relpath(path, project_dir) - if relative in (".", ""): + """ + Convert a path inside the project into a dotted module prefix. + + Both separators are normalised so a Windows path (``src\\app``) maps to + ``src.app`` on every OS. ``os.path.relpath`` raises ``ValueError`` on + Windows when the two paths sit on different drives; such a path is not + inside the project, so the historical ``src`` package is assumed. + """ + try: + relative = os.path.relpath(path, project_dir) + except ValueError: + debug_log( + f"{path} is not on the same drive as {project_dir}; assuming 'src'", + "warning", + ) + return "src" + normalized = relative.replace("\\", "/").strip("/") + if normalized in (".", ""): return "" - return relative.replace(os.sep, ".") + return ".".join(part for part in normalized.split("/") if part and part != ".") # Router module filenames templates use, in precedence order. ``api.py`` is @@ -1217,7 +1295,12 @@ def insert_import_line(content: str, import_line: str) -> str: Insert an import statement using the ``# fastkit:imports`` anchor. Templates declare the anchor to say exactly where generated imports - belong. Without one the insertion point is computed from the module's + belong. When the anchor sits in the module's top-level import block the + import is placed where isort / ruff's ``I`` rule expects it (see + :func:`_insert_import_sorted`): below the anchor whenever that keeps the + block sorted, otherwise in its own section higher up (a third-party + ``from fastapi_pagination import ...`` joins ``from fastapi import ...``). + Without an anchor the insertion point is computed from the module's AST (right after the last top-level import), which is precise where the previous line-prefix scan was merely approximate. @@ -1225,9 +1308,13 @@ def insert_import_line(content: str, import_line: str) -> str: :param import_line: Import statement to add :return: Updated source (unchanged if the import is already present) """ - if import_line in content: + if _import_already_present(content, import_line): return content + placed = _insert_import_sorted(content, import_line) + if placed is not None: + return placed + anchored = _insert_after_anchor(content, IMPORT_ANCHOR, import_line) if anchored is not None: return anchored @@ -1238,6 +1325,219 @@ def insert_import_line(content: str, import_line: str) -> str: return "\n".join(lines) +def _module_level_imports(body: List[ast.stmt]) -> Iterable[ast.stmt]: + """Imports binding module-level names (also inside ``if`` / ``try``).""" + for node in body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + yield node + elif isinstance(node, (ast.If, ast.Try, ast.With)): + for field in ("body", "orelse", "finalbody"): + yield from _module_level_imports(getattr(node, field, [])) + for handler in getattr(node, "handlers", []): + yield from _module_level_imports(handler.body) + + +def _import_bindings(nodes: Iterable[ast.stmt]) -> set[tuple[Any, ...]]: + """One key per imported name: what is imported, from where, bound as what.""" + bindings: set[tuple[Any, ...]] = set() + for node in nodes: + if isinstance(node, ast.Import): + bindings.update(("import", a.name, a.asname) for a in node.names) + elif isinstance(node, ast.ImportFrom): + bindings.update( + ("from", node.level, node.module, a.name, a.asname) for a in node.names + ) + return bindings + + +def _import_already_present(content: str, import_line: str) -> bool: + """ + Whether every name ``import_line`` imports is already imported. + + Compared as whole logical imports, never as substrings: an existing + ``from .routes import users`` does not satisfy ``from .routes import + user``. Modules that do not parse fall back to comparing whole stripped + lines. + """ + try: + new_nodes = ast.parse(import_line.strip()).body + tree = ast.parse(content) + except SyntaxError: + new_nodes, tree = [], None + wanted = _import_bindings(new_nodes) + if tree is not None and wanted: + return wanted <= _import_bindings(_module_level_imports(tree.body)) + target = import_line.strip() + return any(line.strip() == target for line in content.splitlines()) + + +#: Top-level packages generated projects import as first party. Matches the +#: ``known-first-party`` the generated ruff configuration declares. +_FIRST_PARTY_ROOTS = frozenset({"src"}) + +# isort section order (ruff's default ``section-order``). +_SECTION_FUTURE, _SECTION_STDLIB, _SECTION_THIRD_PARTY = 0, 1, 2 +_SECTION_FIRST_PARTY, _SECTION_LOCAL = 3, 4 + + +def _import_sort_key(node: ast.stmt) -> Optional[tuple[int, int, str]]: + """isort / ruff sort key of a top-level import: (section, kind, module). + + Within a section ruff's defaults put ``import x`` before ``from x import + y`` and compare module names case-insensitively. + """ + if isinstance(node, ast.Import): + module, level, kind = node.names[0].name, 0, 0 + elif isinstance(node, ast.ImportFrom): + module, level, kind = node.module or "", node.level, 1 + else: + return None + + root = module.split(".", 1)[0] + if level: + section = _SECTION_LOCAL + elif module == "__future__": + section = _SECTION_FUTURE + elif root in _FIRST_PARTY_ROOTS: + section = _SECTION_FIRST_PARTY + elif root in sys.stdlib_module_names: + section = _SECTION_STDLIB + else: + section = _SECTION_THIRD_PARTY + return section, kind, module.lower() + + +def _insert_import_sorted(content: str, import_line: str) -> Optional[str]: + """ + Insert a single-line import into the anchored top-level import block, + keeping the block sorted the way ruff's ``I`` rule (isort) expects. + + ``# fastkit:imports`` sits inside the template's import block, so ruff + sorts what comes after it together with what comes before it (the anchor + comment travels with the import right below it). Appending every import + under the anchor in wiring order therefore produced I001 findings. The + import goes below the anchor, sorted among the imports already there, + whenever it sorts after every import above the anchor (the usual case + for generated first-party routers); otherwise it joins its own isort + section above, at its sorted position, opening the section with a blank + line when it is new. Existing lines are never moved. + + :param content: Module source + :param import_line: The import statement to add (one line) + :return: Updated source, or None when the module has no parsable + top-level import block holding the anchor (callers fall back) + """ + try: + new_nodes = ast.parse(import_line.strip()).body + tree = ast.parse(content) + except SyntaxError: + return None + if len(new_nodes) != 1: + return None + new_key = _import_sort_key(new_nodes[0]) + if new_key is None: + return None + + block: List[ast.stmt] = [] + block_end = 0 + for node in tree.body: + if _import_sort_key(node) is not None: + block.append(node) + continue + if block: + block_end = node.lineno + break + if not (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant)): + return None + if not block: + return None + if not block_end: + block_end = len(content.split("\n")) + 1 + + anchor_line = next( + ( + number + for number in _anchor_line_numbers(content, IMPORT_ANCHOR) + if block[0].lineno < number < block_end + ), + None, + ) + if anchor_line is None: + return None + + lines = content.split("\n") + indent = "" + keyed = [(node, _import_sort_key(node)) for node in block] + above = [(node, key) for node, key in keyed if node.lineno < anchor_line] + below = [(node, key) for node, key in keyed if node.lineno > anchor_line] + + def attached_start(node: ast.stmt, floor: int = 0) -> int: + """0-based first line of ``node`` including comments glued above it. + + ``floor`` is the first line the comments may extend to (the line + right below the anchor for imports below it: the anchor comment + itself never belongs to the import that follows it). + """ + start = node.lineno - 1 + while start > floor and lines[start - 1].strip().startswith("#"): + start -= 1 + return start + + if all(key is not None and key < new_key for _, key in above): + greater = [(node, key) for node, key in below if key and key > new_key] + smaller = [(node, key) for node, key in below if key and key < new_key] + section = new_key[0] + if greater and greater[0][1] and greater[0][1][0] == section: + # Joins the section of the next import, right above it (and above + # any comment attached to it). + lines.insert(attached_start(greater[0][0], anchor_line), import_line) + return "\n".join(lines) + if smaller and smaller[-1][1] and smaller[-1][1][0] == section: + # Joins the section of the previous import, right below it. + last = smaller[-1][0] + lines.insert(last.end_lineno or last.lineno, import_line) + return "\n".join(lines) + if greater: + # A new section between two others (or opening the block below + # the anchor): separated from the next section by a blank line, + # from the previous one by the blank line already there. + at = attached_start(greater[0][0], anchor_line) + new_lines = [import_line, ""] + if smaller and at > 0 and lines[at - 1].strip(): + new_lines.insert(0, "") + lines[at:at] = new_lines + return "\n".join(lines) + if smaller: + last = smaller[-1][0] + at = last.end_lineno or last.lineno + lines[at:at] = ["", import_line] + return "\n".join(lines) + anchor_text = lines[anchor_line - 1] + indent = anchor_text[: len(anchor_text) - len(anchor_text.lstrip())] + lines.insert(anchor_line, f"{indent}{import_line}") + return "\n".join(lines) + + same = [(node, key) for node, key in keyed if key and key[0] == new_key[0]] + if same: + greater_same = [node for node, key in same if key > new_key] + if greater_same: + at = attached_start(greater_same[0]) + lines.insert(at, import_line) + else: + last = same[-1][0] + lines.insert(last.end_lineno or last.lineno, import_line) + return "\n".join(lines) + + earlier = [node for node, key in keyed if key and key[0] < new_key[0]] + if earlier: + at = earlier[-1].end_lineno or earlier[-1].lineno + lines[at:at] = ["", import_line] + else: + at = block[0].lineno - 1 + lines[at:at] = [import_line, ""] + return "\n".join(lines) + + def insert_statement_line( content: str, statement: str, anchor: str = ROUTES_ANCHOR ) -> str: @@ -1388,8 +1688,7 @@ def _ensure_project_structure(src_dir: str) -> Dict[str, str]: # Create __init__.py if it doesn't exist init_file = os.path.join(dir_path, "__init__.py") if not os.path.exists(init_file): - with open(init_file, "w"): - pass + write_generated_text(init_file, "") return target_dirs @@ -1470,10 +1769,10 @@ def _handle_api_router_file( with open(api_router_file, "r", encoding="utf-8") as f: content = f.read() if not content.strip(): - with open(api_router_file, "w", encoding="utf-8") as f: - f.write( - "from fastapi import APIRouter\n\napi_router = APIRouter()\n" - ) + write_generated_text( + api_router_file, + "from fastapi import APIRouter\n\napi_router = APIRouter()\n", + ) # Update API router to include new route if os.path.exists(api_router_file): @@ -1569,8 +1868,7 @@ def _update_main_app( return try: - with open(main_py_path, "r", encoding="utf-8") as f: - main_content = f.read() + main_content, newline = read_text_preserving_newlines(main_py_path) # Check if router is already imported or included router_import = f"from {router_module} import api_router" @@ -1594,8 +1892,7 @@ def _update_main_app( main_content, "app.include_router(api_router)" ) - with open(main_py_path, "w", encoding="utf-8") as f: - f.write(main_content) + write_text_preserving_newlines(main_py_path, main_content, newline) debug_log(f"Updated main.py to include router for {route_name}", "info") diff --git a/src/fastapi_fastkit/backend/package_managers/base.py b/src/fastapi_fastkit/backend/package_managers/base.py index f18ad36b..c371eb06 100644 --- a/src/fastapi_fastkit/backend/package_managers/base.py +++ b/src/fastapi_fastkit/backend/package_managers/base.py @@ -4,15 +4,30 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import os +import shutil import subprocess from abc import ABC, abstractmethod from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.logging import debug_log -from fastapi_fastkit.utils.main import console, handle_exception, print_error +from fastapi_fastkit.utils.main import ( + console, + handle_exception, + print_error, + print_warning, +) +from fastapi_fastkit.utils.platform import resolve_command, venv_executable +from fastapi_fastkit.utils.textio import ( + UNTRANSLATED, + read_text_preserving_newlines, + write_generated_text, + write_text_preserving_newlines, +) + +from .pyproject import PyprojectMergeError, parse_toml def _with_stderr_tail(message: str, stderr: str, max_lines: int = 5) -> str: @@ -125,15 +140,9 @@ def get_executable_path( :param venv_path: Path to virtual environment (optional) :return: Full path to the executable """ - import os - if venv_path: - if os.name == "nt": # Windows - return os.path.join(venv_path, "Scripts", f"{executable_name}.exe") - else: # Unix-based - return os.path.join(venv_path, "bin", executable_name) - else: - return executable_name + return venv_executable(venv_path, executable_name) + return executable_name def run_command( self, command: List[str], **kwargs: Any @@ -149,13 +158,17 @@ def run_command( default_kwargs: Dict[str, Any] = { "check": True, "capture_output": True, + # Child output is decoded as UTF-8 whatever the console code page + # is; undecodable bytes become U+FFFD instead of raising. "text": True, + "encoding": "utf-8", + "errors": "replace", "cwd": str(self.project_dir), "timeout": settings.get_subprocess_timeout(), } default_kwargs.update(kwargs) - return subprocess.run(command, **default_kwargs) + return subprocess.run(resolve_command(command), **default_kwargs) def _check_command_available(self, command: List[str]) -> bool: """ @@ -166,10 +179,12 @@ def _check_command_available(self, command: List[str]) -> bool: """ try: subprocess.run( - command, + resolve_command(command), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout("check"), ) return True @@ -207,11 +222,13 @@ def _run_checked( try: with console.status(f"[bold green]{status_msg}"): result: subprocess.CompletedProcess[str] = subprocess.run( - command, + resolve_command(command), cwd=cwd if cwd is not None else str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=timeout, ) @@ -307,6 +324,82 @@ def _require_dependency_file(self, error_message: Optional[str] = None) -> Path: raise BackendExceptions(error_message or f"{file_name} file not found") return dependency_path + def _write_pyproject( + self, build: Callable[[Optional[str]], str], fresh_content: str + ) -> None: + """ + Write the project's ``pyproject.toml`` without discarding its content. + + ``build`` receives the current file text (None when there is no file) + and returns the text to write, merging the manager's own tables into + it; templates ship a complete pyproject whose ``requires-python``, + ``[tool.*]`` tables and ``[tool.fastapi-fastkit]`` marker must survive. + An existing file keeps its line endings; a leading UTF-8 BOM is + dropped (``tomllib`` rejects it). + + - Existing file is not valid TOML: it cannot be merged into, so it is + kept as ``pyproject.toml.bak`` and ``fresh_content`` (the manager's + standalone skeleton) is written, with a warning naming the backup. + - Existing file is valid but ``build`` cannot update it safely: the + file is left untouched and :class:`BackendExceptions` is raised. + + :param build: Produces the new text from the existing one + :param fresh_content: Standalone pyproject used when there is nothing + valid to merge into + :raises BackendExceptions: if a valid file cannot be updated safely + :raises OSError: if the file cannot be read or written + :raises UnicodeDecodeError: if the existing file is not UTF-8 + """ + pyproject_path = self.get_dependency_file_path() + + existing: Optional[str] = None + newline = UNTRANSLATED + if pyproject_path.exists(): + existing, newline = read_text_preserving_newlines(pyproject_path) + existing = existing.removeprefix("\ufeff") + + if existing is not None and existing.strip(): + try: + parse_toml(existing) + except PyprojectMergeError as e: + backup = self._backup_path(pyproject_path) + shutil.copy2(pyproject_path, backup) + debug_log( + f"Replacing invalid pyproject.toml (backup: {backup}): {e}", + "warning", + ) + print_warning( + f"Existing pyproject.toml is not valid TOML ({e}). " + f"It was kept as {backup.name} and replaced with a " + "generated one." + ) + write_text_preserving_newlines(pyproject_path, fresh_content, newline) + return + + try: + content = build(existing) + except PyprojectMergeError as e: + debug_log(f"Leaving pyproject.toml unchanged: {e}", "error") + raise BackendExceptions( + f"Could not update {pyproject_path} safely: {e}. " + "The file was left unchanged; add the dependencies manually." + ) from e + + if existing is None: + write_generated_text(pyproject_path, content) + else: + write_text_preserving_newlines(pyproject_path, content, newline) + + @staticmethod + def _backup_path(path: Path) -> Path: + """First of ``.bak``, ``.bak.1``, ... that does not exist.""" + candidate = path.with_name(f"{path.name}.bak") + counter = 1 + while candidate.exists(): + candidate = path.with_name(f"{path.name}.bak.{counter}") + counter += 1 + return candidate + def get_dependency_file_path(self) -> Path: """ Get the full path to the dependency file. diff --git a/src/fastapi_fastkit/backend/package_managers/pdm_manager.py b/src/fastapi_fastkit/backend/package_managers/pdm_manager.py index b1cd5666..2778c11a 100644 --- a/src/fastapi_fastkit/backend/package_managers/pdm_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/pdm_manager.py @@ -8,15 +8,56 @@ from typing import List from fastapi_fastkit.core.exceptions import BackendExceptions -from fastapi_fastkit.core.settings import settings +from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON, settings from fastapi_fastkit.utils.logging import debug_log, get_logger from fastapi_fastkit.utils.main import print_success +from fastapi_fastkit.utils.platform import resolve_command +from fastapi_fastkit.utils.textio import write_generated_text from .base import BasePackageManager +from .pyproject import ( + render_dependency_array, + toml_string, + update_pep621_pyproject, +) logger = get_logger(__name__) +def _pdm_pyproject( + dependencies: List[str], + project_name: str, + description: str, + author: str, + author_email: str, +) -> str: + """Render a standalone pyproject.toml for a PDM project.""" + author_entry = ( + f"{{name = {toml_string(author)}, " f"email = {toml_string(author_email)}}}" + ) + return f"""[project] +name = {toml_string(project_name)} +version = "0.1.0" +description = {toml_string(description)} +authors = [ + {author_entry}, +] +dependencies = {render_dependency_array(dependencies)} +requires-python = {toml_string(DEFAULT_REQUIRES_PYTHON)} +readme = "README.md" +license = {{text = "MIT"}} + +[build-system] +requires = ["pdm-backend"] +build-backend = "pdm.backend" + +[tool.hatch.build.targets.wheel] +packages = ["src"] + +[tool.pdm] +""" + + class PdmManager(BasePackageManager): """PDM package manager implementation.""" @@ -78,7 +119,14 @@ def generate_dependency_file( description: str = "", ) -> None: """ - Generate a pyproject.toml file with the given dependencies and metadata. + Write the dependencies and metadata into pyproject.toml. + + A pyproject.toml the template already shipped is updated in place: + only ``[project].dependencies`` is replaced (and ``requires-python`` + filled in when missing), so the template's Python floor, dependency + groups, build backend, ``[tool.*]`` tables and fastkit marker are + kept. Without an existing file a standalone PDM pyproject.toml is + written. :param dependencies: List of dependency specifications :param project_name: Name of the project @@ -89,44 +137,26 @@ def generate_dependency_file( pyproject_path = self.get_dependency_file_path() try: - # Create dependencies list as TOML format - deps_toml = "[\n" - for dep in dependencies: - deps_toml += f' "{dep}",\n' - deps_toml += "]" - - # Create basic pyproject.toml content as string - pyproject_content = f"""[project] -name = "{project_name or "fastapi-project"}" -version = "0.1.0" -description = "{description or "A FastAPI project"}" -authors = [ - {{name = "{author or "Author"}", email = "{author_email or "author@example.com"}"}}, -] -dependencies = {deps_toml} -requires-python = ">=3.8" -readme = "README.md" -license = {{text = "MIT"}} - -[build-system] -requires = ["pdm-backend"] -build-backend = "pdm.backend" - -[tool.hatch.build.targets.wheel] -packages = ["src"] - -[tool.pdm] -""" - - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(pyproject_content) + fresh_content = _pdm_pyproject( + dependencies, + project_name or "fastapi-project", + description or "A FastAPI project", + author or "Author", + author_email or "author@example.com", + ) + self._write_pyproject( + lambda existing: update_pep621_pyproject( + existing, fresh_content, dependencies + ), + fresh_content, + ) debug_log( f"Generated {pyproject_path} with {len(dependencies)} dependencies", "info", ) - except (OSError, UnicodeEncodeError) as e: + except (OSError, UnicodeError) as e: debug_log(f"Error generating pyproject.toml: {e}", "error") raise BackendExceptions(f"Failed to generate pyproject.toml: {str(e)}") @@ -145,11 +175,13 @@ def add_dependency(self, dependency: str, dev: bool = False) -> None: cmd.append(dependency) subprocess.run( - cmd, + resolve_command(cmd), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout("install"), ) @@ -179,42 +211,23 @@ def initialize_project( try: # Use PDM init command for interactive setup subprocess.run( - ["pdm", "init", "--non-interactive"], + resolve_command(["pdm", "init", "--non-interactive"]), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout(), ) # Create or update pyproject.toml with provided metadata pyproject_path = self.get_dependency_file_path() - # Create basic pyproject.toml with project metadata - pyproject_content = f"""[project] -name = "{project_name}" -version = "0.1.0" -description = "{description}" -authors = [ - {{name = "{author}", email = "{author_email}"}}, -] -dependencies = [] -requires-python = ">=3.8" -readme = "README.md" -license = {{text = "MIT"}} - -[build-system] -requires = ["pdm-backend"] -build-backend = "pdm.backend" - -[tool.hatch.build.targets.wheel] -packages = ["src"] - -[tool.pdm] -""" - - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(pyproject_content) + pyproject_content = _pdm_pyproject( + [], project_name, description, author, author_email + ) + write_generated_text(pyproject_path, pyproject_content) debug_log(f"Initialized PDM project: {project_name}", "info") diff --git a/src/fastapi_fastkit/backend/package_managers/pip_manager.py b/src/fastapi_fastkit/backend/package_managers/pip_manager.py index 081495f0..1ef2d205 100644 --- a/src/fastapi_fastkit/backend/package_managers/pip_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/pip_manager.py @@ -10,6 +10,12 @@ from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.logging import debug_log, get_logger from fastapi_fastkit.utils.main import print_success +from fastapi_fastkit.utils.textio import ( + UNTRANSLATED, + read_text_preserving_newlines, + write_generated_text, + write_text_preserving_newlines, +) from .base import BasePackageManager @@ -20,8 +26,21 @@ class PipManager(BasePackageManager): """Pip package manager implementation.""" def is_available(self) -> bool: - """Check if pip is available on the system.""" - return self._check_command_available([sys.executable, "-m", "pip", "--version"]) + """Check if a pip-managed virtual environment can be set up. + + The project's venv is created with ``python -m venv``, which installs + pip into it through ``ensurepip``, and dependencies are installed with + that venv's own pip. pip does not have to be installed next to fastkit + itself (a ``uv tool install`` / pipx environment usually has none), + so either a usable host pip or ``venv`` + ``ensurepip`` is enough. + Without this, an explicit ``--package-manager pip`` silently fell back + to uv whenever fastkit's interpreter lacked pip. + """ + if self._check_command_available([sys.executable, "-m", "pip", "--version"]): + return True + return self._check_command_available( + [sys.executable, "-c", "import ensurepip, venv"] + ) def get_dependency_file_name(self) -> str: """Get the dependency file name for pip.""" @@ -99,9 +118,9 @@ def generate_dependency_file( requirements_path = self.get_dependency_file_path() try: - with open(requirements_path, "w", encoding="utf-8") as f: - for dep in dependencies: - f.write(f"{dep}\n") + write_generated_text( + requirements_path, "".join(f"{dep}\n" for dep in dependencies) + ) debug_log( f"Generated {requirements_path} with {len(dependencies)} dependencies", @@ -125,21 +144,25 @@ def add_dependency(self, dependency: str, dev: bool = False) -> None: requirements_path = self.get_dependency_file_path() try: - # Read existing dependencies + # Read existing dependencies, remembering the file's own line + # endings so the rewrite keeps them. existing_deps = [] + newline = UNTRANSLATED if requirements_path.exists(): - with open(requirements_path, "r", encoding="utf-8") as f: - existing_deps = [ - line.strip() for line in f.readlines() if line.strip() - ] + content, newline = read_text_preserving_newlines(requirements_path) + existing_deps = [ + line.strip() for line in content.splitlines() if line.strip() + ] # Add new dependency if not already present if dependency not in existing_deps: existing_deps.append(dependency) - with open(requirements_path, "w", encoding="utf-8") as f: - for dep in existing_deps: - f.write(f"{dep}\n") + write_text_preserving_newlines( + requirements_path, + "".join(f"{dep}\n" for dep in existing_deps), + newline, + ) debug_log( f"Added dependency '{dependency}' to requirements.txt", "info" diff --git a/src/fastapi_fastkit/backend/package_managers/poetry_manager.py b/src/fastapi_fastkit/backend/package_managers/poetry_manager.py index a95f4a77..00639d24 100644 --- a/src/fastapi_fastkit/backend/package_managers/poetry_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/poetry_manager.py @@ -4,17 +4,32 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import subprocess -from typing import List, Tuple +from typing import Any, Dict, List, Optional, Tuple from fastapi_fastkit.core.exceptions import BackendExceptions -from fastapi_fastkit.core.settings import settings +from fastapi_fastkit.core.settings import DEFAULT_POETRY_PYTHON, settings from fastapi_fastkit.utils.logging import debug_log, get_logger from fastapi_fastkit.utils.main import console, handle_exception, print_success +from fastapi_fastkit.utils.platform import resolve_command +from fastapi_fastkit.utils.textio import write_generated_text from .base import BasePackageManager +from .pyproject import ( + declared_requires_python, + merge_pyproject_tables, + parse_toml, + toml_string, + toml_string_array, +) logger = get_logger(__name__) +#: Tables whose whole content (sub-tables included) the manager rewrites. +_POETRY_DEPENDENCY_TABLES = ( + "tool.poetry.dependencies", + "tool.poetry.group.dev.dependencies", +) + # PEP 440 version specifier operators, longest-match first so "===" beats "==". _PEP440_OPERATORS = ("===", "==", "!=", "<=", ">=", "~=", "<", ">") @@ -57,6 +72,80 @@ def _parse_pip_requirement( return req, extras, version_spec, marker +def _poetry_dependency_line(requirement: str) -> str: + """Render one pip requirement as a Poetry dependency line ("" to skip).""" + name_part, extras, version_spec, marker = _parse_pip_requirement(requirement) + if not name_part: + return "" + + if not version_spec: + version_str = "*" + elif version_spec.startswith("=="): + # Poetry treats a bare version as a pin; keep the old formatting to + # avoid churn in generated files. + version_str = version_spec[2:].strip() + else: + version_str = version_spec + + if extras or marker: + parts = [f"version = {toml_string(version_str)}"] + if extras: + parts.append(f"extras = {toml_string_array(extras)}") + if marker: + parts.append(f"markers = {toml_string(marker)}") + return f"{name_part} = {{{', '.join(parts)}}}\n" + return f"{name_part} = {toml_string(version_str)}\n" + + +def _dev_dependency_group(data: Dict[str, Any]) -> List[str]: + """The string entries of a parsed pyproject's ``[dependency-groups].dev``.""" + groups = data.get("dependency-groups") + if not isinstance(groups, dict): + return [] + dev = groups.get("dev") + if not isinstance(dev, list): + return [] + return [entry for entry in dev if isinstance(entry, str)] + + +def _poetry_tables( + dependencies: List[str], + dev_dependencies: List[str], + python: str, + project_name: str, + description: str, + author: str, + author_email: str, +) -> str: + """Render the tables Poetry owns: ``[tool.poetry*]`` and ``[build-system]``. + + Each requirement is parsed as PEP 508 so non-``==`` specifiers (``>=``, + ``~=``, ...), extras and environment markers all round-trip to valid + TOML. + """ + deps_section = "".join(_poetry_dependency_line(dep) for dep in dependencies) + dev_section = "".join(_poetry_dependency_line(dep) for dep in dev_dependencies) + authors = toml_string_array([f"{author} <{author_email}>"]) + return f"""[tool.poetry] +name = {toml_string(project_name)} +version = "0.1.0" +description = {toml_string(description)} +authors = {authors} +readme = "README.md" +license = "MIT" +packages = [{{include = "src"}}] + +[tool.poetry.dependencies] +python = {toml_string(python)} +{deps_section} +[tool.poetry.group.dev.dependencies] +{dev_section} +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" +""" + + class PoetryManager(BasePackageManager): """Poetry package manager implementation.""" @@ -85,10 +174,12 @@ def create_virtual_environment(self) -> str: try: with console.status("[bold green]Querying Poetry environment..."): result = subprocess.run( - ["poetry", "env", "info", "--path"], + resolve_command(["poetry", "env", "info", "--path"]), cwd=str(self.project_dir), capture_output=True, text=True, + encoding="utf-8", + errors="replace", check=False, # Don't fail if venv doesn't exist yet timeout=venv_timeout, ) @@ -132,14 +223,14 @@ def create_virtual_environment(self) -> str: def _create_minimal_pyproject(self) -> None: """Create a minimal pyproject.toml for Poetry.""" - pyproject_content = """[tool.poetry] + pyproject_content = f"""[tool.poetry] name = "temp-project" version = "0.1.0" description = "" authors = ["Author "] [tool.poetry.dependencies] -python = "^3.8" +python = "{DEFAULT_POETRY_PYTHON}" [tool.poetry.group.dev.dependencies] @@ -148,8 +239,7 @@ def _create_minimal_pyproject(self) -> None: build-backend = "poetry.core.masonry.api" """ pyproject_path = self.get_dependency_file_path() - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(pyproject_content) + write_generated_text(pyproject_path, pyproject_content) def install_dependencies(self, venv_path: str) -> None: """ @@ -180,7 +270,17 @@ def generate_dependency_file( description: str = "", ) -> None: """ - Generate a pyproject.toml file with the given dependencies and metadata. + Write the Poetry tables for the given dependencies into pyproject.toml. + + Poetry owns ``[tool.poetry]``, ``[tool.poetry.dependencies]``, + ``[tool.poetry.group.dev.dependencies]`` and ``[build-system]``; + those are replaced (keys of ``[tool.poetry]`` fastkit does not set + are kept). Every other table of a pyproject.toml the template + already shipped is kept, including ``[project]``, other + ``[tool.poetry.*]`` tables, ``[tool.*]`` and the fastkit marker. Poetry's + ``python`` constraint is the template's ``requires-python`` (the + shared default when the template declares none), and the dev group + is filled from the template's ``[dependency-groups].dev``. :param dependencies: List of dependency specifications :param project_name: Name of the project @@ -190,67 +290,46 @@ def generate_dependency_file( """ pyproject_path = self.get_dependency_file_path() - try: - # Create dependencies section for Poetry. Parse each requirement as - # PEP 508 so non-``==`` specifiers (``>=``, ``~=``, ...), extras, and - # environment markers all round-trip to valid TOML. - deps_section = "" - for dep in dependencies: - name_part, extras, version_spec, marker = _parse_pip_requirement(dep) - if not name_part: - continue - - if not version_spec: - version_str = "*" - elif version_spec.startswith("=="): - # Poetry treats a bare version as a pin; keep the old - # formatting to avoid churn in generated files. - version_str = version_spec[2:].strip() - else: - version_str = version_spec - - if extras or marker: - parts = [f'version = "{version_str}"'] - if extras: - extras_str = ", ".join(f'"{extra}"' for extra in extras) - parts.append(f"extras = [{extras_str}]") - if marker: - escaped_marker = marker.replace('"', '\\"') - parts.append(f'markers = "{escaped_marker}"') - deps_section += f"{name_part} = {{{', '.join(parts)}}}\n" - else: - deps_section += f'{name_part} = "{version_str}"\n' - - # Create basic pyproject.toml content for Poetry - pyproject_content = f"""[tool.poetry] -name = "{project_name or "fastapi-project"}" -version = "0.1.0" -description = "{description or "A FastAPI project"}" -authors = ["{author or "Author"} <{author_email or "author@example.com"}>"] -readme = "README.md" -license = "MIT" -packages = [{{include = "src"}}] - -[tool.poetry.dependencies] -python = "^3.8" -{deps_section} - -[tool.poetry.group.dev.dependencies] - -[build-system] -requires = ["poetry-core"] -build-backend = "poetry.core.masonry.api" -""" + def render(existing: Optional[str]) -> str: + python = DEFAULT_POETRY_PYTHON + dev_dependencies: List[str] = [] + if existing is not None and existing.strip(): + python = declared_requires_python(existing) or python + dev_dependencies = _dev_dependency_group(parse_toml(existing)) + tables = _poetry_tables( + dependencies, + dev_dependencies, + python, + project_name or "fastapi-project", + description or "A FastAPI project", + author or "Author", + author_email or "author@example.com", + ) + if existing is None or not existing.strip(): + return tables + # Owned: [tool.poetry], [build-system] and the two dependency + # tables (with their sub-tables, which are dependency entries). + # Other [tool.poetry.*] tables ([[tool.poetry.source]], + # [tool.poetry.scripts], other groups, ...) are kept. Inside + # [tool.poetry] only the keys _poetry_tables sets (name, version, + # description, authors, readme, license, packages) are + # regenerated; every other key of the existing table is kept. + return merge_pyproject_tables( + existing, + tables, + owned_prefixes=_POETRY_DEPENDENCY_TABLES, + preserve_keys_in=("tool.poetry",), + ) - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(pyproject_content) + try: + self._write_pyproject(render, render(None)) debug_log( f"Generated {pyproject_path} with {len(dependencies)} dependencies", "info", ) - except (OSError, UnicodeEncodeError) as e: + except (OSError, UnicodeError) as e: debug_log(f"Error generating pyproject.toml: {e}", "error") raise BackendExceptions(f"Failed to generate pyproject.toml: {str(e)}") @@ -269,11 +348,13 @@ def add_dependency(self, dependency: str, dev: bool = False) -> None: cmd.append(dependency) subprocess.run( - cmd, + resolve_command(cmd), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout("install"), ) @@ -303,25 +384,29 @@ def initialize_project( try: # Use Poetry init command with non-interactive mode subprocess.run( - [ - "poetry", - "init", - "--name", - project_name, - "--description", - description, - "--author", - f"{author} <{author_email}>", - "--license", - "MIT", - "--python", - "^3.8", - "--no-interaction", - ], + resolve_command( + [ + "poetry", + "init", + "--name", + project_name, + "--description", + description, + "--author", + f"{author} <{author_email}>", + "--license", + "MIT", + "--python", + DEFAULT_POETRY_PYTHON, + "--no-interaction", + ] + ), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout(), ) @@ -359,11 +444,13 @@ def run_script(self, script_command: str) -> None: """ try: subprocess.run( - ["poetry", "run"] + script_command.split(), + resolve_command(["poetry", "run"] + script_command.split()), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout(), ) @@ -385,11 +472,13 @@ def show_dependencies(self) -> str: """ try: result = subprocess.run( - ["poetry", "show"], + resolve_command(["poetry", "show"]), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout(), ) diff --git a/src/fastapi_fastkit/backend/package_managers/pyproject.py b/src/fastapi_fastkit/backend/package_managers/pyproject.py new file mode 100644 index 00000000..b38cd283 --- /dev/null +++ b/src/fastapi_fastkit/backend/package_managers/pyproject.py @@ -0,0 +1,804 @@ +# -------------------------------------------------------------------------- +# pyproject.toml editing helpers shared by the package managers. +# +# Every template ships a complete ``pyproject.toml`` (PEP 621 metadata, the +# template's ``requires-python``, dependency groups, ``[tool.black]``, +# ``[tool.mypy]``, ``[tool.pytest.ini_options]``, the ``[tool.fastapi-fastkit]`` +# marker, ...). The package managers used to replace that file wholesale with +# a hard-coded skeleton, which dropped all of it and declared Python 3.8. +# +# These helpers edit the file at the table / statement level instead. Text +# the caller does not own is kept byte for byte (comments, formatting and +# order included); only the tables or keys a package manager actually owns +# are replaced. +# +# Locating tables and keys is done on a *masked* copy of the text in which +# every string and comment character is blanked out, so brackets, ``#`` and +# header-looking lines inside strings or comments are never mistaken for +# syntax. Whatever the scanner might still get wrong is caught by a semantic +# post-condition: the edited document, parsed with ``tomllib``, must equal the +# original except for the keys / tables the operation owns. Anything else +# raises :class:`PyprojectMergeError` instead of being written. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import copy +import re +import tomllib +from dataclasses import dataclass +from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple + +from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON +from fastapi_fastkit.utils.logging import debug_log + +#: Fallback for a header line ``tomllib`` cannot parse on its own. +_TABLE_HEADER_PATTERN = re.compile( + r"^[ \t]*\[\[?[ \t]*(?P[^\[\]]+?)[ \t]*\]\]?[ \t]*(?:#.*)?$" +) + +#: A key that needs no quoting in a table header. +_BARE_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$") + +#: Mask characters standing in for string and comment characters. +_MASK_STRING = "S" +_MASK_COMMENT = "C" + +#: (table name, text) pairs; ``None`` names the text before the first table. +TomlBlocks = List[Tuple[Optional[str], str]] + +#: A key path inside a parsed TOML document. +KeyPath = Tuple[str, ...] + + +_TOML_ESCAPES = {"\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t"} + + +def toml_string(value: str) -> str: + """ + Render ``value`` as a TOML basic string. + + Quotes, backslashes and control characters are escaped, so user input + (project name, description, author) can never break the document. + ``fastapi_fastkit.utils.config_file`` is not used here because it + imports the interactive package, which imports this module back. + + :param value: Text to quote + :return: TOML string literal + """ + escaped = [] + for char in str(value): + if char in _TOML_ESCAPES: + escaped.append(_TOML_ESCAPES[char]) + elif ord(char) < 0x20 or ord(char) == 0x7F: + escaped.append(f"\\u{ord(char):04X}") + else: + escaped.append(char) + return '"' + "".join(escaped) + '"' + + +def toml_string_array(values: List[str]) -> str: + """Render a list of strings as a single-line TOML array.""" + return "[" + ", ".join(toml_string(value) for value in values) + "]" + + +class PyprojectMergeError(ValueError): + """The pyproject text is invalid TOML, or cannot be edited safely.""" + + +# ------------------------------------------------------------------ +# Lexical scanning +# ------------------------------------------------------------------ + + +def _mask_toml(content: str) -> str: + """ + Return ``content`` with every string and comment character masked. + + Single-line basic / literal strings, both multi-line string kinds + (including the newlines inside them) and comments are replaced + character for character, so indices into the mask are indices into + ``content``. A ``\\n`` left in the mask is therefore always a real line + break of TOML syntax, and brackets left in it are real brackets. + + :param content: TOML text + :return: Masked text of the same length + """ + out = list(content) + index = 0 + length = len(content) + + def blank(start: int, end: int, char: str) -> None: + out[start:end] = char * (end - start) + + while index < length: + char = content[index] + if char == "#": + end = content.find("\n", index) + end = length if end == -1 else end + blank(index, end, _MASK_COMMENT) + index = end + continue + if content.startswith('"""', index) or content.startswith("'''", index): + delimiter = content[index : index + 3] + end = index + 3 + closed = False + while end < length: + if delimiter == '"""' and content[end] == "\\": + end += 2 + continue + if content.startswith(delimiter, end): + # Up to two quote characters may directly precede the + # closing delimiter: the last three of a run of 3-5 + # quotes close the string. + run = end + while run < length and content[run] == delimiter[0]: + run += 1 + end = min(run, end + 5) + closed = True + break + end += 1 + end = min(end, length) if closed else length + blank(index, end, _MASK_STRING) + index = end + continue + if char in "\"'": + end = index + 1 + while end < length and content[end] not in (char, "\n"): + end += 2 if char == '"' and content[end] == "\\" else 1 + end = min(end, length) + if end < length and content[end] == char: + end += 1 + blank(index, end, _MASK_STRING) + index = end + continue + index += 1 + return "".join(out) + + +def _logical_lines(mask: str) -> List[Tuple[int, int]]: + """ + ``(start, end)`` spans of the logical lines of masked TOML text. + + A logical line ends at a real line break (``end`` points past the + ``\\n``); newlines inside multi-line strings do not end one, so a logical + line always starts outside any string. + """ + spans: List[Tuple[int, int]] = [] + start = 0 + while start < len(mask): + newline = mask.find("\n", start) + end = len(mask) if newline == -1 else newline + 1 + spans.append((start, end)) + start = end + return spans + + +def _bracket_delta(masked_line: str) -> int: + return ( + masked_line.count("[") + + masked_line.count("{") + - masked_line.count("]") + - masked_line.count("}") + ) + + +def _newline_of(content: str) -> str: + """The line ending to use for text inserted into ``content``.""" + crlf = content.count("\r\n") + return "\r\n" if crlf and crlf == content.count("\n") else "\n" + + +def _key_repr(part: str) -> str: + return part if _BARE_KEY_PATTERN.match(part) else toml_string(part) + + +def _header_parts(line: str) -> Optional[Tuple[KeyPath, bool]]: + """ + Parse a table header line into its key parts. + + The header is parsed with ``tomllib`` on its own, so quoted parts are + decoded (``[tool."poetry"]`` is ``("tool", "poetry")``) and whitespace + around dots is ignored. + + :param line: One logical line starting with ``[`` + :return: ``(parts, is_array_of_tables)``, or None when it doesn't parse + """ + try: + node: Any = tomllib.loads(line.strip()) + except tomllib.TOMLDecodeError: + return None + parts: List[str] = [] + while isinstance(node, dict) and len(node) == 1: + key, node = next(iter(node.items())) + parts.append(key) + if isinstance(node, list): + return (tuple(parts), True) if node == [{}] else None + # A lone header line always parses to a chain of single-key tables + # ending in ``{}``, so ``parts`` names the table. + return tuple(parts), False + + +def _normalise_table_name(raw: str) -> str: + """``tool . black`` -> ``tool.black`` (whitespace around dots is legal).""" + return ".".join(part.strip() for part in raw.split(".")) + + +@dataclass +class _Block: + """One top-level table block (or the text before the first table).""" + + name: Optional[str] + parts: Optional[KeyPath] + is_array: bool + text: str + + +def _split_blocks(content: str) -> List[_Block]: + """ + Split TOML text into its top-level table blocks. + + A header is a logical line that starts outside every array and inline + table and whose first syntax character is ``[``. Header-looking lines + inside multi-line strings, comments or multi-line arrays (an inline + array on its own line) are therefore never headers. + """ + mask = _mask_toml(content) + blocks: List[_Block] = [_Block(None, None, False, "")] + texts: List[List[str]] = [[]] + depth = 0 + for start, end in _logical_lines(mask): + masked = mask[start:end] + line = content[start:end] + if depth == 0 and masked.lstrip().startswith("["): + parsed = _header_parts(line) + if parsed is not None: + parts, is_array = parsed + name = ".".join(_key_repr(part) for part in parts) + else: + match = _TABLE_HEADER_PATTERN.match(line.rstrip("\r\n")) + raw = match.group("name") if match else line.strip() + name = _normalise_table_name(raw) + parts, is_array = None, masked.lstrip().startswith("[[") + blocks.append(_Block(name, parts, is_array, "")) + texts.append([line]) + # A header line is self-contained; never let a broken one leak + # bracket depth into the next lines. + continue + texts[-1].append(line) + depth = max(0, depth + _bracket_delta(masked)) + for block, lines in zip(blocks, texts): + block.text = "".join(lines) + return blocks + + +def split_toml_tables(content: str) -> TomlBlocks: + """ + Split TOML text into its top-level table blocks. + + Each block runs from its header line up to (not including) the next + header, so blank lines and comments between two tables belong to the + first one. Header-looking lines inside multi-line strings (black's + ``exclude`` regex, for example) or multi-line arrays are not treated as + headers, and quoted header parts are normalised (``[tool."poetry"]`` is + named ``tool.poetry``). + + :param content: TOML text + :return: ``(name, text)`` pairs; joining the texts gives back ``content`` + """ + return [(block.name, block.text) for block in _split_blocks(content)] + + +@dataclass +class _Statement: + """A ``key = value`` statement inside a block.""" + + #: First key part (``a`` for ``a.b = 1``), None when it doesn't parse. + key: Optional[str] + #: Offset of the key's first character. + key_start: int + #: Offset just past the value (before any trailing comment). + value_end: int + #: Offset of the start of the statement's first line. + line_start: int + #: Offset just past the statement's last line break (or the text end). + line_end: int + + +def _statements(block_text: str, has_header: bool) -> List[_Statement]: + """ + List the top-level ``key = value`` statements of a block. + + A statement starts on a logical line outside every array / inline table + and runs until the bracket depth is back to zero, so multi-line arrays + (whatever strings or comments they hold) form one statement. + """ + mask = _mask_toml(block_text) + spans = _logical_lines(mask) + if has_header and spans: + spans = spans[1:] + + statements: List[_Statement] = [] + index = 0 + while index < len(spans): + start, end = spans[index] + masked = mask[start:end] + stripped = masked.strip() + if not stripped or stripped.startswith(_MASK_COMMENT): + index += 1 + continue + depth = _bracket_delta(masked) + last = index + while depth > 0 and last + 1 < len(spans): + last += 1 + depth += _bracket_delta(mask[spans[last][0] : spans[last][1]]) + line_end = spans[last][1] + + value_end = line_end + while value_end > start and mask[value_end - 1] in f" \t\r\n{_MASK_COMMENT}": + value_end -= 1 + key_start = start + (len(masked) - len(masked.lstrip())) + + key: Optional[str] = None + try: + parsed = tomllib.loads(block_text[key_start:value_end]) + if len(parsed) == 1: + key = next(iter(parsed)) + except tomllib.TOMLDecodeError: + key = None + statements.append(_Statement(key, key_start, value_end, start, line_end)) + index = last + 1 + return statements + + +# ------------------------------------------------------------------ +# Parsing and the semantic post-condition +# ------------------------------------------------------------------ + + +def parse_toml(content: str) -> Dict[str, Any]: + """ + Parse TOML text, raising :class:`PyprojectMergeError` when it is invalid. + + :param content: TOML text + :return: Parsed document + """ + try: + return tomllib.loads(content) + except tomllib.TOMLDecodeError as e: + raise PyprojectMergeError(f"Invalid pyproject.toml: {e}") from e + + +def _prune_empty(doc: Dict[str, Any], path: KeyPath) -> None: + """Remove the dict at ``path`` and its ancestors while they are empty.""" + for depth in range(len(path), 0, -1): + parent: Any = doc + for part in path[: depth - 1]: + parent = parent.get(part) if isinstance(parent, dict) else None + if not isinstance(parent, dict): + continue + value = parent.get(path[depth - 1], None) + if isinstance(value, dict) and not value: + del parent[path[depth - 1]] + + +def _remove_path(doc: Dict[str, Any], path: KeyPath) -> None: + parent: Any = doc + for part in path[:-1]: + parent = parent.get(part) if isinstance(parent, dict) else None + if isinstance(parent, dict): + parent.pop(path[-1], None) + _prune_empty(doc, path[:-1]) + + +def _first_difference(before: Any, after: Any, prefix: str = "") -> str: + if isinstance(before, dict) and isinstance(after, dict): + for key in list(before) + [key for key in after if key not in before]: + if before.get(key, ...) != after.get(key, ...): + return _first_difference( + before.get(key), after.get(key), f"{prefix}.{key}" + ) + return prefix.lstrip(".") or "" + + +def _check_preserved( + before: str, + after: str, + owned_keys: Iterable[KeyPath] = (), + owned_tables: Iterable[KeyPath] = (), +) -> Dict[str, Any]: + """ + Check that an edit changed nothing but what it owns. + + Both documents are parsed; the owned keys are removed (and owned tables + left empty by that are dropped) from both, after which they must be + equal. + + :param before: Text before the edit + :param after: Text after the edit + :param owned_keys: Key paths the edit may add, change or remove + :param owned_tables: Table paths that may appear or vanish when empty + :return: The parsed ``after`` document + :raises PyprojectMergeError: if ``after`` is invalid or anything not + owned differs + """ + try: + parsed_after = tomllib.loads(after) + except tomllib.TOMLDecodeError as e: + raise PyprojectMergeError( + f"Editing pyproject.toml would produce invalid TOML ({e})" + ) from e + left = copy.deepcopy(parse_toml(before)) + right = copy.deepcopy(parsed_after) + owned_keys = list(owned_keys) + owned_tables = sorted(owned_tables, key=len, reverse=True) + for doc in (left, right): + for path in owned_keys: + _remove_path(doc, path) + for path in owned_tables: + _prune_empty(doc, path) + if left != right: + raise PyprojectMergeError( + "Editing pyproject.toml would change content fastkit does not own " + f"(at '{_first_difference(left, right)}'); the layout of the file " + "is not supported" + ) + return parsed_after + + +# ------------------------------------------------------------------ +# Table merging (Poetry, PEP 621 files without [project]) +# ------------------------------------------------------------------ + + +def _ensure_trailing_newline(text: str, newline: str = "\n") -> str: + return text if not text or text.endswith("\n") else text + newline + + +def _insert_statement(block_text: str, line: str, newline: str = "\n") -> str: + """Append ``line`` to a block, before its trailing blank lines.""" + text = _ensure_trailing_newline(block_text, newline) + spans = _logical_lines(_mask_toml(text)) + insert_at = len(text) + for start, end in reversed(spans[1:]): + if text[start:end].strip(): + break + insert_at = start + return text[:insert_at] + line.rstrip("\r\n") + newline + text[insert_at:] + + +def _block_keys(block: _Block) -> List[str]: + return [ + statement.key + for statement in _statements(block.text, block.name is not None) + if statement.key is not None + ] + + +def merge_pyproject_tables( + existing: str, + generated: str, + owned_prefixes: Sequence[str] = (), + preserve_keys_in: Sequence[str] = (), +) -> str: + """ + Replace the tables ``generated`` defines inside ``existing``. + + Every standard table named in ``generated`` is owned by the caller and + replaced; its sub-tables are *not* owned (``[[tool.poetry.source]]`` or + ``[tool.poetry.scripts]`` survive a new ``[tool.poetry]``) unless they + fall under one of ``owned_prefixes``. The generated tables are inserted + where the first replaced one was (or at the end); every other table of + ``existing`` is kept unchanged. + + For a table listed in ``preserve_keys_in`` the existing statements whose + key the generated table does not set are carried over into it. + + :param existing: Current pyproject text + :param generated: Tables the caller owns, as TOML text + :param owned_prefixes: Table names whose sub-tables are owned as well + :param preserve_keys_in: Owned tables whose extra keys are kept + :return: Merged TOML text + :raises PyprojectMergeError: if either input is invalid TOML, or the + result is invalid or changes anything the caller does not own + (owned tables defined with dotted keys or inline tables, for example) + """ + parse_toml(existing) + parse_toml(generated) + + newline = _newline_of(existing) + generated_blocks = [ + block for block in _split_blocks(generated) if block.name is not None + ] + owned_names: Set[str] = { + block.name + for block in generated_blocks + if block.name is not None and not block.is_array + } + + def is_owned(block: _Block) -> bool: + if block.name is None: + return False + if not block.is_array and block.name in owned_names: + return True + return any( + block.name == prefix or block.name.startswith(prefix + ".") + for prefix in owned_prefixes + ) + + existing_blocks = _split_blocks(existing) + owned_keys: Set[KeyPath] = set() + owned_tables: Set[KeyPath] = set() + + rendered: List[str] = [] + for block in generated_blocks: + text = block.text + parts = block.parts or tuple((block.name or "").split(".")) + keys = _block_keys(block) + owned_tables.add(parts) + owned_keys.update(parts + (key,) for key in keys) + if block.name in preserve_keys_in: + for old in existing_blocks: + if old.name != block.name or old.is_array: + continue + for statement in _statements(old.text, True): + if statement.key is None or statement.key in keys: + continue + text = _insert_statement( + text, + old.text[statement.line_start : statement.line_end], + "\n", + ) + rendered.append(text) + generated_text = "".join(rendered).replace("\r\n", "\n").strip("\n") + "\n" + if newline != "\n": + generated_text = generated_text.replace("\n", newline) + + kept: List[str] = [] + insert_at: Optional[int] = None + for block in existing_blocks: + if is_owned(block): + if insert_at is None: + insert_at = len(kept) + parts = block.parts or tuple((block.name or "").split(".")) + if block.is_array or block.name not in preserve_keys_in: + owned_tables.add(parts) + if block.is_array: + owned_keys.add(parts) + else: + owned_keys.update(parts + (key,) for key in _block_keys(block)) + continue + kept.append(block.text) + + if insert_at is None or insert_at == len(kept): + body = _ensure_trailing_newline("".join(kept), newline) + if body.strip(): + body = body.rstrip("\r\n") + newline + newline + merged = body + generated_text + else: + before = _ensure_trailing_newline("".join(kept[:insert_at]), newline) + merged = before + generated_text + newline + "".join(kept[insert_at:]) + + try: + parse_toml(merged) + except PyprojectMergeError as e: + raise PyprojectMergeError( + f"{e}; tables fastkit owns ({', '.join(sorted(owned_names))}) must " + "be declared as standard [table] headers, not with dotted keys or " + "inline tables" + ) from e + _check_preserved(existing, merged, owned_keys, owned_tables) + return merged + + +# ------------------------------------------------------------------ +# [project] editing (uv, PDM, ``fastkit addpkg``) +# ------------------------------------------------------------------ + + +def _project_table(content: str) -> Tuple[Dict[str, Any], List[_Block], int]: + """ + Locate the standard ``[project]`` table of ``content``. + + :return: ``(parsed [project], blocks, index of the [project] block)`` + :raises PyprojectMergeError: if ``[project]`` exists but is not a + standard table (dotted keys or an inline table) + """ + project = parse_toml(content).get("project") + if not isinstance(project, dict): + return {}, [], -1 + blocks = _split_blocks(content) + for index, block in enumerate(blocks): + if block.name == "project" and not block.is_array: + return project, blocks, index + raise PyprojectMergeError( + "[project] is defined with dotted keys or as an inline table; fastkit " + "only edits a standard [project] table" + ) + + +def _is_dynamic(project: Dict[str, Any], key: str) -> bool: + dynamic = project.get("dynamic") + return isinstance(dynamic, list) and key in dynamic + + +def _insert_into_project(content: str, line: str) -> str: + _, blocks, index = _project_table(content) + if index < 0: + return content + newline = _newline_of(content) + blocks[index].text = _insert_statement(blocks[index].text, line, newline) + return "".join(block.text for block in blocks) + + +def declared_requires_python(content: str) -> Optional[str]: + """ + Return the Python constraint a pyproject declares, if any. + + ``[project].requires-python`` wins; Poetry's + ``[tool.poetry.dependencies].python`` is the fallback. + + :param content: pyproject text (must be valid TOML) + :return: The constraint string, or None when the file declares none + """ + data = parse_toml(content) + project = data.get("project") + if isinstance(project, dict): + value = project.get("requires-python") + if isinstance(value, str) and value.strip(): + return value.strip() + poetry_deps = data.get("tool", {}).get("poetry", {}).get("dependencies", {}) + if isinstance(poetry_deps, dict): + value = poetry_deps.get("python") + if isinstance(value, str) and value.strip(): + return value.strip() + return None + + +def ensure_requires_python(content: str, default: str = DEFAULT_REQUIRES_PYTHON) -> str: + """ + Make sure ``[project]`` declares ``requires-python``. + + An existing value (the template's floor) is never lowered or otherwise + changed; ``default`` is only written when the key is missing and not + listed in ``[project].dynamic``. + + :param content: pyproject text with a ``[project]`` table + :param default: Constraint written when none is declared + :return: Updated text (unchanged when the key is present or there is no + ``[project]`` table) + :raises PyprojectMergeError: if the key cannot be added safely + """ + project = parse_toml(content).get("project") + if not isinstance(project, dict) or "requires-python" in project: + return content + if _is_dynamic(project, "requires-python"): + debug_log( + "requires-python is dynamic in pyproject.toml; not adding it", "debug" + ) + return content + updated = _insert_into_project(content, f"requires-python = {toml_string(default)}") + _check_preserved(content, updated, [("project", "requires-python")]) + return updated + + +def render_dependency_array(dependencies: List[str], newline: str = "\n") -> str: + """Render a PEP 621 ``dependencies`` array as multi-line TOML.""" + if not dependencies: + return "[]" + body = newline.join(f" {toml_string(dep)}," for dep in dependencies) + return f"[{newline}{body}{newline}]" + + +def replace_project_dependencies( + content: str, dependencies: List[str], insert_missing: bool = False +) -> Optional[str]: + """ + Replace ``[project].dependencies`` in pyproject text. + + The key is looked up among the statements of the standard ``[project]`` + table, so a ``dependencies = [`` inside a multi-line string or another + table is never touched, and the array's end is found by bracket + matching that ignores brackets inside strings and comments + (``redis[hiredis]``, ``# see [extras``). The result is checked with + the semantic post-condition before it is returned. + + :param content: pyproject text + :param dependencies: Dependency specifications to write + :param insert_missing: Add the key when ``[project]`` has none (skipped + when ``[project].dynamic`` lists ``dependencies``) + :return: Updated text, or None when there is no ``[project]`` table or + (without ``insert_missing``) no ``dependencies`` key in it + :raises PyprojectMergeError: if ``content`` is invalid TOML or the key + cannot be replaced without changing anything else + """ + project, blocks, index = _project_table(content) + if index < 0: + return None + + newline = _newline_of(content) + rendered = f"dependencies = {render_dependency_array(dependencies, newline)}" + block = blocks[index] + statement = next( + (item for item in _statements(block.text, True) if item.key == "dependencies"), + None, + ) + + if statement is None: + if "dependencies" in project: + raise PyprojectMergeError( + "[project].dependencies is declared in a form fastkit cannot " + "edit safely" + ) + if not insert_missing: + return None + if _is_dynamic(project, "dependencies"): + debug_log( + "dependencies is dynamic in pyproject.toml; not adding it", "debug" + ) + return content + block.text = _insert_statement(block.text, rendered, newline) + else: + block.text = ( + block.text[: statement.key_start] + + rendered + + block.text[statement.value_end :] + ) + + updated = "".join(item.text for item in blocks) + parsed = _check_preserved(content, updated, [("project", "dependencies")]) + if parsed.get("project", {}).get("dependencies") != list(dependencies): + raise PyprojectMergeError( + "[project].dependencies could not be replaced in pyproject.toml" + ) + return updated + + +def update_pep621_pyproject( + existing: Optional[str], generated: str, dependencies: List[str] +) -> str: + """ + Produce the pyproject a PEP 621 package manager (uv, PDM) should write. + + - No existing file: ``generated`` as is. + - An existing file with a ``[project]`` table (every fastkit template): + kept as is, except that ``[project].dependencies`` is replaced and a + missing ``requires-python`` is filled with the shared default. The + template's floor, dependency groups and ``[tool.*]`` tables survive. + - An existing file without ``[project]``: the generated tables are merged + in and every other table is kept. + + :param existing: Current pyproject text, or None when there is none + :param generated: The manager's full skeleton (used when nothing exists) + :param dependencies: Dependency specifications for ``[project]`` + :return: Text to write + :raises PyprojectMergeError: if ``existing`` is not valid TOML or cannot + be updated without changing content the manager does not own + """ + if existing is None or not existing.strip(): + return generated + + data = parse_toml(existing) + if not isinstance(data.get("project"), dict): + return merge_pyproject_tables(existing, generated) + + updated = replace_project_dependencies(existing, dependencies, insert_missing=True) + if updated is None: + raise PyprojectMergeError( + "Could not locate [project].dependencies in pyproject.toml" + ) + return ensure_requires_python(updated) + + +__all__ = [ + "PyprojectMergeError", + "declared_requires_python", + "ensure_requires_python", + "merge_pyproject_tables", + "parse_toml", + "render_dependency_array", + "replace_project_dependencies", + "split_toml_tables", + "toml_string", + "toml_string_array", + "update_pep621_pyproject", +] diff --git a/src/fastapi_fastkit/backend/package_managers/uv_manager.py b/src/fastapi_fastkit/backend/package_managers/uv_manager.py index 7ccb6a50..77df9336 100644 --- a/src/fastapi_fastkit/backend/package_managers/uv_manager.py +++ b/src/fastapi_fastkit/backend/package_managers/uv_manager.py @@ -7,15 +7,57 @@ from typing import List from fastapi_fastkit.core.exceptions import BackendExceptions -from fastapi_fastkit.core.settings import settings +from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON, settings from fastapi_fastkit.utils.logging import debug_log, get_logger from fastapi_fastkit.utils.main import print_success +from fastapi_fastkit.utils.platform import resolve_command +from fastapi_fastkit.utils.textio import write_generated_text from .base import BasePackageManager +from .pyproject import ( + render_dependency_array, + toml_string, + update_pep621_pyproject, +) logger = get_logger(__name__) +def _uv_pyproject( + dependencies: List[str], + project_name: str, + description: str, + author: str, + author_email: str, +) -> str: + """Render a standalone pyproject.toml for a UV project.""" + author_entry = ( + f"{{name = {toml_string(author)}, " f"email = {toml_string(author_email)}}}" + ) + return f"""[project] +name = {toml_string(project_name)} +version = "0.1.0" +description = {toml_string(description)} +authors = [ + {author_entry}, +] +dependencies = {render_dependency_array(dependencies)} +requires-python = {toml_string(DEFAULT_REQUIRES_PYTHON)} +readme = "README.md" +license = {{text = "MIT"}} + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src"] + +[tool.uv] +dev-dependencies = [] +""" + + class UvManager(BasePackageManager): """UV package manager implementation.""" @@ -81,7 +123,13 @@ def generate_dependency_file( description: str = "", ) -> None: """ - Generate a pyproject.toml file with the given dependencies and metadata. + Write the dependencies and metadata into pyproject.toml. + + A pyproject.toml the template already shipped is updated in place: + only ``[project].dependencies`` is replaced (and ``requires-python`` + filled in when missing), so the template's Python floor, dependency + groups, ``[tool.*]`` tables and fastkit marker are kept. Without an + existing file a standalone UV pyproject.toml is written. :param dependencies: List of dependency specifications :param project_name: Name of the project @@ -92,45 +140,26 @@ def generate_dependency_file( pyproject_path = self.get_dependency_file_path() try: - # Create dependencies list as TOML format - deps_toml = "[\n" - for dep in dependencies: - deps_toml += f' "{dep}",\n' - deps_toml += "]" - - # Create basic pyproject.toml content for UV - pyproject_content = f"""[project] -name = "{project_name or "fastapi-project"}" -version = "0.1.0" -description = "{description or "A FastAPI project"}" -authors = [ - {{name = "{author or "Author"}", email = "{author_email or "author@example.com"}"}}, -] -dependencies = {deps_toml} -requires-python = ">=3.8" -readme = "README.md" -license = {{text = "MIT"}} - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[tool.hatch.build.targets.wheel] -packages = ["src"] - -[tool.uv] -dev-dependencies = [] -""" - - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(pyproject_content) + fresh_content = _uv_pyproject( + dependencies, + project_name or "fastapi-project", + description or "A FastAPI project", + author or "Author", + author_email or "author@example.com", + ) + self._write_pyproject( + lambda existing: update_pep621_pyproject( + existing, fresh_content, dependencies + ), + fresh_content, + ) debug_log( f"Generated {pyproject_path} with {len(dependencies)} dependencies", "info", ) - except (OSError, UnicodeEncodeError) as e: + except (OSError, UnicodeError) as e: debug_log(f"Error generating pyproject.toml: {e}", "error") raise BackendExceptions(f"Failed to generate pyproject.toml: {str(e)}") @@ -149,11 +178,13 @@ def add_dependency(self, dependency: str, dev: bool = False) -> None: cmd.append(dependency) subprocess.run( - cmd, + resolve_command(cmd), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout("install"), ) @@ -183,43 +214,23 @@ def initialize_project( try: # Use UV init command to initialize project subprocess.run( - ["uv", "init", "--name", project_name], + resolve_command(["uv", "init", "--name", project_name]), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout(), ) # Create custom pyproject.toml with provided metadata pyproject_path = self.get_dependency_file_path() - # Create pyproject.toml with project metadata - pyproject_content = f"""[project] -name = "{project_name}" -version = "0.1.0" -description = "{description}" -authors = [ - {{name = "{author}", email = "{author_email}"}}, -] -dependencies = [] -requires-python = ">=3.8" -readme = "README.md" -license = {{text = "MIT"}} - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[tool.hatch.build.targets.wheel] -packages = ["src"] - -[tool.uv] -dev-dependencies = [] -""" - - with open(pyproject_path, "w", encoding="utf-8") as f: - f.write(pyproject_content) + pyproject_content = _uv_pyproject( + [], project_name, description, author, author_email + ) + write_generated_text(pyproject_path, pyproject_content) debug_log(f"Initialized UV project: {project_name}", "info") @@ -255,11 +266,13 @@ def run_script(self, script_command: str) -> None: """ try: subprocess.run( - ["uv", "run"] + script_command.split(), + resolve_command(["uv", "run"] + script_command.split()), cwd=str(self.project_dir), check=True, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=settings.get_subprocess_timeout(), ) diff --git a/src/fastapi_fastkit/backend/project_builder/config_generator.py b/src/fastapi_fastkit/backend/project_builder/config_generator.py index 7ee7dfaf..a2270f7b 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_generator.py +++ b/src/fastapi_fastkit/backend/project_builder/config_generator.py @@ -18,14 +18,20 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import hashlib +import re import sys from dataclasses import dataclass, field from functools import lru_cache from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Sequence, Tuple from jinja2 import Environment, PackageLoader +from fastapi_fastkit.backend.package_managers.pyproject import ( + PyprojectMergeError, + parse_toml, + split_toml_tables, +) from fastapi_fastkit.core.settings import ( NONE_CHOICE, AsyncTaskChoice, @@ -40,6 +46,11 @@ ToolingChoice, UtilityChoice, ) +from fastapi_fastkit.utils.textio import ( + read_text_preserving_newlines, + write_generated_text, + write_text_preserving_newlines, +) #: Dotted SQLAlchemy URLs per relational database choice. SQLALCHEMY_URLS: Dict[str, str] = { @@ -74,6 +85,21 @@ #: Files written with the executable bit set. _EXECUTABLE_ARTIFACTS = frozenset({"scripts/migrate.sh"}) +#: The shareable environment file the generated project documents its +#: variables in. The local ``.env`` is derived from it afterwards. +ENV_EXAMPLE_RELPATH = ".env.example" + +#: Auth choices whose module signs tokens or cookies with ``SECRET_KEY``. +_SIGNING_AUTH_CHOICES = frozenset( + {AuthChoice.JWT, AuthChoice.OAUTH2, AuthChoice.SESSION} +) + + +def _env_example_declares(content: str, variable: str) -> bool: + """Whether ``.env.example`` already mentions ``variable``, even commented out.""" + pattern = rf"^[ \t]*#?[ \t]*(?:export[ \t]+)?{re.escape(variable)}[ \t]*=" + return re.search(pattern, content, re.M) is not None + @lru_cache(maxsize=1) def get_environment() -> Environment: @@ -144,6 +170,23 @@ class MainSections: needs_os: bool = False +def _declares_tool_table(pyproject_text: str, tool: str) -> bool: + """Whether pyproject text already configures ``[tool.]``. + + Parsed as TOML so a mention in a comment or string does not count and a + second table of the same name (invalid TOML) is never appended. Text that + does not parse falls back to a header-line search. + """ + try: + tools = parse_toml(pyproject_text).get("tool", {}) + return isinstance(tools, dict) and tool in tools + except PyprojectMergeError: + return any( + name == f"tool.{tool}" or (name or "").startswith(f"tool.{tool}.") + for name, _ in split_toml_tables(pyproject_text) + ) + + class DynamicConfigGenerator: """ Generates configuration files based on project config. @@ -163,6 +206,7 @@ def __init__( main_py_relpath: str = DEFAULT_MAIN_RELPATH, db_config_relpath: str = DEFAULT_DB_CONFIG_RELPATH, auth_config_relpath: str = DEFAULT_AUTH_CONFIG_RELPATH, + omit_example_routers: Sequence[str] = (), ) -> None: """ Initialize config generator. @@ -174,6 +218,12 @@ def __init__( main_py_relpath: Project-relative path of the application entrypoint db_config_relpath: Project-relative path of the database module auth_config_relpath: Project-relative path of the auth module + omit_example_routers: Labels of features (``"Pagination"``) whose + demo router is not generated because the base template + already serves that collection. Decided by + ``PresetLayoutStrategist.skipped_example_labels``, which only + names features for presets that keep the template's + ``main.py`` (the preserved file is wired separately). """ self.config = config self.project_dir = Path(project_dir) @@ -181,6 +231,7 @@ def __init__( self.main_py_relpath = main_py_relpath self.db_config_relpath = db_config_relpath self.auth_config_relpath = auth_config_relpath + self.omit_example_routers = frozenset(omit_example_routers) # ----------------------------------------------------------------- # # Layout helpers @@ -316,6 +367,19 @@ def _uses_ruff(self) -> bool: """Whether ruff replaces black + isort in the generated tooling.""" return ToolingChoice.RUFF in self._choices(FeatureAxis.TOOLING) + @property + def _needs_black_config(self) -> bool: + """Whether black runs from pre-commit and needs a pyproject target. + + The pre-commit hook no longer passes ``--target-version``; black reads + it from ``pyproject.toml`` instead. Template pyprojects ship their own + ``[tool.black]`` (kept when a package manager updates the file), and + :meth:`apply_black_configuration` only adds one when it is missing. + """ + return not self._uses_ruff and ToolingChoice.PRE_COMMIT in self._choices( + FeatureAxis.TOOLING + ) + @property def _needs_redis_service(self) -> bool: """Whether docker-compose must ship a Redis service.""" @@ -401,8 +465,10 @@ def _main_fragments(self) -> MainSections: if monitoring_type == MonitoringChoice.LOGURU: imports.append("main/imports/loguru.j2") elif monitoring_type == MonitoringChoice.PROMETHEUS: + # Module level, never in the lifespan: instrumenting adds + # middleware, which Starlette refuses once the app has started. imports.append("main/imports/prometheus.j2") - lifespan.append("main/lifespan/prometheus.j2") + setup.append("main/setup/prometheus.j2") elif monitoring_type == MonitoringChoice.OPENTELEMETRY: imports.append("main/imports/opentelemetry.j2") setup.append("main/setup/opentelemetry.j2") @@ -412,6 +478,7 @@ def _main_fragments(self) -> MainSections: needs_os = bool( {"main/lifespan/caching.j2"} & set(lifespan) or { + "main/setup/cors.j2", "main/setup/opentelemetry.j2", "main/setup/structured_logging.j2", } @@ -535,6 +602,10 @@ def planned_files(self, include_main: bool = True) -> List[str]: if self._uses_ruff: planned.add("pyproject.toml") + if self._needs_black_config and (self.project_dir / "pyproject.toml").exists(): + planned.add("pyproject.toml") + if self.env_example_blocks(include_main=include_main): + planned.add(ENV_EXAMPLE_RELPATH) return sorted(planned) @@ -557,7 +628,7 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: for relpath, content in self.build_artifacts(include_main=include_main).items(): target = self.project_dir / relpath target.parent.mkdir(parents=True, exist_ok=True) - target.write_text(content, encoding="utf-8") + write_generated_text(target, content) if relpath in _EXECUTABLE_ARTIFACTS: target.chmod(0o755) written.append(relpath) @@ -566,9 +637,128 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: if self._uses_ruff: written.append(self.apply_ruff_configuration()) + elif self._needs_black_config: + black_target = self.apply_black_configuration() + if black_target: + written.append(black_target) + + env_example = self.apply_env_example(include_main=include_main) + if env_example: + written.append(env_example) return sorted(set(written)) + def env_example_blocks( + self, include_main: bool = True + ) -> List[Tuple[str, List[str]]]: + """ + ``.env.example`` lines documenting the variables the selection reads. + + Each block documents one variable (the first element) in a few + comment lines plus an assignment or a commented example. Values + are placeholders only: ``SECRET_KEY`` is replaced with a unique key + when the local ``.env`` is generated from this file. + + Args: + include_main: Whether the dynamic ``main.py`` overlay is generated + (its CORS setup reads ``BACKEND_CORS_ORIGINS``; template + entrypoints document their own settings) + + Returns: + ``(variable, lines)`` blocks, in the order they are appended + """ + blocks: List[Tuple[str, List[str]]] = [] + + auth_type = self._auth_type + if auth_type in _SIGNING_AUTH_CHOICES: + blocks.append( + ( + "SECRET_KEY", + [ + "# Signs tokens and session cookies. fastkit writes a unique", + "# value to .env; never deploy this example value.", + "SECRET_KEY=changethis", + ], + ) + ) + blocks.append( + ( + "ENVIRONMENT", + [ + '# "production" refuses to start without a real SECRET_KEY.', + "ENVIRONMENT=development", + ], + ) + ) + if auth_type == AuthChoice.OAUTH2: + blocks.append( + ( + "GOOGLE_CLIENT_ID", + [ + "# OAuth2 provider credentials.", + "GOOGLE_CLIENT_ID=", + "GOOGLE_CLIENT_SECRET=", + "GITHUB_CLIENT_ID=", + "GITHUB_CLIENT_SECRET=", + ], + ) + ) + + if include_main and UtilityChoice.CORS in self._choices(FeatureAxis.UTILITIES): + blocks.append( + ( + "BACKEND_CORS_ORIGINS", + [ + "# Comma-separated browser origins allowed to call the API.", + '# Unset: no cross-origin access. "*": any origin, no cookies.', + "# main.py reads it from the process environment: export it", + "# or start uvicorn with --env-file .env.", + "# BACKEND_CORS_ORIGINS=http://localhost:3000", + ], + ) + ) + + return blocks + + def apply_env_example(self, include_main: bool = True) -> Optional[str]: + """ + Append :meth:`env_example_blocks` to the project's ``.env.example``. + + A block is skipped when its variable is already mentioned (also as a + comment), so the template's own entries win and re-running is a + no-op. The file is created when the template ships none. + + Args: + include_main: See :meth:`env_example_blocks` + + Returns: + ``".env.example"`` when the file holds the entries, None when the + selection documents no variable + """ + blocks = self.env_example_blocks(include_main=include_main) + if not blocks: + return None + + path = self.project_dir / ENV_EXAMPLE_RELPATH + if path.exists(): + existing, newline = read_text_preserving_newlines(path) + else: + existing, newline = "", "\n" + + content = existing + for variable, block in blocks: + if _env_example_declares(content, variable): + continue + if content and not content.endswith("\n"): + content += "\n" + if content: + content += "\n" + content += "\n".join(block) + "\n" + + if content != existing: + write_text_preserving_newlines(path, content, newline) + return ENV_EXAMPLE_RELPATH + def generate_main_py(self) -> str: """ Generate main.py with selected features. @@ -703,7 +893,10 @@ def generate_feature_modules(self) -> Dict[str, str]: modules[f"{feature_dir}/websocket.py"] = self._render_module( "features/websocket.py.j2", title="WebSocket Routes" ) - if UtilityChoice.PAGINATION in utilities: + if ( + UtilityChoice.PAGINATION in utilities + and UtilityChoice.PAGINATION not in self.omit_example_routers + ): modules[f"{feature_dir}/pagination.py"] = self._render_module( "features/pagination.py.j2", title="Paginated Routes" ) @@ -821,19 +1014,46 @@ def apply_ruff_configuration(self) -> str: pyproject = self.project_dir / "pyproject.toml" if pyproject.exists(): - existing = pyproject.read_text(encoding="utf-8") - if "[tool.ruff]" not in existing: + existing, newline = read_text_preserving_newlines(pyproject) + if not _declares_tool_table(existing, "ruff"): if not existing.endswith("\n"): existing += "\n" - pyproject.write_text(existing + snippet, encoding="utf-8") + write_text_preserving_newlines(pyproject, existing + snippet, newline) return "pyproject.toml" # ``ruff.toml`` uses bare top-level keys, not ``[tool.ruff]`` tables. standalone = snippet.replace("[tool.ruff.", "[").replace("[tool.ruff]\n", "") ruff_toml = self.project_dir / "ruff.toml" - ruff_toml.write_text(standalone.lstrip("\n"), encoding="utf-8") + write_generated_text(ruff_toml, standalone.lstrip("\n")) return "ruff.toml" + def apply_black_configuration(self) -> Optional[str]: + """ + Merge a ``[tool.black]`` table into the project's ``pyproject.toml``. + + black reads its target version from ``pyproject.toml``, so the + pre-commit hook needs no ``--target-version`` argument and stays + independent of the interpreter the hook shell happens to find. An + existing ``[tool.black]`` table is left untouched. Without a + ``pyproject.toml`` nothing is written: black then infers the target + from the source, and only ``pyproject.toml`` is read for its config. + + Returns: + ``"pyproject.toml"`` when the file holds black's configuration, + None when the project has no ``pyproject.toml`` + """ + pyproject = self.project_dir / "pyproject.toml" + if not pyproject.exists(): + return None + + existing, newline = read_text_preserving_newlines(pyproject) + if not _declares_tool_table(existing, "black"): + if not existing.endswith("\n"): + existing += "\n" + snippet = self._render_module("tooling/black_toml.j2") + write_text_preserving_newlines(pyproject, existing + snippet, newline) + return "pyproject.toml" + def generate_testing_files(self) -> Dict[str, str]: """ Generate the extra test scaffolding for the ``Advanced`` tier. @@ -870,14 +1090,14 @@ def generate_docker_files(self, app_module: str = "src.main:app") -> List[str]: if "Docker" in deployment: dockerfile_path = self.project_dir / "Dockerfile" - dockerfile_path.write_text( - self._generate_dockerfile(app_module=app_module), encoding="utf-8" + write_generated_text( + dockerfile_path, self._generate_dockerfile(app_module=app_module) ) written.append("Dockerfile") if "docker-compose" in deployment: compose_path = self.project_dir / "docker-compose.yml" - compose_path.write_text(self._generate_docker_compose(), encoding="utf-8") + write_generated_text(compose_path, self._generate_docker_compose()) written.append("docker-compose.yml") return written diff --git a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py index aa51b066..9415d03d 100644 --- a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py +++ b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py @@ -8,18 +8,92 @@ # - Additional features # - Custom packages # -# Handles deduplication and version conflict detection. +# Handles deduplication, including folding ``pkg`` and ``pkg[extra]`` into a +# single requirement so a package never appears twice. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- -from typing import Any, Dict, List, Set +import re +from typing import Any, Dict, Iterable, List, Set, Tuple +from fastapi_fastkit.backend.package_managers.poetry_manager import ( + _parse_pip_requirement, +) from fastapi_fastkit.core.settings import ( MULTI_SELECT_AXES, NONE_CHOICE, FeatureAxis, ) +_SIMPLE_NAME_PATTERN = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$") + + +def canonical_package_name(name: str) -> str: + """Normalise a distribution name the way PEP 503 does (``Foo_Bar`` -> ``foo-bar``).""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def merge_requirements(requirements: Iterable[str]) -> List[str]: + """ + Deduplicate requirement strings, folding extras of one package together. + + ``sqlalchemy`` and ``sqlalchemy[asyncio]`` name the same distribution; + listing both is redundant for pip/uv and a duplicate key in Poetry's + ``[tool.poetry.dependencies]`` table. Entries are grouped by canonical + name and environment marker. A group whose entries agree on the version + specifier (or leave it empty) collapses into one requirement carrying the + union of their extras; a group with conflicting specifiers is left as is + so the conflict stays visible to the resolver. Entries that are not plain + ``name[extras]; marker`` requirements (direct URLs, ...) pass + through untouched. + + Args: + requirements: PEP 508 requirement strings + + Returns: + Sorted, deduplicated requirement strings + """ + passthrough: Set[str] = set() + groups: Dict[Tuple[str, str], List[Tuple[str, List[str], str]]] = {} + for requirement in requirements: + requirement = requirement.strip() + if not requirement: + continue + name, extras, spec, marker = _parse_pip_requirement(requirement) + if not _SIMPLE_NAME_PATTERN.match(name): + passthrough.add(requirement) + continue + key = (canonical_package_name(name), marker) + groups.setdefault(key, []).append((name, extras, spec)) + + merged: Set[str] = set(passthrough) + for (_, marker), entries in groups.items(): + specs = {spec for _, _, spec in entries if spec} + if len(specs) > 1: + for name, extras, spec in entries: + merged.add(_format_requirement(name, extras, spec, marker)) + continue + spec = specs.pop() if specs else "" + # Prefer the spelling of the entry that carries the version pin. + name = next((n for n, _, s in entries if s), entries[0][0]) + extras = sorted( + {extra for _, group_extras, _ in entries for extra in group_extras} + ) + merged.add(_format_requirement(name, extras, spec, marker)) + + return sorted(merged) + + +def _format_requirement(name: str, extras: List[str], spec: str, marker: str) -> str: + """Render the pieces :func:`_parse_pip_requirement` returns back into PEP 508.""" + text = name + if extras: + text += f"[{','.join(extras)}]" + text += spec + if marker: + text += f"; {marker}" + return text + class DependencyCollector: """ @@ -234,10 +308,13 @@ def get_final_dependencies(self) -> List[str]: """ Return deduplicated, sorted dependency list. + ``pkg`` and ``pkg[extra]`` are folded into one entry (see + :func:`merge_requirements`). + Returns: Sorted list of all dependencies """ - return sorted(list(self.dependencies)) + return merge_requirements(self.dependencies) def get_dependency_count(self) -> int: """ diff --git a/src/fastapi_fastkit/backend/project_builder/preset_layout.py b/src/fastapi_fastkit/backend/project_builder/preset_layout.py index d5b02fff..5e2a863b 100644 --- a/src/fastapi_fastkit/backend/project_builder/preset_layout.py +++ b/src/fastapi_fastkit/backend/project_builder/preset_layout.py @@ -34,6 +34,10 @@ MonitoringChoice, UtilityChoice, ) +from fastapi_fastkit.utils.textio import ( + read_text_preserving_newlines, + write_text_preserving_newlines, +) # Canonical preset id used when a caller doesn't supply one. Picked to # preserve pre-#45 behaviour: interactive ``init`` historically deployed @@ -51,6 +55,25 @@ def _axis_is(config: Dict[str, Any], axis: str, choice: str) -> bool: return config.get(axis) == choice +@dataclass(frozen=True) +class ShippedCollection: + """A list endpoint the base template already serves for one resource. + + Feature overlays that would generate a demo router for the same + resource (see ``OverlayTarget.example_collection``) skip that router + instead of shadowing the template's own endpoint. + """ + + #: Resource name, matched against ``OverlayTarget.example_collection``. + name: str + #: ``" "`` of the list endpoint as the app serves it. + endpoint: str + #: Project-relative module that defines the list endpoint. + module_relpath: str + #: Response schema of one element of the list. + schema: str + + @dataclass(frozen=True) class OverlayTarget: """One feature whose wiring normally lives in the dynamic main.py overlay. @@ -60,12 +83,32 @@ class OverlayTarget: present) is the import / statement pair that can be spliced into a template-shipped ``main.py`` through its ``# fastkit:`` anchors instead of only being warned about. + + A target whose generated router is a demo collection names that + resource in ``example_collection``. When the preset's base template + already ships that collection (``PresetProfile.shipped_collections``), + the demo router is not generated and ``collection_wiring`` replaces + ``wiring``; its statements are appended to the end of ``main.py``, after + the template's own routers are included, preceded by ``collection_hint`` + as a comment. """ label: str applies: Callable[[Dict[str, Any]], bool] #: ``(import lines, statement lines)`` rendered with ``{pkg}``. wiring: Tuple[Tuple[str, ...], Tuple[str, ...]] = ((), ()) + #: Resource the generated demo router serves as a collection, if any. + example_collection: str = "" + #: Module (relative to the application package) holding the demo router. + example_module: str = "" + #: Wiring used instead of ``wiring`` when the demo router is skipped. + collection_wiring: Tuple[Tuple[str, ...], Tuple[str, ...]] = ((), ()) + #: Comment lines for ``collection_wiring`` (without ``# ``), each rendered + #: with the fields of the matching :class:`ShippedCollection`. + collection_hint: Tuple[str, ...] = () + #: One-line how-to shown with the manual-wiring warning, rendered with + #: ``{auth_module}`` (dotted path of the generated auth module). + manual_hint: str = "" @property def is_wirable(self) -> bool: @@ -102,6 +145,27 @@ def is_wirable(self) -> bool: ), ("app.include_router(pagination_router)", "add_pagination(app)"), ), + # The demo router serves ``GET /api/v1/items``; a template that already + # has an items API keeps its own endpoint and only gets + # ``add_pagination(app)`` plus a how-to comment. + example_collection="items", + example_module="features/pagination.py", + collection_wiring=( + ("from fastapi_pagination import add_pagination",), + ("add_pagination(app)",), + ), + collection_hint=( + "fastapi-pagination: this template already serves {endpoint},", + "so no example pagination router was generated. To paginate that", + "endpoint, edit {module_relpath}:", + " from fastapi_pagination import Page, paginate", + " @router.get(..., response_model=Page[{schema}])", + " ...", + " return paginate(items)", + "?page= and ?size= then become query parameters, and the response", + 'body changes from a list to {{"items": [...], "total": ..., "page": ...,', + '"size": ..., "pages": ...}}, so update the template\'s list test too.', + ), ), OverlayTarget( label="Background tasks", @@ -119,11 +183,18 @@ def is_wirable(self) -> bool: label="Caching (Redis)", applies=lambda c: _axis_is(c, FeatureAxis.CACHING, CachingChoice.REDIS), ), + # Warn-only: the package is installed but nothing is generated, and the + # instrumentation must run at import time, right after ``app = FastAPI``. OverlayTarget( label="Prometheus", applies=lambda c: _axis_is( c, FeatureAxis.MONITORING, MonitoringChoice.PROMETHEUS ), + manual_hint=( + "Prometheus: add `Instrumentator().instrument(app).expose(app)` " + "(from prometheus_fastapi_instrumentator) right after " + "`app = FastAPI(...)`, not inside a lifespan handler." + ), ), OverlayTarget( label="OpenTelemetry", @@ -134,10 +205,23 @@ def is_wirable(self) -> bool: OverlayTarget( label="OAuth2 session middleware", applies=lambda c: _axis_is(c, FeatureAxis.AUTHENTICATION, AuthChoice.OAUTH2), + manual_hint=( + "OAuth2: import `auth_settings` and `router` from {auth_module}, then " + "add `app.add_middleware(SessionMiddleware, " + "secret_key=auth_settings.SECRET_KEY)` and " + "`app.include_router(router)`." + ), ), OverlayTarget( label="Session-based auth middleware", applies=lambda c: _axis_is(c, FeatureAxis.AUTHENTICATION, AuthChoice.SESSION), + manual_hint=( + "Session auth: import `auth_settings` and `router` from {auth_module}, " + "then add `app.add_middleware(SessionMiddleware, " + "secret_key=auth_settings.SECRET_KEY, " + "max_age=auth_settings.SESSION_MAX_AGE)` and " + "`app.include_router(router)`." + ), ), OverlayTarget( label="Structured logging", @@ -171,6 +255,10 @@ class PresetProfile: # "no special note for this preset". manual_wiring_note: str = "" extra_warning_targets: Tuple[str, ...] = field(default_factory=tuple) + # List endpoints the base template ships and keeps (only meaningful when + # ``regenerate_main`` is False: a regenerated main.py does not mount the + # template's routers, so nothing generated can shadow them). + shipped_collections: Tuple[ShippedCollection, ...] = field(default_factory=tuple) _PRESET_PROFILES: Dict[str, PresetProfile] = { @@ -207,6 +295,14 @@ class PresetProfile: "wired — set BACKEND_CORS_ORIGINS in .env to activate it)." ), extra_warning_targets=_NON_CORS_TARGETS, + shipped_collections=( + ShippedCollection( + name="items", + endpoint="GET /items", + module_relpath="src/api/routes/items.py", + schema="ItemResponse", + ), + ), ), "domain-starter": PresetProfile( preset_id="domain-starter", @@ -221,6 +317,14 @@ class PresetProfile: "wired — set BACKEND_CORS_ORIGINS in .env to activate it)." ), extra_warning_targets=_NON_CORS_TARGETS, + shipped_collections=( + ShippedCollection( + name="items", + endpoint="GET /api/v1/items", + module_relpath="src/app/domains/items/router.py", + schema="ItemRead", + ), + ), ), } @@ -232,9 +336,47 @@ def _package_root(main_py_relpath: str) -> str: ``DynamicConfigGenerator.pkg`` so the import lines spliced into a preserved ``main.py`` match where the generator actually wrote them. """ + return _package_dir(main_py_relpath).replace("/", ".") + + +def _package_dir(main_py_relpath: str) -> str: + """Project-relative directory of the application package (``src/app``).""" normalized = main_py_relpath.replace("\\", "/").strip("/") - parent = normalized.rsplit("/", 1)[0] if "/" in normalized else "src" - return parent.replace("/", ".") + return normalized.rsplit("/", 1)[0] if "/" in normalized else "src" + + +def _wire_without_example( + content: str, target: OverlayTarget, collection: ShippedCollection, pkg: str +) -> str: + """Apply ``target.collection_wiring`` to a preserved ``main.py``. + + Imports go through the usual sorted insertion. The statements are + appended to the end of the module, after the template's own + ``include_router`` calls, so that anything that inspects the mounted + routes at call time (``add_pagination``) sees the template's endpoints. + The how-to comment from ``target.collection_hint`` precedes them. + """ + # Imported lazily: ``backend.main`` imports this module at load time. + from fastapi_fastkit.backend.main import insert_import_line + + imports, statements = target.collection_wiring + for line in imports: + content = insert_import_line(content, line.format(pkg=pkg)) + + pending = [line.format(pkg=pkg) for line in statements] + pending = [line for line in pending if line not in content] + if not pending: + return content + + fields = { + "endpoint": collection.endpoint, + "module_relpath": collection.module_relpath, + "schema": collection.schema, + } + block = [f"# {line.format(**fields)}".rstrip() for line in target.collection_hint] + block.extend(pending) + # Two blank lines keep the block valid after a top-level function too. + return content.rstrip("\n") + "\n\n\n" + "\n".join(block) + "\n" def app_module_from_relpath(relpath: str) -> str: @@ -252,9 +394,24 @@ def app_module_from_relpath(relpath: str) -> str: return f"{module_part}:app" +#: Entrypoint assumed when ``main.py`` cannot be expressed relative to the +#: project (the historical ``src/main.py`` layout). +_FALLBACK_APP_MODULE = "src.main:app" + + def app_module_from_main_path(project_dir: str, main_path: str) -> str: - """Convert an absolute ``main.py`` location into ``module:attr``.""" - return app_module_from_relpath(os.path.relpath(main_path, project_dir)) + """Convert an absolute ``main.py`` location into ``module:attr``. + + ``os.path.relpath`` raises ``ValueError`` on Windows when the two paths + are on different drives. Such a ``main.py`` is not inside the project, so + the historical ``src.main:app`` entrypoint is returned instead of + crashing. + """ + try: + relative = os.path.relpath(main_path, project_dir) + except ValueError: + return _FALLBACK_APP_MODULE + return app_module_from_relpath(relative) class PresetLayoutStrategist: @@ -344,14 +501,21 @@ def compatibility_warnings( if self.profile.manual_wiring_note: warnings.append(self.profile.manual_wiring_note) warnings.append( - "Affected selections (modules and packages generated, but you must " - "register them yourself in " + "Affected selections (packages installed and any modules generated, " + "but you must register them yourself in " + self.profile.main_py_relpath + " for the '" + self.profile.preset_id + "' preset): " + ", ".join(affected) ) + auth_module = self.profile.auth_config_relpath.removesuffix(".py").replace( + "/", "." + ) + for label in affected: + hint = _TARGETS_BY_LABEL[label].manual_hint + if hint: + warnings.append(hint.format(auth_module=auth_module)) return warnings def _affected_overlay_targets(self, config: Dict[str, Any]) -> List[str]: @@ -362,6 +526,51 @@ def _affected_overlay_targets(self, config: Dict[str, Any]) -> List[str]: if label in _TARGETS_BY_LABEL and _TARGETS_BY_LABEL[label].applies(config) ] + def skipped_example_routers( + self, config: Dict[str, Any] + ) -> List[Tuple[OverlayTarget, ShippedCollection]]: + """Selected features whose demo router the base template would clash with. + + A feature that generates a demo collection router (for example the + pagination demo on ``GET /api/v1/items``) is not given that router + when the base template already serves the same collection: the demo + would shadow or duplicate the template's own endpoint. + + Args: + config: Interactive project configuration + + Returns: + ``(target, shipped collection)`` pairs, empty for presets that + regenerate ``main.py`` (they do not mount the template's routers) + """ + if self.profile.regenerate_main: + return [] + shipped = { + collection.name: collection + for collection in self.profile.shipped_collections + } + return [ + (target, shipped[target.example_collection]) + for target in OVERLAY_TARGETS + if target.example_collection in shipped and target.applies(config) + ] + + def skipped_example_labels(self, config: Dict[str, Any]) -> List[str]: + """Labels of :meth:`skipped_example_routers`, for the config generator.""" + return [target.label for target, _ in self.skipped_example_routers(config)] + + def skipped_example_notes(self, config: Dict[str, Any]) -> List[str]: + """One user-facing line per demo router that was not generated.""" + package_dir = _package_dir(self.profile.main_py_relpath) + return [ + f"{target.label}: the base template already serves " + f"{collection.endpoint} ({collection.module_relpath}), so the example " + f"router {package_dir}/{target.example_module} was not generated. " + f"See the comment at the end of {self.profile.main_py_relpath} " + "for how to apply it to the existing endpoint." + for target, collection in self.skipped_example_routers(config) + ] + def wire_generated_routers( self, project_dir: str, config: Dict[str, Any] ) -> List[str]: @@ -396,8 +605,13 @@ def wire_generated_routers( return [] pkg = _package_root(self.profile.main_py_relpath) - content = original = main_path.read_text(encoding="utf-8") + content, newline = read_text_preserving_newlines(main_path) + original = content wired: List[str] = [] + skipped = { + target.label: collection + for target, collection in self.skipped_example_routers(config) + } for label in self.profile.extra_warning_targets: target = _TARGETS_BY_LABEL.get(label) @@ -406,6 +620,12 @@ def wire_generated_routers( if not target.applies(config): continue + collection = skipped.get(label) + if collection is not None: + content = _wire_without_example(content, target, collection, pkg) + wired.append(label) + continue + imports, statements = target.wiring for line in imports: content = insert_import_line(content, line.format(pkg=pkg)) @@ -414,7 +634,7 @@ def wire_generated_routers( wired.append(label) if content != original: - main_path.write_text(content, encoding="utf-8") + write_text_preserving_newlines(main_path, content, newline) return wired @@ -424,6 +644,7 @@ def wire_generated_routers( "OverlayTarget", "PresetLayoutStrategist", "PresetProfile", + "ShippedCollection", "app_module_from_main_path", "app_module_from_relpath", ] diff --git a/src/fastapi_fastkit/backend/route_generators.py b/src/fastapi_fastkit/backend/route_generators.py index 53587a33..09a9e9dc 100644 --- a/src/fastapi_fastkit/backend/route_generators.py +++ b/src/fastapi_fastkit/backend/route_generators.py @@ -13,6 +13,7 @@ from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.main import print_warning, read_fastkit_metadata +from fastapi_fastkit.utils.textio import write_generated_text ROUTE_LAYOUTS = ("classic-layer", "domain") @@ -124,7 +125,7 @@ def _create_domain_files( domain_dir.mkdir(parents=True, exist_ok=True) domains_init = domain_dir.parent / "__init__.py" if not domains_init.exists(): - domains_init.write_text("", encoding="utf-8") + write_generated_text(domains_init, "") prefix = project_layout["package_module"] domain_module = ( f"{prefix}.domains.{route_name}" if prefix else f"domains.{route_name}" diff --git a/src/fastapi_fastkit/backend/route_wiring.py b/src/fastapi_fastkit/backend/route_wiring.py index 7667a404..d584a1e9 100644 --- a/src/fastapi_fastkit/backend/route_wiring.py +++ b/src/fastapi_fastkit/backend/route_wiring.py @@ -5,6 +5,11 @@ from typing import Dict from fastapi_fastkit.utils.main import print_info +from fastapi_fastkit.utils.textio import ( + read_text_preserving_newlines, + write_generated_text, + write_text_preserving_newlines, +) def _parse_module(content: str) -> ast.Module: @@ -37,9 +42,13 @@ def register_router( api_dir.mkdir(parents=True, exist_ok=True) init = api_dir / "__init__.py" if not init.exists(): - init.write_text("", encoding="utf-8") + write_generated_text(init, "") target = Path(project_layout["api_router_file"]) - content = target.read_text(encoding="utf-8") if target.exists() else "" + # A router module created here is generated content (LF); an existing + # one keeps its own line endings. + content, newline = "", "\n" + if target.exists(): + content, newline = read_text_preserving_newlines(target) if not content.strip(): content = "from fastapi import APIRouter\n\napi_router = APIRouter()\n" registration = ast.parse(statement).body[0] @@ -81,7 +90,7 @@ def register_router( if existing is None: updated = insert_statement_line(updated, statement) if not target.exists() or updated != content: - target.write_text(updated, encoding="utf-8") + write_text_preserving_newlines(target, updated, newline) def router_alias(file: str, module: str, name: str, preferred: str) -> str: diff --git a/src/fastapi_fastkit/backend/scaffolder.py b/src/fastapi_fastkit/backend/scaffolder.py index 201ef837..14f37751 100644 --- a/src/fastapi_fastkit/backend/scaffolder.py +++ b/src/fastapi_fastkit/backend/scaffolder.py @@ -13,8 +13,6 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import os -import shutil -import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional @@ -22,6 +20,9 @@ from rich.tree import Tree from fastapi_fastkit.backend.main import ( + ENV_EXAMPLE_FILE, + ENV_FILE, + create_local_env_file, create_venv_with_manager, deploy_template_files, generate_dependency_file_with_manager, @@ -40,6 +41,9 @@ from fastapi_fastkit.backend.project_builder.config_schema import ( normalize_project_config, ) +from fastapi_fastkit.backend.project_builder.dependency_collector import ( + merge_requirements, +) from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import FeatureAxis from fastapi_fastkit.utils.logging import debug_log @@ -49,10 +53,20 @@ print_success, print_warning, ) +from fastapi_fastkit.utils.platform import rmtree_force, stdin_is_interactive from .. import __version__ +class ScaffoldCancelled(BackendExceptions): + """The user declined to go on (e.g. refused the in-place overwrite prompt). + + A subclass of ``BackendExceptions`` so existing callers keep catching + it, while the CLI can tell a deliberate cancel (exit status 0) from a + real generation failure (exit status 1). + """ + + def cleanup_failed_project( project_dir: str, user_workspace: str, @@ -84,9 +98,12 @@ def cleanup_failed_project( return if not project_dir or not os.path.exists(project_dir): return - if os.path.abspath(project_dir) == os.path.abspath(user_workspace): + # normcase: Windows paths compare case-insensitively. + if os.path.normcase(os.path.abspath(project_dir)) == os.path.normcase( + os.path.abspath(user_workspace) + ): return - shutil.rmtree(project_dir, ignore_errors=True) + rmtree_force(project_dir, ignore_errors=True) @dataclass @@ -109,7 +126,8 @@ class ScaffoldOptions: create_project_folder: bool = True dry_run: bool = False # Skip the "this will overwrite existing files" confirmation. Set by the - # CLI's ``--yes`` flag; also implied when there is no terminal to ask. + # CLI's ``--yes`` flag. Without it, a run with no terminal to ask refuses + # to overwrite anything. assume_yes: bool = False with_venv: bool = True with_install: bool = True @@ -192,11 +210,13 @@ def resolve_dependencies(self) -> List[str]: if self.options.dependencies is None: return read_template_stack(self.template_dir) - dependencies = set(self.options.dependencies) + dependencies = list(self.options.dependencies) if self.options.config: collector = DependencyCollector(self.settings) - dependencies.update(collector.collect_from_config(self.options.config)) - return sorted(dependencies) + dependencies.extend(collector.collect_from_config(self.options.config)) + # A config saved before a catalog entry gained an extra (plain + # ``sqlalchemy`` vs ``sqlalchemy[asyncio]``) must not list both. + return merge_requirements(dependencies) def build_metadata(self) -> Dict[str, Any]: """ @@ -272,7 +292,10 @@ def run(self) -> ScaffoldResult: project (never the user's workspace itself). :return: Details of the generated project - :raises BackendExceptions: If any generation step fails + :raises ScaffoldCancelled: If the user declines the overwrite prompt + :raises BackendExceptions: If any generation step fails, or an + in-place deployment would overwrite files and there is neither + ``--yes`` nor a terminal to confirm it """ self._require_template() @@ -280,7 +303,7 @@ def run(self) -> ScaffoldResult: return self.preview() if not self._confirm_overwrites(): - raise BackendExceptions("Project creation aborted by user.") + raise ScaffoldCancelled("Project creation aborted by user.") pre_existed = os.path.isdir(self.project_dir) project_dir = "" @@ -308,6 +331,12 @@ def run(self) -> ScaffoldResult: if self.options.config: self._generate_dynamic_config(project_dir, self.options.config) + # After substitution, so placeholders in .env.example are filled + # in the generated .env too, and after the feature overlay, which + # appends the variables the selected features read. Never + # overwrites an existing .env. + create_local_env_file(project_dir) + metadata = self.build_metadata() write_fastkit_metadata(project_dir, metadata) @@ -347,14 +376,21 @@ def existing_targets(self) -> List[str]: return [ relative_path for relative_path in self._planned_files() - if os.path.isfile(os.path.join(project_dir, *relative_path.split("/"))) + # The generated .env never replaces an existing one. + if relative_path != ENV_FILE + and os.path.isfile(os.path.join(project_dir, *relative_path.split("/"))) ] def _confirm_overwrites(self) -> bool: """Ask before overwriting files that are already in the target directory. - Returns True when the run may proceed. Non-interactive sessions and - ``--yes`` skip the prompt rather than hanging on a dead stdin. + Returns True when the run may proceed and False when the user + declines. ``--yes`` skips the prompt. A non-interactive session + without ``--yes`` cannot be asked, and overwriting the user's files + unasked is not a safe default, so it fails instead of proceeding. + + :raises BackendExceptions: If files would be overwritten, stdin is not + interactive and ``assume_yes`` is not set """ if self.options.create_project_folder: return True @@ -370,10 +406,20 @@ def _confirm_overwrites(self) -> bool: for relative_path in clashes: console.print(f" [yellow]{relative_path}[/yellow]") - if self.options.assume_yes or not sys.stdin.isatty(): - print_warning("Proceeding without confirmation (--yes / non-interactive).") + if self.options.assume_yes: + print_warning("Proceeding without confirmation (--yes).") return True + if not stdin_is_interactive(): + # Raised before anything is written, so there is nothing to roll + # back. Not ScaffoldCancelled: nobody declined, and a script must + # see a non-zero exit status. + raise BackendExceptions( + f"Deploying in place would overwrite {len(clashes)} existing " + f"file(s) in '{self.project_dir}' and there is no terminal to " + "confirm it; re-run with --yes to allow it." + ) + return bool(click.confirm("Overwrite these files?", default=False)) def _require_template(self) -> None: @@ -407,6 +453,9 @@ def _config_generator(self, project_dir: str) -> DynamicConfigGenerator: main_py_relpath=self.strategist.profile.main_py_relpath, db_config_relpath=self.strategist.profile.db_config_relpath, auth_config_relpath=self.strategist.profile.auth_config_relpath, + omit_example_routers=self.strategist.skipped_example_labels( + self.options.config or {} + ), ) def _generate_dynamic_config( @@ -438,11 +487,18 @@ def _generate_dynamic_config( # ``# fastkit:`` anchors; whatever can't be spliced in safely is # reported instead so the user knows to wire it up themselves. wired = self.strategist.wire_generated_routers(project_dir, config) - if wired: + # Features whose demo router was skipped (the base template already + # serves that collection) are wired without a router, so they are + # explained on their own line instead of listed as routers. + skipped = set(self.strategist.skipped_example_labels(config)) + routers = [label for label in wired if label not in skipped] + if routers: print_success( f"Registered generated routers in " - f"{self.strategist.profile.main_py_relpath}: {', '.join(wired)}" + f"{self.strategist.profile.main_py_relpath}: {', '.join(routers)}" ) + for note in self.strategist.skipped_example_notes(config): + print_info(note) # Surface preset-specific warnings (e.g. "you picked a preset whose # shipped main.py we kept; Prometheus must be wired manually"). @@ -546,6 +602,13 @@ def _planned_files(self) -> List[str]: if deployment and deployment != ["None"]: planned.append(".dockerignore") + # ``.env`` is generated from ``.env.example`` (see + # ``create_local_env_file``) unless the target already has one. + if ENV_EXAMPLE_FILE in planned and not os.path.lexists( + os.path.join(self.project_dir, ENV_FILE) + ): + planned.append(ENV_FILE) + if self.options.dependencies is not None: planned.append( self.settings.PACKAGE_MANAGER_CONFIG[self.options.package_manager][ @@ -572,6 +635,7 @@ def _add_tree_path(tree: Tree, relative_path: str) -> None: __all__ = [ "ProjectScaffolder", + "ScaffoldCancelled", "ScaffoldOptions", "ScaffoldResult", "cleanup_failed_project", diff --git a/src/fastapi_fastkit/backend/transducer.py b/src/fastapi_fastkit/backend/transducer.py index 42ccce7d..f6783f0d 100644 --- a/src/fastapi_fastkit/backend/transducer.py +++ b/src/fastapi_fastkit/backend/transducer.py @@ -31,6 +31,8 @@ ".cfg", ".css", ".env", + # ``.env.example``: os.path.splitext sees ".example" as the extension. + ".example", ".html", ".ini", ".js", @@ -54,6 +56,7 @@ { ".dockerignore", ".env", + ".gitattributes", ".gitignore", "CHANGELOG", "Dockerfile", diff --git a/src/fastapi_fastkit/cli.py b/src/fastapi_fastkit/cli.py index bbe1868e..7ee67c5c 100644 --- a/src/fastapi_fastkit/cli.py +++ b/src/fastapi_fastkit/cli.py @@ -9,7 +9,6 @@ import atexit import keyword import os -import shutil import subprocess import sys from typing import Any, Dict, List, Optional, Union, cast @@ -40,6 +39,7 @@ from fastapi_fastkit.backend.route_generators import resolve_route_layout from fastapi_fastkit.backend.scaffolder import ( ProjectScaffolder, + ScaffoldCancelled, ScaffoldOptions, cleanup_failed_project, ) @@ -63,6 +63,12 @@ read_fastkit_metadata, validate_email, ) +from fastapi_fastkit.utils.platform import ( + configure_stdio, + rmtree_force, + stdin_is_interactive, + venv_python, +) from . import __version__ @@ -74,7 +80,20 @@ _cleanup_failed_project = cleanup_failed_project -@click.group() +class _FastkitGroup(click.Group): + """Root command group that makes the console safe before any output. + + ``main`` runs for every entry point (``fastkit``, ``python -m + fastapi_fastkit``) before Click prints help, version or usage errors, + which the group callback would be too late for. + """ + + def main(self, *args: Any, **kwargs: Any) -> Any: + configure_stdio() + return super().main(*args, **kwargs) + + +@click.group(cls=_FastkitGroup) @click.option("--debug/--no-debug", default=False) @click.version_option(__version__, prog_name="fastapi-fastkit") @click.pass_context @@ -82,6 +101,9 @@ def fastkit_cli(ctx: Context, debug: bool) -> Union["Command", None]: """ main FastAPI-fastkit CLI operation group """ + # Already done by ``_FastkitGroup.main``; repeated for callers that + # invoke the callback some other way. Idempotent. + configure_stdio() settings = FastkitConfig() ctx.ensure_object(dict) @@ -173,7 +195,7 @@ def list_templates(ctx: Context) -> None: description = "No description" if os.path.exists(readme_path): - with open(readme_path, "r") as f: + with open(readme_path, "r", encoding="utf-8", errors="replace") as f: first_line = f.readline().strip() if first_line.startswith("# "): description = first_line[2:] @@ -224,7 +246,10 @@ def _select_package_manager(settings: Any) -> str: def _scaffold( - ctx: Context, options: ScaffoldOptions, error_context: str + ctx: Context, + options: ScaffoldOptions, + error_context: str, + exit_on_failure: bool = False, ) -> Optional[str]: """ Run the scaffolder and report the outcome. @@ -232,19 +257,28 @@ def _scaffold( :param ctx: Click context (for settings / debug mode) :param options: Scaffold options to execute :param error_context: Command name used in the debug log message - :return: The generated project directory, or None when generation failed - or was only previewed. + :param exit_on_failure: Exit with status 1 when generation fails, so + scripted callers can tell a failed run from a successful one. A user + declining the in-place overwrite prompt is a cancel, not a failure, + and keeps exit status 0. + :return: The generated project directory, or None when generation failed, + was cancelled or was only previewed. """ settings = ctx.obj["settings"] scaffolder = ProjectScaffolder(settings, options) try: result = scaffolder.run() + except ScaffoldCancelled as e: + print_error(str(e)) + return None except Exception as e: if settings.DEBUG_MODE: logger = get_logger() logger.exception(f"Error during project creation in {error_context}: {e}") print_error(f"Error during project creation: {str(e)}") + if exit_on_failure: + ctx.exit(1) return None if result.dry_run: @@ -465,7 +499,7 @@ def _offer_config_save(config: Dict[str, Any], save_config: Optional[str]) -> No if not path: # Only ask when there is a human at the other end: scripted runs # (CI, piped input) opt in with --save-config instead. - if not sys.stdin.isatty(): + if not stdin_is_interactive(): return if not click.confirm( "\nSave these selections to a config file for later reuse?", default=False @@ -562,7 +596,8 @@ def _offer_config_save(config: Dict[str, Any], save_config: Optional[str]) -> No default=False, help=( "Do not ask for confirmation before overwriting existing files when " - "deploying the project in place." + "deploying the project in place. Has no effect with --config, which " + "always creates a new project folder and never prompts." ), ) @click.pass_context @@ -590,7 +625,10 @@ def init( through feature selection (database, auth, testing, deployment, ...). Use --config to replay a saved configuration without any prompts, - and --save-config to record an interactive session as one. + and --save-config to record an interactive session as one. With + --config the project is always created in a new folder named after the + project, and any failure (unusable config, existing project directory, + generation error) exits with a non-zero status. Without either, creates an empty project with predefined stacks. @@ -605,7 +643,7 @@ def init( if config_path: config = _load_config_file(config_path) if config is None: - return + ctx.exit(1) elif interactive: print_info("Starting interactive project setup...") @@ -628,6 +666,10 @@ def init( no_venv=no_venv, no_install=no_install, assume_yes=assume_yes, + # A config file is meant to be replayed unattended (CI, scripts), + # so it must never stop at a question; only the guided session + # asks where to put the project. + ask_project_folder=not config_path, ) return @@ -650,13 +692,13 @@ def init( name_valid, name_error = validate_project_name(project_name) if not name_valid: print_error(f"Invalid project name: {name_error}") - return + ctx.exit(1) project_dir = os.path.join(settings.USER_WORKSPACE, project_name) if os.path.exists(project_dir): print_error(f"Error: Project '{project_name}' already exists.") - return + ctx.exit(1) # Display project information project_info_table = create_info_table( @@ -737,6 +779,9 @@ def init( assume_yes=assume_yes, ), error_context="init", + # Declining the in-place overwrite prompt raises ScaffoldCancelled, + # which ``_scaffold`` reports with exit status 0. + exit_on_failure=True, ) if created_dir: @@ -753,10 +798,14 @@ def _init_from_config( no_venv: bool, no_install: bool, assume_yes: bool = False, + ask_project_folder: bool = True, ) -> None: """ Create a project from an interactive / file-provided configuration. + Failures (unusable configuration, existing project directory, generation + error) exit with status 1. + :param ctx: Click context :param config: Configuration dict (interactive builder shape) :param package_manager: CLI override for the config's package manager @@ -764,10 +813,16 @@ def _init_from_config( :param no_venv: Skip virtualenv creation :param no_install: Skip dependency installation :param assume_yes: Skip the in-place overwrite confirmation + :param ask_project_folder: Ask whether to create a project folder or + deploy in place. When False (``--config``) nothing is asked and the + project always goes into a new folder named after it. """ settings = ctx.obj["settings"] project_name = cast(str, config.get("project_name", "")) + if not project_name: + print_error("Project configuration is missing 'project_name'.") + ctx.exit(1) author = cast(str, config.get("author", "")) author_email = cast(str, config.get("author_email", "")) description = cast(str, config.get("description", "")) @@ -783,13 +838,17 @@ def _init_from_config( # let the interactive builder derive the package set from them so # both entry points resolve dependencies identically. builder = InteractiveConfigBuilder(settings) - config = builder.build_config_from_mapping(config) + try: + config = builder.build_config_from_mapping(config) + except ConfigSchemaError as e: + print_error(f"Invalid project config: {e}") + ctx.exit(1) dependencies = config.get("all_dependencies", []) project_dir = os.path.join(settings.USER_WORKSPACE, project_name) if not dry_run and os.path.exists(project_dir): print_error(f"Error: Project '{project_name}' already exists.") - return + ctx.exit(1) # Pick the base template from the architecture preset. Configs without a # preset fall back to ``minimal`` (= fastapi-empty), preserving pre-#45 @@ -798,7 +857,10 @@ def _init_from_config( strategist = PresetLayoutStrategist(preset_id) template = strategist.base_template - create_project_folder = True if dry_run else ask_create_project_folder(project_name) + if dry_run or not ask_project_folder: + create_project_folder = True + else: + create_project_folder = ask_create_project_folder(project_name) created_dir = _scaffold( ctx, @@ -819,6 +881,9 @@ def _init_from_config( assume_yes=assume_yes, ), error_context="init", + # Declining the in-place overwrite prompt (interactive only) raises + # ScaffoldCancelled, which ``_scaffold`` reports with exit status 0. + exit_on_failure=True, ) if created_dir: @@ -959,7 +1024,9 @@ def deleteproject(ctx: Context, project_name: str) -> None: return try: - shutil.rmtree(project_dir) + # Read-only entries (git marks .git/objects that way) stop a plain + # rmtree on Windows. + rmtree_force(project_dir) print_success(f"Project '{project_name}' has been deleted successfully!") except Exception as e: @@ -1044,6 +1111,7 @@ def runserver( project_dir = settings.USER_WORKSPACE # Check for virtual environment + interpreter: Optional[str] venv_path = os.path.join(project_dir, ".venv") if not os.path.exists(venv_path) or not os.path.isdir(venv_path): print_error( @@ -1054,33 +1122,30 @@ def runserver( ) if not confirm: return - venv_python = None + interpreter = None else: - if os.name == "nt": # Windows - venv_python = os.path.join(venv_path, "Scripts", "python.exe") - else: # Unix/Linux/Mac - venv_python = os.path.join(venv_path, "bin", "python") + interpreter = venv_python(venv_path) - if not os.path.exists(venv_python): + if not os.path.exists(interpreter): print_error( - f"Python interpreter not found in virtual environment: {venv_python}" + f"Python interpreter not found in virtual environment: {interpreter}" ) confirm = click.confirm( "Do you want to continue with system Python?", default=False ) if not confirm: return - venv_python = None + interpreter = None app_module = _resolve_runserver_app_module(project_dir) if not app_module: print_error(f"Could not find 'main.py' in '{project_dir}'.") return - if venv_python: - print_info(f"Using Python from virtual environment: {venv_python}") + if interpreter: + print_info(f"Using Python from virtual environment: {interpreter}") command = [ - venv_python, + interpreter, "-m", "uvicorn", app_module, @@ -1111,12 +1176,13 @@ def runserver( # Set up environment variables for the subprocess env = os.environ.copy() - if venv_python: - python_path = os.path.dirname(os.path.dirname(venv_python)) - if "PYTHONPATH" in env: - env["PYTHONPATH"] = f"{python_path}:{env['PYTHONPATH']}" - else: - env["PYTHONPATH"] = python_path + if interpreter: + # Put the project root on the import path (as the generated + # Dockerfiles do with /app), ahead of anything already set. + existing = env.get("PYTHONPATH") + env["PYTHONPATH"] = ( + os.pathsep.join([project_dir, existing]) if existing else project_dir + ) # Run the server with the configured environment subprocess.run(command, check=True, env=env) @@ -1127,7 +1193,7 @@ def runserver( except FileNotFoundError as e: logger = get_logger() logger.exception(f"FileNotFoundError when starting server: {e}") - if venv_python: + if interpreter: print_error( "Failed to run Python from the virtual environment. Make sure uvicorn is installed in the project's virtual environment." ) diff --git a/src/fastapi_fastkit/core/settings.py b/src/fastapi_fastkit/core/settings.py index ab1716be..0455e033 100644 --- a/src/fastapi_fastkit/core/settings.py +++ b/src/fastapi_fastkit/core/settings.py @@ -4,6 +4,7 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import os +import tempfile from enum import StrEnum from pathlib import Path @@ -40,6 +41,18 @@ class FeatureAxis(StrEnum): FeatureAxis.TOOLING, ) +#: Python version generated projects target. Matches fastkit's own +#: ``requires-python`` floor and the interpreter the generated Dockerfiles and +#: CI workflows use. A template's own ``requires-python`` always wins; this is +#: only written when there is no template value to keep. +DEFAULT_PYTHON_VERSION = "3.12" + +#: PEP 440 form of :data:`DEFAULT_PYTHON_VERSION` for ``requires-python``. +DEFAULT_REQUIRES_PYTHON = f">={DEFAULT_PYTHON_VERSION}" + +#: Poetry caret form of :data:`DEFAULT_PYTHON_VERSION` (``>=3.12,<4.0``). +DEFAULT_POETRY_PYTHON = f"^{DEFAULT_PYTHON_VERSION}" + class DatabaseChoice(StrEnum): """Options of the ``database`` axis.""" @@ -247,13 +260,16 @@ class FastkitConfig: # Based on recommendations from: https://github.com/mjhea0/awesome-fastapi PACKAGE_CATALOG: dict[str, dict[str, list[str]]] = { FeatureAxis.DATABASE: { - DatabaseChoice.POSTGRESQL: ["asyncpg", "sqlalchemy"], - DatabaseChoice.MYSQL: ["aiomysql", "sqlalchemy"], + # The generated database module is async (``sqlalchemy.ext.asyncio``), + # which needs greenlet. SQLAlchemy 2.1 only installs it through the + # ``asyncio`` extra, and 2.0 skipped it on some platforms (macOS arm64). + DatabaseChoice.POSTGRESQL: ["asyncpg", "sqlalchemy[asyncio]"], + DatabaseChoice.MYSQL: ["aiomysql", "sqlalchemy[asyncio]"], DatabaseChoice.MONGODB: ["motor"], # ``aioredis`` is abandoned (merged into redis-py) and does not # install on Python 3.12 — redis[hiredis] ships the asyncio client. DatabaseChoice.REDIS: ["redis[hiredis]"], - DatabaseChoice.SQLITE: ["sqlalchemy", "aiosqlite"], + DatabaseChoice.SQLITE: ["sqlalchemy[asyncio]", "aiosqlite"], DatabaseChoice.NONE: [], }, FeatureAxis.AUTHENTICATION: { @@ -455,9 +471,38 @@ def _validate(cls) -> None: "FASTKIT_TEMPLATE_ROOT is not allocated to valid directory." ) - log_dir = os.path.dirname(cls.LOG_FILE_PATH) - if not os.path.exists(log_dir): - os.makedirs(log_dir) + cls.LOG_FILE_PATH = cls._writable_log_file_path(cls.LOG_FILE_PATH) + + @staticmethod + def _writable_log_file_path(preferred: str) -> str: + """ + Return a log file path whose directory exists and can be created. + + The default sits next to the installed package, which an all-users + install (``C:\\Program Files``, a system ``site-packages``) does not + let a normal user write to. Importing fastkit must not fail over a + debug log, so a per-user directory, then the temp directory, are + used instead. + + :param preferred: The default log file path + :return: ``preferred``, or the same file name in a fallback directory + """ + file_name = os.path.basename(preferred) + candidates = [ + os.path.dirname(preferred), + os.path.join(os.path.expanduser("~"), ".fastapi-fastkit", "logs"), + os.path.join(tempfile.gettempdir(), "fastapi-fastkit", "logs"), + ] + for log_dir in candidates: + try: + os.makedirs(log_dir, exist_ok=True) + except OSError: + continue + if os.access(log_dir, os.W_OK): + return os.path.join(log_dir, file_name) + # Nothing writable: keep the default; the log handlers already + # swallow write failures. + return preferred settings = FastkitConfig() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitignore-tpl index ef6364a9..5656953a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitignore-tpl @@ -28,3 +28,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl index 69825d52..2edd9e64 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl @@ -58,6 +58,10 @@ $ bash scripts/run-server.sh $ uvicorn src.main:app --reload ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + Access API documentation after server starts: ```bash diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl index 019a244b..5a5f1e19 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl @@ -35,6 +35,6 @@ starlette==1.6.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env.example-tpl similarity index 73% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env.example-tpl index 4325db71..74af97e3 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env.example-tpl @@ -2,8 +2,10 @@ PROJECT_NAME= ENVIRONMENT=development -# JWT — replace SECRET_KEY before deploying: +# JWT signing key. .env.example (committed) keeps a public placeholder; fastkit +# put a unique key in your local, git-ignored .env. Generate another with: # python -c "import secrets; print(secrets.token_urlsafe(32))" +# With ENVIRONMENT=production the app refuses to start on the placeholder. SECRET_KEY=changethis-please-generate-a-real-32-byte-key JWT_ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=30 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.gitignore-tpl index 0d045bee..d60b5a02 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.gitignore-tpl @@ -31,3 +31,9 @@ archive.zip # Local SQLite database *.db + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl index a99c7eec..6b326ce4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl @@ -33,7 +33,8 @@ PostgreSQL-first CRUD without auth, use `fastapi-psql-orm`. ├── requirements.txt ├── alembic.ini ├── Dockerfile -├── .env +├── .env # local settings, git-ignored (generated) +├── .env.example # shareable example, committed ├── .gitignore ├── scripts/ │ ├── format.sh @@ -90,6 +91,10 @@ $ bash scripts/run-server.sh $ uvicorn src.app.main:app --reload ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + API docs are then served at: - Swagger UI: @@ -189,8 +194,11 @@ register → login → me → refresh → logout flow plus the rejection paths `src/app/core/config.py` reads settings from environment variables (or a local `.env`). Two of them matter before you deploy: -- **`SECRET_KEY`** signs every token. Leave it unset and a random key is generated - per process, which logs everyone out on restart. +- **`SECRET_KEY`** signs every token. fastkit generated your local `.env` from + `.env.example` with a unique key. `.env` is git-ignored; commit `.env.example`, + which keeps only a placeholder. With `ENVIRONMENT=production` the app refuses + to start while `SECRET_KEY` is still an example value. Leave it unset and a + random key is generated per process, which logs everyone out on restart. - **`DATABASE_URL`** selects the database. Set `FIRST_SUPERUSER_EMAIL` and `FIRST_SUPERUSER_PASSWORD` to have a superuser diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl index 770603d1..a880a3a3 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl @@ -4,7 +4,7 @@ import secrets from typing import Annotated, Any, List, Literal, Union -from pydantic import AnyUrl, BeforeValidator, computed_field +from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict @@ -16,6 +16,18 @@ def _parse_cors(v: Any) -> Union[List[str], str]: raise ValueError(v) +#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` +#: files. They are public, so a production deployment must never sign +#: anything with one of them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + } +) + + class Settings(BaseSettings): """Centralized configuration for the application. @@ -60,5 +72,19 @@ class Settings(BaseSettings): def all_cors_origins(self) -> List[str]: return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + @model_validator(mode="after") + def _reject_example_secret_key_in_production(self) -> "Settings": + if ( + self.ENVIRONMENT == "production" + and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + ): + raise ValueError( + "SECRET_KEY is set to a public example value while " + "ENVIRONMENT=production. Generate a real key with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as the SECRET_KEY environment variable (or in .env)." + ) + return self + settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl index 82164672..a7bdff18 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl @@ -1,9 +1,17 @@ # -------------------------------------------------------------------------- # Refresh token data access. +# +# Write methods only stage changes on the session; they never commit on +# their own. Callers group them inside ``atomic()`` so a multi-step flow +# (e.g. "revoke the old token + store its successor") is committed once, +# or rolled back as a whole. # -------------------------------------------------------------------------- +from collections.abc import Iterator +from contextlib import contextmanager from datetime import datetime from typing import Optional +from sqlalchemy import update from sqlmodel import Session, select from src.app.domains.auth.models import RefreshToken @@ -13,29 +21,62 @@ class RefreshTokenRepository: def __init__(self, session: Session) -> None: self.session = session + @contextmanager + def atomic(self) -> Iterator[None]: + """Commit everything staged inside the block once, or roll it all back.""" + try: + yield + self.session.commit() + except BaseException: + self.session.rollback() + raise + def add(self, jti: str, user_id: int, expires_at: datetime) -> RefreshToken: + """Stage a new refresh token record (flushed, not committed).""" record = RefreshToken(jti=jti, user_id=user_id, expires_at=expires_at) self.session.add(record) - self.session.commit() - self.session.refresh(record) + # Flush so constraint violations surface inside the caller's transaction. + self.session.flush() return record def get_by_jti(self, jti: str) -> Optional[RefreshToken]: statement = select(RefreshToken).where(RefreshToken.jti == jti) return self.session.exec(statement).first() - def revoke(self, record: RefreshToken) -> None: - record.revoked = True - self.session.add(record) - self.session.commit() + def revoke_if_active(self, jti: str) -> bool: + """Atomically flip ``revoked`` from false to true for one token. + + Runs ``UPDATE ... SET revoked = true WHERE jti = :jti AND revoked = + false``. The database serialises concurrent updates of the same row + (row lock on PostgreSQL, write lock on SQLite) and re-checks the + ``WHERE`` clause, so only one caller ever sees an affected row. + + Returns: + True when this call revoked the token, False when it was already + revoked (or does not exist). + """ + statement = ( + update(RefreshToken) + .where( + RefreshToken.jti == jti, # type: ignore[arg-type] + RefreshToken.revoked == False, # type: ignore[arg-type] # noqa: E712 + ) + .values(revoked=True) + .execution_options(synchronize_session=False) + ) + result = self.session.exec(statement) + return result.rowcount == 1 def revoke_all_for_user(self, user_id: int) -> int: - statement = select(RefreshToken).where( - RefreshToken.user_id == user_id, RefreshToken.revoked == False # noqa: E712 + """Revoke every active token of a user; returns how many were revoked.""" + statement = ( + update(RefreshToken) + .where( + RefreshToken.user_id == user_id, # type: ignore[arg-type] + RefreshToken.revoked == False, # type: ignore[arg-type] # noqa: E712 + ) + .values(revoked=True) + .execution_options(synchronize_session=False) ) - records = self.session.exec(statement).all() - for record in records: - record.revoked = True - self.session.add(record) - self.session.commit() - return len(records) + result = self.session.exec(statement) + return int(result.rowcount or 0) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl index 20e427ff..7cfeb585 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl @@ -1,6 +1,11 @@ # -------------------------------------------------------------------------- # Authentication business logic: token issuance, rotation, revocation. +# +# Every public method is one database transaction (``atomic()``): either all +# of its writes are committed together or none of them are. # -------------------------------------------------------------------------- +from datetime import datetime, timezone + from src.app.core.security import ( REFRESH_TOKEN_TYPE, TokenError, @@ -22,33 +27,42 @@ class AuthService: self.refresh_tokens = refresh_tokens def issue_token_pair(self, user: User) -> TokenPair: - scopes = user.scope_list - access_token, _, _ = create_access_token(str(user.id), scopes) - refresh_token, jti, expires_at = create_refresh_token(str(user.id), scopes) - self.refresh_tokens.add(jti, user.id or 0, expires_at) - return TokenPair(access_token=access_token, refresh_token=refresh_token) + """Mint a new access/refresh pair and persist the refresh token.""" + with self.refresh_tokens.atomic(): + return self._stage_token_pair(user) def rotate(self, refresh_token: str) -> TokenPair: """Exchange a refresh token for a brand new pair. - The presented token is revoked first, so a replay of the same token - fails even if the caller never uses the new pair. + The presented token is claimed with a conditional update (only one + caller can flip it from active to revoked) and its successor is + stored in the same transaction. A concurrent or replayed use of the + same token therefore fails, and if storing the successor fails the + whole transaction rolls back, leaving the presented token valid. Raises: TokenError: the token is invalid, expired, already used, or its user is gone / deactivated. """ payload = decode_token(refresh_token, REFRESH_TOKEN_TYPE) - record = self.refresh_tokens.get_by_jti(str(payload.get("jti"))) - if record is None or record.revoked: - raise TokenError("refresh token is no longer valid") + jti = str(payload.get("jti")) + + with self.refresh_tokens.atomic(): + record = self.refresh_tokens.get_by_jti(jti) + if record is None or record.revoked: + raise TokenError("refresh token is no longer valid") + if _as_utc(record.expires_at) <= datetime.now(timezone.utc): + raise TokenError("refresh token has expired") + + user = self.users.get(record.user_id) + if user is None or not user.is_active: + raise TokenError("user is not available") - user = self.users.get(record.user_id) - if user is None or not user.is_active: - raise TokenError("user is not available") + # The read above is only a fast path; this is the real guard. + if not self.refresh_tokens.revoke_if_active(jti): + raise TokenError("refresh token is no longer valid") - self.refresh_tokens.revoke(record) - return self.issue_token_pair(user) + return self._stage_token_pair(user) def revoke(self, refresh_token: str) -> None: """Log out a single session. Unknown tokens are silently accepted.""" @@ -56,10 +70,25 @@ class AuthService: payload = decode_token(refresh_token, REFRESH_TOKEN_TYPE) except TokenError: return - record = self.refresh_tokens.get_by_jti(str(payload.get("jti"))) - if record is not None and not record.revoked: - self.refresh_tokens.revoke(record) + with self.refresh_tokens.atomic(): + self.refresh_tokens.revoke_if_active(str(payload.get("jti"))) def revoke_all(self, user: User) -> int: """Log out every session of a user.""" - return self.refresh_tokens.revoke_all_for_user(user.id or 0) + with self.refresh_tokens.atomic(): + return self.refresh_tokens.revoke_all_for_user(user.id or 0) + + def _stage_token_pair(self, user: User) -> TokenPair: + """Create a pair and stage its refresh record; the caller commits.""" + scopes = user.scope_list + access_token, _, _ = create_access_token(str(user.id), scopes) + refresh_token, jti, expires_at = create_refresh_token(str(user.id), scopes) + self.refresh_tokens.add(jti, user.id or 0, expires_at) + return TokenPair(access_token=access_token, refresh_token=refresh_token) + + +def _as_utc(value: datetime) -> datetime: + """Treat naive datetimes read back from the database as UTC.""" + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_config.py-tpl new file mode 100644 index 00000000..fba88b03 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_config.py-tpl @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Settings validation: production refuses a public example SECRET_KEY. +# -------------------------------------------------------------------------- +import re +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings + +ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" + + +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_production_refuses_example_secret_key(example_key: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + + +@pytest.mark.parametrize("environment", ["development", "staging"]) +def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: + settings = Settings( + _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" + ) + + assert settings.SECRET_KEY == "changethis" + + +def test_production_accepts_a_real_secret_key() -> None: + settings = Settings( + _env_file=None, + ENVIRONMENT="production", + SECRET_KEY="a-real-unique-key-0123456789abcdef", + ) + + assert settings.ENVIRONMENT == "production" + + +def test_env_example_secret_key_is_a_known_example_value() -> None: + """Whatever .env.example ships must be one the production guard rejects.""" + if not ENV_EXAMPLE.is_file(): + pytest.skip(".env.example is not part of this checkout") + + match = re.search( + r"^SECRET_KEY=(.*)$", ENV_EXAMPLE.read_text(encoding="utf-8"), re.M + ) + + assert match is not None + assert match.group(1).strip() in KNOWN_EXAMPLE_SECRET_KEYS diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_refresh_rotation.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_refresh_rotation.py-tpl new file mode 100644 index 00000000..701b3894 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_refresh_rotation.py-tpl @@ -0,0 +1,281 @@ +# -------------------------------------------------------------------------- +# Refresh token rotation under concurrency and partial failure. +# +# These tests use a file-based SQLite database (not the shared in-memory +# connection from conftest) so that separate sessions really are separate +# connections and transactions, as they are in production. +# -------------------------------------------------------------------------- +import threading +from collections.abc import Callable, Generator +from datetime import timedelta +from pathlib import Path +from typing import Any, List, Optional, Tuple + +import pytest +from sqlalchemy import func +from sqlalchemy.engine import Engine +from sqlalchemy.exc import IntegrityError +from sqlmodel import Session, SQLModel, create_engine, select +from src.app.core.security import ( + REFRESH_TOKEN_TYPE, + TokenError, + _create_token, + create_refresh_token, + decode_token, + hash_password, +) +from src.app.domains.auth import service as auth_service_module +from src.app.domains.auth.models import RefreshToken +from src.app.domains.auth.repository import RefreshTokenRepository +from src.app.domains.auth.service import AuthService +from src.app.domains.users.models import User +from src.app.domains.users.repository import UserRepository + + +@pytest.fixture(name="engine") +def engine_fixture(tmp_path: Path) -> Generator[Engine, None, None]: + engine = create_engine( + f"sqlite:///{tmp_path / 'rotation.db'}", + # Generous busy timeout: concurrent writers wait for the lock + # instead of failing with "database is locked". + connect_args={"check_same_thread": False, "timeout": 30}, + ) + SQLModel.metadata.create_all(engine) + yield engine + engine.dispose() + + +@pytest.fixture(name="user_id") +def user_id_fixture(engine: Engine) -> int: + with Session(engine) as session: + user = UserRepository(session).add( + User(email="carol@example.com", hashed_password=hash_password("pw-123456")) + ) + assert user.id is not None + return user.id + + +def _service(session: Session) -> AuthService: + return AuthService(UserRepository(session), RefreshTokenRepository(session)) + + +def _login(engine: Engine, user_id: int) -> str: + with Session(engine) as session: + user = session.get(User, user_id) + assert user is not None + return _service(session).issue_token_pair(user).refresh_token + + +def _record(engine: Engine, refresh_token: str) -> Optional[RefreshToken]: + jti = str(decode_token(refresh_token, REFRESH_TOKEN_TYPE)["jti"]) + with Session(engine) as session: + return session.exec(select(RefreshToken).where(RefreshToken.jti == jti)).first() + + +def _token_count(engine: Engine) -> int: + with Session(engine) as session: + return session.exec(select(func.count()).select_from(RefreshToken)).one() + + +def test_revoke_if_active_affects_exactly_one_row(engine: Engine, user_id: int) -> None: + refresh_token = _login(engine, user_id) + jti = str(decode_token(refresh_token, REFRESH_TOKEN_TYPE)["jti"]) + + with Session(engine) as session: + repo = RefreshTokenRepository(session) + with repo.atomic(): + assert repo.revoke_if_active(jti) is True + with repo.atomic(): + assert repo.revoke_if_active(jti) is False + with repo.atomic(): + assert repo.revoke_if_active("no-such-jti") is False + + +def test_second_rotation_loses_when_its_check_ran_before_first_commit( + engine: Engine, user_id: int +) -> None: + """Deterministic interleaving of two refreshes using the same token. + + Session B reads the token record (sees it active), then session A runs + a complete rotation and commits, then B continues. B's conditional + update must find no active row, so B fails and issues nothing. + """ + refresh_token = _login(engine, user_id) + + with Session(engine) as session_a, Session(engine) as session_b: + service_a = _service(session_a) + service_b = _service(session_b) + results: List[Any] = [] + + original_get = service_b.refresh_tokens.get_by_jti + + def get_then_let_a_win(jti: str) -> Optional[RefreshToken]: + record = original_get(jti) + assert record is not None and record.revoked is False + results.append(service_a.rotate(refresh_token)) + return record + + service_b.refresh_tokens.get_by_jti = get_then_let_a_win # type: ignore[method-assign] + + with pytest.raises(TokenError): + service_b.rotate(refresh_token) + + assert len(results) == 1 + # Exactly one successor exists: login token + A's new token. + assert _token_count(engine) == 2 + record = _record(engine, refresh_token) + assert record is not None and record.revoked is True + # A's successor is usable; B left nothing behind. + assert _record(engine, results[0].refresh_token) is not None + + +def test_concurrent_rotations_of_same_token_only_one_succeeds( + engine: Engine, user_id: int +) -> None: + refresh_token = _login(engine, user_id) + workers = 8 + barrier = threading.Barrier(workers) + outcomes: List[Tuple[str, Any]] = [] + lock = threading.Lock() + + def worker() -> None: + with Session(engine) as session: + service = _service(session) + barrier.wait() + try: + pair = service.rotate(refresh_token) + outcome: Tuple[str, Any] = ("ok", pair) + except TokenError as exc: + outcome = ("rejected", exc) + except Exception as exc: # pragma: no cover - surfaced below + outcome = ("error", exc) + with lock: + outcomes.append(outcome) + + threads = [threading.Thread(target=worker) for _ in range(workers)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=60) + + kinds = [kind for kind, _ in outcomes] + assert len(outcomes) == workers + assert "error" not in kinds, outcomes + assert kinds.count("ok") == 1 + assert kinds.count("rejected") == workers - 1 + assert _token_count(engine) == 2 + + +def test_failed_successor_insert_keeps_presented_token_valid( + engine: Engine, user_id: int, monkeypatch: pytest.MonkeyPatch +) -> None: + refresh_token = _login(engine, user_id) + presented_jti = str(decode_token(refresh_token, REFRESH_TOKEN_TYPE)["jti"]) + + real_create: Callable[..., Tuple[str, str, Any]] = create_refresh_token + + def colliding_create(*args: Any, **kwargs: Any) -> Tuple[str, str, Any]: + # Reuse the presented jti so the successor INSERT violates the + # unique constraint, after the revoke UPDATE already ran. + token, _, expires_at = real_create(*args, **kwargs) + return token, presented_jti, expires_at + + monkeypatch.setattr(auth_service_module, "create_refresh_token", colliding_create) + + with Session(engine) as session: + with pytest.raises(IntegrityError): + _service(session).rotate(refresh_token) + + # No half-state: the revoke was rolled back and nothing was inserted. + record = _record(engine, refresh_token) + assert record is not None and record.revoked is False + assert _token_count(engine) == 1 + + # The presented token still works once the fault is gone. + monkeypatch.setattr(auth_service_module, "create_refresh_token", real_create) + with Session(engine) as session: + pair = _service(session).rotate(refresh_token) + assert _record(engine, pair.refresh_token) is not None + consumed = _record(engine, refresh_token) + assert consumed is not None and consumed.revoked is True + + +def test_session_is_reusable_after_failed_rotation( + engine: Engine, user_id: int +) -> None: + refresh_token = _login(engine, user_id) + with Session(engine) as session: + service = _service(session) + service.rotate(refresh_token) + with pytest.raises(TokenError): + service.rotate(refresh_token) + # Same session keeps working after the rolled-back attempt. + user = session.get(User, user_id) + assert user is not None + assert service.issue_token_pair(user).refresh_token + + +def test_rotation_rejects_expired_record(engine: Engine, user_id: int) -> None: + # JWT still valid, but the stored record says it expired. + refresh_token = _login(engine, user_id) + jti = str(decode_token(refresh_token, REFRESH_TOKEN_TYPE)["jti"]) + with Session(engine) as session: + record = session.exec(select(RefreshToken).where(RefreshToken.jti == jti)).one() + record.expires_at = record.expires_at - timedelta(days=365) + session.add(record) + session.commit() + + with Session(engine) as session: + with pytest.raises(TokenError): + _service(session).rotate(refresh_token) + stored = _record(engine, refresh_token) + assert stored is not None and stored.revoked is False + assert _token_count(engine) == 1 + + +def test_rotation_rejects_inactive_user_without_consuming_token( + engine: Engine, user_id: int +) -> None: + refresh_token = _login(engine, user_id) + with Session(engine) as session: + user = session.get(User, user_id) + assert user is not None + user.is_active = False + session.add(user) + session.commit() + + with Session(engine) as session: + with pytest.raises(TokenError): + _service(session).rotate(refresh_token) + assert _token_count(engine) == 1 + + +def test_expired_jwt_is_rejected(engine: Engine, user_id: int) -> None: + expired, _, _ = _create_token( + str(user_id), REFRESH_TOKEN_TYPE, timedelta(minutes=-1), ["me"] + ) + with Session(engine) as session: + with pytest.raises(TokenError): + _service(session).rotate(expired) + + +def test_revoke_and_revoke_all(engine: Engine, user_id: int) -> None: + first = _login(engine, user_id) + second = _login(engine, user_id) + third = _login(engine, user_id) + + with Session(engine) as session: + service = _service(session) + service.revoke(first) + service.revoke(first) # idempotent + service.revoke("not-a-jwt") # silently ignored + user = session.get(User, user_id) + assert user is not None + assert service.revoke_all(user) == 2 + + for token in (first, second, third): + record = _record(engine, token) + assert record is not None and record.revoked is True + with Session(engine) as session: + with pytest.raises(TokenError): + _service(session).rotate(token) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitignore-tpl index b1016d22..920938a5 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitignore-tpl @@ -7,7 +7,8 @@ [Ll]ib [Ll]ib64 [Ll]ocal -[Ss]cripts +# No bare [Ss]cripts rule: it would hide the project's own scripts/*.sh. +# A Windows venv's Scripts/ is already covered by the .venv / venv/ rules. pyvenv.cfg .venv pip-selfcheck.json @@ -189,3 +190,9 @@ cython_debug/ # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. .idea/ + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl index 2af3eb27..5dec8618 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl @@ -55,6 +55,10 @@ $ bash scripts/run-server.sh $ uvicorn src.main:app --reload ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + Access API documentation after server starts: ```bash diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl index 019a244b..5a5f1e19 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl @@ -35,6 +35,6 @@ starlette==1.6.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.gitignore-tpl index ef6364a9..5656953a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.gitignore-tpl @@ -28,3 +28,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl index 6f5e7c08..a08884ad 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl @@ -51,6 +51,10 @@ $ bash scripts/run-server.sh $ uvicorn src.main:app --reload ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + After running server instance, you can check API documentation below: ```bash diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl index ce370cde..bc4f39de 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl @@ -33,6 +33,6 @@ starlette==1.6.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl index a22e29a1..1c512292 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl @@ -12,11 +12,14 @@ from pydantic_settings import BaseSettings, SettingsConfigDict def parse_cors(v: Any) -> list[str] | str: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",")] - elif isinstance(v, (list, str)): + elif isinstance(v, list | str): return v raise ValueError(v) +CorsOrigins = Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] + + class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=".env", @@ -29,9 +32,7 @@ class Settings(BaseSettings): CLIENT_ORIGIN: str = "" - BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = ( - [] - ) + BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl index 7f78170b..a87d1042 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl @@ -8,7 +8,7 @@ MOCK_FILE = os.path.join(os.path.dirname(__file__), "../mocks/mock_items.json") def read_items(): - with open(MOCK_FILE, "r") as file: + with open(MOCK_FILE) as file: return json.load(file) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl index 81223aec..9f7da2fd 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl @@ -7,6 +7,7 @@ from collections.abc import Generator import pytest from fastapi.testclient import TestClient + from src.main import app MOCK_FILE = os.path.join(os.path.dirname(__file__), "../src/mocks/mock_items.json") diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl index b194928f..5a27cc2d 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl @@ -3,7 +3,6 @@ # -------------------------------------------------------------------------- - def test_read_all_items(client): response = client.get("/items") assert response.status_code == 200 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitignore-tpl index ef6364a9..5656953a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitignore-tpl @@ -28,3 +28,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl index 7b162c8f..4fbe3880 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl @@ -72,6 +72,10 @@ $ bash scripts/run-server.sh $ uvicorn src.main:app --reload ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + After running server instance, you can check API documentation below: ```bash diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl index 54e49501..1d2db0da 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl @@ -36,7 +36,7 @@ starlette==1.6.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" vcs-versioning==2.3.4 watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.gitignore-tpl index e019e0c4..28f6cd68 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.gitignore-tpl @@ -29,3 +29,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl index 62587397..c25120f4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl @@ -30,7 +30,8 @@ sandbox, use `fastapi-single-module`. . ├── README.md ├── pyproject.toml -├── .env +├── .env # local settings, git-ignored (generated) +├── .env.example # shareable example, committed ├── .gitignore ├── scripts/ │ ├── format.sh @@ -80,6 +81,10 @@ $ bash scripts/run-server.sh $ uvicorn src.app.main:app --reload ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + API docs are then served at: - Swagger UI: @@ -107,8 +112,11 @@ $ pytest ## Configuration `src/app/core/config.py` reads settings from environment variables (or a -local `.env` file). The provided `.env` only sets a placeholder -`SECRET_KEY` — replace it before deploying. +local `.env` file). fastkit generated `.env` from `.env.example` with a +unique `SECRET_KEY`. `.env` is git-ignored and stays on your machine; commit +`.env.example` and keep only placeholder values in it. With +`ENVIRONMENT=production` the app refuses to start while `SECRET_KEY` is still +an example value such as `changethis`. ## Project Origin diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl index bfce2141..02fe6591 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl @@ -32,6 +32,6 @@ starlette==1.6.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl index 543a82c7..a88f1ce3 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl @@ -4,18 +4,30 @@ import secrets from typing import Annotated, Any, Literal -from pydantic import AnyUrl, BeforeValidator, computed_field +from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict def _parse_cors(v: Any) -> list[str] | str: if isinstance(v, str) and not v.startswith("["): return [item.strip() for item in v.split(",") if item.strip()] - if isinstance(v, (list, str)): + if isinstance(v, list | str): return v raise ValueError(v) +#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` +#: files. They are public, so a production deployment must never sign +#: anything with one of them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + } +) + + class Settings(BaseSettings): """Centralized configuration for the application. @@ -32,6 +44,9 @@ class Settings(BaseSettings): PROJECT_NAME: str = "" ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # Not read by the shipped code; reserved for signing features you add. + # fastkit writes a unique value to .env, and production refuses the + # public example values (see the validator below). SECRET_KEY: str = secrets.token_urlsafe(32) API_V1_PREFIX: str = "/api/v1" @@ -45,5 +60,19 @@ class Settings(BaseSettings): def all_cors_origins(self) -> list[str]: return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + @model_validator(mode="after") + def _reject_example_secret_key_in_production(self) -> "Settings": + if ( + self.ENVIRONMENT == "production" + and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + ): + raise ValueError( + "SECRET_KEY is set to a public example value while " + "ENVIRONMENT=production. Generate a real key with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as the SECRET_KEY environment variable (or in .env)." + ) + return self + settings = Settings() # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl index 90b26cd9..dd392f1d 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl @@ -31,7 +31,9 @@ class ItemRepository: item.id = new_id return item - def replace(self, item_id: int, name: str, price: float, in_stock: bool) -> Item | None: + def replace( + self, item_id: int, name: str, price: float, in_stock: bool + ) -> Item | None: existing = self._store.get(item_id) if existing is None: return None diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl index 998e188c..622683c2 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl @@ -21,11 +21,15 @@ def list_items(service: ItemService = Depends(get_item_service)) -> list[ItemRea @router.get("/{item_id}", response_model=ItemRead) -def get_item(item_id: int, service: ItemService = Depends(get_item_service)) -> ItemRead: +def get_item( + item_id: int, service: ItemService = Depends(get_item_service) +) -> ItemRead: try: return ItemRead.model_validate(service.get_item(item_id)) except ItemNotFoundError as exc: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) + ) from exc @router.post("", response_model=ItemRead, status_code=status.HTTP_201_CREATED) @@ -44,7 +48,9 @@ def replace_item( try: return ItemRead.model_validate(service.replace_item(item_id, payload)) except ItemNotFoundError as exc: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) + ) from exc @router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) @@ -54,5 +60,7 @@ def delete_item( try: service.delete_item(item_id) except ItemNotFoundError as exc: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) + ) from exc return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl index 7530cfb9..871ee68b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl @@ -7,6 +7,7 @@ from pkgutil import iter_modules import pytest from fastapi.testclient import TestClient + from src.app import domains from src.app.domains.items.repository import ItemRepository from src.app.main import app diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_config.py-tpl new file mode 100644 index 00000000..fba88b03 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_config.py-tpl @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Settings validation: production refuses a public example SECRET_KEY. +# -------------------------------------------------------------------------- +import re +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings + +ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" + + +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_production_refuses_example_secret_key(example_key: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + + +@pytest.mark.parametrize("environment", ["development", "staging"]) +def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: + settings = Settings( + _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" + ) + + assert settings.SECRET_KEY == "changethis" + + +def test_production_accepts_a_real_secret_key() -> None: + settings = Settings( + _env_file=None, + ENVIRONMENT="production", + SECRET_KEY="a-real-unique-key-0123456789abcdef", + ) + + assert settings.ENVIRONMENT == "production" + + +def test_env_example_secret_key_is_a_known_example_value() -> None: + """Whatever .env.example ships must be one the production guard rejects.""" + if not ENV_EXAMPLE.is_file(): + pytest.skip(".env.example is not part of this checkout") + + match = re.search( + r"^SECRET_KEY=(.*)$", ENV_EXAMPLE.read_text(encoding="utf-8"), re.M + ) + + assert match is not None + assert match.group(1).strip() in KNOWN_EXAMPLE_SECRET_KEYS diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.gitignore-tpl index ef6364a9..5656953a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.gitignore-tpl @@ -28,3 +28,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl index 9f5c46f7..19e8bd69 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl @@ -35,7 +35,8 @@ A minimal FastAPI template that provides the basic structure for building FastAP │ ├── conftest.py # pytest configuration │ ├── test_main.py # Main application tests │ └── __init__.py -└── .env # Environment variables +├── .env # Local environment variables (git-ignored) +└── .env.example # Shareable example, committed ``` ## Environment settings diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl index bfce2141..02fe6591 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl @@ -32,6 +32,6 @@ starlette==1.6.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl index 907a0bc3..fe9f5c85 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl @@ -12,11 +12,14 @@ from pydantic_settings import BaseSettings, SettingsConfigDict def parse_cors(v: Any) -> list[str] | str: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",")] - elif isinstance(v, (list, str)): + elif isinstance(v, list | str): return v raise ValueError(v) +CorsOrigins = Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] + + class Settings(BaseSettings): """Default project configuraion module @@ -29,6 +32,7 @@ class Settings(BaseSettings): https://fastapi.tiangolo.com/advanced/settings/?h=config """ + model_config = SettingsConfigDict( env_file=".env", env_ignore_empty=True, @@ -40,9 +44,7 @@ class Settings(BaseSettings): CLIENT_ORIGIN: str = "" - BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = ( - [] - ) + BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/conftest.py-tpl index 36217889..9e9e1eeb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/conftest.py-tpl @@ -5,6 +5,7 @@ from collections.abc import Generator import pytest from fastapi.testclient import TestClient + from src.main import app diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.gitignore-tpl index e019e0c4..28f6cd68 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.gitignore-tpl @@ -29,3 +29,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl index bd28dc72..74aa9954 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl @@ -40,7 +40,8 @@ you need a database-backed API, use `fastapi-sqlmodel`. ├── pyproject.toml ├── requirements.txt ├── Dockerfile -├── .env +├── .env # local settings, git-ignored (generated) +├── .env.example # shareable example, committed ├── .gitignore ├── scripts/ │ ├── chat.sh # send one message to a running server @@ -77,7 +78,10 @@ you need a database-backed API, use `fastapi-sqlmodel`. ## Configuration -Set your key in `.env` before the first run: +fastkit generated a local `.env` from `.env.example` (with a unique +`SECRET_KEY`). `.env` is git-ignored, so put real credentials there and keep +`.env.example` as the shareable copy with placeholders only. Set your key in +`.env` before the first run: ```bash ANTHROPIC_API_KEY=sk-ant-... @@ -107,6 +111,10 @@ $ bash scripts/run-server.sh $ bash scripts/chat.sh "What is 12 * 34?" ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + API docs are then served at: - Swagger UI: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl index 5687de1e..f47bcfc2 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl @@ -7,7 +7,7 @@ import secrets from typing import Annotated, Any, List, Literal, Union -from pydantic import AnyUrl, BeforeValidator, computed_field +from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict @@ -19,6 +19,18 @@ def _parse_cors(v: Any) -> Union[List[str], str]: raise ValueError(v) +#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` +#: files. They are public, so a production deployment must never sign +#: anything with one of them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + } +) + + class Settings(BaseSettings): """Centralized configuration for the application.""" @@ -30,6 +42,9 @@ class Settings(BaseSettings): PROJECT_NAME: str = "" ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # Not read by the shipped code; reserved for signing features you add. + # fastkit writes a unique value to .env, and production refuses the + # public example values (see the validator below). SECRET_KEY: str = secrets.token_urlsafe(32) API_V1_PREFIX: str = "/api/v1" @@ -63,5 +78,19 @@ class Settings(BaseSettings): def all_cors_origins(self) -> List[str]: return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + @model_validator(mode="after") + def _reject_example_secret_key_in_production(self) -> "Settings": + if ( + self.ENVIRONMENT == "production" + and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + ): + raise ValueError( + "SECRET_KEY is set to a public example value while " + "ENVIRONMENT=production. Generate a real key with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as the SECRET_KEY environment variable (or in .env)." + ) + return self + settings = Settings() # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_config.py-tpl new file mode 100644 index 00000000..fba88b03 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_config.py-tpl @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Settings validation: production refuses a public example SECRET_KEY. +# -------------------------------------------------------------------------- +import re +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings + +ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" + + +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_production_refuses_example_secret_key(example_key: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + + +@pytest.mark.parametrize("environment", ["development", "staging"]) +def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: + settings = Settings( + _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" + ) + + assert settings.SECRET_KEY == "changethis" + + +def test_production_accepts_a_real_secret_key() -> None: + settings = Settings( + _env_file=None, + ENVIRONMENT="production", + SECRET_KEY="a-real-unique-key-0123456789abcdef", + ) + + assert settings.ENVIRONMENT == "production" + + +def test_env_example_secret_key_is_a_known_example_value() -> None: + """Whatever .env.example ships must be one the production guard rejects.""" + if not ENV_EXAMPLE.is_file(): + pytest.skip(".env.example is not part of this checkout") + + match = re.search( + r"^SECRET_KEY=(.*)$", ENV_EXAMPLE.read_text(encoding="utf-8"), re.M + ) + + assert match is not None + assert match.group(1).strip() in KNOWN_EXAMPLE_SECRET_KEYS diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env-tpl deleted file mode 100644 index d458312b..00000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env-tpl +++ /dev/null @@ -1,29 +0,0 @@ -# FastAPI MCP Project Configuration - -# Application Settings -PROJECT_NAME=FastAPI MCP Project -VERSION=0.1.0 -API_V1_STR=/api/v1 - -# Server Settings -HOST=0.0.0.0 -PORT=8000 -DEBUG=false - -# CORS Settings -# Comma-separated list of allowed origins -; BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080 - -# MCP (Model Context Protocol) Settings -MCP_ENABLED=true -MCP_MOUNT_PATH=/mcp -MCP_TITLE=FastAPI MCP Server -MCP_DESCRIPTION=FastAPI endpoints exposed as MCP tools - -# Authentication Settings -SECRET_KEY=changethis-please-use-openssl-rand-hex-32 -ALGORITHM=HS256 -ACCESS_TOKEN_EXPIRE_MINUTES=30 - -# MCP API Key (optional, for additional MCP endpoint security) -# MCP_API_KEY=your-mcp-api-key-here diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env.example-tpl new file mode 100644 index 00000000..8d1b4368 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env.example-tpl @@ -0,0 +1,48 @@ +# FastAPI MCP Project Configuration +# +# Copy this file to .env and adjust the values. Never commit .env. +# (Projects generated by FastAPI-fastkit already get a .env with a freshly +# generated SECRET_KEY.) + +# Application Settings +PROJECT_NAME=FastAPI MCP Project +VERSION=0.1.0 +API_V1_STR=/api/v1 +# One of: development, staging, production. +# In production the app refuses to start if SECRET_KEY is unset or still an +# example value, or if ENABLE_DEMO_USERS=true. +ENVIRONMENT=development + +# Server Settings +HOST=0.0.0.0 +PORT=8000 +DEBUG=false + +# CORS Settings +# Comma-separated list of allowed origins +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080 + +# MCP (Model Context Protocol) Settings +MCP_ENABLED=true +MCP_MOUNT_PATH=/mcp +MCP_TITLE=FastAPI MCP Server +MCP_DESCRIPTION=FastAPI endpoints exposed as MCP tools + +# Authentication Settings +# Example value only: replace it with your own key, e.g. `openssl rand -hex 32`. +SECRET_KEY=changethis-please-use-openssl-rand-hex-32 +ALGORITHM=HS256 +ACCESS_TOKEN_EXPIRE_MINUTES=30 + +# Demo accounts (user1/password123, user2/password456, admin/admin123). +# Disabled by default. Set to true only for local experiments; the app refuses +# to start with ENABLE_DEMO_USERS=true when ENVIRONMENT=production. +ENABLE_DEMO_USERS=false + +# MCP endpoint authentication +# The MCP endpoint is PROTECTED by default; it is never open. +# - MCP_API_KEY unset: clients must send a valid JWT access token +# (Authorization: Bearer ). +# - MCP_API_KEY set: clients must send Authorization: Bearer , +# and JWTs are no longer accepted on the MCP endpoint. +# MCP_API_KEY=your-mcp-api-key-here diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.gitignore-tpl new file mode 100644 index 00000000..a533c605 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.gitignore-tpl @@ -0,0 +1,42 @@ +.idea +.ipynb_checkpoints +.mypy_cache +.vscode +__pycache__ +.pytest_cache +htmlcov +dist +site +.coverage* +coverage.xml +.netlify +test.db +log.txt +Pipfile.lock +env3.* +env +docs_build +site_build +venv +docs.zip +archive.zip + +# vim temporary files +*~ +.*.sw? +.cache + +# macOS +.DS_Store + +# Local SQLite database +*.db + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example + +# Virtual environments +.venv diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl index c05a6fd4..c5a47727 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl @@ -7,6 +7,7 @@ A FastAPI application with Model Context Protocol (MCP) integration, providing a - **FastAPI Integration**: Modern, fast web framework for building APIs - **MCP Support**: Expose API endpoints as Model Context Protocol tools - **Authentication**: JWT-based authentication with OAuth2 support +- **Protected MCP endpoint**: API key or JWT required on the MCP transport - **Authorization**: Role-based access control for API endpoints - **Auto-generated Documentation**: Swagger UI and ReDoc integration - **Type Safety**: Full type hints and Pydantic models @@ -46,18 +47,25 @@ pip install -r requirements.txt 3. Set up environment variables: ```bash -# Edit .env with your configuration +# Projects generated by FastAPI-fastkit already ship a .env with a freshly +# generated SECRET_KEY. Otherwise, start from the example file: +cp .env.example .env +# then replace SECRET_KEY, e.g. with the output of: openssl rand -hex 32 ``` +`.env` holds secrets and is listed in `.gitignore`; commit `.env.example` instead. + ### Environment Variables -The `.env` file contains the following configuration options: +`.env.example` documents every option: ```env # Application Settings PROJECT_NAME=FastAPI MCP Project VERSION=0.1.0 API_V1_STR=/api/v1 +# development | staging | production +ENVIRONMENT=development # Server Settings HOST=0.0.0.0 @@ -66,7 +74,7 @@ DEBUG=false # CORS Settings # Comma-separated list of allowed origins -BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080 +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080 # MCP (Model Context Protocol) Settings MCP_ENABLED=true @@ -74,20 +82,52 @@ MCP_MOUNT_PATH=/mcp MCP_TITLE=FastAPI MCP Server MCP_DESCRIPTION=FastAPI endpoints exposed as MCP tools -# Authentication Settings +# Authentication Settings (example value, replace it) SECRET_KEY=changethis-please-use-openssl-rand-hex-32 ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=30 -# MCP API Key (optional, for additional MCP endpoint security) +# Demo accounts with well-known passwords (off by default) +ENABLE_DEMO_USERS=false + +# MCP endpoint authentication (the MCP endpoint is protected by default) # MCP_API_KEY=your-mcp-api-key-here ``` +| Variable | Default | Meaning | +|---|---|---| +| `ENVIRONMENT` | `development` | `development`, `staging` or `production`. Production turns on the startup safety checks below. | +| `SECRET_KEY` | random per process | JWT signing key. When unset, a new random key is generated on every start, so tokens stop working after a restart and differ between workers. | +| `ENABLE_DEMO_USERS` | `false` | Enables the built-in demo accounts (see [Authentication](#authentication)). | +| `MCP_API_KEY` | unset | Static API key for the MCP endpoint. When unset, the MCP endpoint requires a JWT. See [MCP Authentication](#mcp-authentication). | +| `MCP_MOUNT_PATH` | `/mcp` | Path where the MCP server is mounted. | + +### Production Safety Checks + +When `ENVIRONMENT=production`, the application refuses to start (a settings +validation error is raised at import time) if: + +- `SECRET_KEY` is not set explicitly; +- `SECRET_KEY` is one of the public example values + (`changethis-please-use-openssl-rand-hex-32`, + `your-secret-key-here-change-in-production`); +- `ENABLE_DEMO_USERS=true`. + +The error message explains how to generate a key: + +```bash +openssl rand -hex 32 +# or +python -c "import secrets; print(secrets.token_urlsafe(32))" +``` + ### Important Security Notes -- **Always change `SECRET_KEY`** in production +- **Always set your own `SECRET_KEY`** outside local development - Use a strong, random secret key (minimum 32 characters) - Set `DEBUG=false` in production +- Keep `ENABLE_DEMO_USERS=false` anywhere other than your own machine +- Set `MCP_API_KEY` (or keep JWT auth) before exposing the MCP endpoint - Configure `BACKEND_CORS_ORIGINS` appropriately for your frontend domains ## Usage @@ -103,6 +143,9 @@ Start the development server: uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload ``` +> **Windows:** `fastkit runserver` or the `uvicorn` command above works in any +> shell; the `scripts/*.sh` helpers need Git Bash or WSL. + ### Authentication The application provides several authentication endpoints: @@ -111,11 +154,21 @@ The application provides several authentication endpoints: 2. **OAuth2 Token**: `POST /api/v1/auth/token` 3. **Current User**: `GET /api/v1/auth/me` -Default users: +The user store is empty by default; `src/api/routes/auth.py` has a +`get_users_db()` hook where you plug in a real database. + +For local experiments you can enable three demo accounts by setting +`ENABLE_DEMO_USERS=true` in `.env`: + - Username: `user1`, Password: `password123` - Username: `user2`, Password: `password456` - Username: `admin`, Password: `admin123` +These passwords are public, so the demo accounts are **disabled by default**: +with `ENABLE_DEMO_USERS=false` logging in as them fails with the normal `401`. +The application refuses to start with `ENABLE_DEMO_USERS=true` when +`ENVIRONMENT=production`. + ### API Endpoints - **Items**: CRUD operations for items (`/api/v1/items/`) @@ -133,16 +186,51 @@ The application exposes API endpoints as MCP tools at `/mcp` and provides additi - **MCP Status**: `GET /mcp-routes/status` - MCP configuration status - **MCP Tools**: `/mcp` - Main MCP protocol endpoint (via fastapi-mcp) +#### MCP Authentication + +**The MCP endpoint is protected by default; it is never open.** Authentication +is attached to the transport routes that fastapi-mcp registers +(`GET {MCP_MOUNT_PATH}` for the SSE connection and +`POST {MCP_MOUNT_PATH}/messages/` for messages) through +`AuthConfig(dependencies=[Depends(verify_mcp_access)])` in +`src/mcp_server/router.py`. The `/mcp-routes/*` helper endpoints stay public. + +| `MCP_API_KEY` | What the MCP endpoint requires | +|---|---| +| unset (default) | `Authorization: Bearer ` obtained from `/api/v1/auth/login` or `/api/v1/auth/token` | +| set | `Authorization: Bearer ` (compared in constant time); JWTs are no longer accepted | + +Requests with a missing or wrong credential get `401 Unauthorized`. + +Note: fastapi-mcp forwards the client's `Authorization` header to the API +endpoints it calls as tools. In JWT mode, tools for JWT-protected endpoints +(create/update/delete items, current user) work with the caller's token. In +`MCP_API_KEY` mode the forwarded header is the MCP key, which is not a JWT, so +those tools return `401`; only public endpoints work as tools. + +The quickest way to try MCP locally is to set an API key in `.env`: + +```env +MCP_API_KEY=some-long-random-string +``` + Example MCP usage: ```bash -# Test MCP hello endpoint +# Test MCP hello endpoint (public) curl http://localhost:8000/mcp-routes/hello -# Check MCP status +# Check MCP status (public) curl http://localhost:8000/mcp-routes/status -# Access MCP tools (requires authentication) -curl -H "Authorization: Bearer YOUR_TOKEN" http://localhost:8000/mcp +# Open the MCP SSE stream with the API key (MCP_API_KEY set) +curl -N -H "Authorization: Bearer $MCP_API_KEY" http://localhost:8000/mcp + +# Or, with MCP_API_KEY unset, use a JWT (e.g. from a demo login when +# ENABLE_DEMO_USERS=true) +TOKEN=$(curl -s -X POST http://localhost:8000/api/v1/auth/login \ + -H "Content-Type: application/json" \ + -d '{"username": "user1", "password": "password123"}' | jq -r .access_token) +curl -N -H "Authorization: Bearer $TOKEN" http://localhost:8000/mcp ``` ## Development @@ -210,11 +298,14 @@ The application exposes the following tools and endpoints via MCP: For production deployment: -1. Set `DEBUG=False` in environment -2. Use a secure `SECRET_KEY` -3. Configure proper CORS origins -4. Set up SSL/TLS certificates -5. Use a production WSGI server like Gunicorn +1. Set `ENVIRONMENT=production` (enables the startup safety checks) +2. Set `DEBUG=False` in environment +3. Use a secure, explicit `SECRET_KEY` +4. Keep `ENABLE_DEMO_USERS=false` (required in production) +5. Set `MCP_API_KEY` or rely on JWT auth for the MCP endpoint +6. Configure proper CORS origins +7. Set up SSL/TLS certificates +8. Use a production WSGI server like Gunicorn ### Docker Support diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl index ad0749be..4b709688 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl @@ -61,6 +61,6 @@ typing-extensions==4.16.0 typing-inspection==0.4.4 urllib3==2.8.0 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl index 3463dce2..a6f15241 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl @@ -2,6 +2,7 @@ Authentication-related API endpoints. """ from datetime import datetime, timedelta, timezone +from functools import cache import jwt from fastapi import APIRouter, Depends, HTTPException, status @@ -20,29 +21,37 @@ password_hash = PasswordHash.recommended() # OAuth2 scheme oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") -# Mock user database -mock_users = { - "user1": { - "user_id": "user1", - "username": "user1", - "hashed_password": password_hash.hash("password123"), - "active": True, - }, - "user2": { - "user_id": "user2", - "username": "user2", - "hashed_password": password_hash.hash("password456"), - "active": True, - }, - "admin": { - "user_id": "admin", - "username": "admin", - "hashed_password": password_hash.hash("admin123"), - "active": True, - }, +# Demo accounts with well-known passwords. They only exist when +# ENABLE_DEMO_USERS=true (never allowed in production), and their hashes are +# computed lazily on first use, not at import time. +DEMO_USER_CREDENTIALS = { + "user1": "password123", + "user2": "password456", + "admin": "admin123", } +@cache +def _demo_users() -> dict[str, dict]: + """Build the demo user records (hashed once, on first use).""" + return { + username: { + "user_id": username, + "username": username, + "hashed_password": password_hash.hash(password), + "active": True, + } + for username, password in DEMO_USER_CREDENTIALS.items() + } + + +def get_users_db() -> dict[str, dict]: + """Return the user store. Replace this with a real database lookup.""" + if settings.ENABLE_DEMO_USERS: + return _demo_users() + return {} + + def verify_password(plain_password: str, hashed_password: str) -> bool: """Verify a password against its hash.""" return password_hash.verify(plain_password, hashed_password) @@ -55,7 +64,7 @@ def get_password_hash(password: str) -> str: def authenticate_user(username: str, password: str) -> dict | None: """Authenticate user with username and password.""" - user = mock_users.get(username) + user = get_users_db().get(username) if not user: return None if not verify_password(password, user["hashed_password"]): @@ -129,5 +138,5 @@ async def get_users(current_user: dict = Depends(get_current_active_user)): """ return [ UserInfo(user_id=user["user_id"], username=user["username"], active=user["active"]) - for user in mock_users.values() + for user in get_users_db().values() ] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl index a9c904b2..88c49288 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl @@ -2,6 +2,8 @@ Authentication dependencies for API and MCP endpoints. """ +import secrets + import jwt from fastapi import Depends, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer @@ -53,10 +55,24 @@ def get_current_active_user(current_user: dict = Depends(get_current_user)): def verify_mcp_access(credentials: HTTPAuthorizationCredentials | None = Depends(security)): - """Verify MCP access permissions.""" + """Verify access to the MCP transport endpoints. + + Wired into the MCP server through ``AuthConfig(dependencies=[...])`` in + ``src/mcp_server/router.py``, so it guards both the SSE connection + endpoint (``GET {MCP_MOUNT_PATH}``) and the message endpoint + (``POST {MCP_MOUNT_PATH}/messages/``). + + - ``MCP_API_KEY`` set: require ``Authorization: Bearer ``. + - ``MCP_API_KEY`` unset: require a valid JWT access token instead. + + The MCP endpoint is never open without credentials. + """ if settings.MCP_API_KEY: - # Use API key authentication for MCP - if not credentials or credentials.credentials != settings.MCP_API_KEY: + # Use API key authentication for MCP (constant-time comparison) + if not credentials or not secrets.compare_digest( + credentials.credentials.encode("utf-8"), + settings.MCP_API_KEY.encode("utf-8"), + ): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid MCP API key", diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl index cc2bd36a..9adc4b58 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl @@ -2,8 +2,45 @@ Application configuration settings. """ -from pydantic import AnyHttpUrl, ConfigDict, field_validator -from pydantic_settings import BaseSettings +import json +import secrets +from typing import Annotated, Any, Literal + +from pydantic import AnyHttpUrl, BeforeValidator, model_validator +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict + + +def parse_cors(v: Any) -> Any: + """Accept CORS origins as a comma-separated string or a JSON list. + + ``NoDecode`` on the field stops pydantic-settings from JSON-decoding the + raw environment value first, which would reject the comma-separated form. + """ + if isinstance(v, str): + v = v.strip() + if v.startswith("["): + return json.loads(v) + return [item.strip() for item in v.split(",") if item.strip()] + return v + + +# SECRET_KEY values that ship in this template's docs and example files. They +# are public, so anyone could forge JWTs signed with them: the app refuses to +# start in production while SECRET_KEY is still one of these. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + } +) + +_GENERATE_KEY_HINT = ( + "Generate one with `openssl rand -hex 32` or " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) class Settings(BaseSettings): @@ -12,14 +49,17 @@ class Settings(BaseSettings): PROJECT_NAME: str = "FastAPI MCP Project" VERSION: str = "0.1.0" API_V1_STR: str = "/api/v1" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" # Server settings HOST: str = "0.0.0.0" PORT: int = 8000 DEBUG: bool = False - # CORS settings - BACKEND_CORS_ORIGINS: list[AnyHttpUrl] = [] + # CORS settings: comma-separated (http://a,http://b) or a JSON list + BACKEND_CORS_ORIGINS: Annotated[ + list[AnyHttpUrl], NoDecode, BeforeValidator(parse_cors) + ] = [] # MCP settings MCP_ENABLED: bool = True @@ -28,31 +68,58 @@ class Settings(BaseSettings): MCP_DESCRIPTION: str = "FastAPI endpoints exposed as MCP tools" # Authentication settings - SECRET_KEY: str = "your-secret-key-here-change-in-production" + # Signing key for JWTs. Generated per-process when unset, which invalidates + # every token on restart and differs between workers, so production + # refuses to start without an explicit SECRET_KEY. + SECRET_KEY: str = secrets.token_urlsafe(32) ALGORITHM: str = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 - # API Key for MCP authentication (optional) + # Built-in demo accounts (user1 / user2 / admin) with well-known passwords. + # Off by default; never allowed in production. + ENABLE_DEMO_USERS: bool = False + + # Static API key for the MCP endpoint. When set, MCP clients must send + # ``Authorization: Bearer ``. When unset, the MCP endpoint + # requires a valid JWT access token instead. It is never open. MCP_API_KEY: str | None = None - @field_validator("BACKEND_CORS_ORIGINS", mode="before") - @classmethod - def assemble_cors_origins(cls, v: str | list[str]) -> list[str] | str: - """Assemble CORS origins from environment variable.""" - if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, (list, str)): - return v - raise ValueError(v) + @model_validator(mode="after") + def check_production_safety(self) -> "Settings": + """Refuse insecure settings when running in production.""" + if self.ENVIRONMENT != "production": + return self + + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + "SECRET_KEY must be set explicitly when ENVIRONMENT=production " + "(the per-process random default breaks tokens across restarts " + "and workers). " + _GENERATE_KEY_HINT + ) + if self.SECRET_KEY in KNOWN_EXAMPLE_SECRET_KEYS: + raise ValueError( + "SECRET_KEY is set to a public example value, which must not be " + "used when ENVIRONMENT=production. " + _GENERATE_KEY_HINT + ) + if self.ENABLE_DEMO_USERS: + raise ValueError( + "ENABLE_DEMO_USERS=true is not allowed when ENVIRONMENT=production: " + "the demo accounts use well-known passwords. " + "Set ENABLE_DEMO_USERS=false." + ) + return self @property def all_cors_origins(self) -> list[str]: - """Get all CORS origins.""" - return self.BACKEND_CORS_ORIGINS + """CORS origins as plain strings, without the trailing slash that + ``AnyHttpUrl`` adds (browsers send ``Origin`` without one).""" + return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] - model_config = ConfigDict( + model_config = SettingsConfigDict( case_sensitive=True, - env_file=".env" + env_file=".env", + env_ignore_empty=True, + extra="ignore", ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl index cac9f110..163ebca7 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl @@ -2,9 +2,10 @@ MCP router configuration and setup. """ -from fastapi import APIRouter, FastAPI -from fastapi_mcp import FastApiMCP +from fastapi import APIRouter, Depends, FastAPI +from fastapi_mcp import AuthConfig, FastApiMCP +from src.auth.dependencies import verify_mcp_access from src.core.config import settings # Create MCP specific router @@ -52,8 +53,14 @@ def create_mcp_router(app: FastAPI) -> FastApiMCP: # Include MCP specific routes in the main app app.include_router(mcp_router, prefix="/mcp-routes", tags=["mcp"]) - # Create MCP instance with app - mcp = FastApiMCP(app) + # Create MCP instance with app. The auth dependencies are attached by + # fastapi-mcp to the transport routes it registers on mount(): the SSE + # connection endpoint and the messages endpoint. See verify_mcp_access + # for the API key / JWT semantics. + mcp = FastApiMCP( + app, + auth_config=AuthConfig(dependencies=[Depends(verify_mcp_access)]), + ) return mcp @@ -92,7 +99,7 @@ def setup_mcp_server(app: FastAPI) -> FastApiMCP | None: # Configure MCP tools configure_mcp_tools(mcp) - # Mount MCP server - mcp.mount() + # Mount MCP server at the configured path + mcp.mount(mount_path=settings.MCP_MOUNT_PATH) return mcp diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl index b6b5763f..904cfa32 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl @@ -4,6 +4,7 @@ Test configuration and fixtures. import pytest from fastapi.testclient import TestClient from src.api.routes.auth import create_access_token +from src.core.config import settings from src.main import app @@ -13,6 +14,26 @@ def client(): return TestClient(app) +@pytest.fixture +def demo_users(monkeypatch): + """Enable the built-in demo accounts (off by default) for one test.""" + monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", True) + + +@pytest.fixture +def mcp_api_key(monkeypatch): + """Protect the MCP endpoint with a static API key for one test.""" + key = "test-mcp-api-key" + monkeypatch.setattr(settings, "MCP_API_KEY", key) + return key + + +@pytest.fixture +def no_mcp_api_key(monkeypatch): + """Make sure MCP_API_KEY is unset, whatever .env says.""" + monkeypatch.setattr(settings, "MCP_API_KEY", None) + + @pytest.fixture def test_user(): """Test user data.""" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl index ea9d405b..2b0434f8 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl @@ -1,10 +1,18 @@ """ Tests for authentication API endpoints. """ +import os +import subprocess +import sys +from pathlib import Path + from fastapi.testclient import TestClient +from src.api.routes.auth import DEMO_USER_CREDENTIALS +from src.core.config import Settings, settings + -def test_login_valid_credentials(client: TestClient): +def test_login_valid_credentials(client: TestClient, demo_users): """Test login with valid credentials.""" login_data = {"username": "user1", "password": "password123"} response = client.post("/api/v1/auth/login", json=login_data) @@ -15,7 +23,7 @@ def test_login_valid_credentials(client: TestClient): assert data["token_type"] == "bearer" -def test_login_invalid_credentials(client: TestClient): +def test_login_invalid_credentials(client: TestClient, demo_users): """Test login with invalid credentials.""" login_data = {"username": "user1", "password": "wrongpassword"} response = client.post("/api/v1/auth/login", json=login_data) @@ -29,7 +37,7 @@ def test_login_nonexistent_user(client: TestClient): assert response.status_code == 401 -def test_oauth2_token_valid_credentials(client: TestClient): +def test_oauth2_token_valid_credentials(client: TestClient, demo_users): """Test OAuth2 token endpoint with valid credentials.""" token_data = {"username": "user1", "password": "password123"} response = client.post("/api/v1/auth/token", data=token_data) @@ -40,7 +48,7 @@ def test_oauth2_token_valid_credentials(client: TestClient): assert data["token_type"] == "bearer" -def test_oauth2_token_invalid_credentials(client: TestClient): +def test_oauth2_token_invalid_credentials(client: TestClient, demo_users): """Test OAuth2 token endpoint with invalid credentials.""" token_data = {"username": "user1", "password": "wrongpassword"} response = client.post("/api/v1/auth/token", data=token_data) @@ -53,7 +61,7 @@ def test_get_current_user_without_token(client: TestClient): assert response.status_code == 401 -def test_get_current_user_with_token(client: TestClient): +def test_get_current_user_with_token(client: TestClient, demo_users): """Test getting current user with valid token.""" # First, login to get a token login_data = {"username": "user1", "password": "password123"} @@ -83,7 +91,7 @@ def test_get_users_without_auth(client: TestClient): assert response.status_code == 401 -def test_get_users_with_auth(client: TestClient): +def test_get_users_with_auth(client: TestClient, demo_users): """Test getting users with authentication.""" # First, login to get a token login_data = {"username": "user1", "password": "password123"} @@ -98,3 +106,63 @@ def test_get_users_with_auth(client: TestClient): assert isinstance(data, list) assert len(data) > 0 assert all("username" in user for user in data) + + +def test_demo_users_flag_defaults_to_off(monkeypatch): + """ENABLE_DEMO_USERS is off unless explicitly enabled.""" + monkeypatch.delenv("ENABLE_DEMO_USERS", raising=False) + assert Settings.model_fields["ENABLE_DEMO_USERS"].default is False + assert Settings(_env_file=None).ENABLE_DEMO_USERS is False + + +def test_demo_users_disabled(client: TestClient, monkeypatch): + """Demo accounts must not authenticate while ENABLE_DEMO_USERS is off.""" + monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", False) + for username, password in DEMO_USER_CREDENTIALS.items(): + response = client.post( + "/api/v1/auth/login", json={"username": username, "password": password} + ) + assert response.status_code == 401 + response = client.post( + "/api/v1/auth/token", data={"username": username, "password": password} + ) + assert response.status_code == 401 + + +def test_demo_users_enabled(client: TestClient, demo_users): + """Every demo account can log in once ENABLE_DEMO_USERS is on.""" + for username, password in DEMO_USER_CREDENTIALS.items(): + response = client.post( + "/api/v1/auth/login", json={"username": username, "password": password} + ) + assert response.status_code == 200 + assert response.json()["token_type"] == "bearer" + + +def test_users_list_empty_without_demo_users( + client: TestClient, auth_headers, monkeypatch +): + """With demo users off the user store is empty.""" + monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", False) + response = client.get("/api/v1/auth/users", headers=auth_headers) + assert response.status_code == 200 + assert response.json() == [] + + +def test_demo_user_hashes_not_computed_at_import(): + """Importing the app must not hash the demo passwords when they are off.""" + project_root = Path(__file__).resolve().parent.parent + env = {**os.environ, "ENABLE_DEMO_USERS": "false", "ENVIRONMENT": "development"} + code = ( + "import src.main\n" + "from src.api.routes.auth import _demo_users\n" + "assert _demo_users.cache_info().currsize == 0\n" + ) + result = subprocess.run( + [sys.executable, "-c", code], + cwd=project_root, + env=env, + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_config.py-tpl new file mode 100644 index 00000000..33ba8948 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_config.py-tpl @@ -0,0 +1,155 @@ +""" +Tests for the production safety checks in application settings. +""" + +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings + +STRONG_KEY = "x" * 64 + + +@pytest.fixture(autouse=True) +def clean_env(monkeypatch): + """Keep shell environment variables from leaking into Settings().""" + for name in ( + "ENVIRONMENT", + "SECRET_KEY", + "ENABLE_DEMO_USERS", + "BACKEND_CORS_ORIGINS", + ): + monkeypatch.delenv(name, raising=False) + + +def make_settings(**values) -> Settings: + """Build settings from explicit values only, ignoring any .env file.""" + return Settings(_env_file=None, **values) + + +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_production_rejects_example_secret_key(example_key: str): + with pytest.raises(ValidationError) as exc_info: + make_settings(ENVIRONMENT="production", SECRET_KEY=example_key) + message = str(exc_info.value) + assert "SECRET_KEY" in message + assert "openssl rand -hex 32" in message + + +@pytest.mark.parametrize( + "example_key", + [ + # Placeholders used by the other fastkit templates' examples; a key + # copied from one of them must not pass in production either. + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + ], +) +def test_shared_placeholder_keys_are_rejected_in_production(example_key: str): + assert example_key in KNOWN_EXAMPLE_SECRET_KEYS + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT="production", SECRET_KEY=example_key) + + +def test_env_example_secret_key_is_rejected_in_production(): + """The SECRET_KEY shipped in .env.example is on the deny list.""" + env_example = Path(__file__).resolve().parent.parent / ".env.example" + if not env_example.exists(): + pytest.skip(".env.example not present") + lines = [ + line.split("=", 1)[1].strip() + for line in env_example.read_text().splitlines() + if line.startswith("SECRET_KEY=") + ] + assert len(lines) == 1 + assert lines[0] in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_production_requires_explicit_secret_key(): + with pytest.raises(ValidationError, match="SECRET_KEY must be set explicitly"): + make_settings(ENVIRONMENT="production") + + +def test_production_rejects_demo_users(): + with pytest.raises(ValidationError, match="ENABLE_DEMO_USERS"): + make_settings( + ENVIRONMENT="production", SECRET_KEY=STRONG_KEY, ENABLE_DEMO_USERS=True + ) + + +def test_production_accepts_strong_key_without_demo_users(): + settings = make_settings(ENVIRONMENT="production", SECRET_KEY=STRONG_KEY) + assert settings.ENVIRONMENT == "production" + assert settings.ENABLE_DEMO_USERS is False + + +def test_production_guard_reads_environment_variables(monkeypatch): + """The guard also fires when values come from the environment.""" + monkeypatch.setenv("ENVIRONMENT", "production") + monkeypatch.setenv("SECRET_KEY", "changethis-please-use-openssl-rand-hex-32") + with pytest.raises(ValidationError): + Settings(_env_file=None) + + +@pytest.mark.parametrize("environment", ["development", "staging"]) +def test_non_production_allows_example_key_and_demo_users(environment: str): + settings = make_settings( + ENVIRONMENT=environment, + SECRET_KEY="changethis-please-use-openssl-rand-hex-32", + ENABLE_DEMO_USERS=True, + ) + assert settings.ENABLE_DEMO_USERS is True + + +def test_default_secret_key_is_random_per_process(): + settings = make_settings() + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + assert len(settings.SECRET_KEY) >= 32 + + +@pytest.mark.parametrize( + "raw", + [ + "http://localhost:3000,http://localhost:8080", + " http://localhost:3000 , http://localhost:8080 ,", + '["http://localhost:3000", "http://localhost:8080"]', + ], +) +def test_cors_origins_from_environment(monkeypatch, raw: str): + """Comma-separated and JSON-list values both load from the environment.""" + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + settings = Settings(_env_file=None) + assert settings.all_cors_origins == [ + "http://localhost:3000", + "http://localhost:8080", + ] + + +def test_cors_origins_from_env_file(tmp_path: Path): + """The commented example line in .env.example works once uncommented.""" + env_file = tmp_path / ".env" + env_file.write_text( + "BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080\n" + ) + settings = Settings(_env_file=env_file) + assert settings.all_cors_origins == [ + "http://localhost:3000", + "http://localhost:8080", + ] + + +def test_empty_cors_origins_is_empty_list(monkeypatch): + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "") + assert Settings(_env_file=None).all_cors_origins == [] + assert make_settings(BACKEND_CORS_ORIGINS="").all_cors_origins == [] + assert make_settings().all_cors_origins == [] + + +def test_invalid_cors_origin_is_rejected(monkeypatch): + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + with pytest.raises(ValidationError): + Settings(_env_file=None) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl index bcd7ad21..c8d4e269 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl @@ -1,8 +1,19 @@ """ Tests for MCP (Model Context Protocol) functionality. """ +import json +import uuid + +import anyio from fastapi.testclient import TestClient +from src.core.config import settings +from src.main import app + +MCP_PATH = settings.MCP_MOUNT_PATH +MCP_MESSAGES_PATH = f"{MCP_PATH}/messages/" +UNKNOWN_SESSION = "?session_id=" + uuid.uuid4().hex + def test_mcp_hello_endpoint(client: TestClient): """Test MCP hello world endpoint.""" @@ -28,32 +39,145 @@ def test_mcp_status_endpoint(client: TestClient): assert "mcp_description" in data -# def test_mcp_endpoint_exists(client: TestClient): -# """Test that MCP endpoint is available.""" -# response = client.get("/mcp") -# # MCP endpoint should be available (mounted by fastapi-mcp) -# # The exact response depends on fastapi-mcp implementation -# # This test verifies the endpoint exists and doesn't return 404 -# assert response.status_code != 404 +def _bearer(token: str) -> dict[str, str]: + return {"Authorization": f"Bearer {token}"} + + +async def _open_sse_stream_async(headers: dict[str, str]) -> tuple[int, str]: + """Drive the real ASGI app until the first SSE event arrives, then disconnect. + + TestClient cannot stop an endless SSE response, so this talks ASGI directly: + it sends the GET to the MCP mount path, waits for the first body chunk and + then cancels the request. + """ + scope = { + "type": "http", + "asgi": {"version": "3.0"}, + "http_version": "1.1", + "method": "GET", + "scheme": "http", + "path": MCP_PATH, + "raw_path": MCP_PATH.encode(), + "root_path": "", + "query_string": b"", + "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()] + + [(b"host", b"testserver")], + "client": ("testclient", 50000), + "server": ("testserver", 80), + } + status_code = 0 + body = b"" + first_chunk = anyio.Event() + request_sent = False + + async def receive() -> dict: + nonlocal request_sent + if not request_sent: + request_sent = True + return {"type": "http.request", "body": b"", "more_body": False} + await first_chunk.wait() + return {"type": "http.disconnect"} + + async def send(message: dict) -> None: + nonlocal status_code, body + if message["type"] == "http.response.start": + status_code = message["status"] + elif message["type"] == "http.response.body": + body += message.get("body", b"") + if body.strip() or not message.get("more_body", False): + first_chunk.set() + + with anyio.fail_after(10): + async with anyio.create_task_group() as tg: + tg.start_soon(app, scope, receive, send) + await first_chunk.wait() + tg.cancel_scope.cancel() + return status_code, body.decode() + + +def _open_sse_stream(client: TestClient, headers: dict[str, str]) -> tuple[int, str]: + """Open the MCP SSE connection and return (status, first chunk of body).""" + return anyio.run(_open_sse_stream_async, headers) + + +# --- MCP_API_KEY mode -------------------------------------------------------- + +def test_mcp_api_key_missing_is_rejected(client: TestClient, mcp_api_key: str): + """The MCP connection endpoint rejects requests without a key.""" + status_code, body = _open_sse_stream(client, {}) + assert status_code == 401 + assert "event: endpoint" not in body -def test_mcp_with_auth_token(client: TestClient): - """Test MCP access with authentication token.""" - # First, get an auth token + +def test_mcp_api_key_wrong_is_rejected(client: TestClient, mcp_api_key: str): + """The MCP connection endpoint rejects a wrong key.""" + status_code, body = _open_sse_stream(client, _bearer("wrong-key")) + assert status_code == 401 + assert json.loads(body)["detail"] == "Invalid MCP API key" + + +def test_mcp_api_key_rejects_jwt(client: TestClient, mcp_api_key: str, auth_token): + """Once MCP_API_KEY is set, a JWT no longer opens the MCP endpoint.""" + status_code, _ = _open_sse_stream(client, _bearer(auth_token)) + assert status_code == 401 + + +def test_mcp_api_key_correct_is_accepted(client: TestClient, mcp_api_key: str): + """The correct key opens the SSE stream, which announces the messages URL.""" + status_code, first_chunk = _open_sse_stream(client, _bearer(mcp_api_key)) + assert status_code == 200 + assert "event: endpoint" in first_chunk + assert MCP_MESSAGES_PATH in first_chunk + + +def test_mcp_messages_endpoint_requires_api_key(client: TestClient, mcp_api_key: str): + """The POST messages endpoint is guarded by the same dependency.""" + url = MCP_MESSAGES_PATH + UNKNOWN_SESSION + assert client.post(url, json={}).status_code == 401 + assert client.post(url, json={}, headers=_bearer("wrong-key")).status_code == 401 + # With the right key the request reaches the transport, which then + # complains about the unknown session instead of the credentials. + response = client.post(url, json={}, headers=_bearer(mcp_api_key)) + assert response.status_code == 404 + + +# --- default mode (no MCP_API_KEY): JWT required ---------------------------- + + +def test_mcp_without_api_key_requires_credentials(client: TestClient, no_mcp_api_key): + """With no MCP_API_KEY the MCP endpoint is still protected, not open.""" + status_code, body = _open_sse_stream(client, {}) + assert status_code == 401 + assert json.loads(body)["detail"] == "MCP authentication required" + + +def test_mcp_without_api_key_rejects_invalid_jwt(client: TestClient, no_mcp_api_key): + status_code, _ = _open_sse_stream(client, _bearer("not-a-jwt")) + assert status_code == 401 + + +def test_mcp_without_api_key_accepts_jwt( + client: TestClient, no_mcp_api_key, auth_token +): + status_code, first_chunk = _open_sse_stream(client, _bearer(auth_token)) + assert status_code == 200 + assert "event: endpoint" in first_chunk + + +def test_mcp_with_demo_user_login(client: TestClient, no_mcp_api_key, demo_users): + """A token from the demo login opens the MCP endpoint.""" login_data = {"username": "user1", "password": "password123"} login_response = client.post("/api/v1/auth/login", json=login_data) + assert login_response.status_code == 200 + token = login_response.json()["access_token"] - if login_response.status_code == 200: - token = login_response.json()["access_token"] - headers = {"Authorization": f"Bearer {token}"} - - # Test MCP hello endpoint with token - response = client.get("/mcp-routes/hello", headers=headers) - assert response.status_code == 200 + status_code, _ = _open_sse_stream(client, _bearer(token)) + assert status_code == 200 - # Test MCP status endpoint with token - response = client.get("/mcp-routes/status", headers=headers) - assert response.status_code == 200 + # Plain MCP helper routes stay public + assert client.get("/mcp-routes/hello", headers=_bearer(token)).status_code == 200 + assert client.get("/mcp-routes/status", headers=_bearer(token)).status_code == 200 def test_root_endpoint_shows_mcp_info(client: TestClient): diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitignore-tpl index ef6364a9..5656953a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitignore-tpl @@ -28,3 +28,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl index 6039faad..fb55f5d2 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl @@ -40,6 +40,6 @@ tenacity==9.1.4 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.gitignore-tpl index ef6364a9..5656953a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.gitignore-tpl @@ -28,3 +28,9 @@ archive.zip # macOS .DS_Store + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl index 14643b91..e2fd4ce4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl @@ -22,6 +22,6 @@ starlette==1.6.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 -uvloop==0.22.1 +uvloop==0.22.1; sys_platform != "win32" watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/conftest.py-tpl index 8eee6f0d..6bcd0752 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/conftest.py-tpl @@ -5,6 +5,7 @@ from collections.abc import Generator import pytest from fastapi.testclient import TestClient + from src.main import app diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env.example-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env.example-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.gitattributes-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.gitattributes-tpl new file mode 100644 index 00000000..4ec864ab --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.gitattributes-tpl @@ -0,0 +1,27 @@ +# Line-ending policy for this project. +# +# Git for Windows (and GUI clients such as GitKraken or Sourcetree) default to +# core.autocrlf=true, which checks text files out with CRLF. Files that run +# inside a Linux container or under a POSIX shell break with CRLF +# (e.g. `env: 'bash\r': No such file or directory`), so they are pinned to LF. +# Everything else keeps the platform's native line endings. +* text=auto + +# Shell scripts +*.sh text eol=lf +*.bash text eol=lf + +# Container and build files +Dockerfile* text eol=lf +*.dockerfile text eol=lf +.dockerignore text eol=lf +docker-compose*.yml text eol=lf +docker-compose*.yaml text eol=lf +compose*.yml text eol=lf +compose*.yaml text eol=lf +Makefile text eol=lf + +# Environment files read by docker compose `env_file` and shell `source` +.env text eol=lf +.env.* text eol=lf +*.env text eol=lf diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.gitignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.gitignore-tpl index e667af7b..b43c5742 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.gitignore-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.gitignore-tpl @@ -33,3 +33,9 @@ archive.zip # SQLite databases *.db *.db-journal + +# Local environment files hold real secrets (fastkit generates .env with a +# unique SECRET_KEY). Never commit them; .env.example is the shareable copy. +.env +.env.* +!.env.example diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl index eb144c9a..b4867707 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl @@ -43,7 +43,8 @@ want a Docker Compose PostgreSQL stack with synchronous SQLModel, use ├── requirements.txt ├── alembic.ini ├── Dockerfile -├── .env +├── .env # local settings, git-ignored (generated) +├── .env.example # shareable example, committed ├── .gitignore ├── scripts/ │ ├── format.sh @@ -97,6 +98,10 @@ $ bash scripts/run-server.sh $ uvicorn src.app.main:app --reload ``` +> **Windows:** activate the virtualenv with `.venv\Scripts\activate` instead of +> `source .venv/bin/activate`. `fastkit runserver` starts the dev server on every +> OS, while the `scripts/*.sh` helpers need Git Bash or WSL. + API docs are then served at: - Swagger UI: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl index 07e7a969..bccb3764 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl @@ -4,7 +4,7 @@ import secrets from typing import Annotated, Any, List, Literal, Union -from pydantic import AnyUrl, BeforeValidator, computed_field +from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict @@ -16,6 +16,18 @@ def _parse_cors(v: Any) -> Union[List[str], str]: raise ValueError(v) +#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` +#: files. They are public, so a production deployment must never sign +#: anything with one of them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + } +) + + class Settings(BaseSettings): """Centralized configuration for the application. @@ -32,6 +44,9 @@ class Settings(BaseSettings): PROJECT_NAME: str = "" ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # Not read by the shipped code; reserved for signing features you add. + # fastkit writes a unique value to .env, and production refuses the + # public example values (see the validator below). SECRET_KEY: str = secrets.token_urlsafe(32) API_V1_PREFIX: str = "/api/v1" @@ -58,5 +73,19 @@ class Settings(BaseSettings): def all_cors_origins(self) -> List[str]: return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + @model_validator(mode="after") + def _reject_example_secret_key_in_production(self) -> "Settings": + if ( + self.ENVIRONMENT == "production" + and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + ): + raise ValueError( + "SECRET_KEY is set to a public example value while " + "ENVIRONMENT=production. Generate a real key with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as the SECRET_KEY environment variable (or in .env)." + ) + return self + settings = Settings() # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_config.py-tpl new file mode 100644 index 00000000..fba88b03 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_config.py-tpl @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Settings validation: production refuses a public example SECRET_KEY. +# -------------------------------------------------------------------------- +import re +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings + +ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" + + +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_production_refuses_example_secret_key(example_key: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + + +@pytest.mark.parametrize("environment", ["development", "staging"]) +def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: + settings = Settings( + _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" + ) + + assert settings.SECRET_KEY == "changethis" + + +def test_production_accepts_a_real_secret_key() -> None: + settings = Settings( + _env_file=None, + ENVIRONMENT="production", + SECRET_KEY="a-real-unique-key-0123456789abcdef", + ) + + assert settings.ENVIRONMENT == "production" + + +def test_env_example_secret_key_is_a_known_example_value() -> None: + """Whatever .env.example ships must be one the production guard rejects.""" + if not ENV_EXAMPLE.is_file(): + pytest.skip(".env.example is not part of this checkout") + + match = re.search( + r"^SECRET_KEY=(.*)$", ENV_EXAMPLE.read_text(encoding="utf-8"), re.M + ) + + assert match is not None + assert match.group(1).strip() in KNOWN_EXAMPLE_SECRET_KEYS diff --git a/src/fastapi_fastkit/fragments/README.md b/src/fastapi_fastkit/fragments/README.md index 51d1f4b0..deced0ec 100644 --- a/src/fastapi_fastkit/fragments/README.md +++ b/src/fastapi_fastkit/fragments/README.md @@ -21,6 +21,7 @@ main/lifespan/*.j2 4-space-indented statements inside the lifespan handle main/setup/*.j2 top-level statements placed right after `app = FastAPI(...)` db/*.py.j2 database configuration modules (sqlalchemy, mongodb, redis) auth/*.py.j2 authentication modules (jwt, fastapi_users, oauth2, session) +auth/settings.j2 shared AuthSettings macro (SECRET_KEY + production guard) tasks/*.py.j2 background worker modules (celery, dramatiq) features/*.py.j2 routers main.py mounts (tasks, cache, websocket, pagination) logging/*.py.j2 structured logging + request-id middleware @@ -65,7 +66,11 @@ project it is being generated into, so a fragment never hard-codes `src`: `selectors.confirm_selections()`. 3. **Fragments.** Drop the pieces you need into `main/imports/`, `main/lifespan/` and/or `main/setup/`. Lifespan fragments are indented by - 4 spaces; the other two are not. Register them in + 4 spaces; the other two are not. Anything that adds middleware, routes or + instrumentation (`add_middleware`, `include_router`, `mount`, + `Instrumentator().instrument(app)`) belongs in `main/setup/`: Starlette + refuses new middleware once the app has started, which is when the + lifespan runs. Register them in `DynamicConfigGenerator._main_fragments()`, guarded by the relevant `self._choice(...)` lookup. 4. **Standalone modules.** Add `/.py.j2` and return it from diff --git a/src/fastapi_fastkit/fragments/auth/jwt.py.j2 b/src/fastapi_fastkit/fragments/auth/jwt.py.j2 index a7c5385f..4db5170a 100644 --- a/src/fastapi_fastkit/fragments/auth/jwt.py.j2 +++ b/src/fastapi_fastkit/fragments/auth/jwt.py.j2 @@ -1,22 +1,18 @@ {% include "header.j2" %} +{% from "auth/settings.j2" import auth_settings_class %} +import secrets from datetime import UTC, datetime, timedelta +from typing import Literal import jwt from pwdlib import PasswordHash +from pydantic import model_validator from pydantic_settings import BaseSettings, SettingsConfigDict - -class AuthSettings(BaseSettings): - """Authentication configuration settings.""" - - SECRET_KEY: str = "your-secret-key-here-change-in-production" +{% call auth_settings_class("JWT access tokens") %} ALGORITHM: str = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 - - model_config = SettingsConfigDict(env_file=".env", extra="ignore") - - -settings = AuthSettings() +{% endcall %} # Password hashing — argon2id, the recommended default for new applications. password_hash = PasswordHash.recommended() @@ -32,13 +28,13 @@ def get_password_hash(password: str) -> str: return password_hash.hash(password) -def create_access_token( - data: dict, expires_delta: timedelta | None = None -) -> str: +def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str: """Create JWT access token.""" to_encode = data.copy() expire = datetime.now(UTC) + ( - expires_delta or timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + expires_delta or timedelta(minutes=auth_settings.ACCESS_TOKEN_EXPIRE_MINUTES) ) to_encode.update({"exp": expire}) - return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) + return jwt.encode( + to_encode, auth_settings.SECRET_KEY, algorithm=auth_settings.ALGORITHM + ) diff --git a/src/fastapi_fastkit/fragments/auth/oauth2.py.j2 b/src/fastapi_fastkit/fragments/auth/oauth2.py.j2 index 9cb731df..bd658ca4 100644 --- a/src/fastapi_fastkit/fragments/auth/oauth2.py.j2 +++ b/src/fastapi_fastkit/fragments/auth/oauth2.py.j2 @@ -1,39 +1,49 @@ {% include "header.j2" %} +{% from "auth/settings.j2" import auth_settings_class %} """OAuth2 social login (Google / GitHub) built on Authlib. Wire it up by mounting :data:`router` and adding ``SessionMiddleware`` — both are done for you in the generated ``main.py``. -Set the following environment variables before using a provider: +Set the following variables (environment or ``.env``) before using a +provider: GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET - SESSION_SECRET_KEY + +The session cookie that carries the OAuth state is signed with ``SECRET_KEY``. """ -import os -from typing import Any +import secrets +from typing import Any, Literal from authlib.integrations.starlette_client import OAuth, OAuthError from fastapi import APIRouter, HTTPException, Request, status +from pydantic import model_validator +from pydantic_settings import BaseSettings, SettingsConfigDict from starlette.responses import RedirectResponse -SESSION_SECRET_KEY = os.getenv("SESSION_SECRET_KEY", "change-me-in-production") +{% call auth_settings_class("the session cookie that stores the OAuth state") %} + GOOGLE_CLIENT_ID: str = "" + GOOGLE_CLIENT_SECRET: str = "" + GITHUB_CLIENT_ID: str = "" + GITHUB_CLIENT_SECRET: str = "" +{% endcall %} oauth = OAuth() oauth.register( name="google", - client_id=os.getenv("GOOGLE_CLIENT_ID", ""), - client_secret=os.getenv("GOOGLE_CLIENT_SECRET", ""), + client_id=auth_settings.GOOGLE_CLIENT_ID, + client_secret=auth_settings.GOOGLE_CLIENT_SECRET, server_metadata_url="https://accounts.google.com/.well-known/openid-configuration", client_kwargs={"scope": "openid email profile"}, ) oauth.register( name="github", - client_id=os.getenv("GITHUB_CLIENT_ID", ""), - client_secret=os.getenv("GITHUB_CLIENT_SECRET", ""), + client_id=auth_settings.GITHUB_CLIENT_ID, + client_secret=auth_settings.GITHUB_CLIENT_SECRET, access_token_url="https://github.com/login/oauth/access_token", authorize_url="https://github.com/login/oauth/authorize", api_base_url="https://api.github.com/", diff --git a/src/fastapi_fastkit/fragments/auth/session.py.j2 b/src/fastapi_fastkit/fragments/auth/session.py.j2 index 2ab44153..4fba73cd 100644 --- a/src/fastapi_fastkit/fragments/auth/session.py.j2 +++ b/src/fastapi_fastkit/fragments/auth/session.py.j2 @@ -1,19 +1,23 @@ {% include "header.j2" %} +{% from "auth/settings.j2" import auth_settings_class %} """Cookie-session authentication. ``SessionMiddleware`` (Starlette + itsdangerous) signs the session cookie; the routes below show the minimal login / logout / whoami cycle. Replace -:func:`authenticate_user` with a real user-store lookup. +:func:`authenticate_user` with a real user-store lookup. The cookie is signed +with ``SECRET_KEY`` (see :class:`AuthSettings`). """ -import os import secrets +from typing import Literal from fastapi import APIRouter, HTTPException, Request, status -from pydantic import BaseModel +from pydantic import BaseModel, model_validator +from pydantic_settings import BaseSettings, SettingsConfigDict -SESSION_SECRET_KEY = os.getenv("SESSION_SECRET_KEY", "change-me-in-production") -SESSION_MAX_AGE = int(os.getenv("SESSION_MAX_AGE", "1209600")) # 14 days +{% call auth_settings_class("the session cookie") %} + SESSION_MAX_AGE: int = 1209600 # 14 days +{% endcall %} #: Demo credential store. Swap for your database before going to production. _DEMO_USERS: dict[str, str] = {"demo": "demo-password"} diff --git a/src/fastapi_fastkit/fragments/auth/settings.j2 b/src/fastapi_fastkit/fragments/auth/settings.j2 new file mode 100644 index 00000000..6f136ec8 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/settings.j2 @@ -0,0 +1,61 @@ +{# + Shared ``AuthSettings`` class for the auth modules that sign something + (JWT, session cookie, OAuth2 state cookie). The caller block adds the + module's own fields. The module must import ``secrets``, ``Literal``, + ``model_validator``, ``BaseSettings`` and ``SettingsConfigDict``. +#} +{% macro auth_settings_class(purpose) %} +#: SECRET_KEY values published in fastkit templates, fragments and docs. Anyone +#: can sign with them, so the app refuses to start with one of them (or without +#: an explicit SECRET_KEY) when ENVIRONMENT=production. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "change-me-in-production", + "your-secret-key-here", + "your-secret-key-here-change-in-production", + } +) + +_GENERATE_KEY_HINT = ( + "Generate one with `python -c " + '"import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + + +class AuthSettings(BaseSettings): + """Authentication settings, read from the environment or ``.env``.""" + + model_config = SettingsConfigDict( + env_file=".env", + env_ignore_empty=True, + extra="ignore", + ) + + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # Signs {{ purpose }}. fastkit writes a unique SECRET_KEY to .env; without + # one, a per-process random key is used (development only). + SECRET_KEY: str = secrets.token_urlsafe(32) +{{ caller() }} + @model_validator(mode="after") + def _reject_unsafe_secret_key_in_production(self) -> "AuthSettings": + if self.ENVIRONMENT != "production": + return self + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + "SECRET_KEY must be set explicitly when ENVIRONMENT=production. " + + _GENERATE_KEY_HINT + ) + if self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS: + raise ValueError( + "SECRET_KEY is set to a public example value, which must not be " + "used when ENVIRONMENT=production. " + _GENERATE_KEY_HINT + ) + return self + + +auth_settings = AuthSettings() +{% endmacro %} diff --git a/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 b/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 index fe833563..0ced7d7f 100644 --- a/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 +++ b/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 @@ -1,5 +1,6 @@ {% include "header.j2" %} """Task submission / status endpoints backed by Celery.""" + from typing import Any from celery.result import AsyncResult diff --git a/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 b/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 index 093b59c3..f0237d9a 100644 --- a/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 +++ b/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 @@ -1,5 +1,6 @@ {% include "header.j2" %} """Task submission / status endpoints backed by Dramatiq.""" + from typing import Any from dramatiq.results.errors import ResultMissing diff --git a/src/fastapi_fastkit/fragments/features/websocket.py.j2 b/src/fastapi_fastkit/fragments/features/websocket.py.j2 index 8cbf9e86..779add94 100644 --- a/src/fastapi_fastkit/fragments/features/websocket.py.j2 +++ b/src/fastapi_fastkit/fragments/features/websocket.py.j2 @@ -1,5 +1,6 @@ {% include "header.j2" %} """WebSocket endpoint with a broadcast-capable connection manager.""" + import logging from fastapi import APIRouter, WebSocket, WebSocketDisconnect diff --git a/src/fastapi_fastkit/fragments/main/imports/jwt.j2 b/src/fastapi_fastkit/fragments/main/imports/jwt.j2 index 6d8b2e26..c27a70ba 100644 --- a/src/fastapi_fastkit/fragments/main/imports/jwt.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/jwt.j2 @@ -1 +1,3 @@ from fastapi.security import HTTPBearer # noqa: F401 + +from {{ auth_module }} import auth_settings # noqa: F401 diff --git a/src/fastapi_fastkit/fragments/main/imports/loguru.j2 b/src/fastapi_fastkit/fragments/main/imports/loguru.j2 index fcc3e275..7e7dbf4a 100644 --- a/src/fastapi_fastkit/fragments/main/imports/loguru.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/loguru.j2 @@ -1 +1 @@ -from loguru import logger +from loguru import logger # noqa: F401 diff --git a/src/fastapi_fastkit/fragments/main/imports/oauth2.j2 b/src/fastapi_fastkit/fragments/main/imports/oauth2.j2 index 2309e58a..5e24871c 100644 --- a/src/fastapi_fastkit/fragments/main/imports/oauth2.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/oauth2.j2 @@ -1,4 +1,4 @@ from starlette.middleware.sessions import SessionMiddleware -from {{ auth_module }} import SESSION_SECRET_KEY +from {{ auth_module }} import auth_settings from {{ auth_module }} import router as auth_router diff --git a/src/fastapi_fastkit/fragments/main/imports/session_auth.j2 b/src/fastapi_fastkit/fragments/main/imports/session_auth.j2 index 3aed638b..5e24871c 100644 --- a/src/fastapi_fastkit/fragments/main/imports/session_auth.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/session_auth.j2 @@ -1,4 +1,4 @@ from starlette.middleware.sessions import SessionMiddleware -from {{ auth_module }} import SESSION_MAX_AGE, SESSION_SECRET_KEY +from {{ auth_module }} import auth_settings from {{ auth_module }} import router as auth_router diff --git a/src/fastapi_fastkit/fragments/main/lifespan/prometheus.j2 b/src/fastapi_fastkit/fragments/main/lifespan/prometheus.j2 deleted file mode 100644 index 32f4794a..00000000 --- a/src/fastapi_fastkit/fragments/main/lifespan/prometheus.j2 +++ /dev/null @@ -1,2 +0,0 @@ - # Initialize Prometheus metrics - Instrumentator().instrument(app).expose(app) diff --git a/src/fastapi_fastkit/fragments/main/setup/cors.j2 b/src/fastapi_fastkit/fragments/main/setup/cors.j2 index fe12a155..b92c80ce 100644 --- a/src/fastapi_fastkit/fragments/main/setup/cors.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/cors.j2 @@ -1,8 +1,16 @@ -# CORS middleware -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], # Configure appropriately - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) +# CORS: BACKEND_CORS_ORIGINS is a comma-separated list of browser origins, e.g. +# "http://localhost:3000,https://app.example.com". Unset means no cross-origin +# access. "*" allows any origin, but then never with credentials (cookies). +cors_origins = [ + origin.strip().rstrip("/") + for origin in os.getenv("BACKEND_CORS_ORIGINS", "").split(",") + if origin.strip() +] +if cors_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=cors_origins, + allow_credentials="*" not in cors_origins, + allow_methods=["*"], + allow_headers=["*"], + ) diff --git a/src/fastapi_fastkit/fragments/main/setup/oauth2.j2 b/src/fastapi_fastkit/fragments/main/setup/oauth2.j2 index df565ea6..d091d575 100644 --- a/src/fastapi_fastkit/fragments/main/setup/oauth2.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/oauth2.j2 @@ -1,3 +1,3 @@ # Authlib stores the OAuth state in the session cookie. -app.add_middleware(SessionMiddleware, secret_key=SESSION_SECRET_KEY) +app.add_middleware(SessionMiddleware, secret_key=auth_settings.SECRET_KEY) app.include_router(auth_router) diff --git a/src/fastapi_fastkit/fragments/main/setup/prometheus.j2 b/src/fastapi_fastkit/fragments/main/setup/prometheus.j2 new file mode 100644 index 00000000..3fb54c37 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/setup/prometheus.j2 @@ -0,0 +1,3 @@ +# Prometheus metrics on GET /metrics. Instrumented at import time: Starlette +# refuses to add middleware once the application has started. +Instrumentator().instrument(app).expose(app) diff --git a/src/fastapi_fastkit/fragments/main/setup/session_auth.j2 b/src/fastapi_fastkit/fragments/main/setup/session_auth.j2 index 72b9bd94..5e6e2583 100644 --- a/src/fastapi_fastkit/fragments/main/setup/session_auth.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/session_auth.j2 @@ -1,6 +1,6 @@ app.add_middleware( SessionMiddleware, - secret_key=SESSION_SECRET_KEY, - max_age=SESSION_MAX_AGE, + secret_key=auth_settings.SECRET_KEY, + max_age=auth_settings.SESSION_MAX_AGE, ) app.include_router(auth_router) diff --git a/src/fastapi_fastkit/fragments/test/factories.py.j2 b/src/fastapi_fastkit/fragments/test/factories.py.j2 index 585d9aef..e57ee2c7 100644 --- a/src/fastapi_fastkit/fragments/test/factories.py.j2 +++ b/src/fastapi_fastkit/fragments/test/factories.py.j2 @@ -24,9 +24,7 @@ class User: email: str full_name: str is_active: bool = True - created_at: datetime = field( - default_factory=lambda: datetime.now(tz=UTC) - ) + created_at: datetime = field(default_factory=lambda: datetime.now(tz=UTC)) @dataclass diff --git a/src/fastapi_fastkit/fragments/test/test_factories.py.j2 b/src/fastapi_fastkit/fragments/test/test_factories.py.j2 index f1f84faf..ab811b75 100644 --- a/src/fastapi_fastkit/fragments/test/test_factories.py.j2 +++ b/src/fastapi_fastkit/fragments/test/test_factories.py.j2 @@ -1,5 +1,6 @@ {% include "header.j2" %} """Sanity checks for the generated factories.""" + from tests.factories import ItemFactory, UserFactory, build_users diff --git a/src/fastapi_fastkit/fragments/tooling/black_toml.j2 b/src/fastapi_fastkit/fragments/tooling/black_toml.j2 new file mode 100644 index 00000000..2a20554d --- /dev/null +++ b/src/fastapi_fastkit/fragments/tooling/black_toml.j2 @@ -0,0 +1,4 @@ + +[tool.black] +line-length = 88 +target-version = ["py312"] diff --git a/src/fastapi_fastkit/fragments/tooling/pre_commit.j2 b/src/fastapi_fastkit/fragments/tooling/pre_commit.j2 index 8f7a4382..c4e8ba4b 100644 --- a/src/fastapi_fastkit/fragments/tooling/pre_commit.j2 +++ b/src/fastapi_fastkit/fragments/tooling/pre_commit.j2 @@ -1,10 +1,12 @@ # -------------------------------------------------------------------------- # pre-commit configuration # Generated by FastAPI-fastkit +# +# No interpreter is pinned: every hook runs in an isolated environment built +# with the Python pre-commit itself runs under, so it also works from Git GUI +# clients whose hook shell has no activated virtualenv or ``python3.X`` on +# PATH. Formatters read their target version from pyproject.toml. # -------------------------------------------------------------------------- -default_language_version: - python: python3.12 - repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 @@ -26,7 +28,6 @@ repos: rev: 25.1.0 hooks: - id: black - args: [--target-version, py312] - repo: https://github.com/PyCQA/isort rev: 6.0.0 diff --git a/src/fastapi_fastkit/fragments/tooling/ruff_toml.j2 b/src/fastapi_fastkit/fragments/tooling/ruff_toml.j2 index f4068c9a..c4a223ac 100644 --- a/src/fastapi_fastkit/fragments/tooling/ruff_toml.j2 +++ b/src/fastapi_fastkit/fragments/tooling/ruff_toml.j2 @@ -8,6 +8,31 @@ src = [{{ package_dir | tojson }}, "tests"] select = ["E", "F", "I", "B", "UP", "W"] ignore = ["E501"] +# FastAPI declares dependencies and parameters by calling Depends(), Query() +# and friends in argument defaults. Mark them immutable so flake8-bugbear's +# B008 keeps flagging real mutable defaults but not every endpoint signature. +[tool.ruff.lint.flake8-bugbear] +extend-immutable-calls = [ + "fastapi.Body", + "fastapi.Cookie", + "fastapi.Depends", + "fastapi.File", + "fastapi.Form", + "fastapi.Header", + "fastapi.Path", + "fastapi.Query", + "fastapi.Security", + "fastapi.params.Body", + "fastapi.params.Cookie", + "fastapi.params.Depends", + "fastapi.params.File", + "fastapi.params.Form", + "fastapi.params.Header", + "fastapi.params.Path", + "fastapi.params.Query", + "fastapi.params.Security", +] + [tool.ruff.lint.isort] known-first-party = [{{ pkg.split(".")[0] | tojson }}] diff --git a/src/fastapi_fastkit/utils/config_file.py b/src/fastapi_fastkit/utils/config_file.py index 76a82885..ce55749d 100644 --- a/src/fastapi_fastkit/utils/config_file.py +++ b/src/fastapi_fastkit/utils/config_file.py @@ -13,6 +13,7 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import codecs import importlib import json import os @@ -90,19 +91,67 @@ def load_project_config(path: str) -> Dict[str, Any]: return raw +#: Byte order marks of encodings that are not UTF-8. PowerShell 5's ``>`` +#: and ``Out-File`` write UTF-16 LE with a BOM by default, so a config file +#: produced on Windows is often in one of these. +_NON_UTF8_BOMS: Tuple[Tuple[bytes, str], ...] = ( + (codecs.BOM_UTF32_LE, "UTF-32"), + (codecs.BOM_UTF32_BE, "UTF-32"), + (codecs.BOM_UTF16_LE, "UTF-16"), + (codecs.BOM_UTF16_BE, "UTF-16"), +) + + +def _read_config_text(path: str, kind: str) -> str: + """ + Read a config file as UTF-8 text, tolerating a UTF-8 byte order mark. + + Windows editors (Notepad, PowerShell's ``Out-File -Encoding utf8``) often + prefix UTF-8 files with a BOM, which ``json`` and ``tomllib`` reject, so + the file is decoded with ``utf-8-sig``. UTF-16 / UTF-32 files get an + error that names the actual problem instead of a parser traceback. + + :param path: Path to the configuration file + :param kind: Format label used in error messages (``JSON``, ``TOML``...) + :return: Decoded file content without a BOM + :raises ConfigFileError: If the file cannot be read or is not UTF-8 + """ + try: + with open(path, "rb") as f: + data = f.read() + except OSError as e: + raise ConfigFileError(f"Could not parse {kind} config '{path}': {e}") + + for bom, encoding in _NON_UTF8_BOMS: + if data.startswith(bom): + raise ConfigFileError( + f"Could not parse {kind} config '{path}': the file is {encoding} " + "encoded, but config files must be UTF-8. Re-save it as UTF-8 " + "(in PowerShell: Get-Content | Set-Content -Encoding utf8 )." + ) + + try: + return data.decode("utf-8-sig") + except UnicodeDecodeError as e: + raise ConfigFileError( + f"Could not parse {kind} config '{path}': the file must be UTF-8 " + f"encoded ({e})." + ) + + def _load_json(path: str) -> Any: + text = _read_config_text(path, "JSON") try: - with open(path, "r", encoding="utf-8") as f: - return json.load(f) - except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e: + return json.loads(text) + except json.JSONDecodeError as e: raise ConfigFileError(f"Could not parse JSON config '{path}': {e}") def _load_toml(path: str) -> Any: + text = _read_config_text(path, "TOML") try: - with open(path, "rb") as f: - return tomllib.load(f) - except (OSError, tomllib.TOMLDecodeError) as e: + return tomllib.loads(text) + except tomllib.TOMLDecodeError as e: raise ConfigFileError(f"Could not parse TOML config '{path}': {e}") @@ -113,9 +162,9 @@ def _load_yaml(path: str) -> Any: "YAML config files need PyYAML, which is not installed. " "Install it (pip install pyyaml) or use a .json / .toml config file instead." ) + text = _read_config_text(path, "YAML") try: - with open(path, "r", encoding="utf-8") as f: - return yaml.safe_load(f) + return yaml.safe_load(text) except Exception as e: # PyYAML raises its own YAMLError hierarchy; catching broadly keeps # this import-optional module free of a yaml type import. @@ -210,7 +259,7 @@ def save_project_config(config: Dict[str, Any], path: str) -> None: try: parent = os.path.dirname(os.path.abspath(path)) os.makedirs(parent, exist_ok=True) - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(content) except OSError as e: raise ConfigFileError(f"Could not write config file '{path}': {e}") diff --git a/src/fastapi_fastkit/utils/main.py b/src/fastapi_fastkit/utils/main.py index 01c61eb9..e28e60eb 100644 --- a/src/fastapi_fastkit/utils/main.py +++ b/src/fastapi_fastkit/utils/main.py @@ -209,19 +209,15 @@ def create_info_table( :param console: Rich console instance :return: Configured Rich Table instance """ - # Calculate exact content lengths if data exists + # Size the field column to its longest entry. Field values are often + # identifiers the user types back (template names, package managers), so + # that column never wraps; on a narrow terminal the value column wraps. if data: max_field_length = max(len(str(key)) for key in data.keys()) - max_value_length = max(len(str(value)) for value in data.values()) - - # Set column widths to exactly match the longest content - # Add small padding to ensure content fits comfortably field_width = max_field_length + 2 - value_width = max_value_length + 2 else: - # Default widths for empty tables + # Default width for empty tables field_width = 15 - value_width = 30 # Create table that prioritizes full text display over terminal fitting table = Table( @@ -237,7 +233,7 @@ def create_info_table( table.add_column( "Field", style="cyan", - no_wrap=False, # Allow wrapping instead of truncating + no_wrap=True, # Keep identifiers on one line width=field_width, # Exact width for content min_width=field_width, # Minimum width to prevent shrinking max_width=None, # No maximum width limit @@ -246,9 +242,7 @@ def create_info_table( table.add_column( "Value", style="green", - no_wrap=False, # Allow wrapping instead of truncating - width=value_width, # Exact width for content - min_width=value_width, # Minimum width to prevent shrinking + no_wrap=False, # Wrap to the terminal instead of truncating max_width=None, # No maximum width limit overflow="fold", # Fold text instead of truncating ) diff --git a/src/fastapi_fastkit/utils/platform.py b/src/fastapi_fastkit/utils/platform.py new file mode 100644 index 00000000..d71dcd82 --- /dev/null +++ b/src/fastapi_fastkit/utils/platform.py @@ -0,0 +1,286 @@ +# -------------------------------------------------------------------------- +# Operating-system differences in one place. +# +# Virtual environment layouts (``bin/python`` vs ``Scripts\python.exe``), +# console encodings that cannot print emoji, read-only files that stop +# ``shutil.rmtree`` on Windows, ``.cmd`` shims that CreateProcess cannot +# find, and a ``sys.stdin`` that may be ``None`` used to be handled (or not) +# separately in every module that ran into them. Callers use these helpers +# instead, and tests patch :func:`is_windows` rather than ``os.name``. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import codecs +import os +import shutil +import stat +import sys +from typing import Any, Callable, List, Sequence, Union + +PathLike = Union[str, "os.PathLike[str]"] + +#: Extensions of Windows launchers that ``CreateProcess`` does not try on its +#: own when it is given a bare command name. +_WINDOWS_SHIM_EXTENSIONS = (".cmd", ".bat") + + +def is_windows() -> bool: + """Return True when running on Windows.""" + return os.name == "nt" + + +# ---------------------------------------------------------------- +# Virtual environments +# ---------------------------------------------------------------- + + +def venv_bin_dir(venv: PathLike) -> str: + """Directory holding a virtual environment's executables.""" + return os.path.join(os.fspath(venv), "Scripts" if is_windows() else "bin") + + +def venv_executable(venv: PathLike, name: str) -> str: + """ + Path to an executable inside a virtual environment. + + :param venv: Virtual environment directory + :param name: Executable name without extension (``pip``, ``uvicorn``) + :return: ``/bin/`` or ``\\Scripts\\.exe`` + """ + if is_windows() and not os.path.splitext(name)[1]: + name = f"{name}.exe" + return os.path.join(venv_bin_dir(venv), name) + + +def venv_python(venv: PathLike) -> str: + """Path to a virtual environment's Python interpreter.""" + return venv_executable(venv, "python") + + +# ---------------------------------------------------------------- +# Executables +# ---------------------------------------------------------------- + + +def resolve_executable(name: str) -> str: + """ + Return a form of ``name`` that ``subprocess`` can start on this OS. + + On Windows, tools installed as ``.cmd`` / ``.bat`` shims (npm-style + launchers, some pipx / scoop setups) are not found when only the bare + name is passed, so those are replaced with their full path. Everything + else, including every POSIX lookup and ordinary ``.exe`` files, is left + as the bare name so that ``PATH`` resolution and the command lines shown + to users stay unchanged. + + :param name: Command name such as ``uv`` or ``poetry`` + :return: The full path of a Windows shim, otherwise ``name`` itself + """ + if not is_windows() or os.path.dirname(name): + return name + found = shutil.which(name) + if found and os.path.splitext(found)[1].lower() in _WINDOWS_SHIM_EXTENSIONS: + return found + return name + + +def resolve_command(command: Sequence[str]) -> List[str]: + """Return ``command`` with its program name passed through + :func:`resolve_executable`.""" + resolved = list(command) + if resolved: + resolved[0] = resolve_executable(resolved[0]) + return resolved + + +# ---------------------------------------------------------------- +# Console streams +# ---------------------------------------------------------------- + + +def _is_utf8(encoding: Any) -> bool: + if not isinstance(encoding, str) or not encoding: + return False + try: + return codecs.lookup(encoding).name == "utf-8" + except LookupError: + return False + + +def configure_stdio() -> None: + """ + Keep console output from crashing on encodings that lack emoji. + + A Windows console code page (cp1252, cp949, ...) or a redirected stream + using one raises ``UnicodeEncodeError`` on the first emoji the CLI + prints. Such streams are switched to ``errors="replace"``, so the + character degrades to ``?`` instead. UTF-8 streams, and streams that + cannot be reconfigured (test runners, ``None`` under ``pythonw``), are + left alone. Safe to call more than once. + """ + for name in ("stdout", "stderr"): + stream = getattr(sys, name, None) + if stream is None or _is_utf8(getattr(stream, "encoding", None)): + continue + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is None: + continue + try: + reconfigure(errors="replace") + except (AttributeError, OSError, ValueError, TypeError): + continue + + +def _windows_console_attached(stream: Any) -> bool: + """ + Whether ``stream`` is a real Windows console. + + ``NUL`` reports ``isatty() == True`` on Windows, but it is a character + device, not a console, so ``GetConsoleMode`` fails on it. This is only + exercised on Windows; any failure to ask keeps the ``isatty()`` verdict. + """ + if sys.platform != "win32": + return True + try: + import ctypes + import msvcrt + + handle = msvcrt.get_osfhandle(stream.fileno()) + mode = ctypes.c_ulong() + return bool(ctypes.windll.kernel32.GetConsoleMode(handle, ctypes.byref(mode))) + except Exception: + return True + + +def stdin_is_interactive() -> bool: + """ + Whether a human can answer a prompt on stdin. + + False when ``sys.stdin`` is ``None`` (``pythonw``, some service + runners), closed, redirected from a file or pipe, or ``NUL`` on Windows. + """ + stream = sys.stdin + if stream is None: + return False + try: + if not stream.isatty(): + return False + except (AttributeError, OSError, ValueError): + return False + if is_windows(): + return _windows_console_attached(stream) + return True + + +# ---------------------------------------------------------------- +# Filesystem +# ---------------------------------------------------------------- + + +def _is_within(path: str, root: str) -> bool: + """Whether absolute ``path`` is ``root`` or lies below it.""" + try: + return os.path.commonpath([path, root]) == root + except ValueError: # different drives on Windows + return False + + +def _add_owner_permissions(path: str) -> None: + """Give the owner read, write and search permission on ``path``.""" + os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) | stat.S_IRWXU) + + +def _make_removable(path: str, root: str) -> None: + """Change the least that lets ``path`` be removed on a retry. + + Permissions are only ever changed inside ``root``, and never through an + entry that may be shared with a file outside it. + + * POSIX: unlinking or ``rmdir``-ing an entry needs write and search + permission on its parent directory; the entry's own mode is + irrelevant. Only the parent is touched, never the entry: a hard link + shares its inode (and so its mode) with a file outside the tree, and + chmod-ing it would widen that file's permissions. + * Windows: the parent's attributes do not matter; a file with the + read-only attribute (git's ``.git/objects``) cannot be deleted. Only + the write bit is added, and not on a hard-linked file, whose + attribute is shared with its other links. + """ + if is_windows(): + if os.path.islink(path) or not _is_within(os.path.abspath(path), root): + return + st = os.lstat(path) + if st.st_nlink > 1 and not stat.S_ISDIR(st.st_mode): + return + os.chmod(path, stat.S_IMODE(st.st_mode) | stat.S_IWRITE) + return + + parent = os.path.dirname(os.path.abspath(path)) + if _is_within(parent, root): + _add_owner_permissions(parent) + + +def _rmtree_onexc( + root: str, ignore_errors: bool +) -> Callable[[Any, str, BaseException], None]: + """Build the ``onexc`` handler used by :func:`rmtree_force`. + + Permissions are only ever changed inside ``root``, the tree being + removed: never on its parent directory or anything outside it. + """ + + def handler(func: Any, path: str, exc: BaseException) -> None: + if isinstance(exc, FileNotFoundError): + # Already gone (removed concurrently): nothing left to do. + return + # Only a failed removal is retried. ``rmtree`` also reports errors + # from ``lstat`` / ``open`` / ``scandir`` (and refuses a symlink + # root through ``os.path.islink``); calling those again would + # "succeed" without deleting anything and hide the error. + if isinstance(exc, PermissionError) and func in ( + os.unlink, + os.remove, + os.rmdir, + ): + try: + _make_removable(path, root) + func(path) + return + except OSError: + pass + if ignore_errors: + return + raise exc + + return handler + + +def rmtree_force(path: PathLike, ignore_errors: bool = False) -> None: + """ + ``shutil.rmtree`` that also removes read-only files. + + Git marks the files under ``.git/objects`` read-only, and on Windows + plain ``rmtree`` fails on them with ``PermissionError``. The handler makes + the entry removable (see :func:`_make_removable`) and retries once. + + :param path: Directory to remove + :param ignore_errors: Swallow failures (missing path, entries that stay + undeletable) like ``shutil.rmtree(ignore_errors=True)`` + """ + # ``onexc`` replaced ``onerror`` in Python 3.12, the oldest supported + # version (``requires-python = ">=3.12"``). + root = os.path.abspath(os.fspath(path)) + shutil.rmtree(path, onexc=_rmtree_onexc(root, ignore_errors)) + + +__all__ = [ + "configure_stdio", + "is_windows", + "resolve_command", + "resolve_executable", + "rmtree_force", + "stdin_is_interactive", + "venv_bin_dir", + "venv_executable", + "venv_python", +] diff --git a/src/fastapi_fastkit/utils/textio.py b/src/fastapi_fastkit/utils/textio.py new file mode 100644 index 00000000..2f14d1d9 --- /dev/null +++ b/src/fastapi_fastkit/utils/textio.py @@ -0,0 +1,81 @@ +# -------------------------------------------------------------------------- +# Text file I/O with explicit encodings and line endings. +# +# Python's text mode defaults to the locale encoding (cp1252, cp949, ...) and +# translates "\n" to os.linesep on write. On Windows both defaults corrupt +# generated projects: non-ASCII content fails to round-trip and shell +# scripts, Dockerfiles and pyproject.toml come out as CRLF. Every write of +# generated content goes through ``write_generated_text`` (UTF-8, LF), and +# every in-place rewrite of an existing file through the +# ``*_preserving_newlines`` pair, which keeps the file's own line endings. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +from typing import Tuple, Union + +PathLike = Union[str, "os.PathLike[str]"] + +#: Line-ending mode returned for a file whose every newline is ``\r\n``. +CRLF = "\r\n" + +#: Line-ending mode meaning "write the text exactly as given". +UNTRANSLATED = "" + + +def write_generated_text(path: PathLike, content: str) -> None: + """ + Write content fastkit generated as UTF-8 with LF line endings on every OS. + + :param path: Destination file + :param content: Text using ``\\n`` line endings + """ + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(content) + + +def read_text_preserving_newlines(path: PathLike) -> Tuple[str, str]: + """ + Read a UTF-8 file for an in-place rewrite without losing its line endings. + + A file whose every newline is ``\\r\\n`` is returned with ``\\n`` line + endings, so callers' line-oriented logic (regexes with ``$``, ``"\\n"`` + joins) works unchanged, together with the mode that restores ``\\r\\n`` + on write. Any other file (LF only, or mixed) is returned untranslated. + + :param path: File to read + :return: ``(text, newline)``; pass ``newline`` to + :func:`write_text_preserving_newlines` + :raises OSError: If the file cannot be read + :raises UnicodeDecodeError: If the file is not valid UTF-8 + """ + with open(path, "r", encoding="utf-8", newline="") as f: + raw = f.read() + + crlf_count = raw.count(CRLF) + if crlf_count and crlf_count == raw.count("\n"): + return raw.replace(CRLF, "\n"), CRLF + return raw, UNTRANSLATED + + +def write_text_preserving_newlines(path: PathLike, content: str, newline: str) -> None: + """ + Write back text obtained from :func:`read_text_preserving_newlines`. + + Unchanged regions of the file keep their original bytes. + + :param path: File to write + :param content: Text as returned by the read (possibly edited) + :param newline: The ``newline`` value the read returned + """ + with open(path, "w", encoding="utf-8", newline=newline) as f: + f.write(content) + + +__all__ = [ + "CRLF", + "UNTRANSLATED", + "read_text_preserving_newlines", + "write_generated_text", + "write_text_preserving_newlines", +] diff --git a/tests/test_backends/test_console_sizing.py b/tests/test_backends/test_console_sizing.py index d0763b9e..63bf11e3 100644 --- a/tests/test_backends/test_console_sizing.py +++ b/tests/test_backends/test_console_sizing.py @@ -4,6 +4,7 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import os +from io import StringIO from unittest.mock import MagicMock, patch import pytest @@ -82,8 +83,10 @@ def test_create_adaptive_console_normal(self) -> None: console = create_adaptive_console() assert isinstance(console, Console) - # Console should have adaptive sizing - assert console.width == 80 + # Console should have adaptive sizing. Rich keeps the last column + # free on a legacy Windows console (no VT support), so it reports + # one column less there. + assert console.width == 80 - console.legacy_windows # Rich Console may use different height handling assert console.height >= 25 or console.height == 30 @@ -116,9 +119,8 @@ def test_create_info_table_adaptive_sizing(self) -> None: assert ( table.columns[0].width is not None and table.columns[0].width >= 14 ) # Length of "Project Name" + 2 - assert ( - table.columns[1].width is not None and table.columns[1].width >= 27 - ) # Length of "A test project description" + 2 + # The value column sizes itself to the content / terminal. + assert table.columns[1].width is None def test_create_info_table_long_content(self) -> None: """Test table creation with long content that needs scaling.""" @@ -138,14 +140,32 @@ def test_create_info_table_long_content(self) -> None: table.columns[0].width is not None and table.columns[0].width >= len("Very Long Project Name Field") + 2 ) - assert ( - table.columns[1].width is not None - and table.columns[1].width - >= len( - "This is a very long project description that might exceed normal terminal width" - ) - + 2 - ) + assert table.columns[0].no_wrap is True + assert table.columns[1].no_wrap is False + + @pytest.mark.parametrize("width", [80, 79, 60]) + def test_info_table_keeps_field_values_on_one_line(self, width: int) -> None: + """Field values (e.g. template ids) never wrap; long values wrap instead.""" + # given: the template list that wrapped ids on an 80/79-column console + data = { + "fastapi-custom-response": "Async Item Management API with Custom Response System", + "fastapi-domain-starter": "FastAPI Domain Starter", + "fastapi-psql-orm": "Dockerized FastAPI Item Management API with PostgreSQL", + } + console = Console(file=StringIO(), width=width, no_color=True) + + # when + console.print(create_info_table("Available Templates", data)) + output = console.file.getvalue() # type: ignore[attr-defined] + + # then: every line fits and every id is intact on a single line + lines = output.splitlines() + assert all(len(line) <= width for line in lines) + for key in data: + assert any(key in line for line in lines), f"{key!r} was wrapped" + words = " ".join(output.replace("\u2502", " ").split()) + for value in data.values(): + assert value in words @patch("fastapi_fastkit.utils.main.console") def test_print_functions_use_adaptive_sizing(self, mock_console: MagicMock) -> None: @@ -180,7 +200,7 @@ def test_empty_data_table_creation(self) -> None: # Should create table with default column setup assert len(table.columns) == 2 assert table.columns[0].width == 15 # Default field width - assert table.columns[1].width == 30 # Default value width + assert table.columns[1].width is None # Sized by Rich def test_console_sizing_edge_cases(self) -> None: """Test edge cases in console sizing.""" diff --git a/tests/test_backends/test_generated_runtime_safety.py b/tests/test_backends/test_generated_runtime_safety.py new file mode 100644 index 00000000..1f507215 --- /dev/null +++ b/tests/test_backends/test_generated_runtime_safety.py @@ -0,0 +1,547 @@ +# -------------------------------------------------------------------------- +# Runtime-safety contracts of the generated application code. +# +# - Nothing that changes the app's middleware stack or routes runs inside the +# lifespan handler (Starlette refuses middleware once the app has started, +# which made every Prometheus project crash at startup). +# - The CORS setup takes its origins from BACKEND_CORS_ORIGINS only and never +# combines a wildcard origin with credentials. +# - Auth modules carry no usable public default secret and refuse the known +# example values in production; the local .env gets a unique SECRET_KEY. +# +# The repository's virtualenv does not have the generated projects' +# dependencies, so these checks work on the rendered source (AST) and on +# the CORS snippet executed against stubs. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import itertools +import re +from pathlib import Path +from typing import Any, Dict, List, Optional + +import pytest + +import fastapi_fastkit +from fastapi_fastkit.backend.project_builder.config_generator import ( + DynamicConfigGenerator, + get_environment, +) +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.core.settings import FastkitConfig + +#: Calls that add middleware, routes or instrumentation to the app. +APP_MUTATING_CALLS = frozenset( + { + "add_middleware", + "include_router", + "mount", + "instrument", + "instrument_app", + "expose", + } +) + +#: Every public example secret that fragments, templates or docs have shipped. +KNOWN_EXAMPLE_SECRETS = frozenset( + { + "changethis", + "change-me-in-production", + "your-secret-key-here", + "your-secret-key-here-change-in-production", + } +) + +#: Auth choices whose module signs tokens or cookies. +SIGNING_AUTHS = ["JWT", "OAuth2", "Session-based"] + +PRESETS = ["minimal", "single-module", "classic-layered", "domain-starter"] + + +# -------------------------------------------------------------------------- +# Helpers +# -------------------------------------------------------------------------- + + +def _lifespan_functions(tree: ast.Module) -> List[ast.AST]: + """Functions used as a lifespan: passed as ``lifespan=`` or named so.""" + passed = { + keyword.value.id + for node in ast.walk(tree) + if isinstance(node, ast.Call) + for keyword in node.keywords + if keyword.arg == "lifespan" and isinstance(keyword.value, ast.Name) + } + return [ + node + for node in ast.walk(tree) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and (node.name in passed or node.name == "lifespan") + ] + + +def app_calls_inside_lifespan(source: str) -> List[str]: + """Names of app-mutating calls nested anywhere in a lifespan function.""" + found: List[str] = [] + for function in _lifespan_functions(ast.parse(source)): + for node in ast.walk(function): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in APP_MUTATING_CALLS + ): + found.append(node.func.attr) + return found + + +def _config(**overrides: Any) -> Dict[str, Any]: + config: Dict[str, Any] = { + "project_name": "SafetyProject", + "description": "runtime safety", + "database": {"type": "None"}, + "authentication": "None", + "monitoring": "None", + "utilities": [], + } + config.update(overrides) + return config + + +def _template_main(preset: str) -> str: + """The template-shipped ``main.py`` a preserve-main preset keeps.""" + profile = PresetLayoutStrategist(preset).profile + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) / profile.base_template + return (root / f"{profile.main_py_relpath}-tpl").read_text(encoding="utf-8") + + +def _generated_main(preset: str, config: Dict[str, Any], tmp: Path) -> str: + """The ``main.py`` a project of ``preset`` ends up with for ``config``.""" + strategist = PresetLayoutStrategist(preset) + profile = strategist.profile + if profile.regenerate_main: + return DynamicConfigGenerator( + config, str(tmp), main_py_relpath=profile.main_py_relpath + ).generate_main_py() + + main_path = tmp / profile.main_py_relpath + main_path.parent.mkdir(parents=True, exist_ok=True) + main_path.write_text(_template_main(preset), encoding="utf-8") + strategist.wire_generated_routers(str(tmp), config) + return main_path.read_text(encoding="utf-8") + + +def _render_cors_fragment() -> str: + return get_environment().get_template("main/setup/cors.j2").render() + + +class _RecordingApp: + """Stand-in for ``FastAPI`` that records ``add_middleware`` calls.""" + + def __init__(self) -> None: + self.middleware: List[Dict[str, Any]] = [] + + def add_middleware(self, cls: Any, **options: Any) -> None: + self.middleware.append({"cls": cls, **options}) + + +def _run_cors_setup( + monkeypatch: pytest.MonkeyPatch, origins: Optional[str] +) -> _RecordingApp: + """Execute the rendered CORS setup with a stub app and ``origins`` env.""" + if origins is None: + monkeypatch.delenv("BACKEND_CORS_ORIGINS", raising=False) + else: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", origins) + app = _RecordingApp() + namespace = { + "os": __import__("os"), + "app": app, + "CORSMiddleware": "CORSMiddleware", + } + exec(compile(_render_cors_fragment(), "cors.j2", "exec"), namespace) + return app + + +def _secret_key(content: str) -> str: + match = re.search(r"^SECRET_KEY=(.*)$", content, re.M) + assert match, content + return match.group(1) + + +# -------------------------------------------------------------------------- +# F1: nothing mutates the app inside the lifespan +# -------------------------------------------------------------------------- + + +class TestNoAppMutationInLifespan: + def test_detector_flags_middleware_added_in_lifespan(self) -> None: + """Positive control: the pre-1.5.2 Prometheus fragment is caught.""" + source = ( + "from contextlib import asynccontextmanager\n" + "@asynccontextmanager\n" + "async def lifespan(app):\n" + " Instrumentator().instrument(app).expose(app)\n" + " yield\n" + "app = FastAPI(lifespan=lifespan)\n" + ) + assert app_calls_inside_lifespan(source) == ["expose", "instrument"] + + @pytest.mark.parametrize("preset", PRESETS) + def test_every_feature_combination_keeps_the_lifespan_clean( + self, preset: str, tmp_path: Path + ) -> None: + combinations = itertools.product( + ["None", "PostgreSQL", "MongoDB"], + ["None", "JWT", "FastAPI-Users", "OAuth2", "Session-based"], + ["None", "Loguru", "Prometheus", "OpenTelemetry"], + ["None", "Redis"], + ["None", "Celery"], + ["None", "structured"], + [[], ["CORS", "Rate-Limiting", "WebSocket", "Pagination"]], + ) + for index, (db, auth, monitoring, caching, tasks, logging, utils) in enumerate( + combinations + ): + config = _config( + database={"type": db}, + authentication=auth, + monitoring=monitoring, + caching=caching, + async_tasks=tasks, + logging=logging, + utilities=utils, + ) + workdir = tmp_path / str(index) + workdir.mkdir() + + source = _generated_main(preset, config, workdir) + + label = f"{preset}/{db}/{auth}/{monitoring}/{caching}/{tasks}/{logging}" + assert app_calls_inside_lifespan(source) == [], label + + def test_prometheus_is_instrumented_at_module_level(self) -> None: + source = DynamicConfigGenerator( + _config(monitoring="Prometheus"), "/tmp/test" + ).generate_main_py() + + tree = ast.parse(source) + module_level = [ + ast.unparse(node) for node in tree.body if isinstance(node, ast.Expr) + ] + assert "Instrumentator().instrument(app).expose(app)" in module_level + assert app_calls_inside_lifespan(source) == [] + # After the app exists, so the statement has something to instrument. + assert source.index("app = FastAPI(") < source.index("Instrumentator()") + + @pytest.mark.parametrize("preset", ["classic-layered", "domain-starter"]) + def test_preserved_main_explains_how_to_wire_prometheus(self, preset: str) -> None: + warnings = PresetLayoutStrategist(preset).compatibility_warnings( + {"monitoring": "Prometheus"} + ) + + hint = next(line for line in warnings if line.startswith("Prometheus:")) + assert "Instrumentator().instrument(app).expose(app)" in hint + assert "app = FastAPI(...)" in hint + + +# -------------------------------------------------------------------------- +# F2: CORS origins come from configuration only +# -------------------------------------------------------------------------- + + +class TestCorsSetup: + def test_rendered_setup_has_no_wildcard_with_credentials(self) -> None: + source = DynamicConfigGenerator( + _config(utilities=["CORS"]), "/tmp/test" + ).generate_main_py() + tree = ast.parse(source) + + calls = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "add_middleware" + and ast.unparse(node.args[0]) == "CORSMiddleware" + ] + assert len(calls) == 1 + keywords = {kw.arg: kw.value for kw in calls[0].keywords} + assert ast.unparse(keywords["allow_origins"]) == "cors_origins" + assert not ( + isinstance(keywords["allow_credentials"], ast.Constant) + and keywords["allow_credentials"].value is True + ) + assert '["*"], # Configure' not in source + assert "BACKEND_CORS_ORIGINS" in source + + def test_middleware_is_added_only_when_origins_are_configured(self) -> None: + source = DynamicConfigGenerator( + _config(utilities=["CORS"]), "/tmp/test" + ).generate_main_py() + tree = ast.parse(source) + + guarded = [ + node + for node in tree.body + if isinstance(node, ast.If) and ast.unparse(node.test) == "cors_origins" + ] + assert len(guarded) == 1 + assert "add_middleware" in ast.unparse(guarded[0]) + module_calls = [ + ast.unparse(node) for node in tree.body if isinstance(node, ast.Expr) + ] + assert not any("CORSMiddleware" in call for call in module_calls) + + @pytest.mark.parametrize("origins", [None, "", " , ,"]) + def test_unset_or_empty_origins_add_no_middleware( + self, monkeypatch: pytest.MonkeyPatch, origins: Optional[str] + ) -> None: + app = _run_cors_setup(monkeypatch, origins) + + assert app.middleware == [] + + def test_listed_origins_are_stripped_and_allow_credentials( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + app = _run_cors_setup( + monkeypatch, " http://localhost:3000 , ,https://app.example.com/ " + ) + + (middleware,) = app.middleware + assert middleware["allow_origins"] == [ + "http://localhost:3000", + "https://app.example.com", + ] + assert middleware["allow_credentials"] is True + + @pytest.mark.parametrize("origins", ["*", "http://localhost:3000,*"]) + def test_wildcard_origin_never_allows_credentials( + self, monkeypatch: pytest.MonkeyPatch, origins: str + ) -> None: + app = _run_cors_setup(monkeypatch, origins) + + (middleware,) = app.middleware + assert "*" in middleware["allow_origins"] + assert middleware["allow_credentials"] is False + + def test_env_example_documents_the_variable_commented_out( + self, tmp_path: Path + ) -> None: + (tmp_path / ".env.example").write_text( + "SECRET_KEY=changethis\n", encoding="utf-8" + ) + + DynamicConfigGenerator( + _config(utilities=["CORS"]), str(tmp_path) + ).generate_all_files() + + example = (tmp_path / ".env.example").read_text(encoding="utf-8") + assert "# BACKEND_CORS_ORIGINS=http://localhost:3000" in example + assert not re.search(r"^BACKEND_CORS_ORIGINS=", example, re.M) + + def test_preserved_main_gets_no_cors_entry(self, tmp_path: Path) -> None: + """Template entrypoints configure CORS through their own settings.""" + generator = DynamicConfigGenerator(_config(utilities=["CORS"]), str(tmp_path)) + + assert generator.env_example_blocks(include_main=False) == [] + assert ".env.example" not in generator.planned_files(include_main=False) + + +# -------------------------------------------------------------------------- +# F6: no public default secret in the auth modules +# -------------------------------------------------------------------------- + + +def _auth_module(auth: str) -> str: + content = DynamicConfigGenerator( + _config(authentication=auth), "/tmp/test" + ).generate_auth_config() + assert content is not None + return content + + +def _example_set_node(tree: ast.Module) -> ast.AST: + for node in tree.body: + if isinstance(node, ast.Assign) and any( + isinstance(target, ast.Name) and target.id == "KNOWN_EXAMPLE_SECRET_KEYS" + for target in node.targets + ): + return node + raise AssertionError("KNOWN_EXAMPLE_SECRET_KEYS is not defined") + + +class TestAuthModuleSecrets: + @pytest.mark.parametrize("auth", SIGNING_AUTHS) + def test_example_secrets_appear_only_in_the_refusal_list(self, auth: str) -> None: + tree = ast.parse(_auth_module(auth)) + allowed = {id(node) for node in ast.walk(_example_set_node(tree))} + + leaked = [ + node.value + for node in ast.walk(tree) + if isinstance(node, ast.Constant) + and node.value in KNOWN_EXAMPLE_SECRETS + and id(node) not in allowed + ] + assert leaked == [] + + @pytest.mark.parametrize("auth", SIGNING_AUTHS) + def test_refusal_list_covers_every_published_example(self, auth: str) -> None: + tree = ast.parse(_auth_module(auth)) + listed = { + node.value + for node in ast.walk(_example_set_node(tree)) + if isinstance(node, ast.Constant) + } + assert KNOWN_EXAMPLE_SECRETS <= listed + + @pytest.mark.parametrize("auth", SIGNING_AUTHS) + def test_secret_key_has_no_literal_default(self, auth: str) -> None: + tree = ast.parse(_auth_module(auth)) + + (field,) = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.AnnAssign) + and isinstance(node.target, ast.Name) + and node.target.id == "SECRET_KEY" + ] + assert field.value is not None + assert ast.unparse(field.value) == "secrets.token_urlsafe(32)" + + @pytest.mark.parametrize("auth", SIGNING_AUTHS) + def test_production_guard_is_present(self, auth: str) -> None: + source = _auth_module(auth) + + assert '@model_validator(mode="after")' in source + assert 'self.ENVIRONMENT != "production"' in source + assert '"SECRET_KEY" not in self.model_fields_set' in source + assert "in KNOWN_EXAMPLE_SECRET_KEYS" in source + assert 'env_file=".env"' in source + + @pytest.mark.parametrize("auth", ["OAuth2", "Session-based"]) + def test_session_middleware_signs_with_secret_key(self, auth: str) -> None: + main_py = DynamicConfigGenerator( + _config(authentication=auth), "/tmp/test" + ).generate_main_py() + + assert "secret_key=auth_settings.SECRET_KEY" in main_py + assert "SESSION_SECRET_KEY" not in main_py + assert "SESSION_SECRET_KEY" not in _auth_module(auth) + + def test_jwt_settings_are_validated_at_startup(self) -> None: + """main.py imports the JWT settings, so the guard runs on startup.""" + main_py = DynamicConfigGenerator( + _config(authentication="JWT"), "/tmp/test" + ).generate_main_py() + + assert "from src.config.auth import auth_settings # noqa: F401" in main_py + + def test_no_fragment_ships_a_known_example_secret_as_a_value(self) -> None: + """Across every fragment, example secrets only sit in the refusal list.""" + fragments = Path(fastapi_fastkit.__file__).parent / "fragments" + offenders = [] + for path in fragments.rglob("*.j2"): + if path.name == "settings.j2" and path.parent.name == "auth": + continue # defines KNOWN_EXAMPLE_SECRET_KEYS + text = path.read_text(encoding="utf-8") + for secret in KNOWN_EXAMPLE_SECRETS - {"changethis"}: + if secret in text: + offenders.append(f"{path.name}: {secret}") + assert offenders == [] + + +# -------------------------------------------------------------------------- +# .env generation for the auth selections +# -------------------------------------------------------------------------- + + +def _scaffold(tmp_path: Path, preset: str, config: Dict[str, Any], name: str) -> Path: + settings = FastkitConfig() + settings.USER_WORKSPACE = str(tmp_path) + options = ScaffoldOptions( + project_name=name, + author="bnbong", + author_email="bbbong9@gmail.com", + description="runtime safety", + package_manager="pip", + template=PresetLayoutStrategist(preset).base_template, + preset_id=preset, + config=config, + with_venv=False, + with_install=False, + ) + return Path(ProjectScaffolder(settings, options).run().project_dir) + + +class TestLocalEnvForAuth: + @pytest.mark.parametrize("preset", PRESETS) + @pytest.mark.parametrize("auth", SIGNING_AUTHS) + def test_env_gets_a_unique_value_for_every_secret( + self, tmp_path: Path, preset: str, auth: str + ) -> None: + config = {"authentication": auth, "utilities": ["CORS"]} + + first = _scaffold(tmp_path, preset, config, "first") + second = _scaffold(tmp_path, preset, config, "second") + + keys = [] + for project in (first, second): + example = (project / ".env.example").read_text(encoding="utf-8") + env = (project / ".env").read_text(encoding="utf-8") + # SECRET_KEY is the only secret the generated modules read. + assert _secret_key(example) == "changethis" + assert _secret_key(env) not in KNOWN_EXAMPLE_SECRETS + assert len(_secret_key(env)) >= 32 + assert re.search(r"^ENVIRONMENT=development$", env, re.M) + keys.append(_secret_key(env)) + assert keys[0] != keys[1] + + def test_env_example_entries_are_not_duplicated(self, tmp_path: Path) -> None: + (tmp_path / ".env.example").write_bytes( + b"SECRET_KEY=changethis\r\n# ENVIRONMENT=production\r\n" + ) + generator = DynamicConfigGenerator( + _config(authentication="OAuth2", utilities=["CORS"]), str(tmp_path) + ) + + generator.apply_env_example() + once = (tmp_path / ".env.example").read_bytes() + generator.apply_env_example() + + assert (tmp_path / ".env.example").read_bytes() == once + text = once.decode("utf-8") + assert text.count("SECRET_KEY=") == 1 + assert text.count("ENVIRONMENT=") == 1 + assert "GOOGLE_CLIENT_ID=" in text + # The file's CRLF line endings are kept. + assert text.count("\r\n") == text.count("\n") + + def test_entries_start_on_a_new_line_after_an_unterminated_file( + self, tmp_path: Path + ) -> None: + # given: a template .env.example whose last line has no line break + (tmp_path / ".env.example").write_bytes(b"APP_NAME=demo") + + # when + DynamicConfigGenerator( + _config(authentication="JWT"), str(tmp_path) + ).apply_env_example() + + # then: the existing line is kept intact and a blank line separates it + text = (tmp_path / ".env.example").read_text(encoding="utf-8") + assert text.startswith("APP_NAME=demo\n\n# ") + assert re.search(r"^APP_NAME=demo$", text, re.M) + assert _secret_key(text) == "changethis" + + def test_missing_env_example_is_created(self, tmp_path: Path) -> None: + DynamicConfigGenerator( + _config(authentication="JWT"), str(tmp_path) + ).apply_env_example() + + example = (tmp_path / ".env.example").read_text(encoding="utf-8") + assert _secret_key(example) == "changethis" diff --git a/tests/test_backends/test_import_ordering.py b/tests/test_backends/test_import_ordering.py new file mode 100644 index 00000000..e50c13a9 --- /dev/null +++ b/tests/test_backends/test_import_ordering.py @@ -0,0 +1,320 @@ +# -------------------------------------------------------------------------- +# Generated imports keep the module's import block isort / ruff sorted. +# +# ``# fastkit:imports`` sits inside the template's import block, so ruff's +# ``I`` rule sorts the imports below it together with the ones above it. +# Appending each generated import under the anchor in wiring order left a +# third-party ``from fastapi_pagination import add_pagination`` among the +# first-party routers (I001 in classic-layered / domain-starter projects). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +from pathlib import Path + +from fastapi_fastkit.backend.main import _update_api_router, insert_import_line +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) + +TEMPLATE_MAIN = """\ +# -------------------------------------------------------------------------- +# Main server application module +# -------------------------------------------------------------------------- + +from fastapi import FastAPI +from starlette.middleware.cors import CORSMiddleware + +from src.api.api import api_router +from src.core.config import settings + +# fastkit:imports + +app = FastAPI( + title=settings.PROJECT_NAME, +) + +# fastkit:routes +app.include_router(api_router) +""" + +SORTED_IMPORTS = """\ +from fastapi import FastAPI +from fastapi_pagination import add_pagination +from starlette.middleware.cors import CORSMiddleware + +from src.api.api import api_router +from src.core.config import settings + +# fastkit:imports +from src.features.pagination import router as pagination_router +from src.features.tasks import router as tasks_router +from src.features.websocket import router as websocket_router + +app = FastAPI( +""" + +WIRING_ORDER = [ + "from src.features.websocket import router as websocket_router", + "from fastapi_pagination import add_pagination", + "from src.features.pagination import router as pagination_router", + "from src.features.tasks import router as tasks_router", +] + + +def test_wired_imports_come_out_sorted_whatever_the_order() -> None: + for order in (WIRING_ORDER, list(reversed(WIRING_ORDER))): + content = TEMPLATE_MAIN + for line in order: + content = insert_import_line(content, line) + + assert SORTED_IMPORTS in content, content + + +def test_insertion_is_idempotent() -> None: + content = TEMPLATE_MAIN + for line in WIRING_ORDER: + content = insert_import_line(content, line) + + again = content + for line in WIRING_ORDER: + again = insert_import_line(again, line) + + assert again == content + + +def test_first_party_import_sorting_before_the_anchor_joins_its_section() -> None: + content = insert_import_line(TEMPLATE_MAIN, "from src.api.deps import get_db") + + assert ( + "from src.api.api import api_router\n" + "from src.api.deps import get_db\n" + "from src.core.config import settings\n\n" + "# fastkit:imports\n" + ) in content + + +def test_new_section_gets_its_own_group() -> None: + content = insert_import_line(TEMPLATE_MAIN, "import os") + + assert content.startswith(TEMPLATE_MAIN.split("from fastapi")[0]) + assert "\nimport os\n\nfrom fastapi import FastAPI\n" in content + + +def test_anchor_outside_the_import_block_keeps_anchor_behaviour() -> None: + content = ( + "from fastapi import APIRouter\n\nrouter = APIRouter()\n# fastkit:imports\n" + ) + + updated = insert_import_line(content, "from src.x import y") + + assert updated.endswith("# fastkit:imports\nfrom src.x import y\n") + + +def test_preset_wiring_produces_a_sorted_block(tmp_path: Path) -> None: + # given + main_py = tmp_path / "src" / "main.py" + main_py.parent.mkdir() + main_py.write_text(TEMPLATE_MAIN, encoding="utf-8", newline="\n") + config = { + "project_name": "p", + "async_tasks": "Celery", + "utilities": ["WebSocket", "Pagination"], + } + + # when + wired = PresetLayoutStrategist("classic-layered").wire_generated_routers( + str(tmp_path), config + ) + + # then: fastapi-default already serves an items list, so Pagination is + # wired as ``add_pagination`` only and no example router is imported + content = main_py.read_text(encoding="utf-8") + assert set(wired) == {"WebSocket", "Pagination", "Background tasks"} + assert ( + SORTED_IMPORTS.replace( + "from src.features.pagination import router as pagination_router\n", "" + ) + in content + ) + assert "pagination_router" not in content + + +# ------------------------------------------------------------------ +# Deduplication by whole import, and section-aware placement +# ------------------------------------------------------------------ + + +def test_existing_import_with_a_longer_name_does_not_hide_the_new_one() -> None: + content = ( + "from fastapi import FastAPI\n\n# fastkit:imports\n" + "from src.api.routes import users_admin\n\napp = FastAPI()\n" + ) + + updated = insert_import_line(content, "from src.api.routes import users") + + assert "from src.api.routes import users\n" in updated + assert insert_import_line(updated, "from src.api.routes import users") == updated + + +def test_repeated_import_is_still_skipped() -> None: + content = "from fastapi import FastAPI\n\nfrom .routes import user\n\napp = 1\n" + + assert insert_import_line(content, "from .routes import user") == content + assert insert_import_line(content, "from .routes import user as u") != content + + +def test_addroute_singular_next_to_plural_imports_the_router(tmp_path: Path) -> None: + api = tmp_path / "api.py" + api.write_text( + "from fastapi import APIRouter\n\nfrom .routes import users\n\n" + "api_router = APIRouter()\n" + 'api_router.include_router(users.router, prefix="/users", tags=["users"])\n', + encoding="utf-8", + ) + + _update_api_router(str(api), "user") + first = api.read_text(encoding="utf-8") + _update_api_router(str(api), "user") + + assert "from .routes import user\n" in first + assert "include_router(user.router" in first + assert api.read_text(encoding="utf-8") == first + # The module must bind every router it registers. + tree = ast.parse(first) + bound = { + alias.asname or alias.name + for node in tree.body + if isinstance(node, ast.ImportFrom) + for alias in node.names + } + registered = { + node.args[0].value.id + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "include_router" + and isinstance(node.args[0], ast.Attribute) + and isinstance(node.args[0].value, ast.Name) + } + assert registered == {"users", "user"} + assert registered <= bound + + +def test_import_joins_its_section_below_the_anchor() -> None: + content = ( + "from fastapi import FastAPI\n\n# fastkit:imports\nfrom src.api.a import x\n" + "\nfrom .local import y\n\napp = FastAPI()\n" + ) + + updated = insert_import_line(content, "from src.api.b import z") + + assert ( + "# fastkit:imports\nfrom src.api.a import x\nfrom src.api.b import z\n" + "\nfrom .local import y\n" + ) in updated + + +def test_import_goes_above_the_comment_attached_to_its_successor() -> None: + content = ( + "from fastapi import FastAPI\n\n# fastkit:imports\n# comment for c\n" + "from src.api.c import x\n\napp = FastAPI()\n" + ) + + updated = insert_import_line(content, "from src.api.b import z") + + assert ( + "# fastkit:imports\nfrom src.api.b import z\n# comment for c\n" + "from src.api.c import x\n" + ) in updated + + +def test_new_section_between_two_sections_below_the_anchor() -> None: + content = ( + "import os\n\n# fastkit:imports\nimport sys\n\nfrom .local import y\n\nx = 1\n" + ) + + updated = insert_import_line(content, "from src.api.b import z") + + assert ( + "import sys\n\nfrom src.api.b import z\n\nfrom .local import y\n" + ) in updated + + +def test_new_section_next_to_an_adjacent_one_gets_blank_lines() -> None: + # given: two sections below the anchor with no blank line between them + content = ( + "import re\n# fastkit:imports\nimport os\nfrom src.api.a import x\n" + "\napp = 1\n" + ) + + # when: a third-party import falls between them + updated = insert_import_line(content, "import httpx") + + # then: it opens its own section, separated from both neighbours + assert updated == ( + "import re\n# fastkit:imports\nimport os\n\nimport httpx\n\n" + "from src.api.a import x\n\napp = 1\n" + ) + + +def test_import_joins_the_end_of_its_section_above_the_anchor() -> None: + # given: a first-party import above the anchor sorts after the new one + content = "import os\n\nfrom src.api.a import x\n\n# fastkit:imports\n\napp = 1\n" + + # when + updated = insert_import_line(content, "import sys") + + # then: it is appended to the stdlib section, not placed under the anchor + assert updated == ( + "import os\nimport sys\n\nfrom src.api.a import x\n\n# fastkit:imports\n" + "\napp = 1\n" + ) + + +def test_import_block_running_to_the_end_of_the_module() -> None: + # given: a module that is nothing but imports + content = "import os\n# fastkit:imports\nimport sys\n" + + # when + updated = insert_import_line(content, "import pathlib") + + # then + assert updated == "import os\n# fastkit:imports\nimport pathlib\nimport sys\n" + + +def test_module_without_imports_falls_back_to_the_anchor() -> None: + # given: only a docstring and the anchor, so there is no block to sort into + content = '"""Module docstring."""\n# fastkit:imports\n' + + # when + updated = insert_import_line(content, "import os") + + # then + assert updated == '"""Module docstring."""\n# fastkit:imports\nimport os\n' + + +def test_compound_or_non_import_lines_fall_back_to_the_anchor() -> None: + # given + content = "import os\n\n# fastkit:imports\n\napp = 1\n" + + # when: lines that are not a single import statement cannot be sorted + compound = insert_import_line(content, "import json; import sys") + statement = insert_import_line(content, "router = None") + + # then: they still land right below the anchor + assert "# fastkit:imports\nimport json; import sys\n" in compound + assert "# fastkit:imports\nrouter = None\n" in statement + for updated in (compound, statement): + ast.parse(updated) + + +def test_import_bound_in_an_except_handler_counts_as_present() -> None: + # given: ``json`` is bound at module level by the ImportError fallback + content = ( + "try:\n import ujson as json\nexcept ImportError:\n import json\n" + "\n# fastkit:imports\n" + ) + + # when / then + assert insert_import_line(content, "import json") == content diff --git a/tests/test_backends/test_inspection_docker.py b/tests/test_backends/test_inspection_docker.py index 4e6742e9..16abec44 100644 --- a/tests/test_backends/test_inspection_docker.py +++ b/tests/test_backends/test_inspection_docker.py @@ -449,7 +449,11 @@ def test_runs_down_and_prune(self) -> None: def test_ownership_reclaim_is_skipped_for_root(self) -> None: compose = DockerCompose("/tmp/project") with patch.object(compose, "_run", return_value=completed()) as mock_run: - with patch("os.getuid", return_value=0, create=True): + # create=True for both: Windows has neither function + with ( + patch("os.getuid", return_value=0, create=True), + patch("os.getgid", return_value=0, create=True), + ): compose.reclaim_bind_mount_ownership() mock_run.assert_not_called() diff --git a/tests/test_backends/test_inspection_fsutils.py b/tests/test_backends/test_inspection_fsutils.py index ec02dda6..5ee268d7 100644 --- a/tests/test_backends/test_inspection_fsutils.py +++ b/tests/test_backends/test_inspection_fsutils.py @@ -9,6 +9,8 @@ from pathlib import Path from unittest.mock import patch +import pytest + from fastapi_fastkit.backend.inspection import fsutils @@ -63,6 +65,9 @@ def test_fix_permissions_ignores_oserror(self, tmp_path: Path) -> None: # given / when / then - should not raise even for a bogus path fsutils._fix_permissions(str(tmp_path / "does-not-exist")) + @pytest.mark.skipif( + os.name == "nt", reason="Windows only has a read-only bit, no mode bits" + ) def test_fix_directory_permissions_applies_to_tree(self, tmp_path: Path) -> None: # given (tmp_path / "sub").mkdir() @@ -171,13 +176,46 @@ def test_gives_up_and_shells_out_after_max_retries(self, tmp_path: Path) -> None side_effect=OSError("locked"), ): with patch("time.sleep"): - with patch("subprocess.run") as mock_run: + with ( + patch.object(fsutils, "is_windows", return_value=False), + patch("subprocess.run") as mock_run, + ): fsutils.force_cleanup_directory(str(target)) # then mock_run.assert_called_once() assert mock_run.call_args.args[0] == ["rm", "-rf", str(target)] + def test_windows_last_resort_uses_rmtree_force_not_a_shell( + self, tmp_path: Path + ) -> None: + # given + target = tmp_path / "victim" + target.mkdir() + + def force(path: str, ignore_errors: bool = False) -> None: + if not ignore_errors: + raise OSError("locked") + + # when - every strategy fails on a (simulated) Windows host + with patch.object(fsutils, "rmtree_force", side_effect=force) as mock_force: + with patch.object(fsutils, "fix_directory_permissions"): + with patch.object( + fsutils, + "remove_directory_contents", + side_effect=OSError("locked"), + ): + with patch("time.sleep"): + with ( + patch.object(fsutils, "is_windows", return_value=True), + patch("subprocess.run") as mock_run, + ): + fsutils.force_cleanup_directory(str(target)) + + # then - no ``rmdir /s /q`` through cmd.exe + mock_run.assert_not_called() + mock_force.assert_called_with(str(target), ignore_errors=True) + def test_subprocess_fallback_oserror_is_logged(self, tmp_path: Path) -> None: # given target = tmp_path / "victim" @@ -192,7 +230,10 @@ def test_subprocess_fallback_oserror_is_logged(self, tmp_path: Path) -> None: side_effect=OSError("locked"), ): with patch("time.sleep"): - with patch("subprocess.run", side_effect=OSError("no rm")): + with ( + patch.object(fsutils, "is_windows", return_value=False), + patch("subprocess.run", side_effect=OSError("no rm")), + ): fsutils.force_cleanup_directory(str(target)) # then - should not raise; failure is only logged diff --git a/tests/test_backends/test_inspection_portability.py b/tests/test_backends/test_inspection_portability.py new file mode 100644 index 00000000..f677cad2 --- /dev/null +++ b/tests/test_backends/test_inspection_portability.py @@ -0,0 +1,196 @@ +# -------------------------------------------------------------------------- +# Testcases for the inspection pipeline's Windows code paths, simulated on any +# OS: the venv interpreter location, running ``scripts/test.sh`` without a +# POSIX exec, stopping the smoke-test server without SIGKILL / killpg, and +# PATH composition. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import signal +import subprocess +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest + +from fastapi_fastkit.backend.inspection import smoke as smoke_module +from fastapi_fastkit.backend.inspection import strategies as strategies_module +from fastapi_fastkit.backend.inspection.context import InspectionContext + +WINDOWS = "fastapi_fastkit.utils.platform.is_windows" + + +def _context(tmp_path: Path, windows: bool) -> InspectionContext: + """A context whose venv follows the requested OS layout on disk.""" + venv = tmp_path / "venv" + if windows: + interpreter = venv / "Scripts" / "python.exe" + else: + interpreter = venv / "bin" / "python" + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") + return InspectionContext( + template_path=tmp_path, + temp_dir=str(tmp_path), + template_config={"app_module": "src.main:app"}, + venv_path=str(venv), + ) + + +class TestVenvInterpreter: + def test_windows_interpreter_has_exe_suffix(self, tmp_path: Path) -> None: + ctx = _context(tmp_path, windows=True) + with patch(WINDOWS, return_value=True): + assert ctx.python_executable() == str( + tmp_path / "venv" / "Scripts" / "python.exe" + ) + + def test_smoke_test_finds_the_windows_interpreter(self, tmp_path: Path) -> None: + # given: only Scripts\python.exe exists, as on Windows + ctx = _context(tmp_path, windows=True) + + # when: Popen is reached (and fails), so the interpreter was found + with ( + patch(WINDOWS, return_value=True), + patch.object( + smoke_module.subprocess, "Popen", side_effect=OSError("stop here") + ) as popen, + ): + result = smoke_module.check_smoke_test(ctx) + + # then + assert result is False + assert popen.call_args[0][0][0] == str( + tmp_path / "venv" / "Scripts" / "python.exe" + ) + assert not any("no virtual environment" in error for error in ctx.errors) + + +def _completed(*_args: Any, **_kwargs: Any) -> "subprocess.CompletedProcess[str]": + return subprocess.CompletedProcess(["x"], 0, "", "") + + +class TestTestScriptOnWindows: + def _with_script(self, tmp_path: Path) -> InspectionContext: + scripts = tmp_path / "scripts" + scripts.mkdir() + (scripts / "test.sh").write_text("#!/bin/sh\npytest\n") + return _context(tmp_path, windows=True) + + def test_without_bash_runs_pytest_instead(self, tmp_path: Path) -> None: + # given + ctx = self._with_script(tmp_path) + + # when + with ( + patch(WINDOWS, return_value=True), + patch.object(strategies_module, "is_windows", return_value=True), + patch.object(strategies_module, "windows_bash", return_value=None), + patch("subprocess.run", side_effect=_completed) as mock_run, + ): + result = strategies_module.StandardStrategy(ctx).run() + + # then: the script is never executed directly (WinError 193) + assert result is True + command = mock_run.call_args[0][0] + assert command[:3] == [ + str(tmp_path / "venv" / "Scripts" / "python.exe"), + "-m", + "pytest", + ] + + def test_with_git_bash_runs_the_script_through_it(self, tmp_path: Path) -> None: + # given + ctx = self._with_script(tmp_path) + bash = r"C:\Program Files\Git\bin\bash.exe" + + # when + with ( + patch(WINDOWS, return_value=True), + patch.object(strategies_module, "is_windows", return_value=True), + patch.object(strategies_module, "windows_bash", return_value=bash), + patch("subprocess.run", side_effect=_completed) as mock_run, + ): + result = strategies_module.StandardStrategy(ctx).run() + + # then + assert result is True + assert mock_run.call_args[0][0] == [ + bash, + str(tmp_path / "scripts" / "test.sh"), + ] + + def test_path_puts_the_venv_scripts_dir_first(self, tmp_path: Path) -> None: + # given + ctx = _context(tmp_path, windows=True) + + # when + with ( + patch(WINDOWS, return_value=True), + patch.dict(os.environ, {"PATH": "existing"}), + patch("subprocess.run", side_effect=_completed) as mock_run, + ): + strategies_module.StandardStrategy(ctx).run() + + # then + assert mock_run.call_args.kwargs["env"]["PATH"] == os.pathsep.join( + [str(tmp_path / "venv" / "Scripts"), "existing"] + ) + + +class TestWindowsBash: + def test_missing_bash(self) -> None: + with patch.object(strategies_module.shutil, "which", return_value=None): + assert strategies_module.windows_bash() is None + + def test_wsl_launcher_is_rejected(self, tmp_path: Path) -> None: + system_root = tmp_path / "Windows" + wsl = system_root / "System32" / "bash.exe" + with ( + patch.object(strategies_module.shutil, "which", return_value=str(wsl)), + patch.dict(os.environ, {"SystemRoot": str(system_root)}), + ): + assert strategies_module.windows_bash() is None + + def test_git_bash_is_accepted(self, tmp_path: Path) -> None: + git_bash = tmp_path / "Git" / "bin" / "bash.exe" + with ( + patch.object(strategies_module.shutil, "which", return_value=str(git_bash)), + patch.dict(os.environ, {"SystemRoot": str(tmp_path / "Windows")}), + ): + assert strategies_module.windows_bash() == str(git_bash) + + def test_bash_on_another_drive_is_accepted(self, tmp_path: Path) -> None: + # given: paths ``commonpath`` cannot compare (``D:\Git`` vs ``C:\Windows`` + # on Windows; an absolute vs a relative path stands in for that here) + git_bash = tmp_path / "Git" / "bin" / "bash.exe" + with ( + patch.object(strategies_module.shutil, "which", return_value=str(git_bash)), + patch.dict(os.environ, {"SystemRoot": "Windows"}), + ): + # when / then: it cannot be the System32 WSL launcher + assert strategies_module.windows_bash() == str(git_bash) + + +class TestTerminateWithoutPosixSignals: + """Windows has neither ``signal.SIGKILL`` nor ``os.killpg``.""" + + def test_falls_back_to_terminate_and_kill( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + # given + monkeypatch.delattr(signal, "SIGKILL", raising=False) + monkeypatch.delattr(os, "killpg", raising=False) + process = MagicMock() + process.pid = 43210 + process.poll.return_value = None + process.wait.side_effect = [subprocess.TimeoutExpired("uvicorn", 5), 0] + + # when + smoke_module._terminate(process) + + # then + process.terminate.assert_called_once() + process.kill.assert_called_once() diff --git a/tests/test_backends/test_inspector.py b/tests/test_backends/test_inspector.py index f1a0d022..7ab9637b 100644 --- a/tests/test_backends/test_inspector.py +++ b/tests/test_backends/test_inspector.py @@ -26,6 +26,7 @@ TemplateInspector, inspect_fastapi_template, ) +from fastapi_fastkit.utils.platform import venv_python PYPROJECT_TPL = """ [project] @@ -488,9 +489,9 @@ class TestStrategyExecution: """The shared strategy base: environment setup and result grading.""" def _context(self, tmp_path: Path, config: Optional[Dict[str, Any]] = None) -> Any: - venv = tmp_path / "venv" / "bin" - venv.mkdir(parents=True) - (venv / "python").write_text("") + interpreter = Path(venv_python(tmp_path / "venv")) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") return InspectionContext( template_path=tmp_path, temp_dir=str(tmp_path), @@ -533,8 +534,12 @@ def test_strategy_prefers_template_test_script(self, tmp_path: Path) -> None: ctx = self._context(tmp_path) completed = subprocess.CompletedProcess(["test.sh"], 0, "", "") - # when - with patch("subprocess.run", return_value=completed) as mock_run: + # when: POSIX executes the script directly (Windows is covered in + # test_inspection_portability.py) + with ( + patch.object(strategies_module, "is_windows", return_value=False), + patch("subprocess.run", return_value=completed) as mock_run, + ): result = strategies_module.StandardStrategy(ctx).run() # then @@ -742,9 +747,9 @@ class TestStrategyErrorPaths: """Failure branches not covered by the happy-path strategy tests.""" def _context(self, tmp_path: Path, config: Optional[Dict[str, Any]] = None) -> Any: - venv = tmp_path / "venv" / "bin" - venv.mkdir(parents=True) - (venv / "python").write_text("") + interpreter = Path(venv_python(tmp_path / "venv")) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") return InspectionContext( template_path=tmp_path, temp_dir=str(tmp_path), diff --git a/tests/test_backends/test_inspector_checks.py b/tests/test_backends/test_inspector_checks.py index 98abc136..5898170a 100644 --- a/tests/test_backends/test_inspector_checks.py +++ b/tests/test_backends/test_inspector_checks.py @@ -23,6 +23,7 @@ InspectionContext, InspectionOptions, ) +from fastapi_fastkit.utils.platform import venv_python VALID_PYPROJECT = """ [project] @@ -553,9 +554,29 @@ def test_returns_none_when_unresolvable(self, tmp_path: Path) -> None: FAKE_PID = 43210 +#: POSIX has process groups (``os.killpg`` / ``os.getpgid``); Windows has +#: neither, and the smoke test stops the server with ``terminate()`` there. +HAS_PROCESS_GROUPS = hasattr(os, "killpg") + +#: ``signal.SIGKILL`` does not exist on Windows. +SIGKILL: Optional[int] = getattr(signal, "SIGKILL", None) + +posix_process_groups = pytest.mark.skipif( + not HAS_PROCESS_GROUPS, reason="POSIX process groups (os.killpg/os.getpgid)" +) + + @contextmanager def no_real_signals(pid: int = FAKE_PID) -> Iterator[MagicMock]: - """Neuter the process-group calls so no test can ever signal a real group.""" + """Neuter the process-group calls so no test can ever signal a real group. + + Where the platform has no process groups (Windows) nothing is patched: + the production code never reaches ``os.killpg`` there, and the yielded + mock simply records no calls. + """ + if not HAS_PROCESS_GROUPS: + yield MagicMock(name="killpg") + return with ( patch.object(smoke_module.os, "getpgid", return_value=pid) as getpgid, patch.object(smoke_module.os, "killpg") as killpg, @@ -564,6 +585,36 @@ def no_real_signals(pid: int = FAKE_PID) -> Iterator[MagicMock]: yield killpg +def assert_stopped_with_sigterm(killpg: MagicMock, process: MagicMock) -> None: + """The server was asked to stop once, the platform's way. + + POSIX signals the server's own process group (so uvicorn's children go + too) instead of the single process; Windows calls ``terminate()``. + """ + if HAS_PROCESS_GROUPS: + killpg.assert_called_once_with(FAKE_PID, signal.SIGTERM) + process.terminate.assert_not_called() + else: + killpg.assert_not_called() + process.terminate.assert_called_once_with() + + +class TestSignalGroupWithoutProcessGroups: + """Without ``os.killpg`` (Windows) the group path is never taken.""" + + def test_returns_false_so_the_caller_falls_back( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + # given: a platform without process groups, simulated where needed + monkeypatch.delattr(smoke_module.os, "killpg", raising=False) + process = MagicMock() + process.pid = FAKE_PID + + # when / then + assert smoke_module._signal_group(process, signal.SIGTERM) is False + + +@posix_process_groups class TestSignalGroup: """``_signal_group`` must never signal a group that is not ours.""" @@ -669,9 +720,9 @@ def _context(self, tmp_path: Path) -> InspectionContext: ctx = make_context(tmp_path) ctx.template_config = {"app_module": "src.main:app"} ctx.venv_path = str(tmp_path / "venv") - bin_dir = Path(ctx.venv_path) / "bin" - bin_dir.mkdir(parents=True) - (bin_dir / "python").write_text("") + interpreter = Path(venv_python(ctx.venv_path)) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") return ctx def test_skipped_when_disabled(self, tmp_path: Path) -> None: @@ -720,8 +771,7 @@ def test_passes_when_docs_answers(self, tmp_path: Path) -> None: assert result is True assert ctx.errors == [] # The server's own group is signalled, not this process's. - killpg.assert_called_once_with(FAKE_PID, signal.SIGTERM) - process.terminate.assert_not_called() + assert_stopped_with_sigterm(killpg, process) def test_missing_health_endpoint_is_not_an_error(self, tmp_path: Path) -> None: # given @@ -802,8 +852,7 @@ def test_timeout_terminates_the_server(self, tmp_path: Path) -> None: # then assert result is False - killpg.assert_called_once_with(FAKE_PID, signal.SIGTERM) - process.terminate.assert_not_called() + assert_stopped_with_sigterm(killpg, process) class TestAppModulePyprojectHelper: @@ -903,10 +952,19 @@ def test_escalates_to_sigkill_when_sigterm_does_not_stop_it(self) -> None: smoke_module._terminate(process) # then - assert killpg.call_args_list == [ - ((FAKE_PID, signal.SIGTERM),), - ((FAKE_PID, signal.SIGKILL),), - ] + if HAS_PROCESS_GROUPS and SIGKILL is not None: + # POSIX: the whole group gets SIGTERM, then SIGKILL + assert killpg.call_args_list == [ + ((FAKE_PID, signal.SIGTERM),), + ((FAKE_PID, SIGKILL),), + ] + process.terminate.assert_not_called() + process.kill.assert_not_called() + else: + # Windows: terminate(), then kill() (TerminateProcess) + killpg.assert_not_called() + process.terminate.assert_called_once_with() + process.kill.assert_called_once_with() assert process.wait.call_count == 2 def test_falls_back_to_process_kill_when_group_signal_unavailable(self) -> None: @@ -916,13 +974,20 @@ def test_falls_back_to_process_kill_when_group_signal_unavailable(self) -> None: process.poll.return_value = None process.wait.side_effect = subprocess.TimeoutExpired(cmd="uvicorn", timeout=1) - # when - with patch.object( - smoke_module.os, "getpgid", side_effect=ProcessLookupError("gone") + # when: create=True, because Windows has neither function + with ( + patch.object( + smoke_module.os, + "getpgid", + side_effect=ProcessLookupError("gone"), + create=True, + ), + patch.object(smoke_module.os, "killpg", create=True) as killpg, ): smoke_module._terminate(process) # then + killpg.assert_not_called() process.terminate.assert_called_once() process.kill.assert_called_once() @@ -940,9 +1005,9 @@ def _context(self, tmp_path: Path) -> InspectionContext: ctx = make_context(tmp_path) ctx.template_config = {"app_module": "src.main:app"} ctx.venv_path = str(tmp_path / "venv") - bin_dir = Path(ctx.venv_path) / "bin" - bin_dir.mkdir(parents=True) - (bin_dir / "python").write_text("") + interpreter = Path(venv_python(ctx.venv_path)) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") return ctx def test_popen_oserror_is_reported(self, tmp_path: Path) -> None: @@ -1127,7 +1192,13 @@ def test_python_executable_requires_venv(self, tmp_path: Path) -> None: ctx = make_context(tmp_path) assert ctx.python_executable() is None ctx.venv_path = "/tmp/venv" - assert ctx.python_executable() == "/tmp/venv/bin/python" + assert ctx.python_executable() == venv_python("/tmp/venv") + with patch("fastapi_fastkit.utils.platform.is_windows", return_value=True): + assert ctx.python_executable() == os.path.join( + "/tmp/venv", "Scripts", "python.exe" + ) + with patch("fastapi_fastkit.utils.platform.is_windows", return_value=False): + assert ctx.python_executable() == os.path.join("/tmp/venv", "bin", "python") def test_options_defaults(self) -> None: options: Dict[str, Any] = vars(InspectionOptions()) diff --git a/tests/test_backends/test_interactive_config_builder.py b/tests/test_backends/test_interactive_config_builder.py index c966ff26..966d46d9 100644 --- a/tests/test_backends/test_interactive_config_builder.py +++ b/tests/test_backends/test_interactive_config_builder.py @@ -85,7 +85,7 @@ def test_collect_dependencies_with_database(self) -> None: dependencies = builder._collect_all_dependencies() # then - assert "sqlalchemy" in dependencies + assert "sqlalchemy[asyncio]" in dependencies assert "asyncpg" in dependencies def test_collect_dependencies_with_authentication(self) -> None: diff --git a/tests/test_backends/test_local_env.py b/tests/test_backends/test_local_env.py new file mode 100644 index 00000000..4b917c75 --- /dev/null +++ b/tests/test_backends/test_local_env.py @@ -0,0 +1,428 @@ +# -------------------------------------------------------------------------- +# Testcases of the local .env generation. +# +# Templates ship only ``.env.example``; generation derives the git-ignored +# ``.env`` from it with a unique SECRET_KEY. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import logging +import os +import re +import shutil +import subprocess +from pathlib import Path +from typing import Any, Dict, List +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.main import ( + create_local_env_file, + render_local_env, +) +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.core.settings import FastkitConfig, settings +from fastapi_fastkit.utils.logging import debug_log, setup_logging + +EXAMPLE = "ENVIRONMENT=development\nSECRET_KEY=changethis\nDEBUG=false\n" + + +def _secret_key(content: str) -> str: + match = re.search(r"^SECRET_KEY=(.*)$", content, re.M) + assert match, content + return match.group(1) + + +def _write_example(project: Path, content: str) -> None: + (project / ".env.example").write_bytes(content.encode("utf-8")) + + +class TestRenderLocalEnv: + def test_secret_key_value_is_replaced_with_a_random_key(self) -> None: + # when + rendered = render_local_env(EXAMPLE) + + # then + key = _secret_key(rendered) + assert key != "changethis" + assert len(key) >= 32 + assert "ENVIRONMENT=development\n" in rendered + assert "DEBUG=false\n" in rendered + + def test_each_render_gets_a_different_key(self) -> None: + keys = {_secret_key(render_local_env(EXAMPLE)) for _ in range(5)} + assert len(keys) == 5 + + def test_commented_secret_key_is_left_alone(self) -> None: + # given + content = "# SECRET_KEY=changethis\nOTHER=1\n" + + # when / then + assert render_local_env(content) == content + + def test_export_prefixed_and_spaced_assignments_are_replaced(self) -> None: + # given + content = "export SECRET_KEY=changethis\n SECRET_KEY = old\n" + + # when + rendered = render_local_env(content) + + # then + assert "changethis" not in rendered + assert "old" not in rendered + assert rendered.startswith("export SECRET_KEY=") + assert "\n SECRET_KEY =" in rendered + + def test_similar_variable_names_are_not_touched(self) -> None: + # given + content = "JWT_SECRET_KEY=keep\nSECRET_KEY_FILE=keep\n" + + # when / then + assert render_local_env(content) == content + + def test_crlf_input_is_normalised(self) -> None: + rendered = render_local_env("A=1\r\nSECRET_KEY=x\r\nB=2\rC=3\r\n") + assert "\r" not in rendered + assert rendered.startswith("A=1\nSECRET_KEY=") + assert rendered.endswith("\nB=2\nC=3\n") + + +class TestCreateLocalEnvFile: + def test_creates_env_with_unique_key_and_keeps_example( + self, tmp_path: Path + ) -> None: + # given + _write_example(tmp_path, EXAMPLE) + + # when + written = create_local_env_file(str(tmp_path)) + + # then + env = tmp_path / ".env" + assert written == str(env) + assert (tmp_path / ".env.example").read_text(encoding="utf-8") == EXAMPLE + assert _secret_key(env.read_text(encoding="utf-8")) != "changethis" + + def test_two_projects_get_different_keys(self, tmp_path: Path) -> None: + # given + first, second = tmp_path / "a", tmp_path / "b" + for project in (first, second): + project.mkdir() + _write_example(project, EXAMPLE) + + # when + create_local_env_file(str(first)) + create_local_env_file(str(second)) + + # then + assert _secret_key((first / ".env").read_text()) != _secret_key( + (second / ".env").read_text() + ) + + def test_existing_env_is_never_overwritten(self, tmp_path: Path) -> None: + # given + _write_example(tmp_path, EXAMPLE) + (tmp_path / ".env").write_text("SECRET_KEY=mine\n", encoding="utf-8") + + # when + written = create_local_env_file(str(tmp_path)) + + # then + assert written is None + assert (tmp_path / ".env").read_text(encoding="utf-8") == "SECRET_KEY=mine\n" + + def test_no_example_means_no_env(self, tmp_path: Path) -> None: + assert create_local_env_file(str(tmp_path)) is None + assert not (tmp_path / ".env").exists() + + def test_example_without_secret_key_is_copied_verbatim( + self, tmp_path: Path + ) -> None: + # given + content = "DATABASE_URL=sqlite:///./app.db\n# comment\n" + _write_example(tmp_path, content) + + # when + create_local_env_file(str(tmp_path)) + + # then + assert (tmp_path / ".env").read_bytes() == content.encode("utf-8") + + def test_written_file_uses_lf_newlines(self, tmp_path: Path) -> None: + # given: an example checked out with CRLF (Windows, autocrlf) + _write_example(tmp_path, "A=1\r\nSECRET_KEY=changethis\r\nB=ü\r\n") + + # when + create_local_env_file(str(tmp_path)) + + # then + raw = (tmp_path / ".env").read_bytes() + assert b"\r" not in raw + assert raw.startswith(b"A=1\nSECRET_KEY=") + assert raw.endswith("\nB=ü\n".encode("utf-8")) + # .env.example itself is not rewritten by this step + assert (tmp_path / ".env.example").read_bytes().count(b"\r\n") == 3 + + def test_generated_key_is_not_printed( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + # given + _write_example(tmp_path, EXAMPLE) + + # when + create_local_env_file(str(tmp_path)) + + # then + key = _secret_key((tmp_path / ".env").read_text()) + captured = capsys.readouterr() + assert key not in captured.out + assert key not in captured.err + + def test_generated_key_is_not_written_to_the_debug_log( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + # given: debug mode on, with the fastkit log file redirected into + # tmp_path, and stdout/stderr tee'd into it like `fastkit --debug` + project = tmp_path / "project" + project.mkdir() + _write_example(project, EXAMPLE) + log_file = tmp_path / "logs" / "fastkit.log" + monkeypatch.setattr(settings, "DEBUG_MODE", True) + monkeypatch.setattr(settings, "LOG_FILE_PATH", str(log_file)) + logger = logging.getLogger("fastapi-fastkit") + saved_handlers = list(logger.handlers) + saved_level = logger.level + saved_propagate = logger.propagate + + # when + try: + capture = setup_logging(settings) + assert capture is not None + with capture: + create_local_env_file(str(project)) + debug_log("local env step finished", "info") + finally: + logger.handlers[:] = saved_handlers + logger.setLevel(saved_level) + logger.propagate = saved_propagate + + # then: the log did capture this run, but never the key + key = _secret_key((project / ".env").read_text(encoding="utf-8")) + log = log_file.read_text(encoding="utf-8") + assert "local env step finished" in log + assert "SECRET_KEY" in log # the success message went through the tee + assert key not in log + + def test_write_failure_is_raised(self, tmp_path: Path) -> None: + # given + _write_example(tmp_path, EXAMPLE) + + real_open = open + + def refuse_create(file: Any, mode: str = "r", *args: Any, **kwargs: Any) -> Any: + if mode == "x": + raise PermissionError("denied") + return real_open(file, mode, *args, **kwargs) + + # when / then + with patch("builtins.open", side_effect=refuse_create): + with pytest.raises(BackendExceptions): + create_local_env_file(str(tmp_path)) + assert not (tmp_path / ".env").exists() + + def test_undecodable_example_is_raised(self, tmp_path: Path) -> None: + # given: a .env.example saved in a legacy code page + (tmp_path / ".env.example").write_bytes(b"SECRET_KEY=caf\xe9\n") + + # when / then + with pytest.raises(BackendExceptions, match=r"Failed to read \.env\.example"): + create_local_env_file(str(tmp_path)) + assert not (tmp_path / ".env").exists() + + def test_env_appearing_after_the_check_is_kept(self, tmp_path: Path) -> None: + # given: another process creates .env between the existence check and + # the exclusive create + _write_example(tmp_path, EXAMPLE) + env = tmp_path / ".env" + real_open = open + + def create_first(file: Any, mode: str = "r", *args: Any, **kwargs: Any) -> Any: + if mode == "x": + env.write_text("SECRET_KEY=theirs\n", encoding="utf-8") + return real_open(file, mode, *args, **kwargs) + + # when + with patch("builtins.open", side_effect=create_first): + written = create_local_env_file(str(tmp_path)) + + # then: the other process's file wins and is not overwritten + assert written is None + assert env.read_text(encoding="utf-8") == "SECRET_KEY=theirs\n" + + +# -------------------------------------------------------------------------- +# Scaffolder integration +# -------------------------------------------------------------------------- + + +def _settings(workspace: Path) -> FastkitConfig: + settings = FastkitConfig() + settings.USER_WORKSPACE = str(workspace) + return settings + + +def _options(**overrides: Any) -> ScaffoldOptions: + base: Dict[str, Any] = { + "project_name": "env-test", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "env testcase project", + "package_manager": "pip", + "template": "fastapi-default", + "with_venv": False, + "with_install": False, + } + base.update(overrides) + return ScaffoldOptions(**base) + + +def _templates() -> List[str]: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + return sorted( + d.name + for d in root.iterdir() + if d.is_dir() and d.name not in {"__pycache__", "modules"} + ) + + +class TestScaffolderLocalEnv: + def test_run_generates_env_from_example(self, tmp_path: Path) -> None: + # when + result = ProjectScaffolder(_settings(tmp_path), _options()).run() + + # then + project = Path(result.project_dir) + example = (project / ".env.example").read_text(encoding="utf-8") + env = (project / ".env").read_text(encoding="utf-8") + assert _secret_key(example) == "changethis" + assert _secret_key(env) != "changethis" + + def test_in_place_deploy_keeps_existing_env(self, tmp_path: Path) -> None: + # given + (tmp_path / ".env").write_text("SECRET_KEY=mine\n", encoding="utf-8") + scaffolder = ProjectScaffolder( + _settings(tmp_path), + _options(create_project_folder=False, assume_yes=True), + ) + + # when + assert ".env" not in scaffolder.existing_targets() + scaffolder.run() + + # then + assert (tmp_path / ".env").read_text(encoding="utf-8") == "SECRET_KEY=mine\n" + assert (tmp_path / ".env.example").is_file() + + def test_dry_run_writes_nothing_but_lists_env( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + # given + scaffolder = ProjectScaffolder(_settings(tmp_path), _options(dry_run=True)) + + # when + result = scaffolder.run() + + # then + assert result.dry_run is True + assert list(tmp_path.iterdir()) == [] + planned = scaffolder._planned_files() + assert ".env" in planned + assert ".env.example" in planned + + def test_failure_after_env_creation_rolls_back_the_project( + self, tmp_path: Path + ) -> None: + # given + scaffolder = ProjectScaffolder(_settings(tmp_path), _options()) + + # when + with patch( + "fastapi_fastkit.backend.scaffolder.write_fastkit_metadata", + side_effect=BackendExceptions("boom"), + ): + with pytest.raises(BackendExceptions): + scaffolder.run() + + # then + assert not (tmp_path / "env-test").exists() + + @pytest.mark.parametrize("template", _templates()) + def test_template_ships_example_not_env(self, template: str) -> None: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) / template + assert (root / ".env.example-tpl").is_file() + assert not (root / ".env-tpl").exists() + assert not (root / ".env").exists() + + +@pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed") +@pytest.mark.parametrize("template", _templates()) +def test_generated_project_ignores_env_but_tracks_example( + template: str, tmp_path: Path +) -> None: + # given + result = ProjectScaffolder(_settings(tmp_path), _options(template=template)).run() + project = Path(result.project_dir) + assert (project / ".env").is_file() + assert (project / ".env.example").is_file() + + # Isolate from the developer's global/system git config and excludes + # file, which could ignore .env* on their own and mask the template. + empty_excludes = tmp_path / "empty-excludes" + empty_excludes.write_text("", encoding="utf-8") + # An empty file rather than os.devnull: "nul" is not a path git for + # Windows accepts everywhere. + empty_config = tmp_path / "empty-gitconfig" + empty_config.write_text("", encoding="utf-8") + env = { + **os.environ, + "GIT_CONFIG_GLOBAL": str(empty_config), + "GIT_CONFIG_NOSYSTEM": "1", + } + + def git(*args: str) -> "subprocess.CompletedProcess[str]": + return subprocess.run( + ["git", "-c", f"core.excludesFile={empty_excludes}", *args], + cwd=project, + env=env, + capture_output=True, + text=True, + check=False, + ) + + assert git("init", "-q").returncode == 0 + + # when / then: .env and every per-environment variant are ignored, + # including deployment files such as .env.production that hold real + # secrets (not only the *.local ones) + for name in ( + ".env", + ".env.local", + ".env.production", + ".env.staging", + ".env.development", + ".env.production.local", + ): + assert git("check-ignore", "-q", name).returncode == 0, name + # ...while the shareable example is not + assert git("check-ignore", "-q", ".env.example").returncode == 1 + untracked = git("status", "--porcelain", "--untracked-files=all").stdout + assert ".env.example" in untracked + assert not re.search(r"^\?\? \.env$", untracked, re.M) + + # A real .env.production on disk stays untracked as well + (project / ".env.production").write_text("SECRET_KEY=prod\n", encoding="utf-8") + untracked = git("status", "--porcelain", "--untracked-files=all").stdout + assert ".env.production" not in untracked + assert ".env.example" in untracked diff --git a/tests/test_backends/test_main.py b/tests/test_backends/test_main.py index 07a279c7..c86f5bf3 100644 --- a/tests/test_backends/test_main.py +++ b/tests/test_backends/test_main.py @@ -111,6 +111,25 @@ def test_find_template_core_modules(self) -> None: assert result["setup"] == str(setup_py) assert result["config"] == str(config_py) + def test_find_template_core_modules_uses_native_separators(self) -> None: + """``src/main.py`` from TEMPLATE_PATHS is joined part by part.""" + # given: Windows path rules, simulated through ntpath + import ntpath + from types import SimpleNamespace + + from fastapi_fastkit.backend import main as backend_main + + fake_os = SimpleNamespace(path=ntpath) + + # when + with patch.object(backend_main, "os", fake_os): + main_path = backend_main._project_file("C:\\proj", "src/main.py") + config_path = backend_main._project_file("C:\\proj", "", "config.py") + + # then: no mixed ``\\src/main.py`` separators, no empty components + assert main_path == "C:\\proj\\src\\main.py" + assert config_path == "C:\\proj\\config.py" + def test_find_template_core_modules_alternative_paths(self) -> None: """Test find_template_core_modules with alternative file locations.""" # given @@ -296,8 +315,9 @@ def test_process_main_file_os_error_raises_backend_exception(self) -> None: main_py = self.project_path / "main.py" main_py.write_text('app = FastAPI(title="")') + # main.py reads and rewrites through the newline-preserving helpers with patch( - "fastapi_fastkit.backend.main.open", + "fastapi_fastkit.utils.textio.open", side_effect=OSError("disk read failure"), ): # when & then @@ -324,6 +344,26 @@ def test_inject_project_metadata_with_exception( "Test description", ) + @patch("fastapi_fastkit.backend.main._process_main_file") + def test_inject_project_metadata_keeps_specific_backend_errors( + self, mock_process_main: MagicMock + ) -> None: + """A step's own BackendExceptions reaches the caller unchanged.""" + # given + original = BackendExceptions("Failed to process main.py: disk full") + mock_process_main.side_effect = original + + # when & then: not re-wrapped as the generic metadata failure + with pytest.raises(BackendExceptions) as raised: + inject_project_metadata( + str(self.project_path), + "test-project", + "Test Author", + "test@example.com", + "Test description", + ) + assert raised.value is original + def test_read_template_stack(self) -> None: """Test read_template_stack function.""" # given @@ -1187,7 +1227,7 @@ def test_deploy_template_with_folder_option_create_folder( ) # then - expected_project_dir = "/tmp/test-project" + expected_project_dir = os.path.join(user_local, project_name) assert project_dir == expected_project_dir assert "test-project" in deployment_message assert "folder" in deployment_message diff --git a/tests/test_backends/test_package_managers.py b/tests/test_backends/test_package_managers.py index d13f2c85..a9659983 100644 --- a/tests/test_backends/test_package_managers.py +++ b/tests/test_backends/test_package_managers.py @@ -3,6 +3,7 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import os import shutil import subprocess import tempfile @@ -63,9 +64,9 @@ def add_dependency(self, dep: str, dev: bool = False) -> None: manager = TestManager("/test") - with patch("os.name", "nt"): + with patch("fastapi_fastkit.utils.platform.is_windows", return_value=True): path = manager.get_executable_path("pip", "/test/venv") - assert path == "/test/venv/Scripts/pip.exe" + assert path == os.path.join("/test/venv", "Scripts", "pip.exe") def test_get_executable_path_unix(self) -> None: """Test executable path generation for Unix systems.""" @@ -98,9 +99,9 @@ def add_dependency(self, dep: str, dev: bool = False) -> None: manager = TestManager("/test") - with patch("os.name", "posix"): + with patch("fastapi_fastkit.utils.platform.is_windows", return_value=False): path = manager.get_executable_path("pip", "/test/venv") - assert path == "/test/venv/bin/pip" + assert path == os.path.join("/test/venv", "bin", "pip") def test_get_dependency_file_path(self) -> None: """Test dependency file path generation.""" @@ -133,7 +134,44 @@ def add_dependency(self, dep: str, dev: bool = False) -> None: manager = TestManager("/test/project") file_path = manager.get_dependency_file_path() - assert str(file_path) == "/test/project/requirements.txt" + assert str(file_path) == str(Path("/test/project") / "requirements.txt") + + def test_get_executable_path_without_venv_is_the_bare_name( + self, tmp_path: Path + ) -> None: + """Without a venv the executable is looked up on PATH by name.""" + manager = PipManager(str(tmp_path)) + assert manager.get_executable_path("pip") == "pip" + + def test_run_command_defaults(self, tmp_path: Path) -> None: + """Commands run in the project, checked, with UTF-8 decoded output.""" + # given + manager = PipManager(str(tmp_path)) + + # when + with ( + patch( + "fastapi_fastkit.backend.package_managers.base.resolve_command", + return_value=["C:/tools/pdm.cmd", "install"], + ) as resolve, + patch( + "fastapi_fastkit.backend.package_managers.base.subprocess.run" + ) as mock_run, + ): + result = manager.run_command(["pdm", "install"], check=False) + + # then: the program goes through Windows shim resolution, the + # defaults apply, and a caller's keyword wins over a default + resolve.assert_called_once_with(["pdm", "install"]) + assert result is mock_run.return_value + args, kwargs = mock_run.call_args + assert args == (["C:/tools/pdm.cmd", "install"],) + assert kwargs["check"] is False + assert kwargs["capture_output"] is True + assert kwargs["encoding"] == "utf-8" + assert kwargs["errors"] == "replace" + assert kwargs["cwd"] == str(tmp_path) + assert kwargs["timeout"] == settings.get_subprocess_timeout() class TestPackageManagerFactory: @@ -1042,6 +1080,48 @@ def test_generate_dependency_file_with_pep508_specifiers(self) -> None: "extras": ["hiredis"], } + def test_generate_dependency_file_skips_nameless_requirements(self) -> None: + """Blank or marker-only requirement strings produce no dependency line.""" + import tomllib + + self.manager.generate_dependency_file( + ["fastapi", " ", "; python_version > '3'"] + ) + + content = (Path(self.temp_dir) / "pyproject.toml").read_text(encoding="utf-8") + deps_table = tomllib.loads(content)["tool"]["poetry"]["dependencies"] + assert set(deps_table) == {"python", "fastapi"} + + @pytest.mark.parametrize( + ("dev_group", "expected"), + [ + ('["pytest", {include-group = "lint"}]', {"pytest": "*"}), + ('"pytest"', {}), + ], + ids=["list", "not-a-list"], + ) + def test_dev_group_comes_from_the_template_dependency_groups( + self, dev_group: str, expected: Any + ) -> None: + """Only the string entries of a list-valued ``dev`` group are carried over.""" + import tomllib + + # given + pyproject = Path(self.temp_dir) / "pyproject.toml" + pyproject.write_text( + '[project]\nname = "x"\nrequires-python = ">=3.12"\n\n' + f'[dependency-groups]\ndev = {dev_group}\nlint = ["ruff"]\n', + encoding="utf-8", + ) + + # when + self.manager.generate_dependency_file(["fastapi"]) + + # then + poetry = tomllib.loads(pyproject.read_text(encoding="utf-8"))["tool"]["poetry"] + assert poetry["group"]["dev"]["dependencies"] == expected + assert poetry["dependencies"] == {"python": ">=3.12", "fastapi": "*"} + @patch("subprocess.run") def test_add_dependency_success(self, mock_run: Mock) -> None: """Test successful dependency addition with Poetry.""" @@ -1500,3 +1580,24 @@ def test_invalid_env_var_is_ignored(self, monkeypatch: pytest.MonkeyPatch) -> No """Test a non-numeric override falls back to the built-in value.""" monkeypatch.setenv("FASTKIT_SUBPROCESS_TIMEOUT", "not-a-number") assert settings.get_subprocess_timeout("venv") == 120 + + +class TestPipRequirementsLineEndings: + """Generated files are LF; in-place edits keep the file's own endings.""" + + def test_generated_requirements_use_lf(self, tmp_path: Path) -> None: + manager = PipManager(str(tmp_path)) + manager.generate_dependency_file(["fastapi", "uvicorn"]) + assert (tmp_path / "requirements.txt").read_bytes() == b"fastapi\nuvicorn\n" + + def test_add_dependency_preserves_crlf(self, tmp_path: Path) -> None: + requirements = tmp_path / "requirements.txt" + requirements.write_bytes(b"fastapi\r\nuvicorn\r\n") + PipManager(str(tmp_path)).add_dependency("httpx") + assert requirements.read_bytes() == b"fastapi\r\nuvicorn\r\nhttpx\r\n" + + def test_add_dependency_keeps_lf(self, tmp_path: Path) -> None: + requirements = tmp_path / "requirements.txt" + requirements.write_bytes(b"fastapi\n") + PipManager(str(tmp_path)).add_dependency("httpx") + assert requirements.read_bytes() == b"fastapi\nhttpx\n" diff --git a/tests/test_backends/test_preset_layout.py b/tests/test_backends/test_preset_layout.py index 559127a9..08c0e103 100644 --- a/tests/test_backends/test_preset_layout.py +++ b/tests/test_backends/test_preset_layout.py @@ -349,3 +349,79 @@ def test_caching_is_never_auto_wired(self, tmp_path: Path) -> None: assert wired == [] assert main_py.read_text(encoding="utf-8") == self.MAIN_PY + + +class TestSkippedExampleRouters: + """Demo routers are skipped where the base template ships the collection.""" + + PAGINATION = {"utilities": ["Pagination"]} + + @pytest.mark.parametrize( + "preset,expected", + [ + ("minimal", []), + ("single-module", []), + ("classic-layered", ["Pagination"]), + ("domain-starter", ["Pagination"]), + ], + ) + def test_presets_with_an_items_api_skip_the_pagination_demo( + self, preset: str, expected: list + ) -> None: + strategist = PresetLayoutStrategist(preset) + + assert strategist.skipped_example_labels(self.PAGINATION) == expected + assert strategist.skipped_example_labels({"utilities": ["WebSocket"]}) == [] + + def test_note_names_the_shipped_endpoint_and_the_skipped_module(self) -> None: + notes = PresetLayoutStrategist("domain-starter").skipped_example_notes( + self.PAGINATION + ) + + assert len(notes) == 1 + assert "GET /api/v1/items" in notes[0] + assert "src/app/features/pagination.py was not generated" in notes[0] + + def test_wiring_adds_only_add_pagination_after_the_template_routers( + self, tmp_path: Path + ) -> None: + # given + main_py = tmp_path / "src" / "app" / "main.py" + main_py.parent.mkdir(parents=True) + main_py.write_text(TestWireGeneratedRouters.MAIN_PY, encoding="utf-8") + strategist = PresetLayoutStrategist("domain-starter") + + # when: wired twice, the second run must not duplicate anything + wired = strategist.wire_generated_routers(str(tmp_path), self.PAGINATION) + strategist.wire_generated_routers(str(tmp_path), self.PAGINATION) + + # then + content = main_py.read_text(encoding="utf-8") + assert wired == ["Pagination"] + assert "from fastapi_pagination import add_pagination" in content + assert "pagination_router" not in content + assert content.count("add_pagination(app)") == 1 + assert content.index("app.include_router(api_router)") < content.index( + "add_pagination(app)" + ) + assert content.rstrip().endswith("add_pagination(app)") + assert "response_model=Page[ItemRead]" in content + assert "src/app/domains/items/router.py" in content + assert all(len(line) <= 88 for line in content.splitlines()) + assert strategist.compatibility_warnings(self.PAGINATION, wired=wired) == [] + + def test_wiring_without_example_keeps_crlf(self, tmp_path: Path) -> None: + main_py = tmp_path / "src" / "main.py" + main_py.parent.mkdir(parents=True) + main_py.write_bytes( + TestWireGeneratedRouters.MAIN_PY.replace("\n", "\r\n").encode() + ) + + PresetLayoutStrategist("classic-layered").wire_generated_routers( + str(tmp_path), self.PAGINATION + ) + + data = main_py.read_bytes() + assert data.count(b"\n") == data.count(b"\r\n") + assert b"add_pagination(app)\r\n" in data + assert b"Page[ItemResponse]" in data diff --git a/tests/test_backends/test_project_builder_config_generator.py b/tests/test_backends/test_project_builder_config_generator.py index f24ca903..0c8f770c 100644 --- a/tests/test_backends/test_project_builder_config_generator.py +++ b/tests/test_backends/test_project_builder_config_generator.py @@ -6,8 +6,14 @@ import ast import itertools import json +import os +import re import tempfile +import tomllib from pathlib import Path +from typing import List + +import pytest from fastapi_fastkit.backend.project_builder.config_generator import ( DynamicConfigGenerator, @@ -363,7 +369,7 @@ def test_generated_dockerfile_uses_exec_form_cmd(self) -> None: # then dockerfile = Path(tmp) / "Dockerfile" assert dockerfile.exists() - content = dockerfile.read_text() + content = dockerfile.read_text(encoding="utf-8") # Find the CMD line and validate it parses as JSON array (exec form) cmd_lines = [ @@ -400,7 +406,7 @@ def test_generated_dockerfile_honors_custom_app_module(self) -> None: # then dockerfile = Path(tmp) / "Dockerfile" - content = dockerfile.read_text() + content = dockerfile.read_text(encoding="utf-8") cmd_lines = [ line for line in content.splitlines() if line.startswith("CMD ") ] @@ -503,11 +509,11 @@ def test_all_feature_combinations_render_valid_python(self) -> None: for relative in written: if relative.endswith(".py"): ast.parse( - (Path(tmp) / relative).read_text(), + (Path(tmp) / relative).read_text(encoding="utf-8"), filename=f"{label}:{relative}", ) - main_py = (Path(tmp) / "src/main.py").read_text() + main_py = (Path(tmp) / "src/main.py").read_text(encoding="utf-8") assert "# fastkit:imports" in main_py, label assert "# fastkit:routes" in main_py, label assert '@app.get("/health", tags=["Health"])' in main_py, label @@ -529,8 +535,10 @@ def test_all_feature_combinations_render_valid_python(self) -> None: assert dockerfile.exists() is with_docker, label assert compose.exists() is with_docker, label if with_docker: - assert "FROM python:3.12-slim" in dockerfile.read_text(), label - compose_text = compose.read_text() + assert "FROM python:3.12-slim" in dockerfile.read_text( + encoding="utf-8" + ), label + compose_text = compose.read_text(encoding="utf-8") # Caching is always Redis here, so the service is mandatory. assert "redis:" in compose_text, label if tasks != "None": @@ -635,7 +643,7 @@ def test_async_tasks_add_worker_and_redis_compose_services(self) -> None: # when with tempfile.TemporaryDirectory() as tmp: DynamicConfigGenerator(config, tmp).generate_docker_files() - compose = (Path(tmp) / "docker-compose.yml").read_text() + compose = (Path(tmp) / "docker-compose.yml").read_text(encoding="utf-8") # then assert "worker:" in compose @@ -681,6 +689,28 @@ def test_pagination_utility_calls_add_pagination(self) -> None: assert "Page[Item]" in module assert "add_pagination(app)" in artifacts["src/main.py"] + def test_omitted_pagination_example_is_neither_written_nor_planned( + self, + ) -> None: + """A skipped demo router is absent from both the plan and the output.""" + # given + config = {"project_name": "p", "utilities": ["Pagination", "WebSocket"]} + + with tempfile.TemporaryDirectory() as tmp: + generator = DynamicConfigGenerator( + config, tmp, omit_example_routers=["Pagination"] + ) + + # when + planned = generator.planned_files(include_main=False) + written = generator.generate_all_files(include_main=False) + + # then + assert "src/features/pagination.py" not in planned + assert "src/features/pagination.py" not in written + assert "src/features/websocket.py" in planned + assert "src/features/websocket.py" in written + def test_opentelemetry_instruments_the_app(self) -> None: """OpenTelemetry must instrument the app and configure an exporter.""" # given / when @@ -746,7 +776,7 @@ def test_mysql_gets_a_compose_service(self) -> None: # when with tempfile.TemporaryDirectory() as tmp: DynamicConfigGenerator(config, tmp).generate_docker_files() - compose = (Path(tmp) / "docker-compose.yml").read_text() + compose = (Path(tmp) / "docker-compose.yml").read_text(encoding="utf-8") # then assert "mysql:" in compose @@ -924,9 +954,9 @@ def test_ruff_configuration_is_merged_into_pyproject(self) -> None: # when with tempfile.TemporaryDirectory() as tmp: pyproject = Path(tmp) / "pyproject.toml" - pyproject.write_text('[project]\nname = "p"\n') + pyproject.write_text('[project]\nname = "p"\n', encoding="utf-8") target = DynamicConfigGenerator(config, tmp).apply_ruff_configuration() - content = pyproject.read_text() + content = pyproject.read_text(encoding="utf-8") # then assert target == "pyproject.toml" @@ -943,7 +973,7 @@ def test_ruff_falls_back_to_a_standalone_file(self) -> None: # when with tempfile.TemporaryDirectory() as tmp: target = DynamicConfigGenerator(config, tmp).apply_ruff_configuration() - content = (Path(tmp) / "ruff.toml").read_text() + content = (Path(tmp) / "ruff.toml").read_text(encoding="utf-8") # then assert target == "ruff.toml" @@ -964,6 +994,164 @@ def test_pre_commit_swaps_black_for_ruff_when_ruff_is_selected(self) -> None: assert "psf/black" in without_ruff assert "ruff" not in without_ruff + @pytest.mark.parametrize( + "tooling", [["pre-commit"], ["pre-commit", "ruff"]], ids=["black", "ruff"] + ) + def test_pre_commit_does_not_depend_on_the_hook_shell( + self, tooling: List[str] + ) -> None: + """Hooks must run from a Git GUI shell with no venv and a bare PATH. + + A ``default_language_version`` pin fails every hook on a machine + without that exact ``python3.X``, and a ``language: system`` (or + ``repo: local``) hook needs the tool on the hook shell's PATH. + """ + # given / when + content = self._generate(tooling=tooling)[".pre-commit-config.yaml"] + + # then + assert "default_language_version" not in content + assert "language_version" not in content + assert "python3.12" not in content + # black reads its target version from pyproject.toml instead. + assert "--target-version" not in content + assert not re.search(r"^\s*language:\s*system\b", content, re.M) + assert not re.search(r"^\s*-?\s*repo:\s*(local|meta)\b", content, re.M) + assert re.search(r"^\s*-\s*id:\s*\S", content, re.M) + + def test_black_target_version_moves_into_pyproject(self) -> None: + """Without the hook argument, black must find py312 in pyproject.""" + # given + config = { + "project_name": "P", + "database": {"type": "None"}, + "tooling": ["pre-commit"], + } + + # when + with tempfile.TemporaryDirectory() as tmp: + pyproject = Path(tmp) / "pyproject.toml" + pyproject.write_text( + '[project]\nname = "p"\nrequires-python = ">=3.12"', encoding="utf-8" + ) + written = DynamicConfigGenerator(config, tmp).generate_all_files() + content = pyproject.read_text(encoding="utf-8") + + # then + assert "pyproject.toml" in written + assert '[project]\nname = "p"' in content + assert '[tool.black]\nline-length = 88\ntarget-version = ["py312"]' in content + assert tomllib.loads(content)["tool"]["black"]["target-version"] == ["py312"] + + def test_black_configuration_keeps_an_existing_table(self) -> None: + """A template-shipped ``[tool.black]`` is not duplicated.""" + # given + config = {"project_name": "P", "database": {"type": "None"}} + original = '[project]\nname = "p"\n\n[tool.black]\ntarget-version = ["py313"]\n' + + # when + with tempfile.TemporaryDirectory() as tmp: + pyproject = Path(tmp) / "pyproject.toml" + pyproject.write_text(original, encoding="utf-8") + target = DynamicConfigGenerator(config, tmp).apply_black_configuration() + content = pyproject.read_text(encoding="utf-8") + + # then + assert target == "pyproject.toml" + assert content == original + + def test_black_configuration_needs_a_pyproject(self) -> None: + """black only reads pyproject.toml, so nothing is written without it.""" + # given + config = {"project_name": "P", "database": {"type": "None"}} + + # when + with tempfile.TemporaryDirectory() as tmp: + target = DynamicConfigGenerator(config, tmp).apply_black_configuration() + leftovers = list(Path(tmp).iterdir()) + + # then + assert target is None + assert leftovers == [] + + def test_ruff_tooling_writes_no_black_table(self) -> None: + """ruff replaces black, so pyproject must not configure both.""" + # given + config = { + "project_name": "P", + "database": {"type": "None"}, + "tooling": ["pre-commit", "ruff"], + } + + # when + with tempfile.TemporaryDirectory() as tmp: + pyproject = Path(tmp) / "pyproject.toml" + pyproject.write_text('[project]\nname = "p"\n', encoding="utf-8") + DynamicConfigGenerator(config, tmp).generate_all_files() + content = pyproject.read_text(encoding="utf-8") + + # then + assert "[tool.ruff]" in content + assert "[tool.black]" not in content + + @pytest.mark.parametrize("with_pyproject", [True, False]) + def test_planned_files_lists_the_black_table_only_with_a_pyproject( + self, with_pyproject: bool + ) -> None: + """``--dry-run`` reports the pyproject black edit exactly when it happens.""" + # given + config = { + "project_name": "P", + "database": {"type": "None"}, + "tooling": ["pre-commit"], + } + with tempfile.TemporaryDirectory() as tmp: + if with_pyproject: + (Path(tmp) / "pyproject.toml").write_text( + '[project]\nname = "p"\n', encoding="utf-8" + ) + generator = DynamicConfigGenerator(config, tmp) + + # when + planned = generator.planned_files() + written = generator.generate_all_files() + + # then + assert planned == written + assert ("pyproject.toml" in planned) is with_pyproject + + @pytest.mark.parametrize( + ("tail", "keeps_original"), + [ + ("[tool.black]\nline-length = 100\n", True), + ("[tool.black.extra]\nflag = true\n", True), + ("[tool.other]\nflag = true\n", False), + ], + ids=["declared", "declared-subtable", "absent"], + ) + def test_black_table_detection_survives_invalid_toml( + self, tail: str, keeps_original: bool + ) -> None: + """A pyproject that does not parse falls back to a header search.""" + # given: a duplicate key makes the file invalid TOML + config = {"project_name": "P", "database": {"type": "None"}} + original = '[project]\nname = "p"\nname = "q"\n\n' + tail + + # when + with tempfile.TemporaryDirectory() as tmp: + pyproject = Path(tmp) / "pyproject.toml" + pyproject.write_text(original, encoding="utf-8") + target = DynamicConfigGenerator(config, tmp).apply_black_configuration() + content = pyproject.read_text(encoding="utf-8") + + # then: an existing [tool.black] is never declared a second time + assert target == "pyproject.toml" + if keeps_original: + assert content == original + else: + assert content.startswith(original) + assert content.count("[tool.black]") == 1 + class TestGenerateAllFiles: """``generate_all_files`` is the single write-everything entry point.""" @@ -988,7 +1176,9 @@ def test_writes_every_artifact_to_disk(self) -> None: """Everything the config implies lands under the project directory.""" # given with tempfile.TemporaryDirectory() as tmp: - (Path(tmp) / "pyproject.toml").write_text('[project]\nname = "p"\n') + (Path(tmp) / "pyproject.toml").write_text( + '[project]\nname = "p"\n', encoding="utf-8" + ) generator = DynamicConfigGenerator(self.FULL_CONFIG, tmp) # when @@ -999,7 +1189,7 @@ def test_writes_every_artifact_to_disk(self) -> None: target = Path(tmp) / relative assert target.exists(), relative if relative.endswith(".py"): - ast.parse(target.read_text(), filename=relative) + ast.parse(target.read_text(encoding="utf-8"), filename=relative) for expected in ( "src/main.py", @@ -1032,14 +1222,20 @@ def test_migrate_script_is_executable(self) -> None: generator.generate_all_files() # then - mode = (Path(tmp) / "scripts" / "migrate.sh").stat().st_mode + script = Path(tmp) / "scripts" / "migrate.sh" + assert b"\r\n" not in script.read_bytes() + if os.name == "nt": + pytest.skip("Windows has no POSIX executable bit to check") + mode = script.stat().st_mode assert mode & 0o111, oct(mode) def test_planned_files_matches_what_gets_written(self) -> None: """``--dry-run`` must not lie about what a real run produces.""" # given with tempfile.TemporaryDirectory() as tmp: - (Path(tmp) / "pyproject.toml").write_text('[project]\nname = "p"\n') + (Path(tmp) / "pyproject.toml").write_text( + '[project]\nname = "p"\n', encoding="utf-8" + ) generator = DynamicConfigGenerator(self.FULL_CONFIG, tmp) # when @@ -1055,7 +1251,7 @@ def test_include_main_false_preserves_the_template_entrypoint(self) -> None: with tempfile.TemporaryDirectory() as tmp: main_py = Path(tmp) / "src" / "main.py" main_py.parent.mkdir(parents=True) - main_py.write_text("# template-shipped\n") + main_py.write_text("# template-shipped\n", encoding="utf-8") generator = DynamicConfigGenerator(self.FULL_CONFIG, tmp) # when @@ -1063,7 +1259,7 @@ def test_include_main_false_preserves_the_template_entrypoint(self) -> None: # then assert "src/main.py" not in written - assert main_py.read_text() == "# template-shipped\n" + assert main_py.read_text(encoding="utf-8") == "# template-shipped\n" def test_layout_paths_flow_into_generated_imports(self) -> None: """A domain-starter layout must import from ``src.app``, not ``src``.""" @@ -1085,7 +1281,9 @@ def test_layout_paths_flow_into_generated_imports(self) -> None: assert "src/app/worker.py" in written assert "src/app/features/tasks.py" in written assert "src/app/core/database.py" in written - routes = (Path(tmp) / "src/app/features/tasks.py").read_text() + routes = (Path(tmp) / "src/app/features/tasks.py").read_text( + encoding="utf-8" + ) assert "from src.app.worker import" in routes - main_py = (Path(tmp) / "src/app/main.py").read_text() + main_py = (Path(tmp) / "src/app/main.py").read_text(encoding="utf-8") assert "from src.app.features.tasks import router" in main_py diff --git a/tests/test_backends/test_project_builder_dependency_collector.py b/tests/test_backends/test_project_builder_dependency_collector.py index 5e958a22..da4959ab 100644 --- a/tests/test_backends/test_project_builder_dependency_collector.py +++ b/tests/test_backends/test_project_builder_dependency_collector.py @@ -4,10 +4,31 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import itertools +from typing import Any, Dict, List + +import pytest + +from fastapi_fastkit.backend.package_managers.poetry_manager import ( + _parse_pip_requirement, +) +from fastapi_fastkit.backend.project_builder import ( + DynamicConfigGenerator, + PresetLayoutStrategist, +) +from fastapi_fastkit.backend.project_builder.config_generator import SQL_DATABASES +from fastapi_fastkit.backend.project_builder.config_schema import ( + normalize_project_config, +) from fastapi_fastkit.backend.project_builder.dependency_collector import ( DependencyCollector, + merge_requirements, +) +from fastapi_fastkit.core.settings import ( + FastkitConfig, + FeatureAxis, + MigrationsChoice, ) -from fastapi_fastkit.core.settings import FastkitConfig class TestDependencyCollectorInitialization: @@ -87,7 +108,7 @@ def test_collect_with_postgresql(self) -> None: dependencies = collector.collect_from_config(config) # then - assert "sqlalchemy" in dependencies + assert "sqlalchemy[asyncio]" in dependencies assert "asyncpg" in dependencies assert "fastapi" in dependencies @@ -277,7 +298,7 @@ def test_collect_full_stack_config(self) -> None: assert "fastapi" in dependencies assert "uvicorn" in dependencies # Database - assert "sqlalchemy" in dependencies + assert "sqlalchemy[asyncio]" in dependencies assert "asyncpg" in dependencies # Authentication assert "pyjwt[crypto]" in dependencies @@ -397,7 +418,7 @@ def test_add_database_dependencies_postgresql(self) -> None: collector.add_database_dependencies("PostgreSQL") # then - assert "sqlalchemy" in collector.dependencies + assert "sqlalchemy[asyncio]" in collector.dependencies assert "asyncpg" in collector.dependencies def test_add_database_dependencies_mysql(self) -> None: @@ -410,7 +431,7 @@ def test_add_database_dependencies_mysql(self) -> None: collector.add_database_dependencies("MySQL") # then - assert "sqlalchemy" in collector.dependencies + assert "sqlalchemy[asyncio]" in collector.dependencies assert "aiomysql" in collector.dependencies def test_add_authentication_dependencies_oauth2(self) -> None: @@ -621,3 +642,172 @@ def test_add_feature_dependencies_replays_metadata_strings(self) -> None: assert "alembic" in dependencies assert "ruff" in dependencies assert "fastapi-cache2" not in dependencies + + +class TestMergeRequirements: + """Test cases for merge_requirements (extras-aware de-duplication).""" + + def test_bare_name_folds_into_extras_form(self) -> None: + """``sqlalchemy`` and ``sqlalchemy[asyncio]`` collapse into one entry.""" + assert merge_requirements(["sqlalchemy", "sqlalchemy[asyncio]"]) == [ + "sqlalchemy[asyncio]" + ] + + def test_extras_are_unioned_and_pin_is_kept(self) -> None: + """Extras merge across spellings; the pinned entry's spelling wins.""" + merged = merge_requirements( + ["SQLAlchemy==2.0.52", "sqlalchemy[asyncio]", "sqlalchemy[mypy]"] + ) + assert merged == ["SQLAlchemy[asyncio,mypy]==2.0.52"] + + def test_names_are_compared_canonically(self) -> None: + """``fastapi_users`` and ``fastapi-users[sqlalchemy]`` are one package.""" + merged = merge_requirements(["fastapi_users", "fastapi-users[sqlalchemy]"]) + assert len(merged) == 1 + assert merged[0].endswith("[sqlalchemy]") + + def test_conflicting_specifiers_are_left_alone(self) -> None: + """Different version specifiers are kept so the resolver reports them.""" + assert merge_requirements(["httpx>=0.27", "httpx<0.28"]) == [ + "httpx<0.28", + "httpx>=0.27", + ] + + def test_markers_and_direct_urls_pass_through(self) -> None: + """Entries under different markers, and URL requirements, are untouched.""" + merged = merge_requirements( + [ + "uvloop; sys_platform != 'win32'", + "uvloop", + "pkg @ https://example.com/pkg.whl", + "fastapi", + "fastapi", + ] + ) + assert merged == [ + "fastapi", + "pkg @ https://example.com/pkg.whl", + "uvloop", + "uvloop; sys_platform != 'win32'", + ] + + def test_blank_entries_are_dropped_and_whitespace_trimmed(self) -> None: + """Blank strings never become requirements; padding is stripped.""" + assert merge_requirements(["", " ", " fastapi ", "\tuvicorn\n"]) == [ + "fastapi", + "uvicorn", + ] + + def test_collector_does_not_duplicate_sqlalchemy(self) -> None: + """A custom ``sqlalchemy`` package does not sit next to the extras form.""" + # given + collector = DependencyCollector(FastkitConfig()) + + # when + dependencies = collector.collect_from_config( + {"database": {"type": "SQLite"}, "custom_packages": ["sqlalchemy"]} + ) + + # then + names = [_parse_pip_requirement(dep)[0].lower() for dep in dependencies] + assert names.count("sqlalchemy") == 1 + assert "sqlalchemy[asyncio]" in dependencies + + +def _ships_greenlet(dependencies: List[str]) -> bool: + """Whether a dependency set installs greenlet on a fresh resolve.""" + for dependency in dependencies: + name, extras, _, _ = _parse_pip_requirement(dependency) + name = name.lower() + if name == "greenlet": + return True + if name == "sqlalchemy" and "asyncio" in extras: + return True + return False + + +def _sql_asyncio_cases() -> List[Any]: + """Every database x auth x migrations x preset combination, from the catalog. + + Alembic is only offered for relational databases, so it is paired with + the databases that have a SQLAlchemy URL. + """ + catalog = FastkitConfig.PACKAGE_CATALOG + return [ + pytest.param( + preset, + database, + auth, + migrations, + id=f"{preset}-{database}-{auth}-{migrations}", + ) + for preset, database, auth, migrations in itertools.product( + PresetLayoutStrategist.supported_presets(), + catalog[FeatureAxis.DATABASE], + catalog[FeatureAxis.AUTHENTICATION], + catalog[FeatureAxis.MIGRATIONS], + ) + if migrations != MigrationsChoice.ALEMBIC or database in SQL_DATABASES + ] + + +class TestAsyncSqlalchemyDependencies: + """Generated code that imports sqlalchemy.ext.asyncio must ship greenlet. + + SQLAlchemy 2.1 only installs greenlet through the ``asyncio`` extra, so a + plain ``sqlalchemy`` requirement produces a project that fails at import + with "the greenlet library is required". + """ + + @pytest.mark.parametrize("preset,database,auth,migrations", _sql_asyncio_cases()) + def test_asyncio_imports_resolve_greenlet( + self, preset: str, database: str, auth: str, migrations: str + ) -> None: + # given + config: Dict[str, Any] = normalize_project_config( + { + "project_name": "asyncio-check", + "architecture_preset": preset, + "database": {"type": database}, + "authentication": auth, + "migrations": migrations, + } + ) + strategist = PresetLayoutStrategist(preset) + generator = DynamicConfigGenerator( + config, + "/tmp/asyncio-check", + app_module=strategist.app_module, + main_py_relpath=strategist.profile.main_py_relpath, + db_config_relpath=strategist.profile.db_config_relpath, + auth_config_relpath=strategist.profile.auth_config_relpath, + ) + + # when + artifacts = generator.build_artifacts( + include_main=strategist.should_regenerate_main + ) + uses_asyncio = any( + "sqlalchemy.ext.asyncio" in content for content in artifacts.values() + ) + dependencies = DependencyCollector(FastkitConfig()).collect_from_config(config) + + # then + if uses_asyncio: + assert _ships_greenlet(dependencies), ( + f"{sorted(artifacts)} import sqlalchemy.ext.asyncio but " + f"{dependencies} would not install greenlet" + ) + + def test_every_sql_database_uses_asyncio(self) -> None: + """Guard the parametrised test above against silently checking nothing.""" + catalog = FastkitConfig.PACKAGE_CATALOG[FeatureAxis.DATABASE] + checked = [] + for database in catalog: + config = normalize_project_config( + {"project_name": "p", "database": {"type": database}} + ) + artifacts = DynamicConfigGenerator(config, "/tmp/p").build_artifacts() + if any("sqlalchemy.ext.asyncio" in c for c in artifacts.values()): + checked.append(database) + assert set(checked) >= {"PostgreSQL", "MySQL", "SQLite"} diff --git a/tests/test_backends/test_project_metadata.py b/tests/test_backends/test_project_metadata.py index ceb255ef..17cc82dd 100644 --- a/tests/test_backends/test_project_metadata.py +++ b/tests/test_backends/test_project_metadata.py @@ -6,10 +6,13 @@ import os from pathlib import Path +import pytest + from fastapi_fastkit.backend.main import ( _ensure_pyproject_fastkit_markers, _update_api_router, _update_main_app, + _update_pyproject_dependencies, build_fastkit_metadata_block, insert_import_line, insert_statement_line, @@ -137,6 +140,66 @@ def test_setup_py_is_updated_only_when_present(self, tmp_path: Path) -> None: assert '"httpx"' in (tmp_path / "setup.py").read_text() assert '"httpx"' in (tmp_path / "pyproject.toml").read_text() + def test_legacy_unannotated_install_requires_is_updated( + self, tmp_path: Path + ) -> None: + # given: an old-style setup.py without the ``list[str]`` annotation + (tmp_path / "setup.py").write_text( + "from setuptools import setup\n\n" + 'install_requires = [\n "flask",\n]\n\n' + "setup(install_requires=install_requires)\n" + ) + + # when + update_setup_py_dependencies(str(tmp_path), ["fastapi", "httpx"]) + + # then + content = (tmp_path / "setup.py").read_text() + assert 'install_requires = [\n "fastapi",\n "httpx",\n]' in content + assert "flask" not in content + assert content.endswith("setup(install_requires=install_requires)\n") + + def test_setup_py_without_install_requires_is_left_alone( + self, tmp_path: Path + ) -> None: + # given + original = 'from setuptools import setup\n\nsetup(name="demo")\n' + (tmp_path / "setup.py").write_text(original) + + # when + update_setup_py_dependencies(str(tmp_path), ["fastapi"]) + + # then + assert (tmp_path / "setup.py").read_text() == original + + def test_undecodable_pyproject_is_not_rewritten(self, tmp_path: Path) -> None: + # given: a pyproject saved in a legacy code page + pyproject = tmp_path / "pyproject.toml" + original = b'[project]\nname = "caf\xe9"\ndependencies = []\n' + pyproject.write_bytes(original) + + # when + updated = _update_pyproject_dependencies(str(pyproject), ["fastapi"]) + + # then + assert updated is False + assert pyproject.read_bytes() == original + + def test_undecodable_pyproject_metadata_write_only_warns( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + # given + pyproject = tmp_path / "pyproject.toml" + original = b'[project]\nname = "caf\xe9"\n' + pyproject.write_bytes(original) + + # when: generation continues; the marker block is simply not written + write_fastkit_metadata(str(tmp_path), {"app_module": "src.main:app"}) + + # then + assert "Could not write fastkit metadata" in capsys.readouterr().out + assert pyproject.read_bytes() == original + class TestCodeInsertion: def test_anchor_wins_over_ast(self) -> None: @@ -253,6 +316,25 @@ def test_classic_layout_is_discovered_without_metadata( assert layout["app_module"] == "src.main:app" assert layout["api_router_module"] == "src.api.api" + def test_unreadable_router_candidate_is_skipped(self, tmp_path: Path) -> None: + # given: api/api.py is not UTF-8, router.py declares the router + src_dir = tmp_path / "src" + (src_dir / "api").mkdir(parents=True) + (src_dir / "main.py").write_text( + "from fastapi import FastAPI\napp = FastAPI()\n" + ) + (src_dir / "api" / "api.py").write_bytes(b"# caf\xe9\napi_router = None\n") + (src_dir / "api" / "router.py").write_text( + "from fastapi import APIRouter\n\napi_router = APIRouter()\n" + ) + + # when + layout = resolve_project_layout(str(tmp_path)) + + # then + assert layout["api_router_file"] == str(src_dir / "api" / "router.py") + assert layout["api_router_module"] == "src.api.router" + def test_domain_starter_main_py_gets_the_right_router_import( self, tmp_path: Path ) -> None: diff --git a/tests/test_backends/test_pyproject_merge.py b/tests/test_backends/test_pyproject_merge.py new file mode 100644 index 00000000..2bdf5841 --- /dev/null +++ b/tests/test_backends/test_pyproject_merge.py @@ -0,0 +1,493 @@ +# -------------------------------------------------------------------------- +# pyproject.toml merging done by the package managers. +# +# Templates ship a complete pyproject.toml. The uv / PDM / Poetry managers +# must keep the template's requires-python, [tool.*] tables and the +# [tool.fastapi-fastkit] marker when they write their dependencies into it. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import re +import tomllib +from pathlib import Path +from typing import Any, Dict, List +from unittest.mock import Mock, patch + +import pytest + +from fastapi_fastkit.backend.main import generate_dependency_file_with_manager +from fastapi_fastkit.backend.package_managers.base import BasePackageManager +from fastapi_fastkit.backend.package_managers.pdm_manager import PdmManager +from fastapi_fastkit.backend.package_managers.pip_manager import PipManager +from fastapi_fastkit.backend.package_managers.poetry_manager import PoetryManager +from fastapi_fastkit.backend.package_managers.pyproject import ( + PyprojectMergeError, + declared_requires_python, + ensure_requires_python, + merge_pyproject_tables, + replace_project_dependencies, + split_toml_tables, + toml_string, + update_pep621_pyproject, +) +from fastapi_fastkit.backend.package_managers.uv_manager import UvManager +from fastapi_fastkit.core.settings import ( + DEFAULT_POETRY_PYTHON, + DEFAULT_PYTHON_VERSION, + DEFAULT_REQUIRES_PYTHON, +) + +TEMPLATE_PYPROJECT = """\ +# leading comment +[project] +name = "demo" +version = "0.1.0" +description = "[FastAPI-fastkit templated] demo" +requires-python = ">=3.13" +dependencies = [ + "fastapi>=0.1", + "redis[hiredis]", +] + +[project.optional-dependencies] +dev = ["pytest"] + +[dependency-groups] +dev = [ + "pytest>=8", + "httpx", +] + +[tool.fastapi-fastkit] +managed = true + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src"] + +[tool.black] +line-length = 88 +target-version = ["py312"] +exclude = ''' +/( + \\.git +[not-a-table] +)/ +''' + +[tool.isort] +profile = "black" + +[tool.mypy] +python_version = "3.12" + +[tool.pytest.ini_options] +testpaths = ["tests"] +""" + +DEPENDENCIES = [ + "fastapi", + "uvicorn[standard]>=0.30", + 'tomli; python_version < "3.11"', +] + +KEPT_TOOL_TABLES = ("black", "isort", "mypy", "pytest", "fastapi-fastkit", "hatch") + + +def _load(path: Path) -> Dict[str, Any]: + return tomllib.loads(path.read_text(encoding="utf-8")) + + +# ------------------------------------------------------------------ +# Low-level helpers +# ------------------------------------------------------------------ + + +class TestSplitTomlTables: + def test_round_trips_and_ignores_headers_inside_multiline_strings(self) -> None: + blocks = split_toml_tables(TEMPLATE_PYPROJECT) + + assert "".join(text for _, text in blocks) == TEMPLATE_PYPROJECT + names = [name for name, _ in blocks] + assert names[0] is None + assert "not-a-table" not in names + assert names.count("tool.black") == 1 + assert "tool.pytest.ini_options" in names + + def test_escaped_quotes_do_not_end_a_multiline_string(self) -> None: + # given: ``\"""`` inside a basic multi-line string is an escaped quote + # followed by two quotes, so the header-looking lines stay inside it + content = ( + '[project]\nname = "x"\n' + 'description = """a \\""" [not.a.table]\n[still.not]"""\n' + 'dependencies = ["old"]\n' + ) + + # when + names = [name for name, _ in split_toml_tables(content)] + updated = replace_project_dependencies(content, ["new"]) + + # then + assert names == [None, "project"] + assert updated is not None + data = tomllib.loads(updated) + assert data["project"]["dependencies"] == ["new"] + assert ( + data["project"]["description"] + == tomllib.loads(content)["project"]["description"] + ) + + def test_headers_tomllib_cannot_parse_alone_are_still_split(self) -> None: + # given: header lines that only the fallback pattern understands (the + # caller handles text that is not valid TOML) + content = "[tool.my key]\nx = 1\n[[ tool . other key ]]\ny = 2\n[tool.ok]\n" + + # when + blocks = split_toml_tables(content) + + # then: names are normalised and the text still round-trips + assert [name for name, _ in blocks] == [ + None, + "tool.my key", + "tool.other key", + "tool.ok", + ] + assert "".join(text for _, text in blocks) == content + + +class TestMergePyprojectTables: + def test_replaces_owned_tables_and_keeps_the_rest(self) -> None: + generated = '[build-system]\nrequires = ["poetry-core"]\n' + + merged = merge_pyproject_tables(TEMPLATE_PYPROJECT, generated) + data = tomllib.loads(merged) + + assert data["build-system"] == {"requires": ["poetry-core"]} + assert data["project"]["requires-python"] == ">=3.13" + for tool in KEPT_TOOL_TABLES: + assert tool in data["tool"] + assert merged.startswith("# leading comment\n") + # inserted where the replaced table was, before [tool.hatch...] + assert merged.index("[build-system]") < merged.index("[tool.hatch") + + def test_keeps_sub_tables_of_owned_tables_unless_prefix_owned(self) -> None: + existing = ( + '[tool.poetry]\nname = "x"\n\n[tool.poetry.dependencies]\na = "*"\n' + '\n[tool.poetry.scripts]\nserve = "a:b"\n' + ) + generated = '[tool.poetry]\nname = "y"\n' + + kept = tomllib.loads(merge_pyproject_tables(existing, generated)) + owned = tomllib.loads( + merge_pyproject_tables( + existing, generated, owned_prefixes=("tool.poetry.dependencies",) + ) + ) + + assert kept == { + "tool": { + "poetry": { + "name": "y", + "dependencies": {"a": "*"}, + "scripts": {"serve": "a:b"}, + } + } + } + assert owned == {"tool": {"poetry": {"name": "y", "scripts": {"serve": "a:b"}}}} + + def test_appends_when_nothing_is_replaced(self) -> None: + merged = merge_pyproject_tables( + "[tool.black]\nline-length = 88", "[a]\nb = 1\n" + ) + + assert tomllib.loads(merged) == { + "tool": {"black": {"line-length": 88}}, + "a": {"b": 1}, + } + + def test_crlf_existing_file_gets_crlf_tables(self) -> None: + merged = merge_pyproject_tables( + "[tool.black]\r\nline-length = 88\r\n", "[build-system]\nrequires = []\n" + ) + + assert merged == ( + "[tool.black]\r\nline-length = 88\r\n\r\n[build-system]\r\nrequires = []\r\n" + ) + + def test_owned_prefix_replaces_arrays_of_tables(self) -> None: + existing = ( + '[tool.poetry]\nname = "x"\n\n' + '[[tool.poetry.source]]\nname = "a"\nurl = "u"\n' + ) + generated = ( + '[tool.poetry]\nname = "y"\n\n' + '[[tool.poetry.source]]\nname = "b"\nurl = "v"\n' + ) + + merged = merge_pyproject_tables( + existing, generated, owned_prefixes=("tool.poetry.source",) + ) + + assert tomllib.loads(merged) == { + "tool": {"poetry": {"name": "y", "source": [{"name": "b", "url": "v"}]}} + } + + def test_invalid_existing_toml_raises(self) -> None: + with pytest.raises(PyprojectMergeError): + merge_pyproject_tables("[a]\nb = \n", "[c]\nd = 1\n") + + +class TestProjectTableHelpers: + def test_replace_dependencies_handles_extras_and_markers(self) -> None: + updated = replace_project_dependencies(TEMPLATE_PYPROJECT, DEPENDENCIES) + + assert updated is not None + data = tomllib.loads(updated) + assert data["project"]["dependencies"] == DEPENDENCIES + assert data["project"]["optional-dependencies"] == {"dev": ["pytest"]} + + def test_replace_dependencies_without_array(self) -> None: + content = '[project]\nname = "x"\n\n[tool.black]\n' + + assert replace_project_dependencies(content, ["a"]) is None + inserted = replace_project_dependencies(content, ["a"], insert_missing=True) + assert inserted is not None + assert tomllib.loads(inserted)["project"]["dependencies"] == ["a"] + + def test_replace_dependencies_without_project_table(self) -> None: + content = "[tool.black]\nline-length = 88\n" + + assert replace_project_dependencies(content, ["a"]) is None + assert replace_project_dependencies(content, ["a"], insert_missing=True) is None + + def test_replace_dependencies_refuses_a_dependencies_table(self) -> None: + # given: valid TOML, but ``dependencies`` is a sub-table, not an array + content = '[project]\nname = "x"\n\n[project.dependencies]\na = "1"\n' + + # when / then + with pytest.raises(PyprojectMergeError, match="cannot edit safely"): + replace_project_dependencies(content, ["b"]) + + def test_update_pep621_without_project_table_merges(self) -> None: + existing = "[tool.black]\nline-length = 88\n" + generated = '[project]\nname = "p"\ndependencies = ["a"]\n' + + updated = update_pep621_pyproject(existing, generated, ["a"]) + + assert tomllib.loads(updated) == { + "tool": {"black": {"line-length": 88}}, + "project": {"name": "p", "dependencies": ["a"]}, + } + assert updated.startswith(existing) + + def test_ensure_requires_python_keeps_template_value(self) -> None: + assert ensure_requires_python(TEMPLATE_PYPROJECT) == TEMPLATE_PYPROJECT + + def test_ensure_requires_python_fills_default(self) -> None: + content = '[project]\nname = "x"\n\n[tool.black]\nline-length = 88\n' + + data = tomllib.loads(ensure_requires_python(content)) + + assert data["project"]["requires-python"] == DEFAULT_REQUIRES_PYTHON + assert data["tool"]["black"] == {"line-length": 88} + + def test_declared_requires_python(self) -> None: + assert declared_requires_python(TEMPLATE_PYPROJECT) == ">=3.13" + poetry = '[tool.poetry.dependencies]\npython = "^3.12"\n' + assert declared_requires_python(poetry) == "^3.12" + assert declared_requires_python("[tool.black]\nx = 1\n") is None + + def test_update_pep621_without_existing_file(self) -> None: + assert update_pep621_pyproject(None, "[x]\n", ["a"]) == "[x]\n" + + def test_toml_string_escapes_user_input(self) -> None: + value = 'say "hi"\\ \n\tok\x01' + + assert tomllib.loads(f"v = {toml_string(value)}")["v"] == value + + +def test_shared_python_defaults() -> None: + assert DEFAULT_PYTHON_VERSION == "3.12" + assert DEFAULT_REQUIRES_PYTHON == ">=3.12" + assert DEFAULT_POETRY_PYTHON == "^3.12" + + +# ------------------------------------------------------------------ +# Package managers +# ------------------------------------------------------------------ + +PYPROJECT_MANAGERS = [UvManager, PdmManager, PoetryManager] + + +def _generate(manager_cls: type, project: Path) -> Dict[str, Any]: + manager: BasePackageManager = manager_cls(str(project)) + manager.generate_dependency_file( + DEPENDENCIES, "demo", 'Au "thor"', "a@example.com", 'A "quoted" project' + ) + return _load(project / "pyproject.toml") + + +def _dependency_names(data: Dict[str, Any], manager_cls: type) -> List[str]: + if manager_cls is PoetryManager: + deps = data["tool"]["poetry"]["dependencies"] + return sorted(name for name in deps if name != "python") + return sorted( + re.split(r"[\[;<>=~! ]", dep, maxsplit=1)[0] + for dep in data["project"]["dependencies"] + ) + + +@pytest.mark.parametrize("manager_cls", PYPROJECT_MANAGERS) +class TestManagerKeepsTemplatePyproject: + def test_template_tables_survive(self, manager_cls: type, tmp_path: Path) -> None: + # given + (tmp_path / "pyproject.toml").write_text( + TEMPLATE_PYPROJECT, encoding="utf-8", newline="\n" + ) + + # when + data = _generate(manager_cls, tmp_path) + + # then + assert data["project"]["requires-python"] == ">=3.13" + for tool in KEPT_TOOL_TABLES: + assert tool in data["tool"], tool + assert data["tool"]["fastapi-fastkit"] == {"managed": True} + assert data["dependency-groups"]["dev"] == ["pytest>=8", "httpx"] + assert data["tool"]["black"]["target-version"] == ["py312"] + if manager_cls is PoetryManager: + assert data["tool"]["poetry"]["dependencies"]["python"] == ">=3.13" + assert data["tool"]["poetry"]["group"]["dev"]["dependencies"] == { + "pytest": ">=8", + "httpx": "*", + } + assert data["build-system"]["build-backend"] == "poetry.core.masonry.api" + else: + assert data["project"]["dependencies"] == DEPENDENCIES + assert data["build-system"]["build-backend"] == "hatchling.build" + assert _dependency_names(data, manager_cls) == ["fastapi", "tomli", "uvicorn"] + + def test_crlf_file_keeps_crlf(self, manager_cls: type, tmp_path: Path) -> None: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_bytes(TEMPLATE_PYPROJECT.replace("\n", "\r\n").encode()) + + _generate(manager_cls, tmp_path) + + raw = pyproject.read_bytes() + assert raw.count(b"\n") == raw.count(b"\r\n") + + def test_without_existing_file_uses_shared_floor( + self, manager_cls: type, tmp_path: Path + ) -> None: + data = _generate(manager_cls, tmp_path) + + if manager_cls is PoetryManager: + python = data["tool"]["poetry"]["dependencies"]["python"] + assert python == DEFAULT_POETRY_PYTHON + assert data["tool"]["poetry"]["description"] == 'A "quoted" project' + else: + assert data["project"]["requires-python"] == DEFAULT_REQUIRES_PYTHON + assert data["project"]["description"] == 'A "quoted" project' + assert _dependency_names(data, manager_cls) == ["fastapi", "tomli", "uvicorn"] + + def test_template_without_floor_gets_shared_floor( + self, manager_cls: type, tmp_path: Path + ) -> None: + content = TEMPLATE_PYPROJECT.replace('requires-python = ">=3.13"\n', "") + (tmp_path / "pyproject.toml").write_text(content, encoding="utf-8") + + data = _generate(manager_cls, tmp_path) + + if manager_cls is PoetryManager: + python = data["tool"]["poetry"]["dependencies"]["python"] + assert python == DEFAULT_POETRY_PYTHON + else: + assert data["project"]["requires-python"] == DEFAULT_REQUIRES_PYTHON + + def test_invalid_existing_file_is_backed_up_then_replaced( + self, manager_cls: type, tmp_path: Path + ) -> None: + (tmp_path / "pyproject.toml").write_text("[project\nbroken", encoding="utf-8") + + with patch( + "fastapi_fastkit.backend.package_managers.base.print_warning" + ) as warning: + data = _generate(manager_cls, tmp_path) + + assert _dependency_names(data, manager_cls) == ["fastapi", "tomli", "uvicorn"] + backup = tmp_path / "pyproject.toml.bak" + assert backup.read_text(encoding="utf-8") == "[project\nbroken" + assert "pyproject.toml.bak" in warning.call_args.args[0] + + def test_existing_backup_is_not_overwritten( + self, manager_cls: type, tmp_path: Path + ) -> None: + (tmp_path / "pyproject.toml").write_text("[broken", encoding="utf-8") + (tmp_path / "pyproject.toml.bak").write_text("older", encoding="utf-8") + + _generate(manager_cls, tmp_path) + + assert (tmp_path / "pyproject.toml.bak").read_text(encoding="utf-8") == "older" + assert (tmp_path / "pyproject.toml.bak.1").read_text(encoding="utf-8") == ( + "[broken" + ) + + def test_second_run_is_stable(self, manager_cls: type, tmp_path: Path) -> None: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text(TEMPLATE_PYPROJECT, encoding="utf-8", newline="\n") + + _generate(manager_cls, tmp_path) + first = pyproject.read_text(encoding="utf-8") + _generate(manager_cls, tmp_path) + + assert pyproject.read_text(encoding="utf-8") == first + + +def test_poetry_minimal_pyproject_uses_shared_floor(tmp_path: Path) -> None: + PoetryManager(str(tmp_path))._create_minimal_pyproject() + + data = _load(tmp_path / "pyproject.toml") + assert data["tool"]["poetry"]["dependencies"]["python"] == DEFAULT_POETRY_PYTHON + + +# ------------------------------------------------------------------ +# pip availability / auto-detection +# ------------------------------------------------------------------ + + +class TestPipAvailability: + @patch("fastapi_fastkit.backend.package_managers.base.subprocess.run") + def test_available_without_host_pip_when_venv_can_bootstrap( + self, mock_run: Mock, tmp_path: Path + ) -> None: + import subprocess + + def fake_run(command: List[str], **_: Any) -> Mock: + if "pip" in command: + raise subprocess.CalledProcessError(1, command) + return Mock(returncode=0) + + mock_run.side_effect = fake_run + + assert PipManager(str(tmp_path)).is_available() is True + probe = mock_run.call_args_list[-1].args[0] + assert probe[-1] == "import ensurepip, venv" + + +def test_requirements_txt_follows_the_manager_actually_used(tmp_path: Path) -> None: + """A pip request that auto-detection turned into uv still gets requirements.txt.""" + (tmp_path / "pyproject.toml").write_text(TEMPLATE_PYPROJECT, encoding="utf-8") + (tmp_path / "requirements.txt").write_text("stale==1.0\n", encoding="utf-8") + + with patch( + "fastapi_fastkit.backend.main.PackageManagerFactory.create_manager", + return_value=UvManager(str(tmp_path)), + ): + generate_dependency_file_with_manager(str(tmp_path), DEPENDENCIES, "pip") + + requirements = (tmp_path / "requirements.txt").read_text(encoding="utf-8") + assert requirements.splitlines() == DEPENDENCIES + assert _load(tmp_path / "pyproject.toml")["project"]["dependencies"] == DEPENDENCIES diff --git a/tests/test_backends/test_pyproject_safety.py b/tests/test_backends/test_pyproject_safety.py new file mode 100644 index 00000000..dc8c681e --- /dev/null +++ b/tests/test_backends/test_pyproject_safety.py @@ -0,0 +1,473 @@ +# -------------------------------------------------------------------------- +# pyproject.toml edits never lose or corrupt content fastkit does not own. +# +# Regression tests for the string/comment-blind dependency scanner, the +# splitter's false headers, the over-broad Poetry ownership, the silent +# overwrite of files the merge could not handle, and the semantic +# post-condition that backs all of them. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import copy +import tomllib +from pathlib import Path +from typing import Any, Dict, List, Tuple +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.main import _update_pyproject_dependencies +from fastapi_fastkit.backend.package_managers import pyproject as pyproject_module +from fastapi_fastkit.backend.package_managers.base import BasePackageManager +from fastapi_fastkit.backend.package_managers.pdm_manager import PdmManager +from fastapi_fastkit.backend.package_managers.poetry_manager import ( + PoetryManager, + _poetry_tables, +) +from fastapi_fastkit.backend.package_managers.pyproject import ( + PyprojectMergeError, + ensure_requires_python, + merge_pyproject_tables, + replace_project_dependencies, + split_toml_tables, +) +from fastapi_fastkit.backend.package_managers.uv_manager import UvManager +from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.core.settings import DEFAULT_REQUIRES_PYTHON, FastkitConfig + +DEPS = ["fastapi", "uvicorn[standard]"] + +COMMENT_CLOSE = ( + '[project]\nname="mine"\ndependencies = [\n "a", # drop ] later\n]\n\n' + "[tool.black]\nline-length=120\n" +) +COMMENT_OPEN = ( + 'dependencies = [\n "a", # see [extras\n]\nrequires-python=">=3.12"\n' + 'keywords = ["k"] # ]' +) +BASIC_ML_DESCRIPTION = ( + 'description = """\ndependencies = [ "evil" ]\n"""\ndependencies = ["real"]' +) +LITERAL_ML_DESCRIPTION = ( + "description = '''\ndependencies = [ 'evil' ]\n'''\ndependencies = ['real']" +) + + +def _write(project: Path, text: str) -> Path: + path = project / "pyproject.toml" + path.write_bytes(text.encode("utf-8")) + return path + + +def _generate(manager_cls: type, project: Path) -> None: + manager: BasePackageManager = manager_cls(str(project)) + manager.generate_dependency_file(DEPS, "proj", "a", "a@b", "desc") + + +# ------------------------------------------------------------------ +# A. Unmergeable vs invalid existing files +# ------------------------------------------------------------------ + + +@pytest.mark.parametrize("manager_cls", [UvManager, PdmManager]) +class TestValidFilesAreNeverClobbered: + def test_comment_with_bracket_in_dependencies( + self, manager_cls: type, tmp_path: Path + ) -> None: + path = _write(tmp_path, COMMENT_CLOSE) + + _generate(manager_cls, tmp_path) + + data = tomllib.loads(path.read_text(encoding="utf-8")) + assert data["project"]["name"] == "mine" + assert data["project"]["dependencies"] == DEPS + assert data["tool"]["black"] == {"line-length": 120} + assert not (tmp_path / "pyproject.toml.bak").exists() + + def test_utf8_bom_is_dropped_and_content_kept( + self, manager_cls: type, tmp_path: Path + ) -> None: + path = _write( + tmp_path, + '\ufeff[project]\nname="mine"\nversion="9"\ndependencies=["x"]\n\n' + "[tool.black]\nline-length=120\n", + ) + + _generate(manager_cls, tmp_path) + + raw = path.read_bytes() + assert not raw.startswith(b"\xef\xbb\xbf") + data = tomllib.loads(raw.decode("utf-8")) + assert data["project"]["name"] == "mine" + assert data["project"]["version"] == "9" + assert data["project"]["dependencies"] == DEPS + assert data["tool"]["black"] == {"line-length": 120} + + def test_unsupported_project_shape_raises_and_leaves_file_untouched( + self, manager_cls: type, tmp_path: Path + ) -> None: + original = 'project = {name="a", dependencies=["x"]}\n' + path = _write(tmp_path, original) + + with pytest.raises(BackendExceptions, match="left unchanged"): + _generate(manager_cls, tmp_path) + + assert path.read_text(encoding="utf-8") == original + assert not (tmp_path / "pyproject.toml.bak").exists() + + +def test_poetry_unsupported_dotted_table_raises_and_leaves_file_untouched( + tmp_path: Path, +) -> None: + original = 'tool.poetry.name="a"\n[tool.black]\nx=1\n' + path = _write(tmp_path, original) + + with pytest.raises(BackendExceptions, match="dotted keys or inline tables"): + _generate(PoetryManager, tmp_path) + + assert path.read_text(encoding="utf-8") == original + + +# ------------------------------------------------------------------ +# B. String- and comment-aware dependency replacement +# ------------------------------------------------------------------ + + +class TestReplaceProjectDependencies: + def test_bracket_in_comments_does_not_swallow_following_keys(self) -> None: + content = f'[project]\nname="a"\n{COMMENT_OPEN}\n\n[tool.black]\nx=1\n' + + updated = replace_project_dependencies(content, DEPS) + + assert updated is not None + project = tomllib.loads(updated)["project"] + assert project["dependencies"] == DEPS + assert project["requires-python"] == ">=3.12" + assert project["keywords"] == ["k"] + assert updated.endswith('keywords = ["k"] # ]\n\n[tool.black]\nx=1\n') + + @pytest.mark.parametrize( + "body", [BASIC_ML_DESCRIPTION, LITERAL_ML_DESCRIPTION], ids=["basic", "literal"] + ) + def test_key_inside_multiline_string_is_not_touched(self, body: str) -> None: + content = f'[project]\nname="a"\n{body}\n' + before = tomllib.loads(content)["project"]["description"] + + updated = replace_project_dependencies(content, DEPS) + + assert updated is not None + project = tomllib.loads(updated)["project"] + assert project["description"] == before + assert project["dependencies"] == DEPS + + def test_key_in_another_table_is_not_touched(self) -> None: + content = ( + '[tool.x]\ndependencies = ["other"]\n\n[project]\nname="a"\n' + 'dependencies = ["real"]\n' + ) + + updated = replace_project_dependencies(content, DEPS) + + assert updated is not None + data = tomllib.loads(updated) + assert data["tool"]["x"]["dependencies"] == ["other"] + assert data["project"]["dependencies"] == DEPS + + def test_quoted_key_and_brackets_in_strings(self) -> None: + content = ( + '[project]\nname="a"\n"dependencies"=["a; extra==\'[\'", "b"]\n' + 'version="1"\n' + ) + + updated = replace_project_dependencies(content, DEPS) + + assert updated is not None + assert tomllib.loads(updated)["project"] == { + "name": "a", + "dependencies": DEPS, + "version": "1", + } + + def test_update_pyproject_dependencies_writes_valid_toml( + self, tmp_path: Path + ) -> None: + path = _write( + tmp_path, + '[project]\nname="mine"\ndependencies = [\n "a", # drop ] later\n' + ' "b",\n]\n\n[tool.black]\nline-length=120\n', + ) + + assert _update_pyproject_dependencies(str(path), ["fastapi"]) is True + + data = tomllib.loads(path.read_text(encoding="utf-8")) + assert data["project"] == {"name": "mine", "dependencies": ["fastapi"]} + assert data["tool"]["black"] == {"line-length": 120} + + def test_update_pyproject_dependencies_leaves_unsupported_file_alone( + self, tmp_path: Path + ) -> None: + original = 'project = {name="a", dependencies=["x"]}\n' + path = _write(tmp_path, original) + + assert _update_pyproject_dependencies(str(path), ["fastapi"]) is False + assert path.read_text(encoding="utf-8") == original + + +# ------------------------------------------------------------------ +# C. The semantic post-condition catches scanner mistakes +# ------------------------------------------------------------------ + + +class TestPostCondition: + def test_replace_rejects_an_edit_that_loses_other_keys(self) -> None: + content = '[project]\nname="a"\ndependencies = ["x"]\nversion = "1"\n' + real = pyproject_module._statements + + def overreaching(block_text: str, has_header: bool) -> List[Any]: + statements = real(block_text, has_header) + for statement in statements: + if statement.key == "dependencies": + # Pretend the array ran to the end of the table. + statement.value_end = len(block_text.rstrip("\n")) + return statements + + with patch.object(pyproject_module, "_statements", overreaching): + with pytest.raises(PyprojectMergeError, match="does not own"): + replace_project_dependencies(content, DEPS) + + def test_merge_rejects_an_edit_that_loses_unowned_tables(self) -> None: + existing = '[tool.poetry]\nname="a"\n\n[tool.black]\nx=1\n' + real = pyproject_module._split_blocks + + def blind(content: str) -> List[Any]: + blocks = real(content) + # Pretend [tool.black] was part of the [tool.poetry] block. + if len(blocks) == 3 and blocks[2].name == "tool.black": + blocks[1].text += blocks[2].text + del blocks[2] + return blocks + + with patch.object(pyproject_module, "_split_blocks", blind): + with pytest.raises(PyprojectMergeError, match="does not own"): + merge_pyproject_tables(existing, '[tool.poetry]\nname = "b"\n') + + def test_invalid_result_is_rejected(self) -> None: + with patch.object( + pyproject_module, "render_dependency_array", lambda *_: "[ broken" + ): + with pytest.raises(PyprojectMergeError, match="invalid TOML"): + replace_project_dependencies('[project]\ndependencies=["x"]\n', DEPS) + + +# ------------------------------------------------------------------ +# D. Splitter false positives +# ------------------------------------------------------------------ + + +class TestSplitter: + def test_inline_array_on_its_own_line_is_not_a_header(self) -> None: + content = '[tool.poetry]\nname="a"\nmatrix = [\n ["x"]\n]\n[tool.black]\nx=1\n' + + names = [name for name, _ in split_toml_tables(content)] + + assert names == [None, "tool.poetry", "tool.black"] + + def test_quoted_header_parts_are_normalised(self) -> None: + content = '[tool."poetry"]\nname="a"\n[ tool . "black" ]\nx=1\n' + + names = [name for name, _ in split_toml_tables(content)] + + assert names == [None, "tool.poetry", "tool.black"] + + def test_quoted_table_is_replaced_not_duplicated(self) -> None: + merged = merge_pyproject_tables( + '[tool."poetry"]\nname="a"\n[tool.black]\nx=1\n', + '[tool.poetry]\nname = "b"\n', + ) + + assert tomllib.loads(merged) == { + "tool": {"poetry": {"name": "b"}, "black": {"x": 1}} + } + + def test_dotted_key_preamble_fails_closed(self) -> None: + with pytest.raises(PyprojectMergeError, match="dotted keys"): + merge_pyproject_tables( + 'tool.poetry.name="a"\n[tool.black]\nx=1\n', + '[tool.poetry]\nname = "b"\n', + ) + + def test_inline_table_project_fails_closed(self) -> None: + with pytest.raises(PyprojectMergeError, match="inline table"): + replace_project_dependencies( + 'project = {name="a", dependencies=["x"]}\n', DEPS + ) + + +# ------------------------------------------------------------------ +# E. Poetry only owns what it writes +# ------------------------------------------------------------------ + + +def test_poetry_keeps_sources_scripts_other_groups_and_extra_keys( + tmp_path: Path, +) -> None: + path = _write( + tmp_path, + '[tool.poetry]\nname="a"\nhomepage = "https://example.com"\n' + 'matrix = [\n ["x"]\n]\n\n' + '[[tool.poetry.source]]\nname="private"\nurl="https://x"\n' + 'priority="primary"\n\n' + '[tool.poetry.dependencies]\npython = "^3.12"\nold = "*"\n\n' + '[tool.poetry.dependencies.pinned]\nversion = "1"\n\n' + '[tool.poetry.group.docs.dependencies]\nmkdocs="*"\n\n' + '[tool.poetry.scripts]\nserve="a:b"\n\n[tool.black]\nx=1\n', + ) + + _generate(PoetryManager, tmp_path) + first = path.read_text(encoding="utf-8") + _generate(PoetryManager, tmp_path) + + assert path.read_text(encoding="utf-8") == first + poetry = tomllib.loads(first)["tool"]["poetry"] + assert poetry["name"] == "proj" + assert poetry["homepage"] == "https://example.com" + assert poetry["matrix"] == [["x"]] + assert poetry["source"] == [ + {"name": "private", "url": "https://x", "priority": "primary"} + ] + assert poetry["group"]["docs"]["dependencies"] == {"mkdocs": "*"} + assert poetry["scripts"] == {"serve": "a:b"} + # The dependency tables (sub-tables included) are regenerated. + assert poetry["dependencies"] == { + "python": "^3.12", + "fastapi": "*", + "uvicorn": {"version": "*", "extras": ["standard"]}, + } + + +# ------------------------------------------------------------------ +# F. dynamic metadata +# ------------------------------------------------------------------ + + +class TestDynamic: + def test_dynamic_dependencies_are_not_added(self) -> None: + content = '[project]\nname="a"\ndynamic = ["dependencies"]\n' + + assert ( + replace_project_dependencies(content, DEPS, insert_missing=True) == content + ) + + def test_dynamic_requires_python_is_not_added(self) -> None: + content = '[project]\nname="a"\ndynamic = ["requires-python"]\n' + + assert ensure_requires_python(content) == content + + def test_manager_respects_dynamic(self, tmp_path: Path) -> None: + original = ( + '[project]\nname="a"\ndynamic = ["dependencies", "requires-python"]\n' + ) + path = _write(tmp_path, original) + + _generate(UvManager, tmp_path) + + assert path.read_text(encoding="utf-8") == original + + +# ------------------------------------------------------------------ +# Property: every template, every manager, every encoding variant +# ------------------------------------------------------------------ + +_TEMPLATE_ROOT = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) +_TEMPLATES = sorted( + d.name for d in _TEMPLATE_ROOT.iterdir() if (d / "pyproject.toml-tpl").is_file() +) +_POETRY_REGENERATED_KEYS = ( + "name", + "version", + "description", + "authors", + "readme", + "license", + "packages", +) + + +def _remove(doc: Dict[str, Any], path: Tuple[str, ...]) -> None: + node: Any = doc + for part in path[:-1]: + node = node.get(part, {}) if isinstance(node, dict) else {} + if isinstance(node, dict): + node.pop(path[-1], None) + + +def _without_owned( + data: Dict[str, Any], manager_cls: type, before: Dict[str, Any] +) -> Dict[str, Any]: + doc = copy.deepcopy(data) + if manager_cls is PoetryManager: + for key in _POETRY_REGENERATED_KEYS: + _remove(doc, ("tool", "poetry", key)) + _remove(doc, ("tool", "poetry", "dependencies")) + _remove(doc, ("tool", "poetry", "group", "dev", "dependencies")) + _remove(doc, ("build-system",)) + for path in ( + ("tool", "poetry", "group", "dev"), + ("tool", "poetry", "group"), + ("tool", "poetry"), + ): + node: Any = doc + for part in path: + node = node.get(part) if isinstance(node, dict) else None + if node == {}: + _remove(doc, path) + else: + _remove(doc, ("project", "dependencies")) + if "requires-python" not in before.get("project", {}): + _remove(doc, ("project", "requires-python")) + return doc + + +def test_every_template_is_covered() -> None: + assert len(_TEMPLATES) == 12 + + +@pytest.mark.parametrize("bom", [False, True], ids=["nobom", "bom"]) +@pytest.mark.parametrize("eol", ["\n", "\r\n"], ids=["lf", "crlf"]) +@pytest.mark.parametrize( + "manager_cls", [UvManager, PdmManager, PoetryManager], ids=["uv", "pdm", "poetry"] +) +@pytest.mark.parametrize("template", _TEMPLATES) +def test_template_pyproject_keeps_everything_but_owned_parts( + template: str, manager_cls: type, eol: str, bom: bool, tmp_path: Path +) -> None: + raw = (_TEMPLATE_ROOT / template / "pyproject.toml-tpl").read_bytes() + text = raw.decode("utf-8").replace("\r\n", "\n") + before = tomllib.loads(text) + path = _write(tmp_path, ("\ufeff" if bom else "") + text.replace("\n", eol)) + + _generate(manager_cls, tmp_path) + first = path.read_bytes() + _generate(manager_cls, tmp_path) + + assert path.read_bytes() == first, "second run must be a no-op" + assert not first.startswith(b"\xef\xbb\xbf") + if eol == "\r\n": + assert first.count(b"\n") == first.count(b"\r\n") + else: + assert b"\r\n" not in first + after = tomllib.loads(first.decode("utf-8")) + assert _without_owned(after, manager_cls, before) == _without_owned( + before, manager_cls, before + ) + if manager_cls is PoetryManager: + deps = after["tool"]["poetry"]["dependencies"] + assert sorted(name for name in deps if name != "python") == [ + "fastapi", + "uvicorn", + ] + else: + assert after["project"]["dependencies"] == DEPS + assert after["project"]["requires-python"] == before["project"].get( + "requires-python", DEFAULT_REQUIRES_PYTHON + ) diff --git a/tests/test_backends/test_ruff_config_fastapi.py b/tests/test_backends/test_ruff_config_fastapi.py new file mode 100644 index 00000000..7ad55e72 --- /dev/null +++ b/tests/test_backends/test_ruff_config_fastapi.py @@ -0,0 +1,143 @@ +# -------------------------------------------------------------------------- +# The generated ruff configuration must accommodate FastAPI. +# +# The generated lint config selects flake8-bugbear (``B``). Without marking +# FastAPI's ``Depends()`` / ``Query()`` / ... as immutable calls, B008 flags +# every endpoint signature and the project's own ruff pre-commit hook fails +# on a freshly generated project. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import shutil +import subprocess +import tomllib +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +from fastapi_fastkit.backend.project_builder.config_generator import ( + DynamicConfigGenerator, +) + +#: FastAPI callables that are meant to be called in argument defaults. +FASTAPI_PARAM_CALLS = ( + "fastapi.Body", + "fastapi.Cookie", + "fastapi.Depends", + "fastapi.File", + "fastapi.Form", + "fastapi.Header", + "fastapi.Path", + "fastapi.Query", + "fastapi.Security", +) + +CONFIG: Dict[str, Any] = { + "project_name": "P", + "database": {"type": "None"}, + "tooling": ["ruff"], +} + +SAMPLE_ROUTER = """\ +from fastapi import APIRouter, Depends, Query + +router = APIRouter() + + +class Service: + pass + + +def get_service() -> Service: + return Service() + + +# Mutable annotations on purpose: B008 skips parameters annotated with an +# immutable type, so these would not exercise the FastAPI accommodation. +@router.get("/") +def read( + tags: list[str] | None = Query(default=None), + service: Service = Depends(get_service), +) -> list[str]: + return tags or [] + + +def make_items(): + return [] + + +def not_a_dependency(items: list[int] = make_items()) -> list[int]: + return items +""" + + +def _immutable_calls(lint_table: Dict[str, Any]) -> List[str]: + return lint_table["flake8-bugbear"]["extend-immutable-calls"] + + +def test_pyproject_ruff_config_marks_fastapi_calls_immutable(tmp_path: Path) -> None: + # given + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text('[project]\nname = "p"\n', encoding="utf-8") + + # when + target = DynamicConfigGenerator(CONFIG, str(tmp_path)).apply_ruff_configuration() + parsed = tomllib.loads(pyproject.read_text(encoding="utf-8")) + + # then + assert target == "pyproject.toml" + lint = parsed["tool"]["ruff"]["lint"] + assert "B" in lint["select"] + calls = _immutable_calls(lint) + for name in FASTAPI_PARAM_CALLS: + assert name in calls, name + # B008 stays enabled for real mutable defaults: no blanket ignore. + assert "B008" not in lint.get("ignore", []) + assert "B" not in lint.get("ignore", []) + + +def test_standalone_ruff_toml_marks_fastapi_calls_immutable(tmp_path: Path) -> None: + # given: no pyproject.toml, so a bare ruff.toml is written + + # when + target = DynamicConfigGenerator(CONFIG, str(tmp_path)).apply_ruff_configuration() + parsed = tomllib.loads((tmp_path / "ruff.toml").read_text(encoding="utf-8")) + + # then + assert target == "ruff.toml" + assert "tool" not in parsed + calls = _immutable_calls(parsed["lint"]) + for name in FASTAPI_PARAM_CALLS: + assert name in calls, name + + +@pytest.mark.skipif(shutil.which("ruff") is None, reason="ruff is not installed") +@pytest.mark.parametrize( + "with_pyproject", [True, False], ids=["pyproject", "ruff.toml"] +) +def test_ruff_accepts_fastapi_defaults_but_flags_mutable_ones( + tmp_path: Path, with_pyproject: bool +) -> None: + # given + if with_pyproject: + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "p"\n', encoding="utf-8" + ) + DynamicConfigGenerator(CONFIG, str(tmp_path)).apply_ruff_configuration() + (tmp_path / "router.py").write_text(SAMPLE_ROUTER, encoding="utf-8") + + # when + result = subprocess.run( + ["ruff", "check", "--no-cache", "--output-format", "concise", "router.py"], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + + # then: only the genuine call in a default is reported + findings = [line for line in result.stdout.splitlines() if "router.py:" in line] + assert len(findings) == 1, result.stdout + result.stderr + assert "B008" in findings[0] + assert "make_items" in findings[0] diff --git a/tests/test_backends/test_safety_regressions.py b/tests/test_backends/test_safety_regressions.py index 9ae3c0e9..6a8da6a1 100644 --- a/tests/test_backends/test_safety_regressions.py +++ b/tests/test_backends/test_safety_regressions.py @@ -172,7 +172,8 @@ def test_declining_the_overwrite_prompt_writes_nothing(self) -> None: # when with ( patch( - "fastapi_fastkit.backend.scaffolder.sys.stdin.isatty", return_value=True + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=True, ), patch( "fastapi_fastkit.backend.scaffolder.click.confirm", return_value=False diff --git a/tests/test_backends/test_transducer.py b/tests/test_backends/test_transducer.py index 974fd017..2c338d7f 100644 --- a/tests/test_backends/test_transducer.py +++ b/tests/test_backends/test_transducer.py @@ -412,12 +412,17 @@ def test_ensure_directory_exists_existing_directory(self) -> None: def test_ensure_directory_exists_permission_error(self) -> None: """Test _ensure_directory_exists raises on failure.""" - # given - new_dir = "/invalid/path/that/cannot/be/created" + # given: a directory below a regular file can never be created. (An + # absolute path such as "/invalid/..." is creatable on Windows, where + # it resolves to the current drive and CI runs as an administrator.) + blocker = self.dest_path / "not-a-directory" + blocker.write_text("file", encoding="utf-8") + new_dir = str(blocker / "child") # when & then - with pytest.raises(TemplateExceptions): + with pytest.raises(TemplateExceptions, match="Failed to create directory"): _ensure_directory_exists(new_dir) + assert blocker.is_file() def test_copy_template_file_success(self) -> None: """Test _copy_template_file with successful copy.""" @@ -614,6 +619,7 @@ def test_crlf_text_templates_are_converted_to_lf(self) -> None: "setup.cfg-tpl": b"[flake8]\r\nmax-line-length = 88\r\n", "alembic.ini-tpl": b"[alembic]\r\nscript_location = m\r\n", ".env-tpl": b"ENVIRONMENT=development\r\nSECRET_KEY=changethis\r\n", + ".env.example-tpl": b"ENVIRONMENT=development\r\nSECRET_KEY=x\r\n", "Dockerfile-tpl": b"FROM python:3.12\r\nWORKDIR /app\r\n", "Makefile-tpl": b"all:\r\n\techo hi\r\n", "script.py.mako-tpl": b"# ${message}\r\n", @@ -621,6 +627,7 @@ def test_crlf_text_templates_are_converted_to_lf(self) -> None: "requirements.txt-tpl": b"fastapi\r\nuvicorn\r\n", # Extension-less text files (alembic ships a bare ``README``). "README-tpl": b"Generic single-database configuration.\r\n", + ".gitattributes-tpl": b"* text=auto\r\n*.sh text eol=lf\r\n", } for name, payload in crlf_files.items(): (self.source_path / name).write_bytes(payload) @@ -648,6 +655,8 @@ def test_executable_bit_survives_normalization(self) -> None: # then converted = self.dest_path / "pre-start.sh" assert converted.read_bytes() == b"#!/usr/bin/env bash\nexit 0\n" + if os.name == "nt": + pytest.skip("Windows has no POSIX executable bit to check") assert os.access(str(converted), os.X_OK) assert converted.stat().st_mode & 0o111 == 0o111 diff --git a/tests/test_backends/test_windows_portability.py b/tests/test_backends/test_windows_portability.py new file mode 100644 index 00000000..1ebf6774 --- /dev/null +++ b/tests/test_backends/test_windows_portability.py @@ -0,0 +1,462 @@ +# -------------------------------------------------------------------------- +# Windows portability of the generation backend, checked on every OS. +# +# - generated files are UTF-8 with LF line endings even when the platform +# default would translate "\n" to "\r\n" (simulated, see tests/windows_sim) +# - in-place rewrites keep a file's own line endings byte for byte +# - Windows paths (backslashes, other drives) map to dotted modules +# - template requirements never force a POSIX-only package onto Windows +# - template READMEs decode regardless of the locale codec +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ntpath +import os +from pathlib import Path +from typing import List +from unittest.mock import patch + +import pytest +from packaging.markers import Marker +from packaging.requirements import Requirement + +from fastapi_fastkit.backend.main import ( + _dotted_module, + _process_pyproject_file, + _update_main_app, + _update_pyproject_dependencies, + replace_placeholders_in_project, + write_fastkit_metadata, +) +from fastapi_fastkit.backend.project_builder.config_generator import ( + DynamicConfigGenerator, +) +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, + app_module_from_main_path, + app_module_from_relpath, +) +from fastapi_fastkit.backend.route_wiring import register_router +from fastapi_fastkit.core.settings import FastkitConfig +from fastapi_fastkit.utils.config_file import save_project_config +from fastapi_fastkit.utils.textio import ( + read_text_preserving_newlines, + write_generated_text, + write_text_preserving_newlines, +) +from tests.windows_sim import crlf_files, windows_newline_default + +TEMPLATE_ROOT = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + +#: Packages that do not build or install on Windows. +POSIX_ONLY_PACKAGES = frozenset({"uvloop"}) + + +def _crlf(text: str) -> bytes: + return text.replace("\n", "\r\n").encode("utf-8") + + +def _only_crlf(data: bytes) -> bool: + """Every newline in ``data`` is ``\\r\\n`` (and there is at least one).""" + return data.count(b"\n") > 0 and data.count(b"\n") == data.count(b"\r\n") + + +# -------------------------------------------------------------------------- +# Simulation sanity +# -------------------------------------------------------------------------- + + +def test_simulation_really_translates_unset_newline(tmp_path: Path) -> None: + """Guard against a vacuous simulation: a naive write must turn CRLF.""" + target = tmp_path / "naive.txt" + with windows_newline_default(): + with open(target, "w", encoding="utf-8") as f: + f.write("a\nb\n") + (tmp_path / "naive2.txt").write_text("a\n", encoding="utf-8") + assert target.read_bytes() == b"a\r\nb\r\n" + assert (tmp_path / "naive2.txt").read_bytes() == b"a\r\n" + + +# -------------------------------------------------------------------------- +# textio helpers +# -------------------------------------------------------------------------- + + +class TestTextIOHelpers: + def test_generated_text_is_lf_under_windows_default(self, tmp_path: Path) -> None: + target = tmp_path / "gen.sh" + with windows_newline_default(): + write_generated_text(target, "#!/bin/sh\necho ü\n") + assert target.read_bytes() == "#!/bin/sh\necho ü\n".encode("utf-8") + + def test_crlf_file_round_trips_byte_for_byte(self, tmp_path: Path) -> None: + target = tmp_path / "f.toml" + original = _crlf('[project]\nname = "x"\n') + target.write_bytes(original) + + text, newline = read_text_preserving_newlines(target) + assert text == '[project]\nname = "x"\n' + with windows_newline_default(): + write_text_preserving_newlines(target, text, newline) + + assert target.read_bytes() == original + + def test_crlf_file_edit_keeps_crlf_everywhere(self, tmp_path: Path) -> None: + target = tmp_path / "f.toml" + target.write_bytes(_crlf("a = 1\n")) + + text, newline = read_text_preserving_newlines(target) + write_text_preserving_newlines(target, text + "b = 2\nc = 3\n", newline) + + assert target.read_bytes() == b"a = 1\r\nb = 2\r\nc = 3\r\n" + + @pytest.mark.parametrize( + "original", + [b"a\nb\n", b"a\r\nb\nc\r\n", b"no newline", b""], + ids=["lf", "mixed", "single-line", "empty"], + ) + def test_non_crlf_files_are_untouched( + self, tmp_path: Path, original: bytes + ) -> None: + target = tmp_path / "f.txt" + target.write_bytes(original) + + text, newline = read_text_preserving_newlines(target) + with windows_newline_default(): + write_text_preserving_newlines(target, text, newline) + + assert target.read_bytes() == original + + +# -------------------------------------------------------------------------- +# In-place rewrites preserve line endings +# -------------------------------------------------------------------------- + + +class TestInPlaceRewritesPreserveLineEndings: + def test_placeholder_substitution_keeps_crlf(self, tmp_path: Path) -> None: + readme = tmp_path / "README.md" + readme.write_bytes(_crlf("# \n\nby \n")) + + rewritten = replace_placeholders_in_project( + str(tmp_path), {"": "demo", "": "me"} + ) + + assert rewritten == ["README.md"] + assert readme.read_bytes() == _crlf("# demo\n\nby me\n") + + def test_placeholder_substitution_keeps_lf_under_windows_default( + self, tmp_path: Path + ) -> None: + readme = tmp_path / "README.md" + readme.write_bytes(b"# \n") + + with windows_newline_default(): + replace_placeholders_in_project(str(tmp_path), {"": "demo"}) + + assert readme.read_bytes() == b"# demo\n" + + def test_pyproject_metadata_injection_keeps_crlf(self, tmp_path: Path) -> None: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_bytes( + _crlf( + "[project]\n" + 'name = ""\n' + 'description = ""\n' + "\n" + "[tool.ruff]\n" + "line-length = 88\n" + ) + ) + + _process_pyproject_file(str(pyproject), "demo", "me", "me@example.com", "d") + + data = pyproject.read_bytes() + assert _only_crlf(data), data + assert b'name = "demo"' in data + assert b"[tool.fastapi-fastkit]\r\nmanaged = true\r\n" in data + + def test_fastkit_metadata_rewrite_keeps_crlf(self, tmp_path: Path) -> None: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_bytes( + _crlf( + '[project]\nname = "demo"\n\n' + "[tool.fastapi-fastkit]\nmanaged = true\n\n" + "[tool.ruff]\nline-length = 88\n" + ) + ) + + write_fastkit_metadata( + str(tmp_path), + {"template": "fastapi-default", "app_module": "src.main:app"}, + ) + + data = pyproject.read_bytes() + assert _only_crlf(data), data + assert b'app_module = "src.main:app"\r\n' in data + assert b"[tool.ruff]\r\nline-length = 88\r\n" in data + + def test_fastkit_metadata_rewrite_keeps_lf_under_windows_default( + self, tmp_path: Path + ) -> None: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_bytes(b'[project]\nname = "demo"\n') + + with windows_newline_default(): + write_fastkit_metadata(str(tmp_path), {"template": "fastapi-default"}) + + assert b"\r" not in pyproject.read_bytes() + + def test_dependency_rewrite_keeps_crlf(self, tmp_path: Path) -> None: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_bytes( + _crlf('[project]\nname = "demo"\ndependencies = [\n "old",\n]\n') + ) + + assert _update_pyproject_dependencies(str(pyproject), ["fastapi", "uvicorn"]) + + data = pyproject.read_bytes() + assert _only_crlf(data), data + assert b' "fastapi",\r\n "uvicorn",\r\n' in data + assert b"old" not in data + + def test_main_app_update_keeps_crlf(self, tmp_path: Path) -> None: + src = tmp_path / "src" + src.mkdir() + main_py = src / "main.py" + main_py.write_bytes(_crlf("from fastapi import FastAPI\n\napp = FastAPI()\n")) + + _update_main_app(str(src), "users") + + data = main_py.read_bytes() + assert _only_crlf(data), data + assert b"from src.api.api import api_router\r\n" in data + assert b"app.include_router(api_router)" in data + + def test_router_registration_keeps_crlf(self, tmp_path: Path) -> None: + api = tmp_path / "api.py" + api.write_bytes( + _crlf("from fastapi import APIRouter\n\napi_router = APIRouter()\n") + ) + + register_router( + {"api_dir": str(tmp_path), "api_router_file": str(api)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + data = api.read_bytes() + assert _only_crlf(data), data + assert b"from .routes import users\r\n" in data + + def test_new_router_module_is_lf_under_windows_default( + self, tmp_path: Path + ) -> None: + api = tmp_path / "api" / "api.py" + + with windows_newline_default(): + register_router( + {"api_dir": str(api.parent), "api_router_file": str(api)}, + "from .routes import users", + 'api_router.include_router(users.router, prefix="/users")', + ) + + assert crlf_files(api.parent) == [] + assert b"from .routes import users\n" in api.read_bytes() + + def test_preset_router_wiring_keeps_crlf(self, tmp_path: Path) -> None: + main_py = tmp_path / "src" / "main.py" + main_py.parent.mkdir(parents=True) + main_py.write_bytes( + _crlf( + "from fastapi import FastAPI\n\n# fastkit:imports\n\n" + "app = FastAPI()\n\n# fastkit:routes\n" + ) + ) + + wired = PresetLayoutStrategist("classic-layered").wire_generated_routers( + str(tmp_path), {"async_tasks": "Celery"} + ) + + data = main_py.read_bytes() + assert wired == ["Background tasks"] + assert _only_crlf(data), data + assert b"app.include_router(tasks_router)\r\n" in data + + def test_ruff_merge_keeps_crlf(self, tmp_path: Path) -> None: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_bytes(_crlf('[project]\nname = "demo"\n')) + + DynamicConfigGenerator( + {"tooling": ["ruff"]}, str(tmp_path) + ).apply_ruff_configuration() + + data = pyproject.read_bytes() + assert _only_crlf(data), data + assert b"[tool.ruff]" in data + + +# -------------------------------------------------------------------------- +# Generated content is LF even with a translating platform default +# -------------------------------------------------------------------------- + + +class TestGeneratedContentIsLF: + FULL_CONFIG = { + "project_name": "Everything App", + "description": "All features at once", + "database": {"type": "PostgreSQL"}, + "authentication": "JWT", + "async_tasks": "Celery", + "caching": "Redis", + "monitoring": "Prometheus", + "logging": "structured", + "testing": "Advanced", + "migrations": "Alembic", + "utilities": ["CORS", "Rate-Limiting", "WebSocket", "Pagination"], + "tooling": ["ruff", "pre-commit", "github-actions", "devcontainer", "makefile"], + "deployment": ["Docker", "docker-compose"], + } + + def test_dynamic_config_artifacts_are_lf(self, tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_bytes(b'[project]\nname = "p"\n') + generator = DynamicConfigGenerator(self.FULL_CONFIG, str(tmp_path)) + + with windows_newline_default(): + written = generator.generate_all_files() + + assert "scripts/migrate.sh" in written + assert "Dockerfile" in written + assert crlf_files(tmp_path) == [] + + def test_standalone_ruff_toml_is_lf(self, tmp_path: Path) -> None: + with windows_newline_default(): + DynamicConfigGenerator( + {"tooling": ["ruff"]}, str(tmp_path) + ).apply_ruff_configuration() + + assert (tmp_path / "ruff.toml").is_file() + assert crlf_files(tmp_path) == [] + + @pytest.mark.parametrize("extension", [".json", ".toml"]) + def test_saved_config_is_lf(self, tmp_path: Path, extension: str) -> None: + path = tmp_path / f"fastkit{extension}" + with windows_newline_default(): + save_project_config( + {"project_name": "x", "utilities": ["CORS", "WebSocket"]}, str(path) + ) + assert b"\r" not in path.read_bytes() + + +# -------------------------------------------------------------------------- +# Windows paths to dotted modules (audit #13) +# -------------------------------------------------------------------------- + + +class TestWindowsPathsToModules: + def test_backslash_relpath_to_app_module(self) -> None: + assert app_module_from_relpath("src\\app\\main.py") == "src.app.main:app" + + def test_dotted_module_with_windows_paths(self) -> None: + with patch("os.path.relpath", ntpath.relpath): + assert _dotted_module("C:\\work\\proj", "C:\\work\\proj\\src\\app") == ( + "src.app" + ) + assert _dotted_module("C:\\work\\proj", "C:\\work\\proj") == "" + + def test_dotted_module_across_drives_does_not_raise(self) -> None: + with patch("os.path.relpath", ntpath.relpath): + assert _dotted_module("C:\\work\\proj", "D:\\elsewhere\\src") == "src" + + def test_dotted_module_posix(self, tmp_path: Path) -> None: + package = tmp_path / "src" / "app" + assert _dotted_module(str(tmp_path), str(package)) == "src.app" + + def test_app_module_from_main_path_with_windows_paths(self) -> None: + with patch("os.path.relpath", ntpath.relpath): + assert ( + app_module_from_main_path( + "C:\\work\\proj", "C:\\work\\proj\\src\\app\\main.py" + ) + == "src.app.main:app" + ) + + def test_app_module_from_main_path_across_drives(self) -> None: + with patch("os.path.relpath", ntpath.relpath): + assert ( + app_module_from_main_path("C:\\work\\proj", "D:\\other\\main.py") + == "src.main:app" + ) + + +# -------------------------------------------------------------------------- +# Template requirements are installable on Windows (audit #9) +# -------------------------------------------------------------------------- + + +def _requirement_files() -> List[Path]: + return sorted(TEMPLATE_ROOT.glob("*/requirements.txt-tpl")) + + +@pytest.mark.parametrize( + "requirements", _requirement_files(), ids=lambda p: p.parent.name +) +def test_posix_only_packages_are_excluded_on_windows(requirements: Path) -> None: + windows = {"sys_platform": "win32", "os_name": "nt", "platform_system": "Windows"} + linux = {"sys_platform": "linux", "os_name": "posix", "platform_system": "Linux"} + + for line in requirements.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line or line.startswith(("#", "-")): + continue + requirement = Requirement(line) + if requirement.name.lower() not in POSIX_ONLY_PACKAGES: + continue + marker = requirement.marker + assert marker is not None, f"{requirements}: {line} has no platform marker" + assert not marker.evaluate(windows), f"{requirements}: {line}" + assert marker.evaluate(linux), f"{requirements}: {line} dropped on Linux" + + +def test_uvloop_marker_shape() -> None: + assert not Marker('sys_platform != "win32"').evaluate({"sys_platform": "win32"}) + + +# -------------------------------------------------------------------------- +# Template README decoding (audit #1, interactive part) +# -------------------------------------------------------------------------- + + +def test_template_selection_reads_readmes_as_utf8(tmp_path: Path) -> None: + """A README with non-ASCII bytes must not depend on the locale codec.""" + from fastapi_fastkit.backend.interactive import prompts + + template = tmp_path / "fastapi-unicode" + template.mkdir() + (template / "README.md-tpl").write_bytes("# Ünïcode 템플릿\n".encode("utf-8")) + + real_open = open + seen = {} + + def strict_ascii_open(file, mode="r", *args, **kwargs): # type: ignore[no-untyped-def] + # Behave like an ASCII locale: text mode without encoding= fails. + if "b" not in mode and kwargs.get("encoding") is None: + kwargs["encoding"] = "ascii" + seen[str(file)] = kwargs["encoding"] + return real_open(file, mode, *args, **kwargs) + + settings = FastkitConfig() + settings.FASTKIT_TEMPLATE_ROOT = str(tmp_path) + + with ( + patch("builtins.open", strict_ascii_open), + patch.object(prompts.click, "prompt", return_value=2), + patch.object(prompts, "render_selection_table") as table, + ): + prompts.prompt_template_selection(settings) + + options = table.call_args[0][1] + assert options["fastapi-unicode"] == "Ünïcode 템플릿" + assert seen[os.path.join(str(tmp_path), "fastapi-unicode", "README.md-tpl")] == ( + "utf-8" + ) diff --git a/tests/test_cli_operations/test_cli.py b/tests/test_cli_operations/test_cli.py index 3d34f83d..f75346bb 100644 --- a/tests/test_cli_operations/test_cli.py +++ b/tests/test_cli_operations/test_cli.py @@ -341,7 +341,7 @@ def mock_subprocess_side_effect(*args: Any, **kwargs: Any) -> MagicMock: # Metadata is injected into pyproject.toml (pyproject-first templates). pyproject = project_path / "pyproject.toml" assert pyproject.exists() - pyproject_content = pyproject.read_text() + pyproject_content = pyproject.read_text(encoding="utf-8") assert project_name in pyproject_content assert author in pyproject_content assert author_email in pyproject_content @@ -428,7 +428,7 @@ def mock_subprocess_side_effect(*args: Any, **kwargs: Any) -> MagicMock: # Metadata is injected into pyproject.toml (pyproject-first templates). pyproject = project_path / "pyproject.toml" assert pyproject.exists() - pyproject_content = pyproject.read_text() + pyproject_content = pyproject.read_text(encoding="utf-8") assert project_name in pyproject_content assert author in pyproject_content assert author_email in pyproject_content @@ -510,8 +510,8 @@ def test_init_backend_error(self, temp_dir: str) -> None: ) # then - # CLI should handle existing project gracefully - assert result.exit_code == 0 + # CLI refuses to overwrite and reports the failure in its exit status + assert result.exit_code == 1 assert "already exists" in result.output def test_init_existing_project(self, temp_dir: str) -> None: @@ -539,8 +539,8 @@ def test_init_existing_project(self, temp_dir: str) -> None: ) # then - # CLI returns 0 even when project already exists (just prints error and returns) - assert result.exit_code == 0 + # CLI prints the error and exits non-zero without touching the directory + assert result.exit_code == 1 assert "already exists" in result.output def test_is_fastkit_project_function(self, temp_dir: str) -> None: @@ -807,9 +807,13 @@ def test_addroute_current_directory_not_fastkit_project( assert result.exit_code == 0 assert "Current directory is not a FastAPI-fastkit project." in result.output - def test_startdemo_no_project_folder(self, temp_dir: str) -> None: + def test_startdemo_no_project_folder(self, tmp_path: Path) -> None: """Test startdemo with no project folder creation (deploy to current directory).""" # given + # A directory of its own: the session-wide temp_dir already holds + # files from other in-place deployments, which a non-interactive + # run without --yes now refuses to overwrite. + temp_dir = str(tmp_path) os.chdir(temp_dir) # when @@ -845,9 +849,13 @@ def test_startdemo_no_project_folder(self, temp_dir: str) -> None: not project_folder.exists() ), "Project folder should not be created when user selects 'N'" - def test_init_no_project_folder(self, temp_dir: str) -> None: + def test_init_no_project_folder(self, tmp_path: Path) -> None: """Test init with no project folder creation (deploy to current directory).""" # given + # A directory of its own: the session-wide temp_dir already holds + # files from other in-place deployments, which a non-interactive + # run without --yes now refuses to overwrite. + temp_dir = str(tmp_path) os.chdir(temp_dir) # Mock subprocess for venv creation diff --git a/tests/test_cli_operations/test_cli_config_noninteractive.py b/tests/test_cli_operations/test_cli_config_noninteractive.py new file mode 100644 index 00000000..fe2755bc --- /dev/null +++ b/tests/test_cli_operations/test_cli_config_noninteractive.py @@ -0,0 +1,453 @@ +# -------------------------------------------------------------------------- +# Testcases of the unattended ``fastkit init --config`` path: it must never +# prompt, and every failure must show up in the exit status. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any, Dict, List +from unittest.mock import MagicMock, patch + +import click +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.cli import _init_from_config, fastkit_cli +from fastapi_fastkit.core.settings import FastkitConfig + +CONFIG: Dict[str, Any] = { + "project_name": "unattended-app", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "created without a terminal", + "package_manager": "pip", + "architecture_preset": "minimal", + "all_dependencies": ["fastapi", "uvicorn"], +} + + +def _write_config(directory: Path, config: Dict[str, Any]) -> Path: + path = directory / "fastkit.config.json" + path.write_text(json.dumps(config), encoding="utf-8") + return path + + +def _run_fastkit( + cwd: Path, *args: str, utf8_override: bool = True +) -> "subprocess.CompletedProcess[str]": + """Run the real CLI in a child process with stdin closed. + + ``FastkitConfig.USER_WORKSPACE`` is the process working directory, so + ``cwd`` is where the project gets written. + + :param utf8_override: Force UTF-8 console I/O in the child. Without it + the child keeps the platform's console encoding (cp1252 on Windows + runners), which the CLI itself must survive. + """ + env = dict(os.environ) + if utf8_override: + # Rich prints emoji; keep a Windows console code page from choking on them. + env["PYTHONIOENCODING"] = "utf-8" + env["PYTHONUTF8"] = "1" + else: + for key in ("PYTHONIOENCODING", "PYTHONUTF8"): + env.pop(key, None) + return subprocess.run( + [sys.executable, "-m", "fastapi_fastkit", *args], + cwd=str(cwd), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + env=env, + timeout=300, + ) + + +class TestConfigInitWithClosedStdin: + """Subprocess runs: no terminal attached, nothing may be asked.""" + + def test_valid_config_creates_project_folder(self, tmp_path: Path) -> None: + # given + config_path = _write_config(tmp_path, CONFIG) + + # when + result = _run_fastkit( + tmp_path, "init", "--config", str(config_path), "--no-venv" + ) + + # then + assert result.returncode == 0, result.stdout + assert "Aborted" not in result.stdout + project_path = tmp_path / "unattended-app" + assert project_path.is_dir(), result.stdout + assert (project_path / "pyproject.toml").is_file() or ( + project_path / "setup.py" + ).is_file() + + def test_valid_config_with_yes_flag_succeeds(self, tmp_path: Path) -> None: + # given + config_path = _write_config(tmp_path, CONFIG) + + # when + result = _run_fastkit( + tmp_path, "init", "--config", str(config_path), "--yes", "--no-venv" + ) + + # then + assert result.returncode == 0, result.stdout + assert (tmp_path / "unattended-app").is_dir() + + def test_missing_required_key_fails_without_project(self, tmp_path: Path) -> None: + # given + config = dict(CONFIG) + config.pop("author_email") + config_path = _write_config(tmp_path, config) + + # when + result = _run_fastkit( + tmp_path, "init", "--config", str(config_path), "--no-venv" + ) + + # then + assert result.returncode != 0 + assert "author_email" in result.stdout + assert not (tmp_path / "unattended-app").exists() + + def test_existing_project_directory_fails(self, tmp_path: Path) -> None: + # given + config_path = _write_config(tmp_path, CONFIG) + existing = tmp_path / "unattended-app" + existing.mkdir() + (existing / "keep.txt").write_text("user data", encoding="utf-8") + + # when + result = _run_fastkit( + tmp_path, "init", "--config", str(config_path), "--no-venv" + ) + + # then + assert result.returncode != 0 + assert "already exists" in result.stdout + assert sorted(os.listdir(existing)) == ["keep.txt"] + + def test_dry_run_writes_nothing(self, tmp_path: Path) -> None: + # given + config_path = _write_config(tmp_path, CONFIG) + + # when + result = _run_fastkit( + tmp_path, "init", "--config", str(config_path), "--dry-run" + ) + + # then + assert result.returncode == 0, result.stdout + assert "Files that would be created" in result.stdout + assert os.listdir(tmp_path) == ["fastkit.config.json"] + + +class TestConfigInitWithoutUtf8Override: + """Same unattended runs, but with the platform's own console encoding.""" + + def test_valid_config_creates_project_folder(self, tmp_path: Path) -> None: + # given + config_path = _write_config(tmp_path, CONFIG) + + # when + result = _run_fastkit( + tmp_path, + "init", + "--config", + str(config_path), + "--no-venv", + utf8_override=False, + ) + + # then + assert result.returncode == 0, result.stdout + assert "UnicodeEncodeError" not in result.stdout + assert (tmp_path / "unattended-app").is_dir(), result.stdout + + def test_failure_is_reported_without_crashing(self, tmp_path: Path) -> None: + # given + config = dict(CONFIG) + config.pop("author_email") + config_path = _write_config(tmp_path, config) + + # when + result = _run_fastkit( + tmp_path, + "init", + "--config", + str(config_path), + "--no-venv", + utf8_override=False, + ) + + # then + assert result.returncode == 1, result.stdout + assert "UnicodeEncodeError" not in result.stdout + assert "author_email" in result.stdout + + +class TestConfigInitExitStatus: + """CliRunner coverage for the remaining --config outcomes.""" + + def setup_method(self) -> None: + self.runner = CliRunner() + self.current_workspace = os.getcwd() + + def teardown_method(self) -> None: + os.chdir(self.current_workspace) + + @patch("fastapi_fastkit.cli.ask_create_project_folder") + def test_config_never_asks_for_the_project_folder( + self, mock_ask: MagicMock, tmp_path: Path + ) -> None: + # given + mock_ask.side_effect = AssertionError("--config must not prompt") + config_path = _write_config(tmp_path, CONFIG) + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + + # then + assert result.exit_code == 0, result.output + mock_ask.assert_not_called() + assert (tmp_path / "unattended-app").is_dir() + + @patch("fastapi_fastkit.cli._select_package_manager") + def test_config_without_package_manager_uses_default( + self, mock_select: MagicMock, tmp_path: Path + ) -> None: + # given: package manager is optional in a config file + mock_select.side_effect = AssertionError("--config must not prompt") + config = dict(CONFIG) + config.pop("package_manager") + config_path = _write_config(tmp_path, config) + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + + # then + assert result.exit_code == 0, result.output + mock_select.assert_not_called() + assert (tmp_path / "unattended-app").is_dir() + + def test_config_schema_error_exits_non_zero(self, tmp_path: Path) -> None: + # given + config_path = _write_config(tmp_path, dict(CONFIG, caching=["Redis"])) + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + + # then + assert result.exit_code == 1 + assert not (tmp_path / "unattended-app").exists() + + def test_unreadable_config_exits_non_zero(self, tmp_path: Path) -> None: + # given + config_path = tmp_path / "fastkit.config.json" + config_path.write_text("{not json", encoding="utf-8") + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + + # then + assert result.exit_code == 1 + + @patch("fastapi_fastkit.backend.scaffolder.inject_project_metadata") + def test_scaffold_failure_exits_non_zero_and_rolls_back( + self, mock_inject: MagicMock, tmp_path: Path + ) -> None: + # given + mock_inject.side_effect = RuntimeError("simulated generation failure") + config_path = _write_config(tmp_path, CONFIG) + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + + # then + assert result.exit_code == 1 + assert "Error during project creation" in result.output + assert "simulated generation failure" in result.output + assert not (tmp_path / "unattended-app").exists() + + def test_existing_project_directory_exits_non_zero(self, tmp_path: Path) -> None: + # given + config_path = _write_config(tmp_path, CONFIG) + existing = tmp_path / "unattended-app" + existing.mkdir() + (existing / "keep.txt").write_text("mine", encoding="utf-8") + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + + # then: nothing was written into the existing directory + assert result.exit_code == 1 + assert "already exists" in result.output + assert os.listdir(existing) == ["keep.txt"] + + def test_dry_run_against_existing_directory_is_allowed( + self, tmp_path: Path + ) -> None: + # given: a preview writes nothing, so an existing directory is fine + config_path = _write_config(tmp_path, CONFIG) + (tmp_path / "unattended-app").mkdir() + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config_path), "--dry-run"] + ) + + # then + assert result.exit_code == 0, result.output + assert os.listdir(tmp_path / "unattended-app") == [] + + +class TestPlainInitExitStatus: + """Error paths of the prompt-driven ``init`` report failure too.""" + + def setup_method(self) -> None: + self.runner = CliRunner() + self.current_workspace = os.getcwd() + + def teardown_method(self) -> None: + os.chdir(self.current_workspace) + + @pytest.mark.parametrize("project_name", ["1bad-name", "class"]) + def test_invalid_project_name_exits_non_zero( + self, project_name: str, tmp_path: Path + ) -> None: + # given + os.chdir(tmp_path) + args: List[str] = [ + "init", + "--project-name", + project_name, + "--author", + "bnbong", + "--author-email", + "bbbong9@gmail.com", + "--description", + "invalid name", + ] + + # when + result = self.runner.invoke(fastkit_cli, args) + + # then + assert result.exit_code == 1 + assert "Invalid project name" in result.output + assert os.listdir(tmp_path) == [] + + def test_declining_creation_keeps_exit_status_zero(self, tmp_path: Path) -> None: + # given + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, + [ + "init", + "--project-name", + "declined-app", + "--author", + "bnbong", + "--author-email", + "bbbong9@gmail.com", + "--description", + "declined", + "--package-manager", + "pip", + ], + input="minimal\nn\n", + ) + + # then + assert result.exit_code == 0, result.output + assert "Project creation aborted!" in result.output + assert not (tmp_path / "declined-app").exists() + + +class TestInitFromConfigGuards: + """``_init_from_config`` refuses configurations it cannot generate from. + + The CLI validates a config file before it gets here, so these guards only + fire for a caller that hands over an unvalidated mapping. + """ + + @staticmethod + def _context(tmp_path: Path) -> click.Context: + settings = FastkitConfig() + settings.USER_WORKSPACE = str(tmp_path) + return click.Context(fastkit_cli, obj={"settings": settings}) + + def _run(self, tmp_path: Path, config: Dict[str, Any]) -> int: + ctx = self._context(tmp_path) + with ctx, pytest.raises(click.exceptions.Exit) as raised: + _init_from_config( + ctx, + config, + package_manager=None, + dry_run=False, + no_venv=True, + no_install=True, + ) + return raised.value.exit_code + + def test_missing_project_name_exits_non_zero( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + # given + config = {key: value for key, value in CONFIG.items() if key != "project_name"} + + # when + exit_code = self._run(tmp_path, config) + + # then + assert exit_code == 1 + assert "missing 'project_name'" in capsys.readouterr().out + assert os.listdir(tmp_path) == [] + + def test_invalid_feature_selection_exits_non_zero( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + # given: no package list, so it is derived from an invalid selection + config = { + key: value for key, value in CONFIG.items() if key != "all_dependencies" + } + config["caching"] = ["Redis"] + + # when + exit_code = self._run(tmp_path, config) + + # then + assert exit_code == 1 + assert "Invalid project config" in capsys.readouterr().out + assert os.listdir(tmp_path) == [] diff --git a/tests/test_cli_operations/test_cli_config_options.py b/tests/test_cli_operations/test_cli_config_options.py index cc522511..9edb6797 100644 --- a/tests/test_cli_operations/test_cli_config_options.py +++ b/tests/test_cli_operations/test_cli_config_options.py @@ -129,10 +129,11 @@ def test_init_from_config_file_creates_project(self, tmp_path: Path) -> None: result = self.runner.invoke( fastkit_cli, ["init", "--config", config_path, "--no-venv"], - input="Y\n", # Create a new project folder ) - # then + # then: no folder question is asked; the project gets its own folder + assert result.exit_code == 0, result.output + assert "Create a new project folder" not in result.output project_path = tmp_path / "config-driven" assert project_path.is_dir(), result.output metadata = read_fastkit_metadata(str(project_path)) @@ -153,6 +154,7 @@ def test_init_from_config_reports_validation_errors(self, tmp_path: Path) -> Non ) # then + assert result.exit_code == 1 assert "Invalid author email" in result.output assert not (tmp_path / "config-driven").exists() @@ -166,6 +168,7 @@ def test_init_from_config_reports_missing_file(self, tmp_path: Path) -> None: ) # then + assert result.exit_code == 1 assert "not found" in result.output def test_init_dry_run_writes_nothing(self, tmp_path: Path) -> None: @@ -179,6 +182,7 @@ def test_init_dry_run_writes_nothing(self, tmp_path: Path) -> None: ) # then + assert result.exit_code == 0, result.output assert "Files that would be created" in result.output assert "Packages that would be installed" in result.output assert not (tmp_path / "config-driven").exists() @@ -223,7 +227,6 @@ def test_init_no_install_still_creates_the_project(self, tmp_path: Path) -> None result = self.runner.invoke( fastkit_cli, ["init", "--config", config_path, "--no-venv", "--no-install"], - input="Y\n", ) # then @@ -247,14 +250,15 @@ def test_init_config_without_dependencies_derives_them( result = self.runner.invoke( fastkit_cli, ["init", "--config", str(path), "--no-venv"], - input="Y\n", ) # then project_path = tmp_path / "derived-deps" assert project_path.is_dir(), result.output - pyproject = (project_path / "pyproject.toml").read_text() - assert "sqlalchemy" in pyproject + pyproject = (project_path / "pyproject.toml").read_text(encoding="utf-8") + # The generated database module is async, so greenlet must come along. + assert '"sqlalchemy[asyncio]"' in pyproject + assert '"sqlalchemy",' not in pyproject assert "database:SQLite" in read_fastkit_metadata(str(project_path))["features"] @@ -314,9 +318,9 @@ def test_addroute_targets_the_domain_starter_layout(self, tmp_path: Path) -> Non # the old package root must not be created alongside it assert not (project_path / "src" / "api").exists() - router_content = ( - project_path / "src" / "app" / "api" / "router.py" - ).read_text() + router_content = (project_path / "src" / "app" / "api" / "router.py").read_text( + encoding="utf-8" + ) assert ( "from src.app.domains.user import router as user_router" in router_content ) @@ -346,7 +350,9 @@ def test_addroute_imports_resolve_for_the_domain_starter_layout( assert "Successfully added new route" in result.output, result.output package = project_path / "src" / "app" if route_layout == "domain": - route_content = (package / "domains" / "user" / "router.py").read_text() + route_content = (package / "domains" / "user" / "router.py").read_text( + encoding="utf-8" + ) assert ( "from src.app.domains.user.schemas import UserCreate, UserRead" in route_content @@ -356,7 +362,9 @@ def test_addroute_imports_resolve_for_the_domain_starter_layout( in route_content ) else: - route_content = (package / "api" / "routes" / "user.py").read_text() + route_content = (package / "api" / "routes" / "user.py").read_text( + encoding="utf-8" + ) assert "from src.app.crud.user import *" in route_content assert "from src.app.schemas.user import *" in route_content assert "" not in route_content @@ -375,9 +383,9 @@ def test_addroute_imports_resolve_for_the_classic_layout( # then assert "Successfully added new route" in result.output, result.output - route_content = ( - project_path / "src" / "api" / "routes" / "user.py" - ).read_text() + route_content = (project_path / "src" / "api" / "routes" / "user.py").read_text( + encoding="utf-8" + ) assert "from src.crud.user import *" in route_content assert "from src.schemas.user import *" in route_content assert _unresolved_project_imports(project_path) == [] @@ -431,7 +439,9 @@ def _unresolved_project_imports(project_path: Path) -> List[str]: missing: List[str] = [] for module_path in sorted(project_path.rglob("*.py")): - tree = ast.parse(module_path.read_text(), filename=str(module_path)) + tree = ast.parse( + module_path.read_text(encoding="utf-8"), filename=str(module_path) + ) for node in ast.walk(tree): if not isinstance(node, ast.ImportFrom) or not node.module: continue @@ -456,7 +466,7 @@ def test_dict_shaped_axes_are_normalized(self) -> None: # then assert normalized["database"] == { "type": "PostgreSQL", - "packages": ["asyncpg", "sqlalchemy"], + "packages": ["asyncpg", "sqlalchemy[asyncio]"], } assert normalized["authentication"] == "JWT" assert normalized["async_tasks"] == "Celery" @@ -771,7 +781,6 @@ def test_dict_shaped_config_generates_an_importable_project( result = self.runner.invoke( fastkit_cli, ["init", "--config", str(path), "--no-venv"], - input="Y\n", ) # then diff --git a/tests/test_cli_operations/test_cli_error_paths.py b/tests/test_cli_operations/test_cli_error_paths.py index 5ad188e4..6b042ffc 100644 --- a/tests/test_cli_operations/test_cli_error_paths.py +++ b/tests/test_cli_operations/test_cli_error_paths.py @@ -15,6 +15,7 @@ from click.testing import CliRunner from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.utils.platform import venv_python MINIMAL_CONFIG: Dict[str, Any] = { "project_name": "config-driven", @@ -56,6 +57,7 @@ def test_config_with_bad_extension_is_rejected(self, tmp_path: Path) -> None: result = self.runner.invoke(fastkit_cli, ["init", "--config", str(config_path)]) # then + assert result.exit_code == 1 assert "Unsupported config file extension" in result.output def test_config_with_malformed_axis_is_rejected(self, tmp_path: Path) -> None: @@ -70,6 +72,7 @@ def test_config_with_malformed_axis_is_rejected(self, tmp_path: Path) -> None: result = self.runner.invoke(fastkit_cli, ["init", "--config", str(config_path)]) # then + assert result.exit_code == 1 assert "takes a single choice, not a list" in result.output assert not (tmp_path / "config-driven").exists() @@ -104,7 +107,7 @@ def test_save_config_writes_selections_after_interactive_flow( # then assert save_path.exists(), result.output - saved = json.loads(save_path.read_text()) + saved = json.loads(save_path.read_text(encoding="utf-8")) assert saved["project_name"] == "config-driven" def test_save_config_reports_unsupported_extension(self, tmp_path: Path) -> None: @@ -156,7 +159,7 @@ def test_offer_config_save_prompts_when_stdin_is_a_tty_and_declined( # when: a tty session that declines the save prompt with ( - patch("fastapi_fastkit.cli.sys.stdin.isatty", return_value=True), + patch("fastapi_fastkit.cli.stdin_is_interactive", return_value=True), patch("fastapi_fastkit.cli.click.confirm", return_value=False) as confirm, ): _offer_config_save(dict(MINIMAL_CONFIG), None) @@ -176,7 +179,7 @@ def test_offer_config_save_prompts_for_a_path_when_confirmed( # when with ( - patch("fastapi_fastkit.cli.sys.stdin.isatty", return_value=True), + patch("fastapi_fastkit.cli.stdin_is_interactive", return_value=True), patch("fastapi_fastkit.cli.click.confirm", return_value=True), patch("fastapi_fastkit.cli.click.prompt", return_value=str(save_path)), ): @@ -374,7 +377,7 @@ def test_rmtree_failure_is_reported(self, tmp_path: Path) -> None: str(tmp_path), ), patch( - "fastapi_fastkit.cli.shutil.rmtree", + "fastapi_fastkit.cli.rmtree_force", side_effect=OSError("permission denied"), ), ): @@ -431,7 +434,7 @@ def test_missing_venv_accepted_falls_back_to_system_python( def test_missing_interpreter_in_venv_declined_returns(self, tmp_path: Path) -> None: # given: a .venv directory exists, but has no python interpreter os.chdir(tmp_path) - (tmp_path / ".venv" / "bin").mkdir(parents=True) + Path(venv_python(tmp_path / ".venv")).parent.mkdir(parents=True) # when with patch( @@ -444,12 +447,40 @@ def test_missing_interpreter_in_venv_declined_returns(self, tmp_path: Path) -> N assert "Python interpreter not found" in result.output assert "Starting FastAPI server" not in result.output + def test_missing_interpreter_in_venv_accepted_uses_system_python( + self, tmp_path: Path + ) -> None: + # given: a .venv without an interpreter, and a resolvable app module + os.chdir(tmp_path) + Path(venv_python(tmp_path / ".venv")).parent.mkdir(parents=True) + (tmp_path / "src").mkdir() + (tmp_path / "src" / "main.py").write_text("app = None\n") + + # when + with ( + patch( + "fastapi_fastkit.core.settings.FastkitConfig.USER_WORKSPACE", + str(tmp_path), + ), + patch("fastapi_fastkit.cli.subprocess.run") as mock_run, + ): + result = self.runner.invoke(fastkit_cli, ["runserver"], input="Y\n") + + # then: the server starts with the system ``uvicorn``, and the venv's + # missing interpreter is not put on the command line + assert "Python interpreter not found" in result.output + assert "Starting FastAPI server" in result.output + command = mock_run.call_args[0][0] + assert command[:2] == ["uvicorn", "src.main:app"] + env = mock_run.call_args.kwargs["env"] + assert env.get("PYTHONPATH") == os.environ.get("PYTHONPATH") + def test_app_module_unresolvable_is_reported(self, tmp_path: Path) -> None: # given: a valid venv but no main.py anywhere os.chdir(tmp_path) - bin_dir = tmp_path / ".venv" / "bin" - bin_dir.mkdir(parents=True) - (bin_dir / "python").write_text("") + interpreter = Path(venv_python(tmp_path / ".venv")) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") # when with patch( @@ -466,9 +497,9 @@ def test_runserver_uses_venv_python_and_extends_pythonpath( ) -> None: # given os.chdir(tmp_path) - bin_dir = tmp_path / ".venv" / "bin" - bin_dir.mkdir(parents=True) - (bin_dir / "python").write_text("") + interpreter = Path(venv_python(tmp_path / ".venv")) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") src_dir = tmp_path / "src" src_dir.mkdir() (src_dir / "main.py").write_text("app = None\n") @@ -484,11 +515,61 @@ def test_runserver_uses_venv_python_and_extends_pythonpath( ): result = self.runner.invoke(fastkit_cli, ["runserver"]) - # then + # then: the project directory goes first, joined with os.pathsep assert "Using Python from virtual environment" in result.output - assert mock_run.call_args[0][0][0] == str(bin_dir / "python") + assert mock_run.call_args[0][0][0] == str(interpreter) env = mock_run.call_args.kwargs["env"] - assert env["PYTHONPATH"].endswith(":/already/here") + assert env["PYTHONPATH"] == os.pathsep.join([str(tmp_path), "/already/here"]) + + def test_runserver_pythonpath_is_project_dir_when_unset( + self, tmp_path: Path + ) -> None: + # given + os.chdir(tmp_path) + interpreter = Path(venv_python(tmp_path / ".venv")) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") + (tmp_path / "src").mkdir() + (tmp_path / "src" / "main.py").write_text("app = None\n") + env_without = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"} + + # when + with ( + patch( + "fastapi_fastkit.core.settings.FastkitConfig.USER_WORKSPACE", + str(tmp_path), + ), + patch("fastapi_fastkit.cli.subprocess.run") as mock_run, + patch.dict(os.environ, env_without, clear=True), + ): + self.runner.invoke(fastkit_cli, ["runserver"]) + + # then + assert mock_run.call_args.kwargs["env"]["PYTHONPATH"] == str(tmp_path) + + def test_runserver_uses_windows_venv_layout(self, tmp_path: Path) -> None: + # given: a Windows-style venv (Scripts\python.exe) + os.chdir(tmp_path) + scripts = tmp_path / ".venv" / "Scripts" + scripts.mkdir(parents=True) + (scripts / "python.exe").write_text("") + (tmp_path / "src").mkdir() + (tmp_path / "src" / "main.py").write_text("app = None\n") + + # when + with ( + patch( + "fastapi_fastkit.core.settings.FastkitConfig.USER_WORKSPACE", + str(tmp_path), + ), + patch("fastapi_fastkit.utils.platform.is_windows", return_value=True), + patch("fastapi_fastkit.cli.subprocess.run") as mock_run, + ): + result = self.runner.invoke(fastkit_cli, ["runserver"]) + + # then + assert "Using Python from virtual environment" in result.output + assert mock_run.call_args[0][0][0] == str(scripts / "python.exe") def test_called_process_error_is_reported(self, tmp_path: Path) -> None: # given @@ -518,9 +599,9 @@ def test_file_not_found_with_venv_reports_uvicorn_missing_in_venv( ) -> None: # given os.chdir(tmp_path) - bin_dir = tmp_path / ".venv" / "bin" - bin_dir.mkdir(parents=True) - (bin_dir / "python").write_text("") + interpreter = Path(venv_python(tmp_path / ".venv")) + interpreter.parent.mkdir(parents=True) + interpreter.write_text("") src_dir = tmp_path / "src" src_dir.mkdir() (src_dir / "main.py").write_text("app = None\n") diff --git a/tests/test_cli_operations/test_cli_extended.py b/tests/test_cli_operations/test_cli_extended.py index 8366b477..0f15b390 100644 --- a/tests/test_cli_operations/test_cli_extended.py +++ b/tests/test_cli_operations/test_cli_extended.py @@ -399,7 +399,7 @@ def test_in_place_init_failure_does_not_delete_workspace( # then assert workspace.exists() assert sibling_file.exists() - assert sibling_file.read_text() == "precious user data" + assert sibling_file.read_text(encoding="utf-8") == "precious user data" def test_folder_init_failure_deletes_only_project_folder( self, temp_dir: str diff --git a/tests/test_cli_operations/test_cli_interactive_integration.py b/tests/test_cli_operations/test_cli_interactive_integration.py index 2149c5fb..9e70cf77 100644 --- a/tests/test_cli_operations/test_cli_interactive_integration.py +++ b/tests/test_cli_operations/test_cli_interactive_integration.py @@ -241,12 +241,12 @@ def mock_subprocess_side_effect(*args: Any, **kwargs: Any) -> MagicMock: # (INI content in a Python module breaks the entire test suite). pytest_ini = project_path / "pytest.ini" assert pytest_ini.exists(), "Generated project should have a pytest.ini" - ini_content = pytest_ini.read_text() + ini_content = pytest_ini.read_text(encoding="utf-8") assert "[pytest]" in ini_content conftest_path = project_path / "tests" / "conftest.py" if conftest_path.exists(): - conftest_content = conftest_path.read_text() + conftest_content = conftest_path.read_text(encoding="utf-8") assert ( "[pytest]" not in conftest_content ), "conftest.py must remain a Python module, not INI content" @@ -268,10 +268,14 @@ def mock_subprocess_side_effect(*args: Any, **kwargs: Any) -> MagicMock: ): target = project_path / relative assert target.exists(), f"{relative} was promised but not generated" - assert marker in target.read_text(), f"{relative} missing {marker!r}" + assert marker in target.read_text( + encoding="utf-8" + ), f"{relative} missing {marker!r}" # ruff was selected, so its configuration belongs in pyproject.toml. - assert "[tool.ruff]" in (project_path / "pyproject.toml").read_text() + assert "[tool.ruff]" in (project_path / "pyproject.toml").read_text( + encoding="utf-8" + ) # Alembic ships on the migrations axis, so it must be installed too. assert "alembic" in deps_lower, "Alembic should be in dependencies" @@ -454,7 +458,7 @@ def _mock_subprocess(*args: Any, **kwargs: Any) -> MagicMock: f"output:\n{result.output}" ) - content = dockerfile.read_text() + content = dockerfile.read_text(encoding="utf-8") assert "src.app.main:app" in content, ( "Domain-starter Dockerfile must target src.app.main:app; " "the CMD currently reads:\n" @@ -620,7 +624,7 @@ def _mock_subprocess(*args: Any, **kwargs: Any) -> MagicMock: # that ``DynamicConfigGenerator.generate_main_py`` always emits. # Presence/absence is the contract: regenerated for minimal / # single-module, preserved for classic-layered / domain-starter. - main_text = main_py.read_text() + main_text = main_py.read_text(encoding="utf-8") if regenerates_main: assert "Generated by FastAPI-fastkit" in main_text, ( f"[{suffix}] main.py was not regenerated by the dynamic " diff --git a/tests/test_cli_operations/test_cli_portability.py b/tests/test_cli_operations/test_cli_portability.py new file mode 100644 index 00000000..57a1998b --- /dev/null +++ b/tests/test_cli_operations/test_cli_portability.py @@ -0,0 +1,394 @@ +# -------------------------------------------------------------------------- +# Testcases for CLI behaviour that differs between operating systems and +# console setups, simulated on any OS: legacy console encodings, non-UTF-8 +# locales, a missing stdin, read-only files on delete, and the exit status of +# an in-place deploy (user cancel vs. real failure). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import os +import shutil +import stat +import subprocess +import sys +from pathlib import Path +from typing import Dict, List +from unittest.mock import MagicMock, patch + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.cli import _offer_config_save, fastkit_cli + +FASTKIT_PYPROJECT = """[project] +name = "proj" +description = "[FastAPI-fastkit templated] demo" + +[tool.fastapi-fastkit] +managed = true +""" + + +def _child_env(**overrides: str) -> Dict[str, str]: + env = dict(os.environ) + for key in ("PYTHONUTF8", "PYTHONIOENCODING", "PYTHONLEGACYWINDOWSSTDIO"): + env.pop(key, None) + env.update(overrides) + return env + + +def _run( + cwd: Path, env: Dict[str, str], *args: str +) -> "subprocess.CompletedProcess[str]": + """Run ``python -m fastapi_fastkit`` with stdin closed.""" + return subprocess.run( + [sys.executable, "-m", "fastapi_fastkit", *args], + cwd=str(cwd), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + # Decode leniently: the point is that the child does not crash. + text=True, + encoding="utf-8", + errors="replace", + env=env, + timeout=120, + ) + + +class TestLegacyConsoleEncoding: + """A cp1252 console (windows-latest's default) cannot encode emoji.""" + + @pytest.mark.parametrize( + ("args", "returncode"), + [ + (["list-templates"], 0), + (["deleteproject", "does-not-exist"], 0), + (["init", "--config", "missing.json"], 1), + (["--version"], 0), + (["--help"], 0), + ], + ) + def test_no_unicode_encode_error( + self, tmp_path: Path, args: List[str], returncode: int + ) -> None: + # when + result = _run( + tmp_path, _child_env(PYTHONIOENCODING="cp1252", PYTHONUTF8="0"), *args + ) + + # then + assert "UnicodeEncodeError" not in result.stdout, result.stdout + assert "Traceback" not in result.stdout, result.stdout + assert result.returncode == returncode, result.stdout + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX locale variables") +class TestNonUtf8Locale: + """An ASCII / C locale must not break reading the bundled templates.""" + + def test_list_templates(self, tmp_path: Path) -> None: + # given + env = _child_env( + LC_ALL="C", + LANG="C", + PYTHONCOERCECLOCALE="0", + PYTHONUTF8="0", + # Output encoding is covered above; this isolates file reading. + PYTHONIOENCODING="utf-8", + ) + + # when + result = _run(tmp_path, env, "list-templates") + + # then + assert result.returncode == 0, result.stdout + assert "UnicodeDecodeError" not in result.stdout + assert "fastapi-default" in result.stdout + + +class TestMissingStdin: + """``sys.stdin is None`` (pythonw, some service runners) never prompts.""" + + def test_offer_config_save_skips_the_question(self, tmp_path: Path) -> None: + with ( + patch("fastapi_fastkit.utils.platform.sys.stdin", None), + patch("fastapi_fastkit.cli.click.confirm") as confirm, + ): + _offer_config_save({"project_name": "x"}, None) + + confirm.assert_not_called() + assert list(tmp_path.iterdir()) == [] + + def test_in_place_overwrite_refuses_without_asking(self, tmp_path: Path) -> None: + # given: nobody can be asked, and --yes was not given + from fastapi_fastkit.backend.scaffolder import ( + ProjectScaffolder, + ScaffoldCancelled, + ScaffoldOptions, + ) + from fastapi_fastkit.core.exceptions import BackendExceptions + from fastapi_fastkit.core.settings import FastkitConfig + + settings = FastkitConfig() + (tmp_path / "README.md").write_text("mine") + options = ScaffoldOptions( + project_name="demo", + author="a", + author_email="a@example.com", + description="d", + package_manager="pip", + template="fastapi-empty", + create_project_folder=False, + with_venv=False, + with_install=False, + ) + + # when + with ( + patch.object(FastkitConfig, "USER_WORKSPACE", str(tmp_path)), + patch("fastapi_fastkit.utils.platform.sys.stdin", None), + patch("fastapi_fastkit.backend.scaffolder.click.confirm") as confirm, + ): + with pytest.raises(BackendExceptions, match="--yes") as exc_info: + ProjectScaffolder(settings, options)._confirm_overwrites() + + # then: a failure (non-zero exit), not a user cancel (exit 0) + assert not isinstance(exc_info.value, ScaffoldCancelled) + assert "1 existing file(s)" in str(exc_info.value) + confirm.assert_not_called() + assert (tmp_path / "README.md").read_text() == "mine" + + +def _fastkit_project(root: Path) -> Path: + project = root / "proj" + project.mkdir() + (project / "pyproject.toml").write_text(FASTKIT_PYPROJECT, encoding="utf-8") + return project + + +class TestDeleteProjectReadOnlyFiles: + def setup_method(self) -> None: + self.runner = CliRunner() + self.current_workspace = os.getcwd() + + def teardown_method(self) -> None: + os.chdir(self.current_workspace) + + def _delete(self, workspace: Path) -> str: + # USER_WORKSPACE is the working directory at invocation time. + os.chdir(workspace) + result = self.runner.invoke(fastkit_cli, ["deleteproject", "proj"], input="Y\n") + return result.output + + def test_read_only_files_are_removed(self, tmp_path: Path) -> None: + # given: read-only object files, as git leaves them + project = _fastkit_project(tmp_path) + objects = project / ".git" / "objects" / "ab" + objects.mkdir(parents=True) + blob = objects / "cdef" + blob.write_bytes(b"blob") + os.chmod(blob, stat.S_IREAD) + + # when + output = self._delete(tmp_path) + + # then + assert "deleted successfully" in output, output + assert not project.exists() + + @pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed") + def test_project_with_a_git_history_is_removed(self, tmp_path: Path) -> None: + # given + project = _fastkit_project(tmp_path) + git_env = dict( + os.environ, + GIT_AUTHOR_NAME="t", + GIT_AUTHOR_EMAIL="t@example.com", + GIT_COMMITTER_NAME="t", + GIT_COMMITTER_EMAIL="t@example.com", + ) + for command in ( + ["git", "init", "-q"], + ["git", "-c", "core.autocrlf=false", "add", "-A"], + ["git", "-c", "commit.gpgsign=false", "commit", "-q", "-m", "init"], + ): + subprocess.run(command, cwd=project, check=True, env=git_env) + + # when + output = self._delete(tmp_path) + + # then + assert "deleted successfully" in output, output + assert not project.exists() + + +class TestInPlaceDeployExitStatus: + """An in-place ``init`` exits 0 when the user cancels, 1 when it fails.""" + + def setup_method(self) -> None: + self.runner = CliRunner() + self.current_workspace = os.getcwd() + + def teardown_method(self) -> None: + os.chdir(self.current_workspace) + + ARGS = [ + "init", + "--project-name", + "inplace-app", + "--author", + "bnbong", + "--author-email", + "bbbong9@gmail.com", + "--description", + "in place", + "--package-manager", + "pip", + "--no-venv", + ] + + def test_declining_the_overwrite_prompt_exits_zero(self, tmp_path: Path) -> None: + # given: a file the template would overwrite + os.chdir(tmp_path) + (tmp_path / "README.md").write_text("mine") + + # when: stack, proceed, deploy in place (no folder), refuse overwrite + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=True, + ): + result = self.runner.invoke( + fastkit_cli, self.ARGS, input="minimal\ny\nn\nn\n" + ) + + # then + assert result.exit_code == 0, result.output + assert "aborted by user" in result.output + assert (tmp_path / "README.md").read_text(encoding="utf-8") == "mine" + + @patch("fastapi_fastkit.backend.scaffolder.inject_project_metadata") + def test_real_failure_exits_non_zero( + self, mock_inject: MagicMock, tmp_path: Path + ) -> None: + # given + mock_inject.side_effect = RuntimeError("simulated failure") + os.chdir(tmp_path) + + # when: stack, proceed, deploy in place + result = self.runner.invoke( + fastkit_cli, [*self.ARGS, "--yes"], input="minimal\ny\nn\n" + ) + + # then + assert result.exit_code == 1, result.output + assert "simulated failure" in result.output + + def test_non_interactive_overwrite_without_yes_fails(self, tmp_path: Path) -> None: + # given: a file the template would overwrite, and no terminal + os.chdir(tmp_path) + (tmp_path / "README.md").write_text("mine", encoding="utf-8") + + # when: stack, proceed, deploy in place; CliRunner's stdin is no tty + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=False, + ): + result = self.runner.invoke(fastkit_cli, self.ARGS, input="minimal\ny\nn\n") + + # then: refused with a pointer to --yes, and nothing was written + assert result.exit_code == 1, result.output + assert "--yes" in result.output + assert "aborted by user" not in result.output + assert (tmp_path / "README.md").read_text(encoding="utf-8") == "mine" + assert sorted(p.name for p in tmp_path.iterdir()) == ["README.md"] + + def test_non_interactive_overwrite_with_yes_proceeds(self, tmp_path: Path) -> None: + # given + os.chdir(tmp_path) + (tmp_path / "README.md").write_text("mine", encoding="utf-8") + + # when + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=False, + ): + result = self.runner.invoke( + fastkit_cli, [*self.ARGS, "--yes"], input="minimal\ny\nn\n" + ) + + # then + assert result.exit_code == 0, result.output + assert (tmp_path / "README.md").read_text(encoding="utf-8") != "mine" + assert (tmp_path / "pyproject.toml").is_file() + + def test_non_interactive_without_clashes_needs_no_yes(self, tmp_path: Path) -> None: + # given: an empty directory, so nothing would be overwritten + os.chdir(tmp_path) + + # when + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=False, + ): + result = self.runner.invoke(fastkit_cli, self.ARGS, input="minimal\ny\nn\n") + + # then + assert result.exit_code == 0, result.output + assert (tmp_path / "pyproject.toml").is_file() + + def test_dry_run_is_unaffected(self, tmp_path: Path) -> None: + # given + os.chdir(tmp_path) + (tmp_path / "README.md").write_text("mine", encoding="utf-8") + + # when + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=False, + ): + result = self.runner.invoke( + fastkit_cli, [*self.ARGS, "--dry-run"], input="minimal\ny\n" + ) + + # then + assert result.exit_code == 0, result.output + assert "--yes" not in result.output + assert sorted(p.name for p in tmp_path.iterdir()) == ["README.md"] + + def test_config_init_always_creates_a_folder_and_needs_no_yes( + self, tmp_path: Path + ) -> None: + # given: files in the working directory that share template names + os.chdir(tmp_path) + (tmp_path / "README.md").write_text("mine", encoding="utf-8") + config = tmp_path / "fastkit.config.json" + config.write_text( + json.dumps( + { + "project_name": "cfg-app", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "config run", + "package_manager": "pip", + "architecture_preset": "minimal", + "all_dependencies": ["fastapi", "uvicorn"], + } + ), + encoding="utf-8", + ) + + # when + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=False, + ): + result = self.runner.invoke( + fastkit_cli, ["init", "--config", str(config), "--no-venv"] + ) + + # then + assert result.exit_code == 0, result.output + assert (tmp_path / "cfg-app" / "pyproject.toml").is_file() + assert (tmp_path / "README.md").read_text(encoding="utf-8") == "mine" diff --git a/tests/test_config_file.py b/tests/test_config_file.py index 5b4ddc0a..ab8c6e2d 100644 --- a/tests/test_config_file.py +++ b/tests/test_config_file.py @@ -3,13 +3,19 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import codecs +import json +import os from pathlib import Path from unittest.mock import patch import pytest +from click.testing import CliRunner +from fastapi_fastkit.cli import fastkit_cli from fastapi_fastkit.utils.config_file import ( ConfigFileError, + _yaml_module, format_toml_value, load_normalized_project_config, load_project_config, @@ -56,6 +62,15 @@ def test_raises_on_invalid_json(self, tmp_path: Path) -> None: with pytest.raises(ConfigFileError, match="Could not parse JSON"): load_project_config(str(path)) + def test_unreadable_file_raises_config_error(self, tmp_path: Path) -> None: + # given: the path exists but cannot be read as a file + path = tmp_path / "config.json" + path.mkdir() + + # when / then: reported as a config error, not an OSError traceback + with pytest.raises(ConfigFileError, match="Could not parse JSON config"): + load_project_config(str(path)) + def test_loads_toml_file(self, tmp_path: Path) -> None: # given path = tmp_path / "config.toml" @@ -294,3 +309,107 @@ def test_list(self) -> None: def test_string_escaping(self) -> None: assert format_toml_value('say "hi"\\') == '"say \\"hi\\"\\\\"' + + +class TestConfigFileEncodings: + """Windows editors and shells write BOM-prefixed UTF-8 or UTF-16 files.""" + + @pytest.mark.parametrize( + "extension,content", + [ + (".json", '{"project_name": "démo", "author": "bnbong"}'), + (".toml", 'project_name = "démo"\nauthor = "bnbong"\n'), + (".yaml", "project_name: démo\nauthor: bnbong\n"), + ], + ) + def test_utf8_bom_is_accepted( + self, tmp_path: Path, extension: str, content: str + ) -> None: + # given: what Notepad / Out-File -Encoding utf8 produce, with CRLF + if extension == ".yaml" and _yaml_module() is None: + pytest.skip("PyYAML is not installed") + path = tmp_path / f"config{extension}" + path.write_bytes( + codecs.BOM_UTF8 + content.replace("\n", "\r\n").encode("utf-8") + ) + + # when + result = load_project_config(str(path)) + + # then + assert result == {"project_name": "démo", "author": "bnbong"} + + @pytest.mark.parametrize("encoding", ["utf-16", "utf-16-be", "utf-32"]) + @pytest.mark.parametrize("extension", [".json", ".toml"]) + def test_utf16_gives_a_readable_error( + self, tmp_path: Path, encoding: str, extension: str + ) -> None: + # given: PowerShell 5 ``>`` writes UTF-16 LE with a BOM + path = tmp_path / f"config{extension}" + text = '{"project_name": "demo"}' if extension == ".json" else 'a = "b"\n' + bom = codecs.BOM_UTF16_BE if encoding == "utf-16-be" else b"" + path.write_bytes(bom + text.encode(encoding)) + + # when / then + with pytest.raises(ConfigFileError, match="must be UTF-8") as excinfo: + load_project_config(str(path)) + assert "UTF-16" in str(excinfo.value) or "UTF-32" in str(excinfo.value) + + def test_invalid_utf8_gives_a_readable_error(self, tmp_path: Path) -> None: + # given: a legacy code page file (cp949 bytes) + path = tmp_path / "config.json" + path.write_bytes('{"author": "홍길동"}'.encode("cp949")) + + # when / then + with pytest.raises(ConfigFileError, match="must be UTF-8"): + load_project_config(str(path)) + + def test_init_with_utf16_config_exits_with_status_1(self, tmp_path: Path) -> None: + # given + config = { + **VALID_CONFIG, + "package_manager": "pip", + "architecture_preset": "minimal", + } + path = tmp_path / "fastkit.config.json" + path.write_bytes(json.dumps(config).encode("utf-16")) + previous = os.getcwd() + os.chdir(tmp_path) + + # when + try: + result = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(path), "--no-venv"] + ) + finally: + os.chdir(previous) + + # then + assert result.exit_code == 1, result.output + assert "UTF-8" in result.output + assert not (tmp_path / VALID_CONFIG["project_name"]).exists() + + def test_init_with_bom_config_succeeds(self, tmp_path: Path) -> None: + # given + config = { + **VALID_CONFIG, + "package_manager": "pip", + "architecture_preset": "minimal", + "all_dependencies": ["fastapi", "uvicorn"], + } + path = tmp_path / "fastkit.config.json" + path.write_bytes(codecs.BOM_UTF8 + json.dumps(config).encode("utf-8")) + previous = os.getcwd() + os.chdir(tmp_path) + + # when + try: + result = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(path), "--no-venv"] + ) + finally: + os.chdir(previous) + + # then + assert result.exit_code == 0, result.output + assert (tmp_path / VALID_CONFIG["project_name"]).is_dir() diff --git a/tests/test_core.py b/tests/test_core.py index 5f583a3a..78fedf8f 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -4,6 +4,7 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import os +from pathlib import Path from unittest.mock import patch import pytest @@ -353,3 +354,46 @@ def test_settings_error_handling_for_missing_template_files(self) -> None: except Exception: # If exception occurs, it should be handled gracefully pass + + +class TestWritableLogFilePath: + """The debug log falls back to a writable directory instead of failing.""" + + def test_unwritable_default_falls_back_to_the_user_directory( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + # given: the default log directory cannot be created (a file is in + # the way, as with a read-only all-users install) + blocker = tmp_path / "site-packages" + blocker.write_text("", encoding="utf-8") + preferred = str(blocker / "fastkit.log") + home = tmp_path / "home" + real_expanduser = os.path.expanduser + monkeypatch.setattr( + os.path, + "expanduser", + lambda path: str(home) if path == "~" else real_expanduser(path), + ) + + # when + resolved = FastkitConfig._writable_log_file_path(preferred) + + # then + expected_dir = home / ".fastapi-fastkit" / "logs" + assert resolved == str(expected_dir / "fastkit.log") + assert expected_dir.is_dir() + + def test_nothing_writable_keeps_the_default(self, tmp_path: Path) -> None: + # given + preferred = str(tmp_path / "logs" / "fastkit.log") + + # when + with patch( + "fastapi_fastkit.core.settings.os.makedirs", + side_effect=PermissionError(13, "denied"), + ) as makedirs: + resolved = FastkitConfig._writable_log_file_path(preferred) + + # then: every candidate was tried, and the default is kept + assert resolved == preferred + assert makedirs.call_count == 3 diff --git a/tests/test_static_portability.py b/tests/test_static_portability.py new file mode 100644 index 00000000..1a8545ac --- /dev/null +++ b/tests/test_static_portability.py @@ -0,0 +1,231 @@ +# -------------------------------------------------------------------------- +# Static portability guard over the fastapi_fastkit package. +# +# Text I/O that leans on platform defaults breaks on Windows: the locale +# codec (cp1252, cp949, ...) decodes files and child-process output, and +# text-mode writes translate "\n" to "\r\n". This AST scan fails when a call +# site relies on either default: +# +# - text-mode ``open()`` / ``Path.open()`` / ``read_text()`` without +# ``encoding=`` +# - text-mode writes (``"w"``, ``"x"``, ``"+"`` and ``write_text()``) without +# ``newline=``; append-mode log files only need ``encoding=`` +# - ``text=True`` / ``universal_newlines=True`` (in a call or in a kwargs dict +# literal) without ``encoding=`` +# +# Generated template payloads (``fastapi_project_template``) are not fastkit +# code and are excluded. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +from pathlib import Path +from typing import Iterator, List, Optional, Set, Tuple + +import pytest + +import fastapi_fastkit + +PACKAGE_ROOT = Path(fastapi_fastkit.__file__).parent +EXCLUDED_DIRS = {"fastapi_project_template", "__pycache__"} + +#: Call sites that are deliberately exempt, as ``(package-relative path, +#: substring of the offending source line)``. Every entry needs a reason. +ALLOWLIST: Set[Tuple[str, str]] = set() + +#: Receivers whose ``.open()`` is not a text-file open. +_NON_FILE_OPEN_RECEIVERS = {"os", "webbrowser", "tarfile", "zipfile", "gzip", "bz2"} + +#: Callables whose ``.open()`` takes the file as the first argument, so the +#: mode is the second positional argument. +_FILE_FIRST_OPEN_RECEIVERS = {"io", "codecs"} + + +def _keyword(call: ast.Call, name: str) -> Optional[ast.keyword]: + return next((kw for kw in call.keywords if kw.arg == name), None) + + +def _has_kwargs_unpack(call: ast.Call) -> bool: + return any(kw.arg is None for kw in call.keywords) + + +def _is_true(node: Optional[ast.expr]) -> bool: + return isinstance(node, ast.Constant) and node.value is True + + +def _open_mode(call: ast.Call, mode_index: int) -> Optional[ast.expr]: + keyword = _keyword(call, "mode") + if keyword is not None: + return keyword.value + if len(call.args) > mode_index: + return call.args[mode_index] + return None + + +def _check_open(call: ast.Call, mode_index: int) -> List[str]: + """Problems of an ``open``-like call whose mode sits at ``mode_index``.""" + if _has_kwargs_unpack(call): + return [] + + mode_node = _open_mode(call, mode_index) + if mode_node is None: + mode: Optional[str] = "r" + elif isinstance(mode_node, ast.Constant) and isinstance(mode_node.value, str): + mode = mode_node.value + else: + mode = None # computed mode: treat as text, demand an encoding + + if mode is not None and "b" in mode: + return [] + + problems = [] + # encoding is the 4th parameter of open() (index 3), 3rd of Path.open(). + encoding_index = mode_index + 2 + if _keyword(call, "encoding") is None and len(call.args) <= encoding_index: + problems.append("text-mode open() without encoding=") + if mode is not None and any(flag in mode for flag in "wx+"): + if _keyword(call, "newline") is None: + problems.append(f"text-mode write open(mode={mode!r}) without newline=") + return problems + + +def _check_call(call: ast.Call) -> List[str]: + func = call.func + problems: List[str] = [] + + if isinstance(func, ast.Name) and func.id == "open": + problems += _check_open(call, mode_index=1) + elif isinstance(func, ast.Attribute) and func.attr == "open": + receiver = func.value + receiver_name = receiver.id if isinstance(receiver, ast.Name) else None + if receiver_name in _FILE_FIRST_OPEN_RECEIVERS: + problems += _check_open(call, mode_index=1) + elif receiver_name not in _NON_FILE_OPEN_RECEIVERS: + problems += _check_open(call, mode_index=0) + elif isinstance(func, ast.Attribute) and func.attr == "read_text": + if not call.args and _keyword(call, "encoding") is None: + problems.append("read_text() without encoding=") + elif isinstance(func, ast.Attribute) and func.attr == "write_text": + if len(call.args) < 2 and _keyword(call, "encoding") is None: + problems.append("write_text() without encoding=") + if len(call.args) < 4 and _keyword(call, "newline") is None: + problems.append("write_text() without newline=") + + text_mode = _keyword(call, "text") or _keyword(call, "universal_newlines") + if ( + text_mode is not None + and _is_true(text_mode.value) + and _keyword(call, "encoding") is None + and not _has_kwargs_unpack(call) + ): + problems.append("text=True without encoding=") + + return problems + + +def _check_dict(node: ast.Dict) -> List[str]: + """``{"text": True, ...}`` kwargs dicts built for subprocess calls.""" + keys = { + key.value: value + for key, value in zip(node.keys, node.values) + if isinstance(key, ast.Constant) and isinstance(key.value, str) + } + text_mode = keys.get("text") or keys.get("universal_newlines") + if _is_true(text_mode) and "encoding" not in keys: + return ["kwargs dict with text=True but no 'encoding'"] + return [] + + +def scan_source(source: str, filename: str = "") -> List[Tuple[int, str]]: + """Return ``(line, problem)`` pairs for one module's source.""" + tree = ast.parse(source, filename=filename) + found: List[Tuple[int, str]] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + found += [(node.lineno, problem) for problem in _check_call(node)] + elif isinstance(node, ast.Dict): + found += [(node.lineno, problem) for problem in _check_dict(node)] + return sorted(found) + + +def _package_modules() -> Iterator[Path]: + for path in sorted(PACKAGE_ROOT.rglob("*.py")): + if EXCLUDED_DIRS.intersection(path.relative_to(PACKAGE_ROOT).parts): + continue + yield path + + +def _violations() -> List[str]: + violations = [] + for path in _package_modules(): + relative = path.relative_to(PACKAGE_ROOT).as_posix() + source = path.read_text(encoding="utf-8") + lines = source.splitlines() + for lineno, problem in scan_source(source, str(path)): + line = lines[lineno - 1].strip() + if any(rel == relative and snippet in line for rel, snippet in ALLOWLIST): + continue + violations.append(f"{relative}:{lineno}: {problem}: {line}") + return violations + + +def test_package_text_io_is_portable() -> None: + violations = _violations() + assert violations == [], "Platform-default text I/O:\n" + "\n".join(violations) + + +def test_package_modules_are_scanned() -> None: + relatives = {p.relative_to(PACKAGE_ROOT).as_posix() for p in _package_modules()} + assert "backend/main.py" in relatives + assert "utils/config_file.py" in relatives + assert not any(r.startswith("fastapi_project_template/") for r in relatives) + + +@pytest.mark.parametrize( + "snippet", + [ + 'open(p, "r")', + "open(p)", + 'open(p, "w", encoding="utf-8")', + 'open(p, mode="x", encoding="utf-8")', + 'open(p, "r+", encoding="utf-8")', + "open(p, mode)", + 'path.open("w", encoding="utf-8")', + "path.open()", + 'io.open(p, "w")', + "path.read_text()", + 'path.write_text("x")', + 'path.write_text("x", encoding="utf-8")', + 'subprocess.run(["x"], text=True)', + 'subprocess.Popen(["x"], universal_newlines=True)', + 'kwargs = {"text": True, "capture_output": True}', + ], +) +def test_scanner_flags_platform_defaults(snippet: str) -> None: + assert scan_source(snippet) != [], snippet + + +@pytest.mark.parametrize( + "snippet", + [ + 'open(p, "rb")', + 'open(p, "wb")', + 'open(p, encoding="utf-8")', + 'open(p, "r", encoding="utf-8", errors="replace")', + 'open(p, "w", encoding="utf-8", newline="\\n")', + 'open(p, "x", encoding="utf-8", newline="")', + 'open(p, "a", encoding="utf-8")', + 'path.open("rb")', + 'path.open("w", encoding="utf-8", newline="\\n")', + "os.open(p, os.O_RDONLY)", + "webbrowser.open(url)", + 'path.read_text(encoding="utf-8")', + 'path.write_text("x", encoding="utf-8", newline="\\n")', + 'subprocess.run(["x"], text=True, encoding="utf-8")', + 'subprocess.run(["x"], capture_output=True)', + "subprocess.run(cmd, **kwargs)", + 'kwargs = {"text": True, "encoding": "utf-8"}', + ], +) +def test_scanner_accepts_explicit_settings(snippet: str) -> None: + assert scan_source(snippet) == [], snippet diff --git a/tests/test_templates/test_all_templates.py b/tests/test_templates/test_all_templates.py index 0fea11fd..13abfb14 100644 --- a/tests/test_templates/test_all_templates.py +++ b/tests/test_templates/test_all_templates.py @@ -19,7 +19,18 @@ #: File suffixes worth scanning for placeholder residue. "" covers extensionless #: files such as Dockerfile and .env, which templates do use placeholders in. -_TEXT_SUFFIXES = {"", ".py", ".toml", ".md", ".txt", ".yml", ".yaml", ".ini", ".sh"} +_TEXT_SUFFIXES = { + "", + ".example", + ".py", + ".toml", + ".md", + ".txt", + ".yml", + ".yaml", + ".ini", + ".sh", +} def _files_with_placeholder_residue(project_path: Path) -> List[str]: @@ -65,7 +76,12 @@ def get_template_metadata(cls, template_name: str) -> Dict[str, Any]: # Every template is pyproject-first: ``pyproject.toml`` is the single # metadata file, and ``setup.py-tpl`` no longer ships with any of them. metadata = { - "expected_files": ["pyproject.toml", "README.md", "src/main.py"], + "expected_files": [ + "pyproject.toml", + "README.md", + "src/main.py", + ".gitattributes", + ], "required_dirs": ["src", "tests"], "package_manager": "uv", # Default package manager } @@ -75,6 +91,7 @@ def get_template_metadata(cls, template_name: str) -> Dict[str, Any]: app_layout_files = [ "README.md", "pyproject.toml", + ".gitattributes", "src/app/main.py", "src/app/core/config.py", "src/app/api/health.py", diff --git a/tests/test_templates/test_domain_starter_e2e.py b/tests/test_templates/test_domain_starter_e2e.py index f14788b0..1bbd9a11 100644 --- a/tests/test_templates/test_domain_starter_e2e.py +++ b/tests/test_templates/test_domain_starter_e2e.py @@ -20,7 +20,6 @@ import os import subprocess -import sys import tomllib from pathlib import Path from typing import Iterator @@ -32,6 +31,7 @@ from fastapi_fastkit.cli import fastkit_cli from fastapi_fastkit.core.settings import FastkitConfig from fastapi_fastkit.utils.main import is_fastkit_project +from fastapi_fastkit.utils.platform import venv_python as platform_venv_python _TEMPLATE_NAME = "fastapi-domain-starter" @@ -210,11 +210,6 @@ class TestStartdemoGeneratedAppRuns: files (e.g. wrong import paths after a refactor) would slip through. """ - @pytest.mark.skipif( - sys.platform == "win32", - reason="venv binary path differs on Windows; the rest of the " - "domain-starter flow is already covered there by other tests.", - ) def test_generated_app_serves_health_endpoint( self, runner: CliRunner, isolated_workspace: Path ) -> None: @@ -227,7 +222,7 @@ def test_generated_app_serves_health_endpoint( # template's deps installed. That's what we want to drive the # TestClient with — fastapi/httpx are not installed in the dev # environment that runs this test suite. - venv_python = project_path / ".venv" / "bin" / "python" + venv_python = Path(platform_venv_python(project_path / ".venv")) assert venv_python.exists(), ( f"Generated venv python missing at {venv_python}. " f"startdemo did not provision a uv venv." diff --git a/tests/test_templates/test_feature_route_collisions.py b/tests/test_templates/test_feature_route_collisions.py new file mode 100644 index 00000000..74d8999d --- /dev/null +++ b/tests/test_templates/test_feature_route_collisions.py @@ -0,0 +1,419 @@ +# -------------------------------------------------------------------------- +# Route-collision regression test for generated feature routers. +# +# Every preset is generated with all route-registering features selected +# (no virtualenv, no install). The generated sources are then read with +# ``ast`` only, nothing is imported: routers, their prefixes, the route +# decorators and the ``include_router`` chain starting at the entrypoint +# ``app`` are resolved statically, and the test asserts that no two mounted +# routes claim the same method and path (or overlap through a path +# parameter), and that no generated feature router claims a route the base +# template serves. This guards against feature fragments shadowing an API +# the base template already ships, such as the pagination demo on +# ``GET /api/v1/items`` that used to be mounted in front of the +# domain-starter items domain. Presets whose base template ships an items +# collection now get ``add_pagination(app)`` without the demo router. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import json +import os +import re +import tomllib +from pathlib import Path +from typing import Dict, List, Optional, Set, Tuple + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) +from fastapi_fastkit.cli import fastkit_cli + +_ROUTE_METHODS = { + "get": "GET", + "post": "POST", + "put": "PUT", + "patch": "PATCH", + "delete": "DELETE", + "head": "HEAD", + "options": "OPTIONS", + "websocket": "WS", +} + +_PAGINATION_PATH = "/api/v1/items" + +#: Presets whose base template ships an items collection (no pagination demo). +_SHIPS_ITEMS = {"classic-layered", "domain-starter"} + +#: ``(module, attribute)`` naming one router (or the ``FastAPI`` app). +RouterRef = Tuple[str, str] + + +def _route_config(preset: str, auth: str) -> Dict[str, object]: + """Every selectable feature that registers a router or route.""" + return { + "project_name": "routeapp", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "route collision check", + "package_manager": "pip", + "preset": preset, + "database": {"type": "PostgreSQL"}, + "authentication": {"type": auth}, + "async_tasks": {"type": "Celery"}, + "caching": {"type": "Redis"}, + "monitoring": "Prometheus", + "logging": {"type": "structured"}, + "testing": "Advanced", + "migrations": {"type": "Alembic"}, + "tooling": ["ruff"], + "utilities": ["CORS", "Rate-Limiting", "WebSocket", "Pagination"], + } + + +def _generate(config: Dict[str, object], workspace: Path) -> Path: + config_path = workspace / "fastkit.config.json" + config_path.write_text(json.dumps(config), encoding="utf-8") + previous = os.getcwd() + os.chdir(workspace) + try: + result = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + finally: + os.chdir(previous) + project = workspace / str(config["project_name"]) + assert result.exit_code == 0, result.output + assert project.is_dir(), result.output + return project + + +class _Module: + """What one generated module contributes to the route graph.""" + + def __init__(self, name: str, tree: ast.Module) -> None: + self.name = name + self.tree = tree + #: local name -> (source module, imported attribute) + self.imports: Dict[str, Tuple[str, str]] = {} + #: local router name -> prefix expression (``None`` for the app) + self.routers: Dict[str, Optional[ast.expr]] = {} + self.routes: Dict[str, List[Tuple[str, str]]] = {} + #: (parent router name, child expression, prefix expression) + self.includes: List[Tuple[str, ast.expr, Optional[ast.expr]]] = [] + + +def _call_name(node: ast.expr) -> Optional[str]: + if isinstance(node, ast.Call): + func = node.func + if isinstance(func, ast.Name): + return func.id + if isinstance(func, ast.Attribute): + return func.attr + return None + + +def _keyword(call: ast.Call, name: str) -> Optional[ast.expr]: + for keyword in call.keywords: + if keyword.arg == name: + return keyword.value + return None + + +def _load_modules(project: Path) -> Dict[str, _Module]: + modules: Dict[str, _Module] = {} + for source in sorted((project / "src").rglob("*.py")): + relative = source.relative_to(project).with_suffix("") + parts = list(relative.parts) + if parts[-1] == "__init__": + parts = parts[:-1] + name = ".".join(parts) + tree = ast.parse(source.read_text(encoding="utf-8"), str(source)) + modules[name] = _scan_module(name, tree) + return modules + + +def _scan_module(name: str, tree: ast.Module) -> _Module: + module = _Module(name, tree) + for node in tree.body: + if isinstance(node, ast.ImportFrom) and node.module and node.level == 0: + for alias in node.names: + module.imports[alias.asname or alias.name] = (node.module, alias.name) + elif isinstance(node, ast.Assign) and len(node.targets) == 1: + target = node.targets[0] + if isinstance(target, ast.Name): + callee = _call_name(node.value) + if callee == "APIRouter": + assert isinstance(node.value, ast.Call) + module.routers[target.id] = _keyword(node.value, "prefix") + elif callee == "FastAPI": + module.routers[target.id] = None + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + for decorator in node.decorator_list: + if not ( + isinstance(decorator, ast.Call) + and isinstance(decorator.func, ast.Attribute) + and isinstance(decorator.func.value, ast.Name) + and decorator.func.attr in _ROUTE_METHODS + ): + continue + path = decorator.args[0] if decorator.args else None + assert isinstance(path, ast.Constant), ast.dump(decorator) + module.routes.setdefault(decorator.func.value.id, []).append( + (_ROUTE_METHODS[decorator.func.attr], str(path.value)) + ) + + # ``include_router`` / Prometheus ``expose`` may sit inside ``if`` blocks + # or the lifespan function, so walk the whole tree for those calls. + for call in ast.walk(tree): + if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)): + continue + if call.func.attr == "include_router" and isinstance(call.func.value, ast.Name): + module.includes.append( + (call.func.value.id, call.args[0], _keyword(call, "prefix")) + ) + elif call.func.attr == "expose" and call.args: + app = call.args[0] + assert isinstance(app, ast.Name) + module.routes.setdefault(app.id, []).append(("GET", "/metrics")) + return module + + +def _string_constants(modules: Dict[str, _Module]) -> Dict[str, str]: + """``NAME = "..."`` / ``NAME: str = "..."`` anywhere (settings classes).""" + constants: Dict[str, str] = {} + for module in modules.values(): + for node in ast.walk(module.tree): + target: Optional[ast.expr] = None + value: Optional[ast.expr] = None + if isinstance(node, ast.AnnAssign): + target, value = node.target, node.value + elif isinstance(node, ast.Assign) and len(node.targets) == 1: + target, value = node.targets[0], node.value + if ( + isinstance(target, ast.Name) + and isinstance(value, ast.Constant) + and isinstance(value.value, str) + and target.id.isupper() + ): + constants[target.id] = value.value + return constants + + +def _prefix(expr: Optional[ast.expr], constants: Dict[str, str]) -> str: + if expr is None: + return "" + if isinstance(expr, ast.Constant) and isinstance(expr.value, str): + return expr.value + name = expr.attr if isinstance(expr, ast.Attribute) else getattr(expr, "id", "") + assert name in constants, f"cannot resolve prefix {ast.dump(expr)}" + return constants[name] + + +def _resolve_name( + modules: Dict[str, _Module], module_name: str, local: str +) -> Optional[RouterRef]: + """Follow ``local`` in ``module_name`` to the module defining it.""" + seen: Set[RouterRef] = set() + while (module_name, local) not in seen: + seen.add((module_name, local)) + module = modules.get(module_name) + if module is None: + return None + if local in module.routers: + return (module_name, local) + if local not in module.imports: + return None + module_name, local = module.imports[local] + return None + + +def _resolve_child( + modules: Dict[str, _Module], module: _Module, expr: ast.expr +) -> RouterRef: + if isinstance(expr, ast.Name): + ref = _resolve_name(modules, module.name, expr.id) + elif isinstance(expr, ast.Attribute) and isinstance(expr.value, ast.Name): + # ``health.router`` where ``health`` is an imported submodule. + source, attr = module.imports[expr.value.id] + ref = _resolve_name(modules, f"{source}.{attr}", expr.attr) + else: + ref = None + assert ref is not None, f"{module.name}: cannot resolve {ast.dump(expr)}" + return ref + + +def _mounted_routes(project: Path) -> List[Tuple[str, str, str]]: + """``(method, full path, defining router)`` for everything ``app`` mounts.""" + pyproject = tomllib.loads((project / "pyproject.toml").read_text(encoding="utf-8")) + app_module, app_attr = pyproject["tool"]["fastapi-fastkit"]["app_module"].split( + ":", 1 + ) + modules = _load_modules(project) + constants = _string_constants(modules) + + collected: List[Tuple[str, str, str]] = [] + + def visit(ref: RouterRef, prefix: str, depth: int) -> None: + assert depth < 10, f"include_router cycle at {ref}" + module = modules[ref[0]] + full_prefix = prefix + _prefix(module.routers[ref[1]], constants) + for method, path in module.routes.get(ref[1], []): + collected.append((method, full_prefix + path, f"{ref[0]}:{ref[1]}")) + for parent, child, include_prefix in module.includes: + if parent != ref[1]: + continue + child_ref = _resolve_child(modules, module, child) + visit( + child_ref, full_prefix + _prefix(include_prefix, constants), depth + 1 + ) + + visit((app_module, app_attr), "", 0) + return collected + + +_PARAM = re.compile(r"^\{[^}]+\}$") + + +def _overlaps(left: str, right: str) -> bool: + """True when one path can match a request meant for the other.""" + left_parts = left.rstrip("/").split("/") + right_parts = right.rstrip("/").split("/") + if len(left_parts) != len(right_parts): + return False + return all( + a == b or _PARAM.match(a) or _PARAM.match(b) + for a, b in zip(left_parts, right_parts) + ) + + +def _collisions(routes: List[Tuple[str, str, str]]) -> List[str]: + found = [] + for index, (method, path, owner) in enumerate(routes): + for other_method, other_path, other_owner in routes[index + 1 :]: + if method == other_method and _overlaps(path, other_path): + found.append( + f"{method} {path} ({owner}) vs {other_path} ({other_owner})" + ) + return found + + +def _base_config(preset: str) -> Dict[str, object]: + """The preset with nothing that registers a route of its own.""" + config = _route_config(preset, "JWT") + config["utilities"] = [] + config["async_tasks"] = {"type": "None"} + config["caching"] = {"type": "None"} + config["monitoring"] = "None" + return config + + +def _is_generated_feature(owner: str) -> bool: + """Routers fastkit generates for a feature (not the template, not main).""" + module = owner.split(":", 1)[0] + return ".features." in module or module.endswith((".auth", ".main")) + + +@pytest.mark.parametrize("auth", ["Session-based", "OAuth2"]) +@pytest.mark.parametrize("preset", PresetLayoutStrategist.supported_presets()) +def test_generated_routes_do_not_collide( + preset: str, auth: str, tmp_path: Path +) -> None: + # given + project = _generate(_route_config(preset, auth), tmp_path) + + # when + routes = _mounted_routes(project) + + # then: the resolver actually reached the generated feature routers + pairs = {(method, path) for method, path, _ in routes} + assert ("POST", "/api/v1/tasks") in pairs, sorted(pairs) + assert ("WS", "/ws") in pairs, sorted(pairs) + pagination_owners = [ + owner for _, _, owner in routes if owner.endswith("features.pagination:router") + ] + if preset in _SHIPS_ITEMS: + # the template's own items list is served, no demo router is mounted + assert pagination_owners == [] + else: + assert len(pagination_owners) == 1 + if preset == "classic-layered": + assert ("GET", "/items") in pairs, sorted(pairs) + else: + # the demo (minimal, single-module) or the domain-starter items list + assert ("GET", _PAGINATION_PATH) in pairs, sorted(pairs) + + # and no two mounted routes compete for the same request + assert _collisions(routes) == [] + + +@pytest.mark.parametrize("preset", PresetLayoutStrategist.supported_presets()) +def test_no_generated_router_claims_a_base_template_route( + preset: str, tmp_path: Path +) -> None: + # given: the routes the preset serves without any route-adding feature + (tmp_path / "base").mkdir() + (tmp_path / "full").mkdir() + base = _mounted_routes(_generate(_base_config(preset), tmp_path / "base")) + assert base, "no base-template routes were collected" + + # when: every route-registering feature is selected + full = _mounted_routes( + _generate(_route_config(preset, "OAuth2"), tmp_path / "full") + ) + generated = [route for route in full if _is_generated_feature(route[2])] + assert generated, "no generated feature routes were collected" + + # then + claimed = [ + f"{method} {path} ({owner}) vs base {base_path} ({base_owner})" + for method, path, owner in generated + for base_method, base_path, base_owner in base + if method == base_method and owner != base_owner and _overlaps(path, base_path) + ] + assert claimed == [] + + +@pytest.mark.parametrize("preset", PresetLayoutStrategist.supported_presets()) +def test_pagination_demo_only_for_presets_without_an_items_api( + preset: str, tmp_path: Path +) -> None: + # given + config = _route_config(preset, "JWT") + config["utilities"] = ["Pagination"] + config_path = tmp_path / "fastkit.config.json" + config_path.write_text(json.dumps(config), encoding="utf-8") + + # when: a dry run and a real run with the same configuration + previous = os.getcwd() + os.chdir(tmp_path) + try: + dry = CliRunner().invoke( + fastkit_cli, + ["init", "--config", str(config_path), "--no-venv", "--dry-run"], + ) + finally: + os.chdir(previous) + project = _generate(config, tmp_path) + + # then: the plan and the generated files agree + assert dry.exit_code == 0, dry.output + demo_files = list(project.rglob("features/pagination.py")) + main_text = ( + project / PresetLayoutStrategist(preset).profile.main_py_relpath + ).read_text(encoding="utf-8") + assert "add_pagination(app)" in main_text + if preset in _SHIPS_ITEMS: + assert demo_files == [] + assert "pagination.py" not in dry.output + assert "pagination_router" not in main_text + # the hint follows the template's own routers, which it applies to + assert main_text.rstrip().endswith("add_pagination(app)") + assert "Page[" in main_text + else: + assert len(demo_files) == 1 + assert "pagination.py" in dry.output + assert "app.include_router(pagination_router)" in main_text diff --git a/tests/test_templates/test_generated_gitignore.py b/tests/test_templates/test_generated_gitignore.py new file mode 100644 index 00000000..7babe71d --- /dev/null +++ b/tests/test_templates/test_generated_gitignore.py @@ -0,0 +1,124 @@ +# -------------------------------------------------------------------------- +# A generated project's .gitignore must not hide files the template ships. +# +# Broad rules copied from stock gitignore blocks (e.g. the virtualenv block's +# bare ``[Ss]cripts``) silently drop shipped files such as ``scripts/*.sh`` +# from the user's first commit. Only ``.env`` is meant to stay ignored. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import shutil +import subprocess +from pathlib import Path +from typing import List + +import pytest + +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.core.settings import FastkitConfig + +#: Files a generated project is expected to keep out of version control. +EXPECTED_IGNORED = {".env"} + + +def _template_root() -> Path: + return Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + + +def _templates() -> List[str]: + return sorted( + d.name + for d in _template_root().iterdir() + if d.is_dir() and d.name not in {"__pycache__", "modules"} + ) + + +def _shipped_files(template: str) -> List[str]: + """Project-relative paths of the files the template ships.""" + root = _template_root() / template + shipped = [] + for path in root.rglob("*"): + if not path.is_file() or "__pycache__" in path.parts: + continue + rel = path.relative_to(root).as_posix() + if rel.endswith("-tpl"): + rel = rel[: -len("-tpl")] + shipped.append(rel) + return sorted(shipped) + + +@pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed") +@pytest.mark.parametrize("template", _templates()) +def test_generated_project_does_not_ignore_shipped_files( + template: str, tmp_path: Path +) -> None: + # given + settings = FastkitConfig() + settings.USER_WORKSPACE = str(tmp_path) + options = ScaffoldOptions( + project_name="gitignore-test", + author="bnbong", + author_email="bbbong9@gmail.com", + description="gitignore testcase project", + package_manager="pip", + template=template, + with_venv=False, + with_install=False, + ) + project = Path(ProjectScaffolder(settings, options).run().project_dir) + + # Isolate from the developer's global/system git config and excludes + # file so only the generated project's .gitignore is evaluated. + empty_excludes = tmp_path / "empty-excludes" + empty_excludes.write_text("", encoding="utf-8") + env = { + **os.environ, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + } + + def git(*args: str, stdin: str = "") -> "subprocess.CompletedProcess[str]": + return subprocess.run( + ["git", "-c", f"core.excludesFile={empty_excludes}", *args], + cwd=project, + env=env, + input=stdin, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + + def paths(output: str) -> "set[str]": + # ``-z`` output is NUL-terminated and never quoted. + return {path for path in output.split("\0") if path} + + assert git("init", "-q").returncode == 0 + + shipped = [rel for rel in _shipped_files(template) if (project / rel).is_file()] + assert shipped, f"{template}: no shipped files found in the generated project" + + # when: paths go through stdin NUL-separated (``-z``). A text-mode pipe + # turns "\n" into "\r\n" on Windows, which would make git check the + # literal path ".env.example\r" instead of ".env.example". + checked = git( + "check-ignore", "--no-index", "--stdin", "-z", stdin="\0".join(shipped) + ) + assert checked.returncode in (0, 1), checked.stderr # 1 = nothing ignored + ignored_shipped = paths(checked.stdout) - EXPECTED_IGNORED + ignored_anywhere = ( + paths( + git("ls-files", "-z", "--others", "--ignored", "--exclude-standard").stdout + ) + - EXPECTED_IGNORED + ) + + # then + assert ( + not ignored_shipped + ), f"{template}: .gitignore hides shipped files {sorted(ignored_shipped)}" + assert ( + not ignored_anywhere + ), f"{template}: generated files are git-ignored {sorted(ignored_anywhere)}" + assert git("check-ignore", "-q", ".env").returncode == 0 diff --git a/tests/test_templates/test_generated_line_endings.py b/tests/test_templates/test_generated_line_endings.py new file mode 100644 index 00000000..cd85fa2b --- /dev/null +++ b/tests/test_templates/test_generated_line_endings.py @@ -0,0 +1,154 @@ +# -------------------------------------------------------------------------- +# Line endings of generated projects on a Windows-style checkout. +# +# Git for Windows and GUI clients (GitKraken, Sourcetree) default to +# ``core.autocrlf=true``. Without a ``.gitattributes`` in the generated +# project, a clone turns shell scripts, the Dockerfile and the Makefile into +# CRLF and the container dies with ``env: 'bash\r'``. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import shutil +import subprocess +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.core.settings import FastkitConfig + +#: Glob patterns (relative to the project root) of files executed by a POSIX +#: shell or inside a Linux container. They must stay LF in the working tree. +LF_REQUIRED_GLOBS = ( + "scripts/*.sh", + "**/*.sh", + "Dockerfile*", + "Makefile", + "docker-compose*.yml", + ".env.example", +) + + +def _templates() -> List[str]: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + return sorted( + d.name + for d in root.iterdir() + if d.is_dir() and d.name not in {"__pycache__", "modules"} + ) + + +def _generate(template: str, workspace: Path) -> Path: + settings = FastkitConfig() + settings.USER_WORKSPACE = str(workspace) + options: Dict[str, Any] = { + "project_name": "eol-test", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "line ending testcase project", + "package_manager": "pip", + "template": template, + "with_venv": False, + "with_install": False, + } + result = ProjectScaffolder(settings, ScaffoldOptions(**options)).run() + return Path(result.project_dir) + + +def _isolated_git_env() -> Dict[str, str]: + """Environment that ignores the developer's global/system git config.""" + return { + **os.environ, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + } + + +def _git(cwd: Path, *args: str) -> "subprocess.CompletedProcess[str]": + return subprocess.run( + ["git", *args], + cwd=cwd, + env=_isolated_git_env(), + capture_output=True, + text=True, + check=True, + ) + + +def commit_and_clone_with_crlf(project: Path, work_dir: Path) -> Path: + """ + Commit ``project`` with LF line endings, then clone it the way a Windows + client would (``core.autocrlf=true``, ``core.eol=crlf``). + + :param project: Generated project directory + :param work_dir: Scratch directory that receives the clone + :return: Path of the clone's working tree + """ + _git(project, "init", "-q") + _git(project, "-c", "core.autocrlf=false", "add", "-A") + _git( + project, + "-c", + "core.autocrlf=false", + "-c", + "user.name=fastkit", + "-c", + "user.email=fastkit@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "-q", + "--no-verify", + "-m", + "initial", + ) + + clone = work_dir / "windows-clone" + _git( + work_dir, + "clone", + "-q", + "-c", + "core.autocrlf=true", + "-c", + "core.eol=crlf", + str(project), + str(clone), + ) + return clone + + +def lf_required_files(clone: Path) -> List[Path]: + """Files in ``clone`` that must keep LF line endings.""" + found = { + path + for pattern in LF_REQUIRED_GLOBS + for path in clone.glob(pattern) + if path.is_file() and ".git" not in path.relative_to(clone).parts + } + return sorted(found) + + +@pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed") +@pytest.mark.parametrize("template", _templates()) +def test_crlf_checkout_keeps_container_files_lf(template: str, tmp_path: Path) -> None: + # given + workspace = tmp_path / "workspace" + workspace.mkdir() + project = _generate(template, workspace) + assert (project / ".gitattributes").is_file() + + # when + clone = commit_and_clone_with_crlf(project, tmp_path) + + # then: the CRLF checkout really happened (otherwise the check is vacuous) + readme = (clone / "README.md").read_bytes() + assert b"\r\n" in readme, "clone was not checked out with CRLF" + + # ...yet every shell / container file stayed LF + checked = lf_required_files(clone) + assert any(p.name == ".env.example" for p in checked) + crlf = [str(p.relative_to(clone)) for p in checked if b"\r\n" in p.read_bytes()] + assert crlf == [], f"CRLF in {template}: {crlf}" diff --git a/tests/test_templates/test_generated_pyproject.py b/tests/test_templates/test_generated_pyproject.py new file mode 100644 index 00000000..81ada44e --- /dev/null +++ b/tests/test_templates/test_generated_pyproject.py @@ -0,0 +1,166 @@ +# -------------------------------------------------------------------------- +# Generated pyproject.toml across every template and package manager. +# +# ``init``-style generation (an explicit dependency list) makes the package +# manager write its dependencies into the template's pyproject.toml. The +# result must stay valid TOML, keep the template's Python floor (never the +# old hard-coded 3.8), its [tool.*] tables and the fastkit marker. No +# virtualenv is created and nothing is installed, so no network is needed; +# the manager binaries are reported available so the requested manager is +# the one exercised whatever is installed on the machine. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import os +import tomllib +from pathlib import Path +from typing import Any, Dict, List +from unittest.mock import patch + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.core.settings import FastkitConfig + +_MANAGERS = { + "pip": "pip_manager.PipManager", + "uv": "uv_manager.UvManager", + "pdm": "pdm_manager.PdmManager", + "poetry": "poetry_manager.PoetryManager", +} + +_DEPENDENCIES = ["fastapi", "uvicorn[standard]", "pydantic-settings>=2.0"] + + +def _templates() -> List[str]: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + return sorted( + d.name + for d in root.iterdir() + if d.is_dir() and (d / "pyproject.toml-tpl").is_file() + ) + + +def _template_pyproject(template: str) -> Dict[str, Any]: + path = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) / template / "pyproject.toml-tpl" + return tomllib.loads(path.read_text(encoding="utf-8")) + + +def test_every_template_is_covered() -> None: + assert len(_templates()) == 12 + + +@pytest.mark.parametrize("manager", sorted(_MANAGERS)) +@pytest.mark.parametrize("template", _templates()) +def test_generated_pyproject_keeps_template_configuration( + template: str, manager: str, tmp_path: Path +) -> None: + # given + settings = FastkitConfig() + settings.USER_WORKSPACE = str(tmp_path) + options = ScaffoldOptions( + project_name="pyproject-app", + author="bnbong", + author_email="bbbong9@gmail.com", + description="pyproject merge test", + package_manager=manager, + template=template, + dependencies=list(_DEPENDENCIES), + with_venv=False, + with_install=False, + ) + target = f"fastapi_fastkit.backend.package_managers.{_MANAGERS[manager]}" + + # when + with patch(f"{target}.is_available", return_value=True): + result = ProjectScaffolder(settings, options).run() + + # then + pyproject = Path(result.project_dir) / "pyproject.toml" + data = tomllib.loads(pyproject.read_text(encoding="utf-8")) + template_data = _template_pyproject(template) + + floor = template_data["project"]["requires-python"] + assert data["project"]["requires-python"] == floor + assert "3.8" not in pyproject.read_text(encoding="utf-8") + + for tool in template_data.get("tool", {}): + if tool == "fastapi-fastkit": + continue + assert data["tool"][tool] == template_data["tool"][tool], tool + + fastkit = data["tool"]["fastapi-fastkit"] + assert fastkit["managed"] is True + assert fastkit["template"] == template + assert fastkit["package_manager"] == manager + + assert data["project"]["dependencies"] == sorted(_DEPENDENCIES) + if "dependency-groups" in template_data: + assert data["dependency-groups"] == template_data["dependency-groups"] + + if manager == "poetry": + poetry_deps = data["tool"]["poetry"]["dependencies"] + assert poetry_deps["python"] == floor + assert {"fastapi", "uvicorn", "pydantic-settings"} <= set(poetry_deps) + if manager != "pip": + requirements = Path(result.project_dir) / "requirements.txt" + lines = requirements.read_text(encoding="utf-8").splitlines() + assert lines == sorted(_DEPENDENCIES) + + +_PRESETS = ["minimal", "single-module", "classic-layered", "domain-starter"] + + +@pytest.mark.parametrize("tooling", [["pre-commit"], ["ruff", "pre-commit"]]) +@pytest.mark.parametrize("manager", sorted(_MANAGERS)) +@pytest.mark.parametrize("preset", _PRESETS) +def test_config_generation_writes_one_valid_pyproject( + preset: str, manager: str, tooling: List[str], tmp_path: Path +) -> None: + """``init --config``: black/ruff tables are added once, never duplicated.""" + # given + config = { + "project_name": "cfgapp", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "config pyproject test", + "package_manager": manager, + "preset": preset, + "database": {"type": "SQLite"}, + "testing": "Basic", + "tooling": tooling, + } + config_path = tmp_path / "fastkit.config.json" + config_path.write_text(json.dumps(config), encoding="utf-8") + target = f"fastapi_fastkit.backend.package_managers.{_MANAGERS[manager]}" + previous = os.getcwd() + os.chdir(tmp_path) + + # when + try: + with patch(f"{target}.is_available", return_value=True): + result = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + finally: + os.chdir(previous) + + # then + assert result.exit_code == 0, result.output + text = (tmp_path / "cfgapp" / "pyproject.toml").read_text(encoding="utf-8") + data = tomllib.loads(text) + template = PresetLayoutStrategist(preset).base_template + floor = _template_pyproject(template)["project"]["requires-python"] + assert data["project"]["requires-python"] == floor + assert text.count("[tool.black]") <= 1 + assert data["tool"]["fastapi-fastkit"]["preset"] == preset + if "ruff" in tooling: + assert text.count("[tool.ruff]") == 1 + else: + assert data["tool"]["black"]["target-version"] == ["py312"] diff --git a/tests/test_templates/test_template_smoke.py b/tests/test_templates/test_template_smoke.py new file mode 100644 index 00000000..14348694 --- /dev/null +++ b/tests/test_templates/test_template_smoke.py @@ -0,0 +1,167 @@ +# -------------------------------------------------------------------------- +# Template smoke test, written to be meaningful on a Windows CI runner. +# +# Every template is generated without a virtualenv while text-mode writes +# behave as on Windows (a missing ``newline=`` turns "\n" into "\r\n", see +# tests/windows_sim). The generated project must then +# +# - contain no CRLF in any file, +# - compile every ``.py`` file, +# - point ``[tool.fastapi-fastkit].app_module`` at a file that exists, +# - ship a local ``.env`` with its own SECRET_KEY next to ``.env.example``. +# +# A full-feature ``init --config`` project is held to the same line-ending +# rule for every package manager and preset. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import os +import re +import tomllib +from pathlib import Path +from typing import Any, Dict, List, Optional + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, +) +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.core.settings import FastkitConfig +from tests.windows_sim import crlf_files, windows_newline_default + +_SECRET_KEY_RE = re.compile(r"^[ \t]*(?:export[ \t]+)?SECRET_KEY[ \t]*=(.*)$", re.M) + + +def _templates() -> List[str]: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + return sorted( + d.name + for d in root.iterdir() + if d.is_dir() and d.name not in {"__pycache__", "modules"} + ) + + +def _generate(template: str, workspace: Path, name: str = "smoke-app") -> Path: + settings = FastkitConfig() + settings.USER_WORKSPACE = str(workspace) + options = ScaffoldOptions( + project_name=name, + author="bnbong", + author_email="bbbong9@gmail.com", + description="template smoke test", + package_manager="pip", + template=template, + with_venv=False, + with_install=False, + ) + with windows_newline_default(): + result = ProjectScaffolder(settings, options).run() + return Path(result.project_dir) + + +def _secret_key(path: Path) -> Optional[str]: + match = _SECRET_KEY_RE.search(path.read_text(encoding="utf-8")) + return match.group(1).strip() if match else None + + +def _app_module_file(project: Path) -> Path: + pyproject = tomllib.loads((project / "pyproject.toml").read_text(encoding="utf-8")) + app_module = pyproject["tool"]["fastapi-fastkit"]["app_module"] + module = app_module.split(":", 1)[0] + return project.joinpath(*module.split(".")).with_suffix(".py") + + +@pytest.mark.parametrize("template", _templates()) +def test_generated_template_is_portable(template: str, tmp_path: Path) -> None: + # given / when + project = _generate(template, tmp_path) + + # then: no CRLF anywhere, even with Windows' newline translation active + assert crlf_files(project) == [] + + # every Python file compiles + for source in sorted(project.rglob("*.py")): + compile(source.read_bytes(), str(source), "exec") + + # the recorded entrypoint exists + main_file = _app_module_file(project) + assert main_file.is_file(), f"app_module points at missing {main_file}" + + # the local .env carries its own key, never the example's + example = project / ".env.example" + env = project / ".env" + if example.is_file(): + assert env.is_file() + assert b"\r" not in env.read_bytes() + example_key = _secret_key(example) + if example_key is not None: + key = _secret_key(env) + assert key is not None and key != example_key + assert len(key) >= 43 + + +def test_two_generations_get_different_secret_keys(tmp_path: Path) -> None: + first = _generate("fastapi-default", tmp_path / "one") + second = _generate("fastapi-default", tmp_path / "two") + + first_key = _secret_key(first / ".env") + second_key = _secret_key(second / ".env") + assert first_key and second_key and first_key != second_key + + +FULL_CONFIG: Dict[str, Any] = { + "project_name": "fullapp", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "every feature at once", + "database": {"type": "PostgreSQL"}, + "authentication": {"type": "JWT"}, + "async_tasks": {"type": "Celery"}, + "caching": {"type": "Redis"}, + "monitoring": "Prometheus", + "logging": {"type": "structured"}, + "testing": "Advanced", + "migrations": {"type": "Alembic"}, + "tooling": ["ruff", "pre-commit", "github-actions", "devcontainer", "makefile"], + "deployment": ["Docker", "docker-compose"], + "utilities": ["CORS", "Rate-Limiting", "WebSocket", "Pagination"], +} + + +#: Every preset once (with pip) and every other package manager once. +_CONFIG_MATRIX = [ + ("pip", preset) for preset in PresetLayoutStrategist.supported_presets() +] +_CONFIG_MATRIX += [(manager, "minimal") for manager in ("uv", "pdm", "poetry")] + + +@pytest.mark.parametrize("package_manager,preset", _CONFIG_MATRIX) +def test_full_feature_config_project_has_no_crlf( + package_manager: str, preset: str, tmp_path: Path +) -> None: + # given + config = dict(FULL_CONFIG, package_manager=package_manager, preset=preset) + config_path = tmp_path / "fastkit.config.json" + config_path.write_text(json.dumps(config), encoding="utf-8") + previous = os.getcwd() + os.chdir(tmp_path) + + # when + try: + with windows_newline_default(): + result = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + finally: + os.chdir(previous) + + # then + project = tmp_path / "fullapp" + assert result.exit_code == 0, result.output + assert project.is_dir(), result.output + assert crlf_files(project) == [] + assert _app_module_file(project).is_file() diff --git a/tests/test_utils_platform.py b/tests/test_utils_platform.py new file mode 100644 index 00000000..3c5a4704 --- /dev/null +++ b/tests/test_utils_platform.py @@ -0,0 +1,525 @@ +# -------------------------------------------------------------------------- +# Testcases for the OS-difference helpers in ``fastapi_fastkit.utils.platform``. +# +# Windows behaviour is simulated by patching ``platform.is_windows``; ``os.name`` +# is never patched globally (Python 3.12's ``pathlib`` would then try to build +# ``WindowsPath`` objects on POSIX). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import io +import os +import shutil +import stat +import sys +from pathlib import Path +from typing import Any, Iterator +from unittest.mock import MagicMock, patch + +import pytest + +from fastapi_fastkit.utils import platform + +WINDOWS = "fastapi_fastkit.utils.platform.is_windows" + + +@pytest.fixture +def as_windows() -> Iterator[None]: + with patch(WINDOWS, return_value=True): + yield + + +@pytest.fixture +def as_posix() -> Iterator[None]: + with patch(WINDOWS, return_value=False): + yield + + +class TestVenvPaths: + @pytest.mark.parametrize( + ("windows", "expected"), + [ + (True, os.path.join("proj", ".venv", "Scripts", "python.exe")), + (False, os.path.join("proj", ".venv", "bin", "python")), + ], + ) + def test_venv_python(self, windows: bool, expected: str) -> None: + with patch(WINDOWS, return_value=windows): + assert platform.venv_python(os.path.join("proj", ".venv")) == expected + + @pytest.mark.parametrize( + ("windows", "expected"), + [ + (True, os.path.join("v", "Scripts", "pip.exe")), + (False, os.path.join("v", "bin", "pip")), + ], + ) + def test_venv_executable(self, windows: bool, expected: str) -> None: + with patch(WINDOWS, return_value=windows): + assert platform.venv_executable("v", "pip") == expected + + def test_venv_executable_keeps_an_explicit_extension( + self, as_windows: None + ) -> None: + assert platform.venv_executable("v", "activate.bat") == os.path.join( + "v", "Scripts", "activate.bat" + ) + + def test_accepts_path_objects(self, as_posix: None) -> None: + assert platform.venv_bin_dir(Path("v")) == os.path.join("v", "bin") + + def test_real_layout_matches_this_interpreter(self) -> None: + # The running test venv itself must follow the layout the helper + # predicts for this OS. + if sys.prefix == sys.base_prefix: + pytest.skip("tests are not running inside a virtual environment") + assert os.path.exists(platform.venv_python(sys.prefix)) + + +class TestResolveExecutable: + def test_posix_never_resolves(self, as_posix: None) -> None: + with patch.object(platform.shutil, "which") as which: + assert platform.resolve_executable("uv") == "uv" + which.assert_not_called() + + def test_windows_cmd_shim_is_resolved_to_its_path(self, as_windows: None) -> None: + shim = r"C:\Users\me\AppData\Roaming\npm\pdm.CMD" + with patch.object(platform.shutil, "which", return_value=shim): + assert platform.resolve_executable("pdm") == shim + + def test_windows_exe_keeps_the_bare_name(self, as_windows: None) -> None: + with patch.object(platform.shutil, "which", return_value=r"C:\tools\uv.exe"): + assert platform.resolve_executable("uv") == "uv" + + def test_windows_missing_tool_keeps_the_bare_name(self, as_windows: None) -> None: + with patch.object(platform.shutil, "which", return_value=None): + assert platform.resolve_executable("poetry") == "poetry" + + def test_paths_are_not_looked_up(self, as_windows: None) -> None: + explicit = os.path.join("tools", "uv") + with patch.object(platform.shutil, "which") as which: + assert platform.resolve_executable(explicit) == explicit + which.assert_not_called() + + def test_resolve_command_only_touches_the_program(self, as_windows: None) -> None: + with patch.object(platform.shutil, "which", return_value=r"C:\s\pdm.bat"): + assert platform.resolve_command(["pdm", "install"]) == [ + r"C:\s\pdm.bat", + "install", + ] + assert platform.resolve_command([]) == [] + + +class TestStdinIsInteractive: + def test_none_stdin(self) -> None: + with patch.object(platform.sys, "stdin", None): + assert platform.stdin_is_interactive() is False + + def test_non_tty(self) -> None: + with patch.object(platform.sys, "stdin", io.StringIO("")): + assert platform.stdin_is_interactive() is False + + def test_closed_stream(self) -> None: + stream = io.StringIO("") + stream.close() + with patch.object(platform.sys, "stdin", stream): + assert platform.stdin_is_interactive() is False + + def test_tty_on_posix(self, as_posix: None) -> None: + stream = MagicMock() + stream.isatty.return_value = True + with patch.object(platform.sys, "stdin", stream): + assert platform.stdin_is_interactive() is True + + def test_windows_asks_the_console_check(self, as_windows: None) -> None: + stream = MagicMock() + stream.isatty.return_value = True + with ( + patch.object(platform.sys, "stdin", stream), + patch.object( + platform, "_windows_console_attached", return_value=False + ) as attached, + ): + assert platform.stdin_is_interactive() is False + attached.assert_called_once_with(stream) + + @pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only fallback") + def test_console_check_falls_back_to_isatty_off_windows(self) -> None: + assert platform._windows_console_attached(MagicMock()) is True + + +def _fake_win32_console(console_mode: int) -> "dict[str, Any]": + """Stand-ins for the ``ctypes`` / ``msvcrt`` pieces the console check uses.""" + kernel32 = MagicMock() + kernel32.GetConsoleMode.return_value = console_mode + ctypes = MagicMock() + ctypes.windll.kernel32 = kernel32 + msvcrt = MagicMock() + msvcrt.get_osfhandle.return_value = 1234 + return {"ctypes": ctypes, "msvcrt": msvcrt} + + +class TestWindowsConsoleAttached: + """The Win32 branch, driven through fake ``ctypes`` / ``msvcrt`` modules.""" + + @pytest.mark.parametrize(("console_mode", "expected"), [(1, True), (0, False)]) + def test_console_mode_decides(self, console_mode: int, expected: bool) -> None: + # given: GetConsoleMode succeeds on a console and fails on ``NUL`` + modules = _fake_win32_console(console_mode) + stream = MagicMock() + stream.fileno.return_value = 0 + + # when + with ( + patch.object(platform.sys, "platform", "win32"), + patch.dict(sys.modules, modules), + ): + attached = platform._windows_console_attached(stream) + + # then: the OS handle of stdin's descriptor was asked + assert attached is expected + modules["msvcrt"].get_osfhandle.assert_called_once_with(0) + kernel32 = modules["ctypes"].windll.kernel32 + assert kernel32.GetConsoleMode.call_args.args[0] == 1234 + + def test_failure_to_ask_keeps_the_isatty_verdict(self) -> None: + # given: a stream without a usable descriptor + modules = _fake_win32_console(0) + stream = MagicMock() + stream.fileno.side_effect = io.UnsupportedOperation("fileno") + + # when + with ( + patch.object(platform.sys, "platform", "win32"), + patch.dict(sys.modules, modules), + ): + attached = platform._windows_console_attached(stream) + + # then + assert attached is True + modules["ctypes"].windll.kernel32.GetConsoleMode.assert_not_called() + + +def _wrapper(encoding: str) -> "tuple[io.BytesIO, io.TextIOWrapper]": + raw = io.BytesIO() + return raw, io.TextIOWrapper(raw, encoding=encoding, errors="strict") + + +class TestConfigureStdio: + def test_legacy_code_page_degrades_emoji_instead_of_raising(self) -> None: + raw, stream = _wrapper("cp1252") + with patch.object(platform.sys, "stdout", stream): + platform.configure_stdio() + stream.write("\u274c done") + stream.flush() + assert stream.errors == "replace" + assert raw.getvalue() == b"? done" + + def test_utf8_stream_is_left_alone(self) -> None: + _raw, stream = _wrapper("utf-8") + with patch.object(platform.sys, "stdout", stream): + platform.configure_stdio() + assert stream.errors == "strict" + + def test_missing_and_odd_streams_are_ignored(self) -> None: + # given: no stdout at all (pythonw), and a legacy-encoded stderr that + # cannot be reconfigured (a test runner's capture object) + odd = MagicMock(spec=["write", "encoding"]) + odd.encoding = "cp949" + + # when + with ( + patch.object(platform.sys, "stdout", None), + patch.object(platform.sys, "stderr", odd), + ): + platform.configure_stdio() + + # then: nothing raised, and neither stream was replaced + assert platform.sys.stdout is None + assert platform.sys.stderr is odd + # ...nor altered: no reconfigure attribute appeared, the encoding is + # untouched and nothing was written to it + assert not hasattr(odd, "reconfigure") + assert odd.encoding == "cp949" + odd.write.assert_not_called() + assert odd.method_calls == [] + + @pytest.mark.parametrize("encoding", [None, "", "no-such-codec"]) + def test_unknown_encoding_is_treated_as_not_utf8( + self, encoding: "str | None" + ) -> None: + # given: a stream whose encoding is missing or unknown to ``codecs`` + stream = MagicMock() + stream.encoding = encoding + + # when + with patch.object(platform.sys, "stdout", stream): + platform.configure_stdio() + + # then: it is made safe like any other non-UTF-8 stream + stream.reconfigure.assert_called_once_with(errors="replace") + + @pytest.mark.parametrize("encoding", ["utf-8", "UTF8", "utf_8"]) + def test_utf8_aliases_are_recognised(self, encoding: str) -> None: + stream = MagicMock() + stream.encoding = encoding + with patch.object(platform.sys, "stdout", stream): + platform.configure_stdio() + stream.reconfigure.assert_not_called() + + def test_reconfigure_failure_is_swallowed(self) -> None: + stream = MagicMock() + stream.encoding = "ascii" + stream.reconfigure.side_effect = ValueError("detached") + with patch.object(platform.sys, "stderr", stream): + platform.configure_stdio() + stream.reconfigure.assert_called_once_with(errors="replace") + + +def _make_read_only_tree(root: Path) -> Path: + """A tree shaped like ``.git/objects``: read-only files in a subdir.""" + objects = root / ".git" / "objects" / "ab" + objects.mkdir(parents=True) + blob = objects / "cdef" + blob.write_bytes(b"blob") + os.chmod(blob, stat.S_IREAD) + return blob + + +def _hard_link_or_skip(source: Path, link: Path) -> None: + try: + os.link(source, link) + except (OSError, AttributeError, NotImplementedError): + pytest.skip("hard links are not available on this file system") + + +class TestRmtreeForce: + def test_removes_read_only_files(self, tmp_path: Path) -> None: + # given + target = tmp_path / "proj" + _make_read_only_tree(target) + + # when + platform.rmtree_force(target) + + # then + assert not target.exists() + + @pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions") + def test_removes_entries_of_a_read_only_directory(self, tmp_path: Path) -> None: + # given + target = tmp_path / "proj" + locked = target / "locked" + locked.mkdir(parents=True) + (locked / "file").write_text("x") + os.chmod(locked, stat.S_IREAD | stat.S_IEXEC) + + # when + platform.rmtree_force(target) + + # then + assert not target.exists() + + @pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions") + def test_never_changes_permissions_outside_the_tree(self, tmp_path: Path) -> None: + # given + parent_mode = stat.S_IMODE(os.stat(tmp_path).st_mode) + target = tmp_path / "proj" + _make_read_only_tree(target) + + # when + platform.rmtree_force(target) + + # then + assert stat.S_IMODE(os.stat(tmp_path).st_mode) == parent_mode + + def test_missing_path_raises_unless_ignored(self, tmp_path: Path) -> None: + missing = tmp_path / "nope" + platform.rmtree_force(missing, ignore_errors=True) + with pytest.raises(FileNotFoundError): + shutil.rmtree(missing) # reference behaviour + # A vanished entry is not an error for rmtree_force either. + platform.rmtree_force(missing) + + def test_unrecoverable_error_propagates(self, tmp_path: Path) -> None: + # given + target = tmp_path / "proj" + target.mkdir() + (target / "f").write_text("x") + + def always_fail(path: Any, *args: Any, **kwargs: Any) -> None: + raise PermissionError(13, "in use", str(path)) + + # when / then: the retry fails too, so the original error surfaces + with patch.object(platform.os, "unlink", side_effect=always_fail): + with pytest.raises(PermissionError): + platform.rmtree_force(target) + platform.rmtree_force(target, ignore_errors=True) + + def test_handler_makes_entry_writable_and_retries(self, tmp_path: Path) -> None: + # given + blob = _make_read_only_tree(tmp_path / "proj") + handler = platform._rmtree_onexc(str(tmp_path / "proj"), False) + + # when + handler(os.unlink, str(blob), PermissionError(13, "denied")) + + # then: made writable, then removed by the retry + assert not blob.exists() + + def test_handler_does_not_retry_non_removal_calls(self, tmp_path: Path) -> None: + # ``rmtree`` reports a failed scandir/open with the same handler; + # repeating that call would succeed without deleting anything. + handler = platform._rmtree_onexc(str(tmp_path), False) + error = PermissionError(13, "denied") + with patch.object(platform.os, "chmod") as chmod: + with pytest.raises(PermissionError) as raised: + handler(os.scandir, str(tmp_path), error) + assert raised.value is error + chmod.assert_not_called() + + def test_handler_does_not_retry_non_permission_errors(self, tmp_path: Path) -> None: + handler = platform._rmtree_onexc(str(tmp_path), False) + error = OSError(39, "not empty") + with patch.object(platform.os, "rmdir") as rmdir: + with pytest.raises(OSError) as raised: + handler(rmdir, str(tmp_path), error) + rmdir.assert_not_called() + assert raised.value is error + + @pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions") + def test_hard_link_never_widens_a_file_outside_the_tree( + self, tmp_path: Path + ) -> None: + # given: a private file outside the tree, hard-linked into a + # read-only directory inside it (same inode, so same mode) + outside = tmp_path / "outside" + outside.mkdir() + secret = outside / "secret" + secret.write_text("s") + os.chmod(secret, stat.S_IRUSR) + target = tmp_path / "tree" + sub = target / "sub" + sub.mkdir(parents=True) + _hard_link_or_skip(secret, sub / "secret") + os.chmod(sub, stat.S_IRUSR | stat.S_IXUSR) + + # when + platform.rmtree_force(target) + + # then: the tree is gone and the outside file kept its 0400 mode + assert not target.exists() + assert secret.read_text() == "s" + assert stat.S_IMODE(os.stat(secret).st_mode) == stat.S_IRUSR + + @pytest.mark.skipif( + os.name == "nt", + reason="POSIX unlink semantics: Windows cannot delete a read-only file " + "by making only its parent writable", + ) + def test_posix_handler_only_touches_the_parent( + self, tmp_path: Path, as_posix: None + ) -> None: + # given + blob = _make_read_only_tree(tmp_path / "proj") + handler = platform._rmtree_onexc(str(tmp_path / "proj"), False) + real_chmod = os.chmod + + # when + with patch.object(platform.os, "chmod", side_effect=real_chmod) as chmod: + handler(os.unlink, str(blob), PermissionError(13, "denied")) + + # then + assert not blob.exists() + assert [Path(c.args[0]) for c in chmod.call_args_list] == [blob.parent] + + def test_windows_handler_adds_only_the_write_bit( + self, tmp_path: Path, as_windows: None + ) -> None: + # given + blob = _make_read_only_tree(tmp_path / "proj") + handler = platform._rmtree_onexc(str(tmp_path / "proj"), False) + real_chmod = os.chmod + expected_mode = stat.S_IMODE(os.lstat(blob).st_mode) | stat.S_IWRITE + + # when + with patch.object(platform.os, "chmod", side_effect=real_chmod) as chmod: + handler(os.unlink, str(blob), PermissionError(13, "denied")) + + # then: the entry itself got S_IWRITE (no other bits), then went away + assert not blob.exists() + chmod.assert_called_once_with(str(blob), expected_mode) + + def test_windows_handler_skips_hard_linked_files( + self, tmp_path: Path, as_windows: None + ) -> None: + # given: a read-only file also linked from outside the tree + outside = tmp_path / "outside" + outside.mkdir() + secret = outside / "secret" + secret.write_text("s") + os.chmod(secret, stat.S_IREAD) + target = tmp_path / "tree" + target.mkdir() + linked = target / "secret" + _hard_link_or_skip(secret, linked) + handler = platform._rmtree_onexc(str(target), False) + error = PermissionError(13, "denied") + + # when: the read-only attribute is shared, so it is left alone and + # the original error surfaces + with ( + patch.object(platform.os, "chmod") as chmod, + patch.object(platform.os, "unlink", side_effect=error) as unlink, + ): + with pytest.raises(PermissionError) as raised: + handler(unlink, str(linked), error) + + # then + assert raised.value is error + chmod.assert_not_called() + assert not os.stat(secret).st_mode & stat.S_IWRITE + os.chmod(secret, stat.S_IREAD | stat.S_IWRITE) # let tmp_path clean up + + def test_windows_handler_never_touches_entries_outside_the_root( + self, tmp_path: Path, as_windows: None + ) -> None: + # given: a read-only file that is not below the tree being removed + root = tmp_path / "tree" + root.mkdir() + outside = tmp_path / "outside" + outside.write_text("s") + os.chmod(outside, stat.S_IREAD) + handler = platform._rmtree_onexc(str(root), False) + error = PermissionError(13, "denied") + + # when + with ( + patch.object(platform.os, "chmod") as chmod, + patch.object(platform.os, "unlink", side_effect=error) as unlink, + ): + with pytest.raises(PermissionError) as raised: + handler(unlink, str(outside), error) + + # then: no attribute changed, and the original error surfaces + assert raised.value is error + chmod.assert_not_called() + os.chmod(outside, stat.S_IREAD | stat.S_IWRITE) # let tmp_path clean up + + def test_paths_that_cannot_be_compared_are_not_within(self) -> None: + # ``commonpath`` raises ValueError for paths on different Windows + # drives; mixing absolute and relative paths does the same on POSIX. + assert platform._is_within(os.path.abspath("a"), "relative") is False + assert platform._is_within(os.path.abspath("a"), os.path.abspath("")) is True + + def test_symlink_root_is_still_refused(self, tmp_path: Path) -> None: + real = tmp_path / "real" + real.mkdir() + link = tmp_path / "link" + try: + link.symlink_to(real, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("creating symlinks needs a privilege on this system") + with pytest.raises(OSError): + platform.rmtree_force(link) + assert real.exists() diff --git a/tests/windows_sim.py b/tests/windows_sim.py new file mode 100644 index 00000000..39174c71 --- /dev/null +++ b/tests/windows_sim.py @@ -0,0 +1,60 @@ +# -------------------------------------------------------------------------- +# Simulation of Windows text-mode defaults for tests running on any OS. +# +# On Windows, ``open(path, "w")`` without ``newline=`` translates every +# "\n" to "\r\n". CPython fixes that default at build time, so POSIX runs can +# not see it. ``windows_newline_default`` swaps ``open`` for a wrapper that +# applies the same translation whenever the caller left ``newline`` unset, +# which makes a forgotten ``newline="\n"`` visible as CRLF bytes on disk. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import io +from contextlib import contextmanager +from typing import Any, Iterator +from unittest.mock import patch + +_real_open = io.open + + +def _windows_default_open( + file: Any, + mode: str = "r", + buffering: int = -1, + encoding: Any = None, + errors: Any = None, + newline: Any = None, + closefd: bool = True, + opener: Any = None, +) -> Any: + if "b" not in mode and newline is None and any(flag in mode for flag in "wax+"): + newline = "\r\n" + return _real_open(file, mode, buffering, encoding, errors, newline, closefd, opener) + + +@contextmanager +def windows_newline_default() -> Iterator[None]: + """Make text-mode writes without ``newline=`` emit CRLF, as on Windows. + + Both ``builtins.open`` and ``io.open`` are patched: ``pathlib.Path`` + (``write_text``/``open``) goes through ``io.open``. + """ + with ( + patch("builtins.open", _windows_default_open), + patch("io.open", _windows_default_open), + ): + yield + + +def crlf_files(root: Any) -> list: + """Project-relative paths of files under ``root`` containing ``\\r\\n``.""" + from pathlib import Path + + base = Path(root) + return sorted( + str(path.relative_to(base)) + for path in base.rglob("*") + if path.is_file() + and ".git" not in path.relative_to(base).parts + and b"\r\n" in path.read_bytes() + )