├── .github ├── actions │ └── setup-python-env │ │ └── action.yml └── workflows │ ├── assets │ └── turing_team_pr_bot.png │ ├── main.yml │ ├── notify-pr-closed.yaml │ └── on-release-main.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yaml ├── docs ├── api-reference.md ├── assets │ ├── softwareone-logo-dark-mode.svg │ └── softwareone-logo-light-mode.svg ├── index.md ├── stylesheets │ └── extra.css └── templates │ └── partials │ └── logo.html ├── env.example ├── examples ├── __init__.py ├── test_missing_setup.py └── test_plugin_setup_with_async_db_engine_fixture.py ├── mkdocs.yml ├── pyproject.toml ├── pytest_capsqlalchemy ├── __init__.py ├── capturer.py ├── context.py ├── expression.py ├── plugin.py └── utils.py ├── sonar-project.properties ├── tests ├── __init__.py ├── conftest.py ├── test_capturer.py ├── test_context.py ├── test_expression.py └── test_plugin_usage.py ├── tox.ini └── uv.lock /.github/actions/setup-python-env/action.yml: -------------------------------------------------------------------------------- 1 | name: "Setup Python Environment" 2 | description: "Set up Python environment for the given Python version" 3 | 4 | inputs: 5 | python-version: 6 | description: "Python version to use" 7 | required: true 8 | default: "3.12" 9 | uv-version: 10 | description: "uv version to use" 11 | required: true 12 | default: "0.6.2" 13 | 14 | runs: 15 | using: "composite" 16 | steps: 17 | - uses: actions/setup-python@v5 18 | with: 19 | python-version: ${{ inputs.python-version }} 20 | 21 | - name: Install uv 22 | uses: astral-sh/setup-uv@v2 23 | with: 24 | version: ${{ inputs.uv-version }} 25 | enable-cache: 'true' 26 | cache-suffix: ${{ matrix.python-version }} 27 | 28 | - name: Install Python dependencies 29 | run: uv sync --frozen 30 | shell: bash 31 | -------------------------------------------------------------------------------- /.github/workflows/assets/turing_team_pr_bot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/softwareone-platform/pytest-capsqlalchemy/f3ce1fd19becd313f85262e1fdd4bf534d5effcf/.github/workflows/assets/turing_team_pr_bot.png -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Main 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | types: [opened, synchronize, reopened, ready_for_review] 9 | 10 | 11 | jobs: 12 | quality: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Check out 16 | uses: actions/checkout@v4 17 | 18 | - uses: actions/cache@v4 19 | with: 20 | path: ~/.cache/pre-commit 21 | key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }} 22 | 23 | - name: Set up the environment 24 | uses: ./.github/actions/setup-python-env 25 | 26 | - name: Run checks 27 | run: make check 28 | 29 | - name: Run type check 30 | run: uv run mypy 31 | 32 | - name: Check if documentation can be built 33 | run: uv run mkdocs build -s 34 | 35 | tests: 36 | services: 37 | db: 38 | image: postgres:17 39 | env: 40 | POSTGRES_DB: test_postgres 41 | POSTGRES_USER: postgres 42 | POSTGRES_PASSWORD: mysecurepassword 43 | options: >- 44 | --health-cmd pg_isready 45 | --health-interval 10s 46 | --health-timeout 5s 47 | --health-retries 5 48 | ports: 49 | - 5432:5432 50 | 51 | runs-on: ubuntu-latest 52 | strategy: 53 | matrix: 54 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] 55 | fail-fast: false 56 | defaults: 57 | run: 58 | shell: bash 59 | steps: 60 | - name: Check out 61 | uses: actions/checkout@v4 62 | 63 | - name: Set up the environment 64 | uses: ./.github/actions/setup-python-env 65 | with: 66 | python-version: ${{ matrix.python-version }} 67 | 68 | - name: Run tests 69 | run: uv run pytest 70 | env: 71 | TEST_POSTGRES_DB: test_postgres 72 | TEST_POSTGRES_USER: postgres 73 | TEST_POSTGRES_PASSWORD: mysecurepassword 74 | TEST_POSTGRES_HOST: localhost 75 | TEST_POSTGRES_PORT: 5432 76 | 77 | - name: Save code coverage report in the artefacts 78 | uses: actions/upload-artifact@v4 79 | if: ${{ !env.ACT }} 80 | with: 81 | name: coverage-report-${{ matrix.python-version }} 82 | path: htmlcov 83 | retention-days: 10 84 | 85 | - name: SonarQube Scan for the lowest supported version 86 | uses: sonarsource/sonarqube-scan-action@v4 87 | if: ${{ !env.ACT && matrix.python-version == '3.9' }} 88 | env: 89 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 90 | 91 | - name: SonarQube Quality Gate check for the lowest supported version 92 | id: sonarqube-quality-gate-check 93 | uses: sonarsource/sonarqube-quality-gate-action@master 94 | if: ${{ !env.ACT && matrix.python-version == '3.9' }} 95 | with: 96 | pollingTimeoutSec: 600 97 | env: 98 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 99 | 100 | - name: Compute added/removed lines for notification 101 | if: ${{ github.event_name == 'pull_request' && !env.ACT && matrix.python-version == '3.9'}} 102 | id: diff 103 | run: | 104 | PR_DATA=$(gh pr view "${{ github.event.pull_request.number }}" --json additions,deletions -q '.') 105 | ADDITIONS=$(echo "$PR_DATA" | jq '.additions') 106 | DELETIONS=$(echo "$PR_DATA" | jq '.deletions') 107 | echo "additions=$ADDITIONS" >> $GITHUB_OUTPUT 108 | echo "deletions=$DELETIONS" >> $GITHUB_OUTPUT 109 | env: 110 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 111 | - name: Notify Microsoft Teams 112 | if: ${{ github.event_name == 'pull_request' && !env.ACT && matrix.python-version == '3.9'}} 113 | uses: softwareone-platform/notify-pr-teams-action@v4 114 | with: 115 | webhook_url: ${{ secrets.TEAMS_WEBHOOK_URL }} 116 | bot_image_url: https://raw.githubusercontent.com/softwareone-platform/pytest-capsqlalchemy/main/.github/workflows/assets/turing_team_pr_bot.png 117 | repo: ${{ github.repository }} 118 | pr_url: ${{ github.event.pull_request.html_url }} 119 | pr_title: ${{ github.event.pull_request.title }} 120 | pr_author: ${{ github.event.pull_request.user.login }} 121 | head_ref: ${{ github.event.pull_request.head.ref }} 122 | base_ref: ${{ github.event.pull_request.base.ref }} 123 | commits: ${{ github.event.pull_request.commits }} 124 | changed_files: ${{ github.event.pull_request.changed_files }} 125 | additions: ${{ steps.diff.outputs.additions }} 126 | deletions: ${{ steps.diff.outputs.deletions }} 127 | pr_number: ${{ github.event.pull_request.number }} 128 | pr_status: ${{ github.event.pull_request.state }} 129 | is_merged: ${{ github.event.pull_request.merged }} 130 | -------------------------------------------------------------------------------- /.github/workflows/notify-pr-closed.yaml: -------------------------------------------------------------------------------- 1 | name: Notify Teams on PR 2 | 3 | on: 4 | pull_request: 5 | types: [closed] 6 | 7 | jobs: 8 | notify-teams: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | with: 13 | fetch-depth: 0 14 | - name: Compute added/removed lines for notification 15 | id: diff 16 | run: | 17 | PR_DATA=$(gh pr view "${{ github.event.pull_request.number }}" --json additions,deletions -q '.') 18 | ADDITIONS=$(echo "$PR_DATA" | jq '.additions') 19 | DELETIONS=$(echo "$PR_DATA" | jq '.deletions') 20 | echo "additions=$ADDITIONS" >> $GITHUB_OUTPUT 21 | echo "deletions=$DELETIONS" >> $GITHUB_OUTPUT 22 | env: 23 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 24 | - name: Notify Microsoft Teams 25 | uses: softwareone-platform/notify-pr-teams-action@v4 26 | with: 27 | webhook_url: ${{ secrets.TEAMS_WEBHOOK_URL }} 28 | bot_image_url: https://raw.githubusercontent.com/softwareone-platform/pytest-capsqlalchemy/main/.github/workflows/assets/turing_team_pr_bot.png 29 | repo: ${{ github.repository }} 30 | pr_url: ${{ github.event.pull_request.html_url }} 31 | pr_title: ${{ github.event.pull_request.title }} 32 | pr_author: ${{ github.event.pull_request.user.login }} 33 | head_ref: ${{ github.event.pull_request.head.ref }} 34 | base_ref: ${{ github.event.pull_request.base.ref }} 35 | commits: ${{ github.event.pull_request.commits }} 36 | changed_files: ${{ github.event.pull_request.changed_files }} 37 | additions: ${{ steps.diff.outputs.additions }} 38 | deletions: ${{ steps.diff.outputs.deletions }} 39 | pr_number: ${{ github.event.pull_request.number }} 40 | pr_status: ${{ github.event.pull_request.state }} 41 | is_merged: ${{ github.event.pull_request.merged }} 42 | -------------------------------------------------------------------------------- /.github/workflows/on-release-main.yml: -------------------------------------------------------------------------------- 1 | name: release-main 2 | 3 | permissions: 4 | id-token: write # for OIDC 5 | contents: write 6 | pages: write 7 | 8 | 9 | 10 | on: 11 | release: 12 | types: [published] 13 | 14 | jobs: 15 | 16 | set-version: 17 | runs-on: ubuntu-24.04 18 | steps: 19 | - uses: actions/checkout@v4 20 | 21 | - name: Export tag 22 | id: vars 23 | run: echo tag=${GITHUB_REF#refs/*/} >> $GITHUB_OUTPUT 24 | if: ${{ github.event_name == 'release' }} 25 | 26 | - name: Update project version 27 | run: | 28 | sed -i "s/^version = \".*\"/version = \"$RELEASE_VERSION\"/" pyproject.toml 29 | env: 30 | RELEASE_VERSION: ${{ steps.vars.outputs.tag }} 31 | if: ${{ github.event_name == 'release' }} 32 | 33 | - name: Upload updated pyproject.toml 34 | uses: actions/upload-artifact@v4 35 | with: 36 | name: pyproject-toml 37 | path: pyproject.toml 38 | 39 | publish: 40 | runs-on: ubuntu-latest 41 | needs: [set-version] 42 | steps: 43 | - name: Check out 44 | uses: actions/checkout@v4 45 | 46 | - name: Set up the environment 47 | uses: ./.github/actions/setup-python-env 48 | 49 | - name: Download updated pyproject.toml 50 | uses: actions/download-artifact@v4 51 | with: 52 | name: pyproject-toml 53 | 54 | - name: Build package 55 | run: uv build 56 | 57 | - name: Publish to PyPI 58 | uses: pypa/gh-action-pypi-publish@release/v1 59 | with: 60 | repository-url: https://upload.pypi.org/legacy/ 61 | 62 | deploy-docs: 63 | needs: publish 64 | runs-on: ubuntu-latest 65 | steps: 66 | - name: Check out 67 | uses: actions/checkout@v4 68 | 69 | - name: Set up the environment 70 | uses: ./.github/actions/setup-python-env 71 | 72 | - name: Deploy documentation 73 | run: uv run mkdocs gh-deploy --force 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # MacOS 30 | .DS_Store 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # UV 101 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 102 | # This is especially recommended for binary packages to ensure reproducibility, and is more 103 | # commonly ignored for libraries. 104 | #uv.lock 105 | 106 | # poetry 107 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 108 | # This is especially recommended for binary packages to ensure reproducibility, and is more 109 | # commonly ignored for libraries. 110 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 111 | #poetry.lock 112 | 113 | # pdm 114 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 115 | #pdm.lock 116 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 117 | # in version control. 118 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 119 | .pdm.toml 120 | .pdm-python 121 | .pdm-build/ 122 | 123 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 124 | __pypackages__/ 125 | 126 | # Celery stuff 127 | celerybeat-schedule 128 | celerybeat.pid 129 | 130 | # SageMath parsed files 131 | *.sage.py 132 | 133 | # Environments 134 | .env 135 | .venv 136 | env/ 137 | venv/ 138 | ENV/ 139 | env.bak/ 140 | venv.bak/ 141 | 142 | # Spyder project settings 143 | .spyderproject 144 | .spyproject 145 | 146 | # Rope project settings 147 | .ropeproject 148 | 149 | # mkdocs documentation 150 | /site 151 | 152 | # mypy 153 | .mypy_cache/ 154 | .dmypy.json 155 | dmypy.json 156 | 157 | # Pyre type checker 158 | .pyre/ 159 | 160 | # pytype static type analyzer 161 | .pytype/ 162 | 163 | # Cython debug symbols 164 | cython_debug/ 165 | 166 | # PyCharm 167 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 168 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 169 | # and can be added to the global gitignore or merged into this file. For a more nuclear 170 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 171 | #.idea/ 172 | 173 | # PyPI configuration file 174 | .pypirc 175 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: "v5.0.0" 4 | hooks: 5 | - id: check-case-conflict 6 | - id: check-merge-conflict 7 | - id: check-toml 8 | - id: check-yaml 9 | - id: check-json 10 | exclude: ^.devcontainer/devcontainer.json 11 | - id: pretty-format-json 12 | exclude: ^.devcontainer/devcontainer.json 13 | args: [--autofix] 14 | - id: end-of-file-fixer 15 | - id: trailing-whitespace 16 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to `pytest-capsqlalchemy` 2 | 3 | Contributions are welcome, and they are greatly appreciated! 4 | Every little bit helps, and credit will always be given. 5 | 6 | You can contribute in many ways: 7 | 8 | # Types of Contributions 9 | 10 | ## Report Bugs 11 | 12 | Report bugs at https://github.com/softwareone-platform/pytest-capsqlalchemy/issues 13 | 14 | If you are reporting a bug, please include: 15 | 16 | - Your operating system name and version. 17 | - Any details about your local setup that might be helpful in troubleshooting. 18 | - Detailed steps to reproduce the bug. 19 | 20 | ## Fix Bugs 21 | 22 | Look through the GitHub issues for bugs. 23 | Anything tagged with "bug" and "help wanted" is open to whoever wants to implement a fix for it. 24 | 25 | ## Implement Features 26 | 27 | Look through the GitHub issues for features. 28 | Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it. 29 | 30 | ## Write Documentation 31 | 32 | pytest-capsqlalchemy could always use more documentation, whether as part of the official docs, in docstrings, or even on the web in blog posts, articles, and such. 33 | 34 | ## Submit Feedback 35 | 36 | The best way to send feedback is to file an issue at https://github.com/softwareone-platform/pytest-capsqlalchemy/issues. 37 | 38 | If you are proposing a new feature: 39 | 40 | - Explain in detail how it would work. 41 | - Keep the scope as narrow as possible, to make it easier to implement. 42 | - Remember that this is a volunteer-driven project, and that contributions 43 | are welcome :) 44 | 45 | # Get Started! 46 | 47 | Ready to contribute? Here's how to set up `pytest-capsqlalchemy` for local development. 48 | Please note this documentation assumes you already have `uv` and `Git` installed and ready to go. 49 | 50 | 1. Fork the `pytest-capsqlalchemy` repo on GitHub. 51 | 52 | 2. Clone your fork locally: 53 | 54 | ```bash 55 | cd 56 | git clone git@github.com:YOUR_NAME/pytest-capsqlalchemy.git 57 | ``` 58 | 59 | 3. Now we need to install the environment. Navigate into the directory 60 | 61 | ```bash 62 | cd pytest-capsqlalchemy 63 | ``` 64 | 65 | Then, install and activate the environment with: 66 | 67 | ```bash 68 | uv sync 69 | ``` 70 | 71 | 4. Install pre-commit to run linters/formatters at commit time: 72 | 73 | ```bash 74 | uv run pre-commit install 75 | ``` 76 | 77 | 5. Create a branch for local development: 78 | 79 | ```bash 80 | git checkout -b name-of-your-bugfix-or-feature 81 | ``` 82 | 83 | Now you can make your changes locally. 84 | 85 | 6. Don't forget to add test cases for your added functionality to the `tests` directory. 86 | 87 | 7. When you're done making changes, check that your changes pass the formatting tests. 88 | 89 | ```bash 90 | make check 91 | ``` 92 | 93 | Now, validate that all unit tests are passing: 94 | 95 | ```bash 96 | make test 97 | ``` 98 | 99 | 9. Before raising a pull request you should also run tox. 100 | This will run the tests across different versions of Python: 101 | 102 | ```bash 103 | tox 104 | ``` 105 | 106 | This requires you to have multiple versions of python installed. 107 | This step is also triggered in the CI/CD pipeline, so you could also choose to skip this step locally. 108 | 109 | 10. Commit your changes and push your branch to GitHub: 110 | 111 | ```bash 112 | git add . 113 | git commit -m "Your detailed description of your changes." 114 | git push origin name-of-your-bugfix-or-feature 115 | ``` 116 | 117 | 11. Submit a pull request through the GitHub website. 118 | 119 | # Pull Request Guidelines 120 | 121 | Before you submit a pull request, check that it meets these guidelines: 122 | 123 | 1. The pull request should include tests. 124 | 125 | 2. If the pull request adds functionality, the docs should be updated. 126 | Put your new functionality into a function with a docstring, and add the feature to the list in `README.md`. 127 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2025 SoftwareOne AG 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .env: ## Create a .env file from the example file 2 | @cp env.example .env 3 | 4 | .PHONY: install 5 | install: .env ## Install the virtual environment and install the pre-commit hooks 6 | @echo "🚀 Creating virtual environment using uv" 7 | @uv sync 8 | @uv run pre-commit install 9 | 10 | .PHONY: check 11 | check: ## Run code quality tools. 12 | @echo "🚀 Checking lock file consistency with 'pyproject.toml'" 13 | @uv lock --locked 14 | @echo "🚀 Linting code: Running pre-commit" 15 | @uv run pre-commit run -a 16 | @echo "🚀 Linting code: Running ruff" 17 | @uv run ruff format --check --diff . 18 | @uv run ruff check . 19 | @echo "🚀 Static type checking: Running mypy" 20 | @uv run mypy 21 | 22 | .PHONY: test 23 | test: .env ## Test the code with pytest 24 | @echo "🚀 Testing code: Running pytest" 25 | @uv run python -m pytest --doctest-modules 26 | 27 | .PHONY: build 28 | build: clean-build ## Build wheel file 29 | @echo "🚀 Creating wheel file" 30 | @uvx --from build pyproject-build --installer uv 31 | 32 | .PHONY: clean-build 33 | clean-build: ## Clean build artifacts 34 | @echo "🚀 Removing build artifacts" 35 | @uv run python -c "import shutil; import os; shutil.rmtree('dist') if os.path.exists('dist') else None" 36 | 37 | .PHONY: publish 38 | publish: ## Publish a release to PyPI. 39 | @echo "🚀 Publishing." 40 | @uvx twine upload --repository-url https://upload.pypi.org/legacy/ dist/* 41 | 42 | .PHONY: build-and-publish 43 | build-and-publish: build publish ## Build and publish. 44 | 45 | .PHONY: docs-test 46 | docs-test: ## Test if documentation can be built without warnings or errors 47 | @uv run mkdocs build -s 48 | 49 | .PHONY: docs 50 | docs: ## Build and serve the documentation 51 | @uv run mkdocs serve 52 | 53 | .PHONY: help 54 | help: 55 | @uv run python -c "import re; \ 56 | [[print(f'\033[36m{m[0]:<20}\033[0m {m[1]}') for m in re.findall(r'^([a-zA-Z_-]+):.*?## (.*)$$', open(makefile).read(), re.M)] for makefile in ('$(MAKEFILE_LIST)').strip().split()]" 57 | 58 | .DEFAULT_GOAL := help 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pytest-capsqlalchemy 2 | 3 | 4 | [![Release](https://img.shields.io/github/v/release/softwareone-platform/pytest-capsqlalchemy)](https://img.shields.io/github/v/release/softwareone-platform/pytest-capsqlalchemy) 5 | [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pytest-capsqlalchemy)](https://img.shields.io/pypi/pyversions/pytest-capsqlalchemy) 6 | [![Build status](https://img.shields.io/github/actions/workflow/status/softwareone-platform/pytest-capsqlalchemy/main.yml?branch=main)](https://github.com/softwareone-platform/pytest-capsqlalchemy/actions/workflows/main.yml?query=branch%3Amain) 7 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=softwareone-platform_pytest-capsqlalchemy&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=softwareone-platform_pytest-capsqlalchemy) 8 | [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=softwareone-platform_pytest-capsqlalchemy&metric=coverage)](https://sonarcloud.io/summary/new_code?id=softwareone-platform_pytest-capsqlalchemy) 9 | [![Commit activity](https://img.shields.io/github/commit-activity/m/softwareone-platform/pytest-capsqlalchemy)](https://img.shields.io/github/commit-activity/m/softwareone-platform/pytest-capsqlalchemy) 10 | [![License](https://img.shields.io/github/license/softwareone-platform/pytest-capsqlalchemy)](https://img.shields.io/github/license/softwareone-platform/pytest-capsqlalchemy) 11 | 12 | Pytest plugin to allow capturing SQLAlchemy queries. 13 | 14 | - **Github repository**: 15 | - **Documentation** 16 | 17 | ## Getting Started 18 | 19 | ### 1. Clone the repository 20 | 21 | First, clone the repository from GitHub: 22 | 23 | ```bash 24 | git clone https://github.com/softwareone-platform/pytest-capsqlalchemy 25 | ``` 26 | 27 | ### 2. Set Up Your Development Environment 28 | 29 | Then, install the environment and the pre-commit hooks with 30 | 31 | ```bash 32 | make install 33 | ``` 34 | 35 | This will also generate your `uv.lock` file 36 | 37 | ### 3. Run the pre-commit hooks 38 | 39 | Initially, the CI/CD pipeline might be failing due to formatting issues. To resolve those run: 40 | 41 | ```bash 42 | uv run pre-commit run -a 43 | ``` 44 | ### 4. Run the tests 45 | 46 | The tests require a Postgres database to be running. If you prefer to use a local database you need to edit the `.env` file with 47 | the connection options for it. Alternatively, you can use the provided `docker-compose.yaml` to run it within docker -- all you 48 | need to do is run: 49 | 50 | ```bash 51 | docker compose up test_postgres -d 52 | ``` 53 | 54 | And after that to run the tests: 55 | 56 | ```bash 57 | make test 58 | ``` 59 | 60 | ### 5. Commit the changes 61 | 62 | Lastly, commit the changes made by the two steps above to your repository. 63 | 64 | ```bash 65 | git add . 66 | git commit -m 'Fix formatting issues' 67 | git push origin main 68 | ``` 69 | 70 | You are now ready to start development on your project! 71 | The CI/CD pipeline will be triggered when you open a pull request, merge to main, or when you create a new release. 72 | 73 | To finalize the set-up for publishing to PyPI, see [here](https://fpgmaas.github.io/cookiecutter-uv/features/publishing/#set-up-for-pypi). 74 | For activating the automatic documentation with MkDocs, see [here](https://fpgmaas.github.io/cookiecutter-uv/features/mkdocs/#enabling-the-documentation-on-github). 75 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | test_postgres: 3 | image: postgres:17 4 | restart: unless-stopped 5 | environment: 6 | POSTGRES_DB: "${TEST_POSTGRES_DB}" 7 | POSTGRES_USER: "${TEST_POSTGRES_USER}" 8 | POSTGRES_PASSWORD: "${TEST_POSTGRES_PASSWORD}" 9 | ports: 10 | - "${TEST_POSTGRES_PORT}:5432" 11 | healthcheck: 12 | test: ["CMD-SHELL", "pg_isready --dbname=$${TEST_POSTGRES_DB} --username=$${TEST_POSTGRES_USER}"] 13 | interval: 10s 14 | timeout: 5s 15 | retries: 5 16 | tmpfs: 17 | - /var/lib/postgresql/data 18 | env_file: 19 | - .env 20 | -------------------------------------------------------------------------------- /docs/api-reference.md: -------------------------------------------------------------------------------- 1 | ::: pytest_capsqlalchemy.plugin 2 | ::: pytest_capsqlalchemy.capturer 3 | ::: pytest_capsqlalchemy.context 4 | ::: pytest_capsqlalchemy.expression 5 | ::: pytest_capsqlalchemy.utils 6 | -------------------------------------------------------------------------------- /docs/assets/softwareone-logo-dark-mode.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /docs/assets/softwareone-logo-light-mode.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # pytest-capsqlalchemy 2 | 3 | [![Release](https://img.shields.io/github/v/release/softwareone-platform/pytest-capsqlalchemy)](https://img.shields.io/github/v/release/softwareone-platform/pytest-capsqlalchemy) 4 | [![Build status](https://img.shields.io/github/actions/workflow/status/softwareone-platform/pytest-capsqlalchemy/main.yml?branch=main)](https://github.com/softwareone-platform/pytest-capsqlalchemy/actions/workflows/main.yml?query=branch%3Amain) 5 | [![Commit activity](https://img.shields.io/github/commit-activity/m/softwareone-platform/pytest-capsqlalchemy)](https://img.shields.io/github/commit-activity/m/softwareone-platform/pytest-capsqlalchemy) 6 | [![License](https://img.shields.io/github/license/softwareone-platform/pytest-capsqlalchemy)](https://img.shields.io/github/license/softwareone-platform/pytest-capsqlalchemy) 7 | 8 | Pytest plugin to allow capturing SQLAlchemy queries. 9 | 10 | # Getting Started 11 | 12 | ## Installation 13 | 14 | Install `pytest-capsqlalchemy` via `pip` or your preferred package manager: 15 | 16 | ```sh 17 | pip install pytest-capsqlalchemy 18 | ``` 19 | 20 | ## Configuration 21 | 22 | In order to use the fixtures provided by the plugin you also need to define a `db_engine` fixture 23 | in your `conftest.py`. This fixture should return an `AsyncEngine` instance. For example: 24 | 25 | ```python title="conftest.py" 26 | import pytest 27 | from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine 28 | 29 | @pytest.fixture(scope="session") 30 | def db_engine() -> AsyncEngine: 31 | return create_async_engine("postgresql+asyncpg://user:pass@localhost:5432/db") 32 | ``` 33 | 34 | ## Usage 35 | 36 | ### Counting number of queries 37 | 38 | Here is a basic example with asserts on the number of queries being performed 39 | 40 | ```python 41 | async def test_query_count(db_session, capsqlalchemy): 42 | await db_session.execute(text("SELECT 1")) 43 | 44 | capsqlalchemy.assert_query_count(1, include_tcl=False) # (1)! 45 | capsqlalchemy.assert_query_count(3, include_tcl=True) # (2)! 46 | ``` 47 | 48 | 1. The `capsqlfixture` starts recording the queries which are sent to the database at the beginning of the test. 49 | As TCL statements (`BEGIN`, `COMMIT`, `ROLLBACK`) are not included in this assert, only `SELECT 1` is counted 50 | 2. This time TCL statements are being counted and since by default SQLAlchemy is configured in `autobegin` mode, 51 | there are 3 queries which are being counted: `BEGIN`, `SELECT 1` and `ROLLBACK` 52 | 53 | ### Capturing queries in specific context 54 | 55 | You can also use `capqsqlalchemy` as a context manager to check only for the queries being performed in a specific 56 | section of your code. For example: 57 | 58 | ```python { hl_lines="8-11" } 59 | async def test_context(db_session, capsqlalchemy): 60 | capsqlalchemy.assert_query_count(0, include_tcl=False) # (1)! 61 | 62 | await db_session.execute(text("SELECT 1")) 63 | capsqlalchemy.assert_query_count(1, include_tcl=False) # (2)! 64 | 65 | with capsqlalchemy: 66 | await db_session.execute(text("SELECT 2")) 67 | await db_session.execute(text("SELECT 3")) 68 | capsqlalchemy.assert_query_count(2, include_tcl=False) # (3)! 69 | 70 | capsqlalchemy.assert_query_count(3, include_tcl=False) # (4)! 71 | ``` 72 | 73 | 1. No queries have been executed yet 74 | 2. Just like in the previous example only `SELECT 1` has been captured yet 75 | 3. Since the assert is being performed inside the `with` block only `SELECT 2` and `SELECT 3` will be counted 76 | 4. When using a context manager, the outer scope still counts the inner scope queries, so this time all 77 | `SELECT 1`, `SELECT 2` and `SELECT 3` are captured 78 | 79 | 80 | ### Checking exact queries 81 | 82 | You can also write tests that the exact query you expected was generated and exectured by SQLALchemy. 83 | Here's an example with SQLAlchemy 2.0 ORM: 84 | 85 | ```python 86 | async def test_exact_query(db_session, capsqlalchemy): 87 | await db_session.execute(select(Order.recipient).where(Order.id == 123)) 88 | 89 | capsqlalchemy.assert_captured_queries( # (1)! 90 | "SELECT orders.id, orders.recipient \nFROM orders \nWHERE orders.id = :id_1", 91 | include_tcl=False, 92 | ) 93 | 94 | capsqlalchemy.assert_captured_queries( # (2)! 95 | "SELECT orders.id, orders.recipient \nFROM orders \nWHERE orders.id = 123", 96 | bind_params=True, 97 | include_tcl=False, 98 | ) 99 | ``` 100 | 101 | 1. By default the of the queries will not be binded, so `123` is replaced with `:id_1` 102 | 2. If we want to check that the query is **exactly** what we expected we can pass 103 | `bind_params=True` and we'll get the full query 104 | 105 | 106 | ### Checking the query types 107 | 108 | There are also cases where we care about the queries being performed beyond just their count but 109 | we don't care about their structure in such a detail -- that's where we can check that the captured 110 | query _types_ are are what we expect: 111 | 112 | ```python 113 | from pytest_capsqlalchemy import SQLExpressionType 114 | 115 | async def test_query_types(db_session, capsqlalchemy): 116 | await db_session.execute(select(Order)) 117 | 118 | await db_session.commit() 119 | 120 | async with db_session.begin(): 121 | await db_session.execute(select(Order).where(Order.id == 123)) 122 | await db_session.execute(select(text("1"))) 123 | 124 | db_session.add(Order(recipient="John Doe")) 125 | 126 | capsqlalchemy.assert_query_types( # (1)! 127 | SQLExpressionType.BEGIN, 128 | SQLExpressionType.SELECT, 129 | SQLExpressionType.COMMIT, 130 | SQLExpressionType.BEGIN, 131 | SQLExpressionType.SELECT, 132 | SQLExpressionType.SELECT, 133 | SQLExpressionType.INSERT, 134 | SQLExpressionType.COMMIT, 135 | ) 136 | 137 | capsqlalchemy.assert_query_types( # (2)! 138 | "SELECT", # (3)! 139 | "SELECT", 140 | "SELECT", 141 | "INSERT", 142 | include_tcl=False, 143 | ) 144 | ``` 145 | 146 | 1. `assert_query_types` allows us to check that the captured queries are a `BEGIN`, a `SELECT`, a `COMMIT` etc. without 147 | specifying their exact structure 148 | 2. Similarly to the other assertion methods, we can exclude the TCL statements if we don't care about them 149 | 3. We can also use strings instead of enum values to make the assert shorter to write 150 | 151 | 152 | !!! warning 153 | The order of the arguments matters -- it's the same order that the queries have been captured in. 154 | 155 | For example, with the following setup: 156 | 157 | ```python 158 | await db_session.execute(select(Order)) 159 | db_session.add(Order(recipient="John Doe")) 160 | ``` 161 | 162 | this will pass: 163 | 164 | ```python 165 | capsqlalchemy.assert_query_types("SELECT", "INSERT", include_tcl=False) 166 | ``` 167 | 168 | but this will fail: 169 | 170 | ```python 171 | capsqlalchemy.assert_query_types("INSERT", "SELECT", include_tcl=False) 172 | ``` 173 | -------------------------------------------------------------------------------- /docs/stylesheets/extra.css: -------------------------------------------------------------------------------- 1 | #logo-light-mode { 2 | display: var(--logo-dark-mode-display); 3 | } 4 | 5 | #logo-dark-mode { 6 | display: var(--logo-light-mode-display); 7 | } 8 | 9 | [data-md-color-scheme="slate"] { 10 | --logo-dark-mode-display: none; 11 | --logo-light-mode-display: block; 12 | } 13 | 14 | [data-md-color-scheme="default"] { 15 | --logo-dark-mode-display: block; 16 | --logo-light-mode-display: none; 17 | } 18 | -------------------------------------------------------------------------------- /docs/templates/partials/logo.html: -------------------------------------------------------------------------------- 1 | logo 2 | logo 3 | -------------------------------------------------------------------------------- /env.example: -------------------------------------------------------------------------------- 1 | TEST_POSTGRES_DB=test_postgres 2 | TEST_POSTGRES_USER=postgres 3 | TEST_POSTGRES_PASSWORD=mysecurepassword 4 | TEST_POSTGRES_HOST=0.0.0.0 5 | TEST_POSTGRES_PORT=5432 6 | -------------------------------------------------------------------------------- /examples/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/softwareone-platform/pytest-capsqlalchemy/f3ce1fd19becd313f85262e1fdd4bf534d5effcf/examples/__init__.py -------------------------------------------------------------------------------- /examples/test_missing_setup.py: -------------------------------------------------------------------------------- 1 | def test_capsqlalchemy_setup(capsqlalchemy): 2 | pass 3 | -------------------------------------------------------------------------------- /examples/test_plugin_setup_with_async_db_engine_fixture.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pytest 4 | from sqlalchemy import text 5 | from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine 6 | 7 | 8 | @pytest.fixture(scope="session") 9 | def db_url() -> str: 10 | db_name = os.environ["TEST_POSTGRES_DB"] 11 | db_user = os.environ["TEST_POSTGRES_USER"] 12 | db_password = os.environ["TEST_POSTGRES_PASSWORD"] 13 | db_host = os.environ["TEST_POSTGRES_HOST"] 14 | db_port = os.environ["TEST_POSTGRES_PORT"] 15 | 16 | return f"postgresql+asyncpg://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}" 17 | 18 | 19 | @pytest.fixture(scope="session") 20 | def db_engine(db_url: str) -> AsyncEngine: 21 | return create_async_engine(db_url, future=True) 22 | 23 | 24 | def test_capsqlalchemy_setup(capsqlalchemy): 25 | pass 26 | 27 | 28 | def test_capsqlalchemy_initial_query_count(capsqlalchemy): 29 | capsqlalchemy.assert_query_count(0) 30 | 31 | 32 | @pytest.mark.asyncio 33 | async def test_capsqlalchemy_counts_executed(capsqlalchemy, db_engine): 34 | async with db_engine.connect() as conn: 35 | await conn.execute(text("SELECT 1")) 36 | 37 | capsqlalchemy.assert_query_count(1, include_tcl=False) 38 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: pytest-capsqlalchemy 2 | repo_url: https://github.com/softwareone-platform/pytest-capsqlalchemy 3 | site_url: https://softwareone-platform.github.io/pytest-capsqlalchemy 4 | site_description: Pytest plugin to allow capturing SQLAlchemy queries. 5 | site_author: Artur Balabanov 6 | edit_uri: edit/main/docs/ 7 | repo_name: softwareone-platform/pytest-capsqlalchemy 8 | copyright: SoftwareOne 9 | 10 | nav: 11 | - Home: index.md 12 | - "API Reference": api-reference.md 13 | 14 | plugins: 15 | - search 16 | - mkdocstrings: 17 | handlers: 18 | python: 19 | paths: ["pytest_capsqlalchemy"] 20 | options: 21 | separate_signature: true 22 | show_signature_annotations: true 23 | signature_crossrefs: true 24 | members_order: source 25 | show_symbol_type_heading: true 26 | show_symbol_type_toc: true 27 | 28 | theme: 29 | name: material 30 | feature: 31 | tabs: true 32 | features: 33 | - content.code.copy 34 | - content.code.annotate 35 | logo_dark_mode: assets/softwareone-logo-dark-mode.svg 36 | logo_light_mode: assets/softwareone-logo-light-mode.svg 37 | palette: 38 | - media: "(prefers-color-scheme: light)" 39 | scheme: default 40 | primary: white 41 | accent: deep orange 42 | toggle: 43 | icon: material/brightness-7 44 | name: Switch to dark mode 45 | - media: "(prefers-color-scheme: dark)" 46 | scheme: slate 47 | primary: black 48 | accent: deep orange 49 | toggle: 50 | icon: material/brightness-4 51 | name: Switch to light mode 52 | icon: 53 | repo: fontawesome/brands/github 54 | custom_dir: docs/templates 55 | 56 | extra_css: 57 | - stylesheets/extra.css 58 | 59 | extra: 60 | social: 61 | - icon: fontawesome/brands/github 62 | link: https://github.com/softwareone-platform/pytest-capsqlalchemy 63 | - icon: fontawesome/brands/python 64 | link: https://pypi.org/project/pytest-capsqlalchemy 65 | 66 | markdown_extensions: 67 | - toc: 68 | permalink: true 69 | - pymdownx.arithmatex: 70 | generic: true 71 | - pymdownx.highlight: 72 | anchor_linenums: true 73 | line_spans: __span 74 | pygments_lang_class: true 75 | - admonition 76 | - pymdownx.details 77 | - pymdownx.inlinehilite 78 | - pymdownx.snippets 79 | - pymdownx.superfences 80 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "pytest-capsqlalchemy" 3 | version = "0.0.1" 4 | description = "Pytest plugin to allow capturing SQLAlchemy queries." 5 | authors = [{ name = "SoftwareOne AG" }] 6 | readme = "README.md" 7 | keywords = ['python'] 8 | requires-python = ">=3.9,<4.0" 9 | license = "Apache-2.0" 10 | classifiers = [ 11 | "Intended Audience :: Developers", 12 | "Development Status :: 4 - Beta", 13 | "Operating System :: OS Independent", 14 | "Programming Language :: Python", 15 | "Programming Language :: Python :: 3 :: Only", 16 | "Programming Language :: Python :: 3.9", 17 | "Programming Language :: Python :: 3.10", 18 | "Programming Language :: Python :: 3.11", 19 | "Programming Language :: Python :: 3.12", 20 | "Programming Language :: Python :: 3.13", 21 | "Framework :: AsyncIO", 22 | "Framework :: Pytest", 23 | "Topic :: Software Development :: Libraries :: Python Modules", 24 | "Topic :: Software Development :: Testing", 25 | "Topic :: Database :: Front-Ends", 26 | "Typing :: Typed", 27 | ] 28 | dependencies = ["sqlalchemy[asyncio]>=2.0.38"] 29 | 30 | [project.urls] 31 | Homepage = "https://softwareone-platform.github.io/pytest-capsqlalchemy/" 32 | Repository = "https://github.com/softwareone-platform/pytest-capsqlalchemy" 33 | Documentation = "https://softwareone-platform.github.io/pytest-capsqlalchemy/" 34 | 35 | [project.entry-points.pytest11] 36 | pytest_capsqlalchemy = "pytest_capsqlalchemy.plugin" 37 | 38 | [dependency-groups] 39 | dev = [ 40 | "pytest>=7.2.0", 41 | "pre-commit>=2.20.0", 42 | "tox-uv>=1.11.3", 43 | "mypy>=0.991", 44 | "ruff>=0.9.2", 45 | "mkdocs>=1.4.2", 46 | "mkdocs-material>=8.5.10", 47 | "mkdocstrings[python]>=0.26.1", 48 | "asyncpg>=0.30.0", 49 | "pytest-asyncio>=0.25.3", 50 | "pytest-dotenv>=0.5.2", 51 | "pytest-cov>=6.0.0", 52 | ] 53 | 54 | [build-system] 55 | requires = ["hatchling"] 56 | build-backend = "hatchling.build" 57 | 58 | [tool.setuptools] 59 | py-modules = ["pytest_capsqlalchemy"] 60 | 61 | [tool.mypy] 62 | files = ["pytest_capsqlalchemy"] 63 | disallow_untyped_defs = true 64 | disallow_any_unimported = true 65 | no_implicit_optional = true 66 | check_untyped_defs = true 67 | warn_return_any = true 68 | warn_unused_ignores = true 69 | show_error_codes = true 70 | 71 | [tool.pytest.ini_options] 72 | testpaths = ["tests"] 73 | asyncio_mode = "auto" 74 | asyncio_default_fixture_loop_scope = "session" 75 | # NOTE: -p 'no:capsqlalchemy' disables this plugin during tests for accurate code coverage 76 | addopts = """ 77 | --cov=pytest_capsqlalchemy 78 | --cov-report=term-missing 79 | --cov-report=html 80 | --cov-report=xml 81 | -p 'no:capsqlalchemy' 82 | """ 83 | pytester_example_dir = "examples" 84 | 85 | [tool.ruff] 86 | line-length = 120 87 | fix = true 88 | 89 | [tool.ruff.lint] 90 | preview = true # enable linting rules in preview 91 | select = [ 92 | "YTT", # flake8-2020 93 | "S", # flake8-bandit 94 | "B", # flake8-bugbear 95 | "A", # flake8-builtins 96 | "C4", # flake8-comprehensions 97 | "T10", # flake8-debugger 98 | "SIM", # flake8-simplify 99 | "I", # isort 100 | "C90", # mccabe 101 | "E", # pycodestyle errors 102 | "W", # pycodestyle warnings 103 | "F", # pyflakes 104 | "PGH", # pygrep-hooks 105 | "UP", # pyupgrade 106 | "RUF", # ruff 107 | "DOC", # pydoclint 108 | "D", # pydocstyle 109 | ] 110 | ignore = [ 111 | "E731", # DoNotAssignLambda 112 | "S101", # assert 113 | "D100", # Missing docstring in public module 114 | "D104", # Missing docstring in public package 115 | "D105", # Missing docstring in magic method 116 | "DOC402", # yield is not documented in docstring 117 | "DOC502", # Raised exception is not explicitly raised 118 | ] 119 | 120 | [tool.ruff.lint.per-file-ignores] 121 | "examples/*" = ["D", "DOC"] 122 | "tests/*" = ["D", "DOC"] 123 | 124 | [tool.ruff.lint.pydocstyle] 125 | convention = "google" 126 | 127 | [tool.ruff.format] 128 | preview = true 129 | docstring-code-format = true 130 | 131 | [tool.coverage.run] 132 | branch = true 133 | source = ["pytest_capsqlalchemy"] 134 | relative_files = true 135 | # SQLAlchemy uses greenlets to pass context, so we need to specify this here, 136 | # so that the coverage is calculated correctly. 'thread' is the default value, 137 | # so including it in case some code relies on it 138 | # 139 | # refs: 140 | # * https://coverage.readthedocs.io/en/7.6.9/config.html#run-concurrency 141 | # * https://github.com/nedbat/coveragepy/issues/1082 142 | concurrency = ["thread", "greenlet"] 143 | 144 | [tool.coverage.report] 145 | show_missing = true 146 | exclude_lines = ["pragma: no cover", "pragma: no branch", "NotImplementedError"] 147 | -------------------------------------------------------------------------------- /pytest_capsqlalchemy/__init__.py: -------------------------------------------------------------------------------- 1 | from pytest_capsqlalchemy.capturer import SQLAlchemyCapturer 2 | from pytest_capsqlalchemy.context import SQLAlchemyCaptureContext 3 | from pytest_capsqlalchemy.expression import SQLExpression 4 | from pytest_capsqlalchemy.plugin import capsqlalchemy, capsqlalchemy_context 5 | 6 | __all__ = [ 7 | "SQLAlchemyCaptureContext", 8 | "SQLAlchemyCapturer", 9 | "SQLExpression", 10 | "capsqlalchemy", 11 | "capsqlalchemy_context", 12 | ] 13 | -------------------------------------------------------------------------------- /pytest_capsqlalchemy/capturer.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from types import TracebackType 3 | from typing import Optional, Union 4 | 5 | if sys.version_info >= (3, 11): # pragma: no cover 6 | from typing import Self 7 | else: # pragma: no cover 8 | from typing_extensions import Self 9 | 10 | from sqlalchemy.ext.asyncio import AsyncEngine 11 | 12 | from pytest_capsqlalchemy.context import SQLAlchemyCaptureContext 13 | from pytest_capsqlalchemy.expression import SQLExpression, SQLExpressionType 14 | 15 | 16 | class SQLAlchemyCapturer: 17 | """The main fixture class for the `capsqlalchemy` plugin. 18 | 19 | Used to perform asserts about the expressions SQLAlchemy has executed during the test. 20 | 21 | Can be used either directly using the assert methods (to perform checks for all expressions 22 | executed in the test), as a context manager (to perform checks only for the expressions 23 | executed in a specific block), or a combination of both. 24 | 25 | Intended to be used via the [`capsqlalchemy`][pytest_capsqlalchemy.plugin.capsqlalchemy] fixture 26 | """ 27 | 28 | _full_test_context: SQLAlchemyCaptureContext 29 | _partial_context: Optional[SQLAlchemyCaptureContext] 30 | 31 | def __init__(self, full_test_context: SQLAlchemyCaptureContext): 32 | """Create a new SQLAlchemyCapturer instance.""" 33 | self._full_test_context = full_test_context 34 | self._partial_context = None 35 | 36 | @property 37 | def engine(self) -> AsyncEngine: 38 | """The SQLAlchemy engine instance being captured.""" 39 | return self._full_test_context._engine 40 | 41 | @property 42 | def captured_expressions(self) -> list[SQLExpression]: 43 | """Returns all SQL expressions captured in the current context. 44 | 45 | When used outside a context manager block, returns all expressions captured 46 | during the entire test. When used inside a context manager block, returns 47 | only the expressions captured within that specific block. 48 | 49 | This property is useful for performing specific assertions on the captured expressions which 50 | cannot be easily achieved with the provided assert methods. 51 | """ 52 | if self._partial_context is not None: 53 | return self._partial_context.captured_expressions 54 | 55 | return self._full_test_context.captured_expressions 56 | 57 | def __enter__(self) -> Self: 58 | self._partial_context = SQLAlchemyCaptureContext(self.engine) 59 | self._partial_context = self._partial_context.__enter__() 60 | return self 61 | 62 | def __exit__( 63 | self, 64 | exc_type: Optional[type[BaseException]] = None, 65 | exc_val: Optional[BaseException] = None, 66 | exc_tb: Optional[TracebackType] = None, 67 | ) -> Optional[bool]: 68 | if self._partial_context is None: # pragma: no cover 69 | raise RuntimeError(f"{self.__class__.__name__}: attempting to call __exit__ before __enter__") 70 | 71 | result = self._partial_context.__exit__(exc_type, exc_val, exc_tb) 72 | 73 | self._partial_context = None 74 | 75 | return result 76 | 77 | def assert_query_types( 78 | self, 79 | *expected_query_types: Union[SQLExpressionType, str], 80 | include_tcl: bool = True, 81 | ) -> None: 82 | """Asserts that the captured SQL expressions match the expected query types in order. 83 | 84 | This is useful for ensuring that your code is generating correct query types but 85 | their exact structure is not important (e.g. complex SELECT statements). 86 | 87 | Args: 88 | *expected_query_types: Variable number of expected query types 89 | include_tcl: Whether to include transaction control language statements (BEGIN, 90 | COMMIT, ROLLBACK) in the comparison 91 | 92 | Raises: 93 | AssertionError: If the actual query types don't match the expected ones. 94 | """ 95 | actual_query_types_values = [] 96 | 97 | for query in self.captured_expressions: 98 | if not include_tcl and query.type.is_tcl: 99 | continue 100 | 101 | actual_query_types_values.append(query.type._value_) 102 | 103 | # Converting to strings as the error message diff will be shorter and more readable 104 | expected_query_types_values = [ 105 | query_type._value_ if isinstance(query_type, SQLExpressionType) else query_type 106 | for query_type in expected_query_types 107 | ] 108 | 109 | assert expected_query_types_values == actual_query_types_values 110 | 111 | def assert_query_count(self, expected_query_count: int, *, include_tcl: bool = True) -> None: 112 | """Asserts that the number of captured SQL expressions matches the expected count. 113 | 114 | This is useful for ensuring that your code is not generating more statements than expected 115 | (e.g. due to N+1 queries), however the exact queries are not important. 116 | 117 | Args: 118 | expected_query_count: The expected number of SQL expressions. 119 | include_tcl: Whether to include transaction control language statements (BEGIN, 120 | COMMIT, ROLLBACK) in the count. 121 | 122 | Raises: 123 | AssertionError: If the actual query count doesn't match the expected count. 124 | """ 125 | actual_query_count = sum(1 for query in self.captured_expressions if include_tcl or not query.type.is_tcl) 126 | 127 | assert expected_query_count == actual_query_count, ( 128 | f"Query count mismatch: expected {expected_query_count}, got {actual_query_count}" 129 | ) 130 | 131 | def assert_max_query_count(self, expected_max_query_count: int, *, include_tcl: bool = True) -> None: 132 | """Asserts that the number of captured SQL expressions doesn't exceed the expected count. 133 | 134 | This is useful for ensuring that your code is not generating more statements than expected 135 | (e.g. due to N+1 queries), however the exact number of queries is not important -- for example 136 | SQLAlchemy's caching mechanism may generate fewer queries than expected. 137 | 138 | Args: 139 | expected_max_query_count: The expected maximum number of SQL expressions. 140 | include_tcl: Whether to include transaction control language statements (BEGIN, 141 | COMMIT, ROLLBACK) in the count. 142 | 143 | Raises: 144 | AssertionError: If the actual query count exceeds the expected maximum count. 145 | """ 146 | actual_query_count = sum(1 for query in self.captured_expressions if include_tcl or not query.type.is_tcl) 147 | 148 | assert expected_max_query_count < actual_query_count, ( 149 | f"Query count mismatch: expected maximum {expected_max_query_count}, got {actual_query_count}" 150 | ) 151 | 152 | def assert_captured_queries( 153 | self, 154 | *expected_queries: str, 155 | include_tcl: bool = True, 156 | bind_params: bool = False, 157 | ) -> None: 158 | """Asserts that the captured SQL queries match the expected SQL strings in order. 159 | 160 | This is useful for ensuring that your code is generating the exact SQL statements you expect. 161 | 162 | Args: 163 | *expected_queries: Variable number of expected SQL query strings. 164 | include_tcl: Whether to include transaction control language statements (BEGIN, 165 | COMMIT, ROLLBACK) in the comparison. 166 | bind_params: Whether to include bound parameters in the SQL strings. When `False`, 167 | parameters are represented as placeholders instead. 168 | 169 | Raises: 170 | AssertionError: If the actual SQL queries don't match the expected ones. 171 | """ 172 | actual_queries = [] 173 | 174 | for query in self.captured_expressions: 175 | if not include_tcl and query.type.is_tcl: 176 | continue 177 | 178 | actual_queries.append(query.get_sql(bind_params=bind_params)) 179 | 180 | assert list(expected_queries) == actual_queries 181 | -------------------------------------------------------------------------------- /pytest_capsqlalchemy/context.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | import sys 3 | from collections.abc import Mapping 4 | from types import TracebackType 5 | from typing import Any, Optional 6 | 7 | if sys.version_info >= (3, 11): # pragma: no cover 8 | from typing import Self 9 | else: # pragma: no cover 10 | from typing_extensions import Self 11 | 12 | from sqlalchemy import Connection, CursorResult, Executable, text 13 | from sqlalchemy.ext.asyncio import AsyncEngine 14 | 15 | from pytest_capsqlalchemy.expression import SQLExpression 16 | from pytest_capsqlalchemy.utils import temp_sqlalchemy_event 17 | 18 | 19 | class SQLAlchemyCaptureContext: 20 | """Captures expressions executed on a SQLAlchemy engine within a specific context. 21 | 22 | These expressions include: 23 | 24 | * SELECT 25 | * INSERT 26 | * UPDATE 27 | * DELETE 28 | * BEGIN 29 | * COMMIT 30 | * ROLLBACK 31 | 32 | Every expression is captured as a SQLExpression object, allowing it to be parsed correctly 33 | and compared against. 34 | 35 | See [`SQLAlchemyCapturer`][pytest_capsqlalchemy.capturer.SQLAlchemyCapturer] for the available 36 | assertions on the captured expressions. 37 | """ 38 | 39 | _engine: AsyncEngine 40 | _captured_expressions: list[SQLExpression] 41 | 42 | def __init__(self, engine: AsyncEngine): 43 | """Create a new SQLAlchemyCaptureContext instance.""" 44 | self._engine = engine 45 | self._captured_expressions = [] 46 | self._sqlaclhemy_events_stack = contextlib.ExitStack() 47 | 48 | @property 49 | def captured_expressions(self) -> list[SQLExpression]: 50 | """Returns all SQL expressions captured in the current context.""" 51 | return self._captured_expressions 52 | 53 | def clear(self) -> None: 54 | """Clear all SQL expressions captured so far in the current context.""" 55 | self._captured_expressions = [] 56 | 57 | def _on_begin(self, conn: Connection) -> None: 58 | self._captured_expressions.append(SQLExpression(executable=text("BEGIN"))) 59 | 60 | def _on_commit(self, conn: Connection) -> None: 61 | self._captured_expressions.append(SQLExpression(executable=text("COMMIT"))) 62 | 63 | def _on_rollback(self, conn: Connection) -> None: 64 | self._captured_expressions.append(SQLExpression(executable=text("ROLLBACK"))) 65 | 66 | def _on_after_execute( 67 | self, 68 | conn: Connection, 69 | clauseelement: Executable, 70 | multiparams: list[dict[str, Any]], 71 | params: dict[str, Any], 72 | execution_options: Mapping[str, Any], 73 | result: CursorResult, 74 | ) -> None: 75 | self._captured_expressions.append( 76 | SQLExpression(executable=clauseelement, params=params, multiparams=multiparams) 77 | ) 78 | 79 | def __enter__(self) -> Self: 80 | events_stack = self._sqlaclhemy_events_stack.__enter__() 81 | 82 | for event_name, listener in ( 83 | ("begin", self._on_begin), 84 | ("commit", self._on_commit), 85 | ("rollback", self._on_rollback), 86 | ("after_execute", self._on_after_execute), 87 | ): 88 | events_stack.enter_context( 89 | temp_sqlalchemy_event( 90 | self._engine.sync_engine, 91 | event_name, 92 | listener, 93 | ) 94 | ) 95 | 96 | return self 97 | 98 | def __exit__( 99 | self, 100 | exc_type: Optional[type[BaseException]], 101 | exc_value: Optional[BaseException], 102 | traceback: Optional[TracebackType], 103 | ) -> Optional[bool]: 104 | return self._sqlaclhemy_events_stack.__exit__(exc_type, exc_value, traceback) 105 | -------------------------------------------------------------------------------- /pytest_capsqlalchemy/expression.py: -------------------------------------------------------------------------------- 1 | import enum 2 | from dataclasses import dataclass, field 3 | from typing import Any 4 | 5 | from sqlalchemy import ClauseElement, Executable, Insert, TextClause, text 6 | 7 | 8 | class SQLExpressionType(str, enum.Enum): 9 | """An enumeration of the different types of SQL expressions that can be captured.""" 10 | 11 | SELECT = "SELECT" 12 | INSERT = "INSERT" 13 | UPDATE = "UPDATE" 14 | DELETE = "DELETE" 15 | BEGIN = "BEGIN" 16 | COMMIT = "COMMIT" 17 | ROLLBACK = "ROLLBACK" 18 | UNKNOWN = "UNKNOWN" 19 | 20 | @property 21 | def is_tcl(self) -> bool: 22 | """Check if the SQL expression type is a transaction control language statement.""" 23 | return self in {SQLExpressionType.BEGIN, SQLExpressionType.COMMIT, SQLExpressionType.ROLLBACK} 24 | 25 | 26 | @dataclass 27 | class SQLExpression: 28 | """A representation of a single SQL expression captured by SQLAlchemy. 29 | 30 | Stores the SQLAlchemy `Executable` object and any parameters used in the query, so that it can be 31 | compared against expected queries in tests. This is useful for performing specific assertions 32 | on the captured expressions which cannot be easily achieved with the provided assert methods. 33 | """ 34 | 35 | executable: Executable 36 | params: dict[str, Any] = field(default_factory=dict) 37 | multiparams: list[dict[str, Any]] = field(default_factory=list) 38 | 39 | def get_sql(self, *, bind_params: bool = False) -> str: 40 | """Get the SQL string generated by SQLAlchemy of the captured expression. 41 | 42 | Args: 43 | bind_params: If True, the SQL string will include the bound parameters in the query. Otherwise the 44 | SQL string will contain placeholders for the bound parameters. 45 | 46 | Returns: 47 | The SQL string of the captured expression 48 | """ 49 | assert isinstance(self.executable, ClauseElement) 50 | 51 | if self.executable.is_insert: 52 | assert isinstance(self.executable, Insert) 53 | 54 | if self.multiparams: 55 | expr = self.executable.values(self.multiparams) 56 | elif self.params: 57 | expr = self.executable.values(self.params) 58 | else: 59 | expr = self.executable 60 | else: 61 | expr = self.executable 62 | 63 | compile_kwargs = {} 64 | if bind_params: 65 | compile_kwargs["literal_binds"] = True 66 | 67 | return str(expr.compile(compile_kwargs=compile_kwargs)) 68 | 69 | @property 70 | def type(self) -> SQLExpressionType: 71 | """Get the type of the captured SQL expression.""" 72 | if self.executable.is_insert: 73 | return SQLExpressionType.INSERT 74 | 75 | if self.executable.is_select: 76 | return SQLExpressionType.SELECT 77 | 78 | if self.executable.is_update: 79 | return SQLExpressionType.UPDATE 80 | 81 | if self.executable.is_delete: 82 | return SQLExpressionType.DELETE 83 | 84 | if isinstance(self.executable, TextClause): 85 | if self.executable.compare(text("BEGIN")): 86 | return SQLExpressionType.BEGIN 87 | 88 | if self.executable.compare(text("COMMIT")): 89 | return SQLExpressionType.COMMIT 90 | 91 | if self.executable.compare(text("ROLLBACK")): 92 | return SQLExpressionType.ROLLBACK 93 | 94 | return SQLExpressionType.UNKNOWN 95 | -------------------------------------------------------------------------------- /pytest_capsqlalchemy/plugin.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Generator 2 | 3 | import pytest 4 | from sqlalchemy.ext.asyncio import AsyncEngine 5 | 6 | from pytest_capsqlalchemy import SQLAlchemyCaptureContext, SQLAlchemyCapturer 7 | 8 | 9 | @pytest.fixture 10 | def capsqlalchemy_context(db_engine: AsyncEngine) -> Generator[SQLAlchemyCaptureContext]: 11 | """The main fixture to get the [`SQLAlchemyCaptureContext`][pytest_capsqlalchemy.context.SQLAlchemyCaptureContext]. 12 | 13 | This is the context for the full test, which captures all SQL expressions executed during the test. 14 | 15 | To capture only the SQL expressions executed within a specific block, use the 16 | [`capsqlalchemy`][pytest_capsqlalchemy.plugin.capsqlalchemy] fixture. 17 | """ 18 | with SQLAlchemyCaptureContext(db_engine) as capsqlalchemy_ctx: 19 | yield capsqlalchemy_ctx 20 | 21 | 22 | @pytest.fixture() 23 | def capsqlalchemy(capsqlalchemy_context: SQLAlchemyCaptureContext) -> SQLAlchemyCapturer: 24 | """The main fixture to get the [`SQLAlchemyCapturer`][pytest_capsqlalchemy.capturer.SQLAlchemyCapturer]. 25 | 26 | Example Usage: 27 | 28 | ```python 29 | async def test_some_sql_queries(db_session, capsqlalchemy): 30 | await db_session.execute(select(text("1"))) 31 | capsqlalchemy.assert_query_count(1, include_tcl=False) 32 | 33 | async with capsqlalchemy: 34 | await db_session.execute(select(text("2"))) 35 | await db_session.execute(select(text("3"))) 36 | capsqlalchemy.assert_query_count(2, include_tcl=False) 37 | 38 | capsqlalchemy.assert_query_count(3, include_tcl=False) 39 | ``` 40 | 41 | Returns: 42 | The capturer object with the full test context already set up. 43 | """ 44 | return SQLAlchemyCapturer(capsqlalchemy_context) 45 | -------------------------------------------------------------------------------- /pytest_capsqlalchemy/utils.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | from collections.abc import Callable, Generator 3 | from typing import Any 4 | 5 | from sqlalchemy import event 6 | 7 | 8 | @contextlib.contextmanager 9 | def temp_sqlalchemy_event( 10 | target: Any, 11 | identifier: str, 12 | fn: Callable[..., Any], 13 | *args: Any, 14 | **kwargs: Any, 15 | ) -> Generator[None, None, None]: 16 | """Temporarily add a SQLAlchemy event listener to the target object. 17 | 18 | The event listener is automatically removed when the context manager exits. 19 | """ 20 | event.listen(target, identifier, fn, *args, **kwargs) 21 | 22 | try: 23 | yield 24 | finally: 25 | event.remove(target, identifier, fn) 26 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | sonar.projectKey=softwareone-platform_pytest-capsqlalchemy 2 | sonar.organization=softwareone-mpt-github 3 | 4 | sonar.language=py 5 | 6 | sonar.sources=pytest_capsqlalchemy 7 | sonar.tests=tests 8 | sonar.inclusions=pytest_capsqlalchemy/** 9 | sonar.exclusions=tests/** 10 | 11 | sonar.python.coverage.reportPaths=coverage.xml 12 | # TODO: Enable bandit once it's set up 13 | # sonar.python.bandit.reportPaths=bandit.json 14 | sonar.python.xunit.reportPath=coverage.xml 15 | # the minumum supported python version 16 | sonar.python.version=3.9 17 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/softwareone-platform/pytest-capsqlalchemy/f3ce1fd19becd313f85262e1fdd4bf534d5effcf/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import os 2 | from collections.abc import AsyncGenerator 3 | 4 | import pytest 5 | from pytest_asyncio import is_async_test 6 | from sqlalchemy import ForeignKey 7 | from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine 8 | from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship 9 | 10 | # Import the plugin fixtures manually since the plugin is explicitly disabled 11 | # in pyproject.toml in order to get accurate coverage reports. The fixtures 12 | # are still useful for the tests, so makes sense to import them here. 13 | from pytest_capsqlalchemy.plugin import * # noqa: F403 14 | 15 | pytest_plugins = ["pytester"] 16 | 17 | 18 | def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: 19 | pytest_asyncio_tests = (item for item in items if is_async_test(item)) 20 | session_scope_marker = pytest.mark.asyncio(loop_scope="session") 21 | 22 | for async_test in pytest_asyncio_tests: 23 | async_test.add_marker(session_scope_marker, append=False) 24 | 25 | 26 | @pytest.fixture(scope="session") 27 | def db_url() -> str: 28 | db_name = os.environ["TEST_POSTGRES_DB"] 29 | db_user = os.environ["TEST_POSTGRES_USER"] 30 | db_password = os.environ["TEST_POSTGRES_PASSWORD"] 31 | db_host = os.environ["TEST_POSTGRES_HOST"] 32 | db_port = os.environ["TEST_POSTGRES_PORT"] 33 | 34 | return f"postgresql+asyncpg://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}" 35 | 36 | 37 | @pytest.fixture(scope="session") 38 | def db_engine(db_url: str) -> AsyncEngine: 39 | return create_async_engine(db_url, future=True) 40 | 41 | 42 | @pytest.fixture() 43 | async def db_session(db_engine: AsyncEngine) -> AsyncGenerator[AsyncSession, None]: 44 | Session = async_sessionmaker(db_engine, class_=AsyncSession, expire_on_commit=False) 45 | 46 | async with Session() as s: 47 | yield s 48 | 49 | 50 | # Set up models used only for testing 51 | class TestingBaseModel(DeclarativeBase): 52 | __test__ = False # Prevent pytest from trying to collect this class 53 | 54 | 55 | class Order(TestingBaseModel): 56 | __tablename__ = "orders" 57 | 58 | id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) 59 | recipient: Mapped[str] 60 | items: Mapped[list["OrderItem"]] = relationship(back_populates="order", cascade="all, delete-orphan") 61 | 62 | 63 | class OrderItem(TestingBaseModel): 64 | __tablename__ = "order_items" 65 | 66 | id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) 67 | item_name: Mapped[str] 68 | price: Mapped[float] 69 | order_id: Mapped[int] = mapped_column(ForeignKey("orders.id")) 70 | order: Mapped[Order] = relationship(back_populates="items") 71 | 72 | 73 | @pytest.fixture(scope="session", autouse=True) 74 | async def create_testing_tables(db_engine: AsyncEngine) -> None: 75 | async with db_engine.begin() as conn: 76 | await conn.run_sync(TestingBaseModel.metadata.create_all) 77 | 78 | yield 79 | 80 | async with db_engine.begin() as conn: 81 | await conn.run_sync(TestingBaseModel.metadata.drop_all) 82 | -------------------------------------------------------------------------------- /tests/test_capturer.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import select, text 2 | from sqlalchemy.ext.asyncio import AsyncSession 3 | 4 | from pytest_capsqlalchemy import SQLAlchemyCapturer 5 | from pytest_capsqlalchemy.expression import SQLExpressionType 6 | from tests.conftest import Order, OrderItem 7 | 8 | 9 | async def test_assert_query_count(db_session: AsyncSession, capsqlalchemy: SQLAlchemyCapturer) -> None: 10 | await db_session.execute(text("SELECT 1")) 11 | await db_session.execute(select(OrderItem)) 12 | 13 | await db_session.commit() 14 | 15 | async with db_session.begin(): 16 | await db_session.execute(select(Order).where(Order.id == 1)) 17 | await db_session.execute(select(text("1"))) 18 | 19 | db_session.add(Order(recipient="John Doe")) 20 | 21 | capsqlalchemy.assert_query_count(9, include_tcl=True) 22 | capsqlalchemy.assert_query_count(5, include_tcl=False) 23 | 24 | 25 | async def test_assert_max_query_count(db_session: AsyncSession, capsqlalchemy: SQLAlchemyCapturer) -> None: 26 | await db_session.execute(text("SELECT 1")) 27 | await db_session.execute(select(OrderItem)) 28 | 29 | await db_session.commit() 30 | 31 | async with db_session.begin(): 32 | await db_session.get(Order, 1) 33 | await db_session.get(Order, 1) 34 | await db_session.execute(select(text("1"))) 35 | 36 | db_session.add(Order(recipient="John Doe")) 37 | 38 | capsqlalchemy.assert_max_query_count(9, include_tcl=True) 39 | capsqlalchemy.assert_max_query_count(5, include_tcl=False) 40 | 41 | 42 | async def test_changing_context(db_session: AsyncSession, capsqlalchemy: SQLAlchemyCapturer) -> None: 43 | await db_session.execute(text("SELECT 1")) 44 | 45 | capsqlalchemy.assert_query_count(1, include_tcl=False) 46 | 47 | await db_session.execute(text("SELECT 1")) 48 | 49 | capsqlalchemy.assert_query_count(2, include_tcl=False) 50 | 51 | with capsqlalchemy: 52 | capsqlalchemy.assert_query_count(0, include_tcl=False) 53 | await db_session.execute(text("SELECT 1")) 54 | capsqlalchemy.assert_query_count(1, include_tcl=False) 55 | 56 | capsqlalchemy.assert_query_count(3, include_tcl=False) 57 | 58 | 59 | async def test_captured_queries(db_session: AsyncSession, capsqlalchemy: SQLAlchemyCapturer) -> None: 60 | await db_session.execute(text("SELECT 1")) 61 | await db_session.execute(select(OrderItem)) 62 | 63 | await db_session.commit() 64 | 65 | async with db_session.begin(): 66 | await db_session.execute(select(Order).where(Order.id == 1)) 67 | await db_session.execute(select(text("1"))) 68 | 69 | db_session.add(Order(recipient="John Doe")) 70 | 71 | capsqlalchemy.assert_captured_queries( 72 | "BEGIN", 73 | "SELECT 1", 74 | "SELECT order_items.id, order_items.item_name, order_items.price, order_items.order_id \nFROM order_items", 75 | "COMMIT", 76 | "BEGIN", 77 | "SELECT orders.id, orders.recipient \nFROM orders \nWHERE orders.id = :id_1", 78 | "SELECT 1", 79 | "INSERT INTO orders (recipient) VALUES (:recipient)", 80 | "COMMIT", 81 | ) 82 | 83 | capsqlalchemy.assert_captured_queries( 84 | "SELECT 1", 85 | "SELECT order_items.id, order_items.item_name, order_items.price, order_items.order_id \nFROM order_items", 86 | "SELECT orders.id, orders.recipient \nFROM orders \nWHERE orders.id = :id_1", 87 | "SELECT 1", 88 | "INSERT INTO orders (recipient) VALUES (:recipient)", 89 | include_tcl=False, 90 | ) 91 | 92 | 93 | async def test_captured_queries_bind_params(db_session: AsyncSession, capsqlalchemy: SQLAlchemyCapturer) -> None: 94 | await db_session.execute(text("SELECT 1")) 95 | await db_session.execute(select(OrderItem)) 96 | 97 | await db_session.commit() 98 | 99 | async with db_session.begin(): 100 | await db_session.execute(select(Order).where(Order.id == 1)) 101 | await db_session.execute(select(text("1"))) 102 | 103 | db_session.add(Order(recipient="John Doe")) 104 | 105 | capsqlalchemy.assert_captured_queries( 106 | "BEGIN", 107 | "SELECT 1", 108 | "SELECT order_items.id, order_items.item_name, order_items.price, order_items.order_id \nFROM order_items", 109 | "COMMIT", 110 | "BEGIN", 111 | "SELECT orders.id, orders.recipient \nFROM orders \nWHERE orders.id = 1", 112 | "SELECT 1", 113 | "INSERT INTO orders (recipient) VALUES ('John Doe')", 114 | "COMMIT", 115 | bind_params=True, 116 | ) 117 | 118 | 119 | async def test_captured_query_types(db_session: AsyncSession, capsqlalchemy: SQLAlchemyCapturer) -> None: 120 | await db_session.execute(select(OrderItem)) 121 | 122 | await db_session.commit() 123 | 124 | async with db_session.begin(): 125 | await db_session.execute(select(Order).where(Order.id == 1)) 126 | await db_session.execute(select(text("1"))) 127 | 128 | db_session.add(Order(recipient="John Doe")) 129 | 130 | capsqlalchemy.assert_query_types( 131 | "BEGIN", 132 | "SELECT", 133 | "COMMIT", 134 | "BEGIN", 135 | "SELECT", 136 | "SELECT", 137 | "INSERT", 138 | "COMMIT", 139 | ) 140 | 141 | capsqlalchemy.assert_query_types( 142 | SQLExpressionType.SELECT, 143 | SQLExpressionType.SELECT, 144 | SQLExpressionType.SELECT, 145 | SQLExpressionType.INSERT, 146 | include_tcl=False, 147 | ) 148 | 149 | 150 | async def test_captured_queries_insert_with_relationship( 151 | db_session: AsyncSession, capsqlalchemy: SQLAlchemyCapturer 152 | ) -> None: 153 | async with db_session.begin(): 154 | order = Order(recipient="John Doe") 155 | db_session.add(order) 156 | db_session.add(OrderItem(item_name="Bread", price=2.00, order=order)) 157 | db_session.add(OrderItem(item_name="Butter", price=3.50, order=order)) 158 | 159 | capsqlalchemy.assert_captured_queries( 160 | "INSERT INTO orders (recipient) VALUES (:recipient)", 161 | ( 162 | "INSERT INTO order_items (item_name, price, order_id) VALUES " 163 | "(:item_name_m0, :price_m0, :order_id_m0), " 164 | "(:item_name_m1, :price_m1, :order_id_m1)" 165 | ), 166 | include_tcl=False, 167 | ) 168 | 169 | capsqlalchemy.assert_captured_queries( 170 | "INSERT INTO orders (recipient) VALUES ('John Doe')", 171 | ( 172 | "INSERT INTO order_items (item_name, price, order_id) VALUES " # noqa: S608 173 | f"('Bread', 2.0, {order.id}), " 174 | f"('Butter', 3.5, {order.id})" 175 | ), 176 | include_tcl=False, 177 | bind_params=True, 178 | ) 179 | -------------------------------------------------------------------------------- /tests/test_context.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import select, text 2 | from sqlalchemy.ext.asyncio import AsyncSession 3 | 4 | from pytest_capsqlalchemy.context import SQLAlchemyCaptureContext 5 | from tests.conftest import Order 6 | 7 | 8 | async def test_capture_session_simple_select( 9 | capsqlalchemy_context: SQLAlchemyCaptureContext, 10 | db_session: AsyncSession, 11 | ) -> None: 12 | await db_session.execute(select(text("1"))) 13 | 14 | expr_types = [expr.type._value_ for expr in capsqlalchemy_context.captured_expressions] 15 | assert expr_types == ["BEGIN", "SELECT"] 16 | 17 | 18 | async def test_capture_session_select_in_explicit_transaction( 19 | capsqlalchemy_context: SQLAlchemyCaptureContext, 20 | db_session: AsyncSession, 21 | ) -> None: 22 | async with db_session.begin(): 23 | await db_session.execute(select(text("1"))) 24 | 25 | expr_types = [expr.type._value_ for expr in capsqlalchemy_context.captured_expressions] 26 | assert expr_types == ["BEGIN", "SELECT", "COMMIT"] 27 | 28 | 29 | async def test_capture_session_mixed_select_statements_multi_transactions( 30 | capsqlalchemy_context: SQLAlchemyCaptureContext, 31 | db_session: AsyncSession, 32 | ) -> None: 33 | await db_session.execute(select(text("1"))) 34 | 35 | await db_session.rollback() 36 | 37 | async with db_session.begin(): 38 | await db_session.execute(select(text("1"))) 39 | await db_session.execute(select(text("1"))) 40 | 41 | await db_session.execute(select(text("1"))) 42 | await db_session.commit() 43 | await db_session.execute(select(text("1"))) 44 | 45 | expr_types = [expr.type._value_ for expr in capsqlalchemy_context.captured_expressions] 46 | assert expr_types == [ 47 | "BEGIN", 48 | "SELECT", 49 | "ROLLBACK", 50 | "BEGIN", 51 | "SELECT", 52 | "SELECT", 53 | "COMMIT", 54 | "BEGIN", 55 | "SELECT", 56 | "COMMIT", 57 | "BEGIN", 58 | "SELECT", 59 | ] 60 | 61 | 62 | async def test_clear( 63 | capsqlalchemy_context: SQLAlchemyCaptureContext, 64 | db_session: AsyncSession, 65 | ) -> None: 66 | await db_session.execute(select(text("1"))) 67 | await db_session.execute(select(text("1"))) 68 | 69 | capsqlalchemy_context.clear() 70 | 71 | await db_session.execute(select(text("1"))) 72 | 73 | assert len(capsqlalchemy_context.captured_expressions) == 1 74 | assert capsqlalchemy_context.captured_expressions[0].type == "SELECT" 75 | 76 | 77 | async def test_capture_session_add_single_order( 78 | capsqlalchemy_context: SQLAlchemyCaptureContext, 79 | db_session: AsyncSession, 80 | ) -> None: 81 | db_session.add(Order(recipient="John Doe")) 82 | await db_session.commit() 83 | 84 | expr_types = [expr.type._value_ for expr in capsqlalchemy_context.captured_expressions] 85 | assert expr_types == ["BEGIN", "INSERT", "COMMIT"] 86 | 87 | insert_expr = capsqlalchemy_context.captured_expressions[1] 88 | assert insert_expr.params == {"recipient": "John Doe"} 89 | assert insert_expr.multiparams == [] 90 | 91 | 92 | async def test_capture_session_add_multiple_orders( 93 | capsqlalchemy_context: SQLAlchemyCaptureContext, 94 | db_session: AsyncSession, 95 | ) -> None: 96 | db_session.add(Order(recipient="John Doe")) 97 | db_session.add(Order(recipient="Jane Doe")) 98 | await db_session.commit() 99 | 100 | expr_types = [expr.type._value_ for expr in capsqlalchemy_context.captured_expressions] 101 | assert expr_types == ["BEGIN", "INSERT", "COMMIT"] 102 | 103 | insert_expr = capsqlalchemy_context.captured_expressions[1] 104 | assert insert_expr.params == {} 105 | assert insert_expr.multiparams == [{"recipient": "John Doe"}, {"recipient": "Jane Doe"}] 106 | 107 | 108 | async def test_capture_session_update_orders( 109 | capsqlalchemy_context: SQLAlchemyCaptureContext, 110 | db_session: AsyncSession, 111 | ) -> None: 112 | order = Order(recipient="John Doe") 113 | db_session.add(order) 114 | await db_session.commit() 115 | 116 | order.recipient = "Jane Doe" 117 | await db_session.commit() 118 | 119 | update_expr = next(expr for expr in capsqlalchemy_context.captured_expressions if expr.type == "UPDATE") 120 | assert update_expr.params == { 121 | "orders_id": order.id, 122 | "recipient": "Jane Doe", 123 | } 124 | assert update_expr.multiparams == [] 125 | -------------------------------------------------------------------------------- /tests/test_expression.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | import pytest 4 | from sqlalchemy import Table, delete, insert, select, text, update 5 | from sqlalchemy.sql.ddl import CreateTable 6 | 7 | from pytest_capsqlalchemy.expression import SQLExpression, SQLExpressionType 8 | from tests.conftest import Order 9 | 10 | 11 | @pytest.mark.parametrize( 12 | ("sql_expression", "expected_type"), 13 | [ 14 | (SQLExpression(insert(Order)), SQLExpressionType.INSERT), 15 | (SQLExpression(insert(Order)), "INSERT"), 16 | (SQLExpression(select(Order)), SQLExpressionType.SELECT), 17 | (SQLExpression(update(Order)), SQLExpressionType.UPDATE), 18 | (SQLExpression(delete(Order)), SQLExpressionType.DELETE), 19 | (SQLExpression(text("BEGIN")), SQLExpressionType.BEGIN), 20 | (SQLExpression(text("COMMIT")), SQLExpressionType.COMMIT), 21 | (SQLExpression(text("ROLLBACK")), SQLExpressionType.ROLLBACK), 22 | (SQLExpression(text("RANDOM TEXT")), SQLExpressionType.UNKNOWN), 23 | (SQLExpression(CreateTable(Table("some_table", Order.metadata))), SQLExpressionType.UNKNOWN), 24 | ], 25 | ) 26 | def test_sql_expression_type_detection( 27 | sql_expression: SQLExpression, expected_type: Union[SQLExpressionType, str] 28 | ) -> None: 29 | assert sql_expression.type == expected_type 30 | 31 | 32 | @pytest.mark.parametrize( 33 | ("sql_expression_type", "expected_is_tcl"), 34 | [ 35 | (SQLExpressionType.SELECT, False), 36 | (SQLExpressionType.INSERT, False), 37 | (SQLExpressionType.UPDATE, False), 38 | (SQLExpressionType.DELETE, False), 39 | (SQLExpressionType.BEGIN, True), 40 | (SQLExpressionType.COMMIT, True), 41 | (SQLExpressionType.ROLLBACK, True), 42 | ], 43 | ) 44 | def test_is_tcl_detection(sql_expression_type: SQLExpressionType, expected_is_tcl: bool) -> None: 45 | assert sql_expression_type.is_tcl == expected_is_tcl 46 | 47 | 48 | @pytest.mark.parametrize( 49 | ("sql_expression", "bind_params", "expected_sql"), 50 | [ 51 | pytest.param( 52 | SQLExpression(select(Order)), 53 | False, 54 | "SELECT orders.id, orders.recipient \nFROM orders", 55 | id="select_full_table", 56 | ), 57 | pytest.param( 58 | SQLExpression(select(Order.id)), 59 | False, 60 | "SELECT orders.id \nFROM orders", 61 | id="select_single_column", 62 | ), 63 | pytest.param( 64 | SQLExpression(select(Order.id).where(Order.id == 1)), 65 | False, 66 | "SELECT orders.id \nFROM orders \nWHERE orders.id = :id_1", 67 | id="select_where_clause_no_bind_params", 68 | ), 69 | pytest.param( 70 | SQLExpression(select(Order.id).where(Order.id == 1)), 71 | True, 72 | "SELECT orders.id \nFROM orders \nWHERE orders.id = 1", 73 | id="select_where_clause_bind_params", 74 | ), 75 | pytest.param( 76 | SQLExpression(insert(Order)), 77 | False, 78 | "INSERT INTO orders (id, recipient) VALUES (:id, :recipient)", 79 | id="test_raw_insert", 80 | ), 81 | pytest.param( 82 | SQLExpression(insert(Order), params={"recipient": "John Doe"}), 83 | False, 84 | "INSERT INTO orders (recipient) VALUES (:recipient)", 85 | id="insert_single_row_no_bind_params", 86 | ), 87 | pytest.param( 88 | SQLExpression(insert(Order), params={"recipient": "John Doe"}), 89 | True, 90 | "INSERT INTO orders (recipient) VALUES ('John Doe')", 91 | id="insert_single_row_bind_params", 92 | ), 93 | pytest.param( 94 | SQLExpression(insert(Order), multiparams=[{"recipient": "John Doe"}, {"recipient": "Jane Doe"}]), 95 | False, 96 | "INSERT INTO orders (recipient) VALUES (:recipient_m0), (:recipient_m1)", 97 | id="insert_multiple_rows_no_bind_params", 98 | ), 99 | pytest.param( 100 | SQLExpression(insert(Order), multiparams=[{"recipient": "John Doe"}, {"recipient": "Jane Doe"}]), 101 | True, 102 | "INSERT INTO orders (recipient) VALUES ('John Doe'), ('Jane Doe')", 103 | id="insert_multiple_rows_bind_params", 104 | ), 105 | pytest.param( 106 | SQLExpression(update(Order).where(Order.id == 1).values(recipient="John Doe")), 107 | False, 108 | "UPDATE orders SET recipient=:recipient WHERE orders.id = :id_1", 109 | id="update_where_clause_no_bind_params", 110 | ), 111 | pytest.param( 112 | SQLExpression(update(Order).where(Order.id == 1).values(recipient="John Doe")), 113 | True, 114 | "UPDATE orders SET recipient='John Doe' WHERE orders.id = 1", 115 | id="update_where_clause_bind_params", 116 | ), 117 | pytest.param( 118 | SQLExpression(delete(Order).where(Order.id == 1)), 119 | False, 120 | "DELETE FROM orders WHERE orders.id = :id_1", 121 | id="delete_where_clause_no_bind_params", 122 | ), 123 | pytest.param( 124 | SQLExpression(delete(Order).where(Order.id == 1)), 125 | True, 126 | "DELETE FROM orders WHERE orders.id = 1", 127 | id="delete_where_clause_bind_params", 128 | ), 129 | ], 130 | ) 131 | def test_get_sql(sql_expression: SQLExpression, bind_params: bool, expected_sql: str) -> None: 132 | assert sql_expression.get_sql(bind_params=bind_params) == expected_sql 133 | -------------------------------------------------------------------------------- /tests/test_plugin_usage.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pytest import Pytester 3 | 4 | 5 | @pytest.fixture(autouse=True) 6 | def setup_asyncio_default_fixture_loop_scope(pytester: Pytester) -> None: 7 | # This option is set on this project but the tests here are for a brand new one 8 | # so we need to set it up here too. This is necessary to suppress a warning 9 | # by pytest-asyncio about the default loop scope. 10 | 11 | pytester.makeini(""" 12 | [pytest] 13 | asyncio_default_fixture_loop_scope = "session" 14 | """) 15 | 16 | 17 | def test_plugin_without_db_engine_fixture(pytester: Pytester) -> None: 18 | pytester.copy_example("test_missing_setup.py") 19 | result = pytester.runpytest() 20 | 21 | result.assert_outcomes(errors=1) 22 | assert "fixture 'db_engine' not found" in result.stdout.str() 23 | 24 | 25 | def test_plugin_setup_with_async_db_engine_fixture(pytester: Pytester) -> None: 26 | pytester.copy_example("test_plugin_setup_with_async_db_engine_fixture.py") 27 | result = pytester.runpytest() 28 | 29 | result.assert_outcomes(passed=3) 30 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | skipsdist = true 3 | envlist = py39, py310, py311, py312, py313 4 | 5 | [gh-actions] 6 | python = 7 | 3.9: py39 8 | 3.10: py310 9 | 3.11: py311 10 | 3.12: py312 11 | 3.13: py313 12 | 13 | [testenv] 14 | passenv = PYTHON_VERSION 15 | allowlist_externals = uv 16 | commands = 17 | uv sync --python {envpython} 18 | uv run python -m pytest --doctest-modules tests --cov --cov-config=pyproject.toml --cov-report=xml 19 | mypy 20 | --------------------------------------------------------------------------------