├── .coveragerc ├── .github ├── ISSUE_TEMPLATE.rst ├── PULL_REQUEST_TEMPLATE.rst ├── dependabot.yml └── workflows │ ├── automerge.yml │ ├── build.yml │ ├── pr-check.yml │ ├── pre-commit.yml │ ├── pypi.yml │ ├── tests-mariadb-linux.yml │ ├── tests-mysql-linux.yml │ └── tests.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .rstcheck.cfg ├── AUTHORS.rst ├── CHANGES.rst ├── CONTRIBUTING.rst ├── COPYING ├── COPYING.lesser ├── MANIFEST.in ├── Pipfile ├── README.rst ├── logo.png ├── logo.svg ├── mypy.ini ├── newsfragments ├── +68766105.misc.rst ├── +83bb8efb.misc.rst ├── +d366fa9c.misc.rst └── .gitignore ├── pyproject.toml ├── pytest_mysql ├── __init__.py ├── config.py ├── exceptions.py ├── executor.py ├── executor_noop.py ├── factories │ ├── __init__.py │ ├── client.py │ ├── noprocess.py │ └── process.py ├── plugin.py └── py.typed └── tests ├── __init__.py ├── conftest.py ├── test_executor.py ├── test_mysql.py └── test_mysqlnoproc.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | include = 3 | pytest_mysql/* 4 | tests/* 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.rst: -------------------------------------------------------------------------------- 1 | ### What action do you want to perform 2 | 3 | 4 | ### What are the results 5 | 6 | 7 | ### What are the expected results 8 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.rst: -------------------------------------------------------------------------------- 1 | Chore that needs to be done: 2 | 3 | * [ ] Add newsfragment `pipenv run towncrier create [issue_number].[type].rst` 4 | 5 | Types are defined in the pyproject.toml, issue_numer either from issue tracker or the Pull request number. 6 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "02:00" 8 | open-pull-requests-limit: 1 9 | - package-ecosystem: github-actions 10 | directory: "/" 11 | schedule: 12 | interval: weekly 13 | time: "06:00" 14 | day: "saturday" 15 | open-pull-requests-limit: 1 16 | -------------------------------------------------------------------------------- /.github/workflows/automerge.yml: -------------------------------------------------------------------------------- 1 | name: Merge me test dependencies! 2 | 3 | on: 4 | workflow_run: 5 | types: 6 | - completed 7 | workflows: 8 | # List all required workflow names here. 9 | - 'Run linters' 10 | - 'Run tests on MySQL' 11 | - 'Run tests on MariaDB' 12 | - 'Test build package' 13 | 14 | jobs: 15 | automerge: 16 | uses: fizyk/actions-reuse/.github/workflows/shared-automerge.yml@v3.1.1 17 | secrets: 18 | app_id: ${{ secrets.MERGE_APP_ID }} 19 | private_key: ${{ secrets.MERGE_APP_PRIVATE_KEY }} 20 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Test build package 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | uses: fizyk/actions-reuse/.github/workflows/shared-pypi.yml@v3.1.1 12 | -------------------------------------------------------------------------------- /.github/workflows/pr-check.yml: -------------------------------------------------------------------------------- 1 | name: Run test commands 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | 7 | jobs: 8 | pr-check: 9 | uses: fizyk/actions-reuse/.github/workflows/shared-pr-check.yml@v3.1.1 10 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yml: -------------------------------------------------------------------------------- 1 | name: Run linters 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | 10 | jobs: 11 | pre-commit: 12 | uses: fizyk/actions-reuse/.github/workflows/shared-pre-commit.yml@v3.1.1 13 | -------------------------------------------------------------------------------- /.github/workflows/pypi.yml: -------------------------------------------------------------------------------- 1 | name: Package and publish 2 | on: 3 | push: 4 | tags: 5 | - v* 6 | jobs: 7 | build-n-publish: 8 | uses: fizyk/actions-reuse/.github/workflows/shared-pypi.yml@v3.1.1 9 | with: 10 | publish: true 11 | secrets: 12 | pypi_token: ${{ secrets.pypi_token }} 13 | -------------------------------------------------------------------------------- /.github/workflows/tests-mariadb-linux.yml: -------------------------------------------------------------------------------- 1 | name: Run pytest tests 2 | 3 | on: 4 | workflow_call: 5 | inputs: 6 | python-versions: 7 | description: 'Supported python versions' 8 | default: '["3.8", "3.9", "3.10", "3.11", "3.12", "pypy-3.8"]' 9 | required: false 10 | type: string 11 | mariadb: 12 | description: 'MariaDB version' 13 | required: true 14 | type: string 15 | secrets: 16 | codecov_token: 17 | description: 'Codecov token' 18 | required: false 19 | 20 | jobs: 21 | mariadb: 22 | runs-on: ubuntu-latest 23 | strategy: 24 | fail-fast: false 25 | matrix: 26 | python-version: ${{ fromJSON(inputs.python-versions) }} 27 | env: 28 | OS: ubuntu-latest 29 | PYTHON: ${{ matrix.python-version }} 30 | services: 31 | mysql: 32 | image: mariadb:${{ inputs.mariadb }} 33 | env: 34 | MARIADB_ALLOW_EMPTY_ROOT_PASSWORD: yes 35 | MARIADB_DATABASE: tests 36 | ports: 37 | - 3333:3306 38 | options: --health-cmd="healthcheck.sh --su-mysql --connect --innodb_initialized" --health-interval=10s --health-timeout=5s --health-retries=3 39 | 40 | steps: 41 | - uses: actions/checkout@v4 42 | - uses: ankane/setup-mariadb@v1 43 | with: 44 | mariadb-version: ${{ inputs.mariadb }} 45 | - name: Set up Python ${{ matrix.python-version }} 46 | uses: actions/setup-python@v5 47 | with: 48 | python-version: ${{ matrix.python-version }} 49 | - name: Check MariaDB Version 50 | run: mysqld --version 51 | - name: Run test 52 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 53 | with: 54 | python-version: ${{ matrix.python-version }} 55 | command: pytest --mysql-user=$USER -n 0 -k "not mysqlnoproc" --cov-report=xml 56 | - name: Run xdist test 57 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 58 | with: 59 | python-version: ${{ matrix.python-version }} 60 | command: pytest --mysql-user=$USER -n 1 -k "not mysqlnoproc" --cov-report=xml:coverage-xdist.xml 61 | - name: Run noproc test 62 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 63 | with: 64 | python-version: ${{ matrix.python-version }} 65 | command: pytest -n 0 -k mysqlnoproc --cov-report=xml:coverage-noproc.xml --mysql-host="127.0.0.1" --mysql-port=3333 66 | - name: Upload coverage to Codecov 67 | uses: codecov/codecov-action@v5.4.3 68 | with: 69 | flags: linux,mariadb 70 | env_vars: OS, PYTHON 71 | fail_ci_if_error: false 72 | token: ${{ secrets.codecov_token }} 73 | -------------------------------------------------------------------------------- /.github/workflows/tests-mysql-linux.yml: -------------------------------------------------------------------------------- 1 | name: Run pytest tests 2 | 3 | on: 4 | workflow_call: 5 | inputs: 6 | python-versions: 7 | description: 'Supported python versions' 8 | default: '["3.8", "3.9", "3.10", "3.11", "3.12", "pypy-3.8"]' 9 | required: false 10 | type: string 11 | mysql: 12 | description: 'MySQL version' 13 | required: true 14 | type: string 15 | secrets: 16 | codecov_token: 17 | description: 'Codecov token' 18 | required: false 19 | 20 | jobs: 21 | mysql: 22 | runs-on: ubuntu-latest 23 | strategy: 24 | fail-fast: false 25 | matrix: 26 | python-version: ${{ fromJSON(inputs.python-versions) }} 27 | env: 28 | OS: ubuntu-latest 29 | PYTHON: ${{ matrix.python-version }} 30 | services: 31 | mysql: 32 | image: mysql:${{ inputs.mysql }} 33 | env: 34 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 35 | MYSQL_DATABASE: tests 36 | ports: 37 | - 3333:3306 38 | options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 39 | 40 | steps: 41 | - uses: actions/checkout@v4 42 | - uses: ankane/setup-mysql@v1 43 | with: 44 | mysql-version: ${{ inputs.mysql }} 45 | - name: Set up Python ${{ matrix.python-version }} 46 | uses: actions/setup-python@v5 47 | with: 48 | python-version: ${{ matrix.python-version }} 49 | - name: Check MySQL Version 50 | run: mysqld --version 51 | - name: Run test 52 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 53 | with: 54 | python-version: ${{ matrix.python-version }} 55 | command: pytest --mysql-user=$USER -n 0 -k "not mysqlnoproc" --cov-report=xml 56 | - name: Run xdist test 57 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 58 | with: 59 | python-version: ${{ matrix.python-version }} 60 | command: pytest --mysql-user=$USER -n 1 -k "not mysqlnoproc" --cov-report=xml:coverage-xdist.xml 61 | - name: Run noproc test 62 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 63 | with: 64 | python-version: ${{ matrix.python-version }} 65 | command: pytest -n 0 -k mysqlnoproc --cov-report=xml:coverage-noproc.xml --mysql-host="127.0.0.1" --mysql-port=3333 66 | - name: Upload coverage to Codecov 67 | uses: codecov/codecov-action@v5.4.3 68 | with: 69 | flags: linux,mysql 70 | env_vars: OS, PYTHON 71 | fail_ci_if_error: false 72 | token: ${{ secrets.codecov_token }} 73 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Run tests on MySQL 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | tests-mysql-linux: 11 | uses: ./.github/workflows/tests-mysql-linux.yml 12 | with: 13 | mysql: "8.4" 14 | python-versions: '["3.9", "3.10", "3.11", "3.12", "3.13", "pypy-3.10"]' 15 | 16 | tests-mysql-linux_8: 17 | needs: [ tests-mysql-linux ] 18 | uses: ./.github/workflows/tests-mysql-linux.yml 19 | with: 20 | mysql: "8.0" 21 | python-versions: '["3.11", "3.12", "3.13"]' 22 | 23 | tests-mariadb-linux-11: 24 | needs: [ tests-mysql-linux ] 25 | uses: ./.github/workflows/tests-mariadb-linux.yml 26 | with: 27 | mariadb: "11.4" 28 | python-versions: '["3.11", "3.12", "3.13"]' 29 | 30 | tests-mariadb-linux-10_11: 31 | needs: [ tests-mariadb-linux-11 ] 32 | uses: ./.github/workflows/tests-mariadb-linux.yml 33 | with: 34 | mariadb: 10.11 35 | python-versions: '["3.12", "3.13"]' 36 | 37 | tests-mysql-macosx: 38 | runs-on: macos-latest 39 | needs: [tests-mysql-linux] 40 | strategy: 41 | fail-fast: false 42 | matrix: 43 | python-version: ["3.11", "3.12", "3.13"] 44 | env: 45 | OS: macos-latest 46 | PYTHON: ${{ matrix.python-version }} 47 | steps: 48 | - uses: actions/checkout@v4 49 | - uses: ankane/setup-mysql@v1 50 | with: 51 | mysql-version: 8.4 52 | - name: Check MySQL Version 53 | run: mysqld --version 54 | - name: Run test 55 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 56 | with: 57 | python-version: ${{ matrix.python-version }} 58 | command: pytest -n 0 -k "not mysqlnoproc" --cov-report=xml --mysql-user=root --basetemp=/tmp/pytest_mysql 59 | cache: false 60 | 61 | tests-mariadb-macosx: 62 | runs-on: macos-latest 63 | needs: [tests-mysql-macosx, tests-mariadb-linux-11] 64 | strategy: 65 | fail-fast: false 66 | matrix: 67 | python-version: ["3.13"] 68 | env: 69 | OS: macos-latest 70 | PYTHON: ${{ matrix.python-version }} 71 | steps: 72 | - uses: actions/checkout@v4 73 | - uses: ankane/setup-mariadb@v1 74 | with: 75 | mariadb-version: "11.4" 76 | - name: Check MySQL Version 77 | run: mysqld --version 78 | - name: Run test 79 | uses: fizyk/actions-reuse/.github/actions/pipenv@v3.1.1 80 | with: 81 | python-version: ${{ matrix.python-version }} 82 | command: pytest --mysql-user=$USER -n 0 -k "not mysqlnoproc" --cov-report=xml --basetemp=/tmp/pytest_mysql 83 | cache: false 84 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | .cache/* 21 | venv/ 22 | 23 | # Installer logs 24 | pip-log.txt 25 | 26 | # Pipenv 27 | Pipfile.lock 28 | 29 | # Unit test / coverage reports 30 | .coverage 31 | .tox 32 | nosetests.xml 33 | 34 | # Translations 35 | *.mo 36 | 37 | # Mr Developer 38 | .mr.developer.cfg 39 | .project 40 | .pydevproject 41 | .idea 42 | /.pytest_cache/ 43 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | ci: 3 | skip: [pipenv, mypy] 4 | 5 | # See https://pre-commit.com for more information 6 | # See https://pre-commit.com/hooks.html for more hooks 7 | minimum_pre_commit_version: 4.0.0 8 | default_stages: [pre-commit] 9 | repos: 10 | - repo: https://github.com/pre-commit/pre-commit-hooks 11 | rev: v5.0.0 12 | hooks: 13 | - id: check-added-large-files 14 | - id: check-case-conflict 15 | - id: check-merge-conflict 16 | - id: trailing-whitespace 17 | - id: check-toml 18 | - id: end-of-file-fixer 19 | - id: mixed-line-ending 20 | - id: check-yaml 21 | - id: pretty-format-json 22 | - id: detect-private-key 23 | - id: debug-statements 24 | 25 | - repo: https://github.com/psf/black 26 | rev: 25.1.0 27 | hooks: 28 | - id: black 29 | entry: black --config pyproject.toml . 30 | 31 | - repo: https://github.com/astral-sh/ruff-pre-commit 32 | rev: v0.11.12 33 | hooks: 34 | - id: ruff 35 | args: [--fix, --exit-non-zero-on-fix, --respect-gitignore, --show-fixes] 36 | 37 | - repo: https://github.com/rstcheck/rstcheck 38 | rev: v6.2.5 39 | hooks: 40 | - id: rstcheck 41 | additional_dependencies: [sphinx, toml] 42 | 43 | - repo: local 44 | hooks: 45 | - id: pipenv 46 | stages: [pre-commit, manual] 47 | language: system 48 | name: Install dependencies for the local linters 49 | entry: bash -c "pip install pipenv && pipenv install --dev" 50 | types_or: 51 | - python 52 | - toml # Pipfile 53 | pass_filenames: false 54 | - id: mypy 55 | stages: [pre-commit, manual] 56 | name: mypy 57 | entry: pipenv run mypy . 58 | language: system 59 | types_or: 60 | - python 61 | - toml # Pipfile 62 | pass_filenames: false 63 | -------------------------------------------------------------------------------- /.rstcheck.cfg: -------------------------------------------------------------------------------- 1 | [rstcheck] 2 | report_level = warning 3 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Authors 2 | ======= 3 | 4 | This file contains the list of people involved in the development 5 | of pytest-mysql along its history. 6 | 7 | * Grzegorz Śliwiński 8 | * Jakub Klinkovský 9 | * Karolina Blümke 10 | * Paweł Wilczyński 11 | * Tomasz Święcicki 12 | * Tomasz Karbownicki 13 | * Michał Masłowski 14 | * Damian Skrzypczak 15 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | CHANGELOG 2 | ========= 3 | 4 | .. towncrier release notes start 5 | 6 | 3.1.0 (2024-12-10) 7 | ================== 8 | 9 | Breaking changes 10 | ---------------- 11 | 12 | - Drop support for Python 3.8 13 | 14 | 15 | Features 16 | -------- 17 | 18 | - Declare support for Python 3.13 19 | 20 | 21 | Miscellaneus 22 | ------------ 23 | 24 | - `#550 `_ 25 | - Fixed last piece of macosx environment setup after moving to pymysql 26 | - Readme fix 27 | - Update MySQL versions in CI 28 | 29 | 30 | 3.0.0 (2024-05-23) 31 | ================== 32 | 33 | Breaking changes 34 | ---------------- 35 | 36 | - Replace mysqlclient with pymysql library. 37 | 38 | Installation of mysqlclient became more and more problematic on macosx which in turn proved to be hard to maintain on github-actions. 39 | 40 | PyMySQL is mostly API compatible so pytest-mysql usage is just changing import location with one exception for poorly documented client fixture closeup. (`#491 `_) 41 | 42 | 43 | Miscellaneus 44 | ------------ 45 | 46 | - `#481 `_, `#527 `_, `#530 `_ 47 | 48 | 49 | 2.5.0 (2023-10-30) 50 | ================== 51 | 52 | Features 53 | -------- 54 | 55 | - Add missing user param (`#474 `_) 56 | - Add support for Python 3.12 (`#480 `_) 57 | 58 | 59 | Miscellaneus 60 | ------------ 61 | 62 | - `#450 `_, `#454 `_, `#460 `_, `#473 `_, `#478 `_, `#479 `_, `#480 `_ 63 | 64 | 65 | 2.4.2 (2023-03-27) 66 | ================== 67 | 68 | Bugfixes 69 | -------- 70 | 71 | - Fix license configuration in pyproject.toml (`#426 `_) 72 | 73 | 74 | 2.4.1 (2023-03-13) 75 | ================== 76 | 77 | Bugfixes 78 | -------- 79 | 80 | - Fix packaging mistake which did not included the subpackages. (`#417 `_) 81 | 82 | 83 | 2.4.0 (2023-03-10) 84 | ================== 85 | 86 | Breaking changes 87 | ---------------- 88 | 89 | - Dropped support for Python 3.7 (`#401 `_) 90 | 91 | 92 | Bugfixes 93 | -------- 94 | 95 | - Raise exception with helpful message if unixsocket is too long on FreeBSD or MacOS system 96 | 97 | OSX gives out super long temp directories. This isn't a problem until 98 | we run into an odd 103-character limit on the names of unix sockets 99 | `see this stackoverflow thread `_. 100 | Here we warn and give the user a way out of it. (`#345 `_) 101 | 102 | 103 | Features 104 | -------- 105 | 106 | - Added support to Python 3.11 (`#392 `_) 107 | - Add type hints and mypy checks (`#401 `_) 108 | 109 | 110 | Miscellaneus 111 | ------------ 112 | 113 | - Run tests on CI on macosx (`#245 `_) 114 | - Update example configuration in README (`#365 `_) 115 | - Readme fixes (`#372 `_) 116 | - Docstring fixes (`#378 `_) 117 | - Added towncrier to manage newsfragments (`#397 `_) 118 | - Migrate dependency management to pipenv (`#398 `_) 119 | - Move most of the package definition to pyproject.toml (`#399 `_) 120 | - Migrate automerge to a shared workflow using github app for short-lived tokens. (`#400 `_) 121 | - Use tbump to manage versioning (`#402 `_) 122 | - Updated codecov configuration: 123 | * Added token 124 | * Turned off pipeline failing if codecov upload fails (`#405 `_) 125 | - Run mariadb tests after MySQL tests run. (`#409 `_) 126 | 127 | 128 | 2.3.1 129 | ===== 130 | 131 | Bugs 132 | ---- 133 | 134 | - Now will accept correctly database names with hyphen 135 | 136 | 2.3.0 137 | ===== 138 | 139 | Features 140 | -------- 141 | 142 | - Import FixtureRequest from pytest, not private _pytest. 143 | Require at least pytest 6.2 144 | - Replace tmpdir_factory with tmp_path_factory 145 | 146 | Docs 147 | ---- 148 | 149 | - List mysql_noproc in README's fixtures list 150 | 151 | Fixes 152 | ----- 153 | 154 | - Database cleanup code will attempt to reconnect to mysql if test accidentally would close the connection 155 | 156 | 2.2.0 157 | ===== 158 | 159 | Features 160 | -------- 161 | 162 | - add `user` option to setup and tear down mysql process as non-privileged 163 | 164 | Misc 165 | ---- 166 | 167 | - Add Python 3.10 to CI 168 | 169 | 2.1.0 170 | ===== 171 | 172 | Features 173 | -------- 174 | 175 | - `mysql_noproc` fixture to connect to already running mysql server 176 | - raise more meaningful error when the test database already exists 177 | 178 | Misc 179 | ---- 180 | 181 | - rely on `get_port` functionality delivered by `port_for` 182 | 183 | 184 | Deprecation 185 | ----------- 186 | 187 | - Deprecated `mysql_logsdir` ini configuration and `--mysql-logsdir` command option 188 | - Deprecated `logs_prefix` process fixture factory setting 189 | 190 | Misc 191 | ---- 192 | 193 | - Require minimum python 3.7 194 | - Migrate CI to Github Actions 195 | 196 | 2.0.3 197 | ===== 198 | 199 | - [enhancement] Do not assume that mysql executables are in /usr/bin 200 | 201 | 2.0.2 202 | ===== 203 | 204 | - [enhancement] Preemptively read data after each test in mysql client fixture. 205 | This will make test run if the test itself forgot to fetch queried data. 206 | - [enhnacement] Require at least mirakuru 2.3.0 - forced by changed stop method parameters change 207 | 208 | 2.0.1 209 | ===== 210 | 211 | - [fix] Improved mysql version detection on osx 212 | - [build] extracted xdist into separate stage on travis 213 | - [build] have deployemt as separate stage on travis 214 | 215 | 2.0.0 216 | ===== 217 | 218 | - [Enhancements] Add support for MySQL 5.7.6 and up with new configuration options. Legacy configuration supports older MySQL and MariaDB databases. 219 | - [breaking] mysql_exec ini option replaced with mysql_mysqld_safe 220 | - [breaking] --mysql-exec cmd option replaced with --mysql-mysqld-safe 221 | - [breaking] replaced mysql_init ini option with mysql_install_db 222 | - [breaking] replaced --mysql-init cmd option with --mysql-install-db 223 | - [breaking] added mysql_mysqld option and --mysql-mysqld cmd option 224 | 225 | 1.1.1 226 | ===== 227 | 228 | - [enhancements] removed path.py dependency 229 | 230 | 1.1.0 231 | ===== 232 | 233 | - [enhancement] change deprecated getfuncargvalaue to getfixturevalues, require at least pytest 3.0.0 234 | 235 | 1.0.0 236 | ===== 237 | 238 | - [enhancements] create command line and pytest.ini configuration options for mysql's log directory location 239 | - [enhancements] create command line and pytest.ini configuration options for mysql's starting parametetrs 240 | - [enhancements] create command line and pytest.ini configuration options for mysql test database name 241 | - [enhancements] create command line and pytest.ini configuration options for mysql's user password 242 | - [enhancements] create command line and pytest.ini configuration options for mysql user 243 | - [enhancements] create command line and pytest.ini configuration options for mysql host 244 | - [enhancements] create command line and pytest.ini configuration options for mysql port 245 | - [enhancements] create command line and pytest.ini configuration options for mysql's init executable 246 | - [enhancements] create command line and pytest.ini configuration options for mysql's admin executable 247 | - [enhancements] create command line and pytest.ini configuration options for mysql executable 248 | - [enhancements] create command line and pytest.ini configuration options for mysql logsdir 249 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contribute to pytest-mysql 2 | ========================== 3 | 4 | Thank you for taking time to contribute to pytest-mysql! 5 | 6 | The following is a set of guidelines for contributing to pytest-mysql. These are just guidelines, not rules, use your best judgment and feel free to propose changes to this document in a pull request. 7 | 8 | Bug Reports 9 | ----------- 10 | 11 | #. Use a clear and descriptive title for the issue - it'll be much easier to identify the problem. 12 | #. Describe the steps to reproduce the problems in as many details as possible. 13 | #. If possible, provide a code snippet to reproduce the issue. 14 | 15 | Feature requests/proposals 16 | -------------------------- 17 | 18 | #. Use a clear and descriptive title for the proposal 19 | #. Provide as detailed description as possible 20 | * Use case is great to have 21 | #. There'll be a bit of discussion for the feature. Don't worry, if it is to be accepted, we'd like to support it, so we need to understand it thoroughly. 22 | 23 | 24 | Pull requests 25 | ------------- 26 | 27 | #. Start with a bug report or feature request 28 | #. Use a clear and descriptive title 29 | #. Provide a description - which issue does it refers to, and what part of the issue is being solved 30 | #. Be ready for code review :) 31 | 32 | Commits 33 | ------- 34 | 35 | #. Make sure commits are atomic, and each atomic change is being followed by test. 36 | #. If the commit solves part of the issue reported, include *refs #[Issue number]* in a commit message. 37 | #. If the commit solves whole issue reported, please refer to `Closing issues via commit messages `_ for ways to close issues when commits will be merged. 38 | 39 | 40 | Coding style 41 | ------------ 42 | 43 | #. Coding style is being handled by black and doublechecked by ruff. 44 | * We provide a `pre-commit `_ configuration for invoking these on commit. 45 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /COPYING.lesser: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.rst *.py 2 | recursive-include pytest_mysql *.py 3 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [packages] 7 | pytest = "==8.4.0" 8 | port-for = "==0.7.4" 9 | mirakuru = "==2.6.0" 10 | packaging = "==25.0" 11 | pymysql = "==1.1.1" 12 | 13 | [dev-packages] 14 | towncrier = "==24.8.0" 15 | pytest-cov = "==6.1.1" 16 | pytest-xdist = "==3.7.0" 17 | mock = "==5.2.0" 18 | coverage = "==7.8.2" 19 | tbump = "==6.11.0" 20 | mypy = "==1.16.0" 21 | types-pymysql = "==1.1.0.20250516" 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://raw.githubusercontent.com/dbfixtures/pytest-mysql/master/logo.png 2 | :width: 100px 3 | :height: 100px 4 | 5 | pytest-mysql 6 | ============ 7 | 8 | .. image:: https://img.shields.io/pypi/v/pytest-mysql.svg 9 | :target: https://pypi.python.org/pypi/pytest-mysql/ 10 | :alt: Latest PyPI version 11 | 12 | .. image:: https://img.shields.io/pypi/wheel/pytest-mysql.svg 13 | :target: https://pypi.python.org/pypi/pytest-mysql/ 14 | :alt: Wheel Status 15 | 16 | .. image:: https://img.shields.io/pypi/pyversions/pytest-mysql.svg 17 | :target: https://pypi.python.org/pypi/pytest-mysql/ 18 | :alt: Supported Python Versions 19 | 20 | .. image:: https://img.shields.io/pypi/l/pytest-mysql.svg 21 | :target: https://pypi.python.org/pypi/pytest-mysql/ 22 | :alt: License 23 | 24 | What is this? 25 | ============= 26 | 27 | This is a pytest plugin, that enables you to test your code that relies on a running MySQL Database. 28 | It allows you to specify fixtures for MySQL process and client. 29 | 30 | .. warning:: 31 | 32 | Only MySQL 5.7.6 and up are supported. For older versions, please use pytest-mysql 2.0.3 33 | Although Pull Request to add back support for older MySQL versions are welcome. 34 | 35 | How to use 36 | ========== 37 | 38 | Plugin contains two fixtures 39 | 40 | * **mysql** - it's a client fixture that has functional scope. After each test drops test database from MySQL ensuring repeatability. 41 | * **mysql_proc** - session scoped fixture, that starts MySQL instance at it's first use and stops at the end of the tests. 42 | * **mysql_noproc** - session scoped fixtures, that allows to connect to already existing MySQL instance, and cleans the database at the end of the tests 43 | 44 | Simply include one of these fixtures into your tests fixture list. 45 | 46 | You can also create additional mysql client and process fixtures if you'd need to: 47 | 48 | 49 | .. code-block:: python 50 | 51 | from pytest_mysql import factories 52 | from getpass import getuser 53 | 54 | mysql_my_proc = factories.mysql_proc( 55 | port=None, user=getuser()) 56 | mysql_my = factories.mysql('mysql_my_proc') 57 | 58 | .. note:: 59 | 60 | Each MySQL process fixture can be configured in a different way than the others through the fixture factory arguments. 61 | 62 | Configuration 63 | ============= 64 | 65 | You can define your settings in three ways, it's fixture factory argument, command line option and pytest.ini configuration option. 66 | You can pick which you prefer, but remember that these settings are handled in the following order: 67 | 68 | * ``Fixture factory argument`` 69 | * ``Command line option`` 70 | * ``Configuration option in your pytest.ini file`` 71 | 72 | .. list-table:: Configuration options 73 | :header-rows: 1 74 | 75 | * - MySQL/MariaDB option 76 | - Fixture factory argument 77 | - Command line option 78 | - pytest.ini option 79 | - Noop process fixture 80 | - Default 81 | * - Path to executable 82 | - mysqld_exec 83 | - --mysql-mysqld 84 | - mysql_mysqld 85 | - - 86 | - mysqld 87 | * - Path to safe executable 88 | - mysqld_safe 89 | - --mysql-mysqld-safe 90 | - mysql_mysqld_safe 91 | - - 92 | - mysqld_safe 93 | * - Path to mysql_install_db for legacy installations 94 | - install_db 95 | - --mysql-install-db 96 | - mysql_install_db 97 | - - 98 | - mysql_install_db 99 | * - Path to Admin executable 100 | - admin_executable 101 | - --mysql-admin 102 | - mysql_admin 103 | - - 104 | - mysqladmin 105 | * - Database hostname 106 | - host 107 | - --mysql-host 108 | - mysql_host 109 | - yes 110 | - localhost 111 | * - Database port 112 | - port 113 | - --mysql-port 114 | - mysql_port 115 | - yes (3306) 116 | - random 117 | * - MySQL user to work with 118 | - user 119 | - --mysql-user 120 | - mysql_user 121 | - - 122 | - root 123 | * - User's password 124 | - passwd 125 | - --mysql-passwd 126 | - mysql_passwd 127 | - - 128 | - 129 | * - Test database name 130 | - dbname 131 | - --mysql-dbname 132 | - mysql_dbname 133 | - - 134 | - test 135 | * - Starting parameters 136 | - params 137 | - --mysql-params 138 | - mysql_params 139 | - - 140 | - 141 | * - Log directory location [DEPRECATED] 142 | - logsdir 143 | - --mysql-logsdir 144 | - mysql_logsdir 145 | - - 146 | - $TMPDIR 147 | 148 | 149 | Example usage: 150 | 151 | * pass it as an argument in your own fixture 152 | 153 | .. code-block:: python 154 | 155 | mysql_proc = factories.mysql_proc( 156 | port=8888) 157 | 158 | * use ``--mysql-port`` command line option when you run your tests 159 | 160 | .. code-block:: 161 | 162 | py.test tests --mysql-port=8888 163 | 164 | 165 | * specify your port as ``mysql_port`` in your ``pytest.ini`` file. 166 | 167 | To do so, put a line like the following under the ``[pytest]`` section of your ``pytest.ini``: 168 | 169 | .. code-block:: ini 170 | 171 | [pytest] 172 | mysql_port = 8888 173 | 174 | Examples 175 | ======== 176 | 177 | Populating database for tests 178 | ----------------------------- 179 | 180 | With SQLAlchemy 181 | +++++++++++++++ 182 | 183 | This example shows how to populate database and create an SQLAlchemy's ORM connection: 184 | 185 | Sample below is simplified session fixture from 186 | `pyramid_fullauth `_ tests: 187 | 188 | .. code-block:: python 189 | 190 | from sqlalchemy import create_engine 191 | from sqlalchemy.orm import scoped_session, sessionmaker 192 | from sqlalchemy.pool import NullPool 193 | from zope.sqlalchemy import register 194 | 195 | 196 | @pytest.fixture 197 | def db_session(mysql): 198 | """Session for SQLAlchemy.""" 199 | from pyramid_fullauth.models import Base # pylint:disable=import-outside-toplevel 200 | 201 | # assumes setting, these can be obtained from pytest-mysql config or mysql_proc 202 | connection = f'mysql+mysqldb://root:@127.0.0.1:3307/tests?charset=utf8' 203 | 204 | engine = create_engine(connection, echo=False, poolclass=NullPool) 205 | pyramid_basemodel.Session = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) 206 | pyramid_basemodel.bind_engine( 207 | engine, pyramid_basemodel.Session, should_create=True, should_drop=True) 208 | 209 | yield pyramid_basemodel.Session 210 | 211 | transaction.commit() 212 | Base.metadata.drop_all(engine) 213 | 214 | 215 | @pytest.fixture 216 | def user(db_session): 217 | """Test user fixture.""" 218 | from pyramid_fullauth.models import User 219 | from tests.tools import DEFAULT_USER 220 | 221 | new_user = User(**DEFAULT_USER) 222 | db_session.add(new_user) 223 | transaction.commit() 224 | return new_user 225 | 226 | 227 | def test_remove_last_admin(db_session, user): 228 | """ 229 | Sample test checks internal login, but shows usage in tests with SQLAlchemy 230 | """ 231 | user = db_session.merge(user) 232 | user.is_admin = True 233 | transaction.commit() 234 | user = db_session.merge(user) 235 | 236 | with pytest.raises(AttributeError): 237 | user.is_admin = False 238 | .. note:: 239 | 240 | See the original code at `pyramid_fullauth's conftest file `_. 241 | Depending on your needs, that in between code can fire alembic migrations in case of sqlalchemy stack or any other code 242 | 243 | Connecting to MySQL/MariaDB (in a docker) 244 | ----------------------------------------- 245 | 246 | To connect to a docker run MySQL and run test on it, use noproc fixtures. 247 | 248 | .. code-block:: sh 249 | 250 | docker run --name some-db -e MYSQL_ALLOW_EMPTY_PASSWORD=yes -d mysql --expose 3306 251 | 252 | .. code-block:: sh 253 | 254 | docker run --name some-db -e MARIADB_ALLOW_EMPTY_PASSWORD=yes -d mariadb --expose 3306 255 | 256 | This will start MySQL in a docker container, however using a MySQL installed locally is not much different. 257 | 258 | In tests, make sure that all your tests are using **mysql_noproc** fixture like that: 259 | 260 | .. code-block:: python 261 | 262 | mysql_in_docker = factories.mysql_noproc() 263 | mysql = factories.mysql("mysql_in_docker") 264 | 265 | 266 | def test_mysql_docker(mysql): 267 | """Run test.""" 268 | cur = mysql.cursor() 269 | cur.query("CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);") 270 | mysql.commit() 271 | cur.close() 272 | 273 | And run tests: 274 | 275 | .. code-block:: sh 276 | 277 | pytest --mysql-host=127.0.0.1 278 | 279 | 280 | 281 | Running on Docker/as root 282 | ========================= 283 | 284 | Unfortunately, running MySQL as root (thus by default on docker) is not possible. 285 | MySQL (and MariaDB as well) will not allow it. 286 | 287 | .. code-block:: 288 | 289 | USER nobody 290 | 291 | This line should switch your docker process to run on user nobody. See `this comment for example `_ 292 | 293 | Package resources 294 | ----------------- 295 | 296 | * Bug tracker: https://github.com/dbfixtures/pytest-mysql/issues 297 | 298 | Release 299 | ======= 300 | 301 | Install pipenv and --dev dependencies first, Then run: 302 | 303 | .. code-block:: 304 | 305 | pipenv run tbump [NEW_VERSION] 306 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbfixtures/pytest-mysql/3ff153229d7149efc829f679af597f375b2c2769/logo.png -------------------------------------------------------------------------------- /logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 18 | 20 | 42 | 44 | Created by potrace 1.15, written by Peter Selinger 2001-2017 45 | 46 | 48 | image/svg+xml 49 | 51 | 52 | 53 | 54 | 55 | 58 | 65 | 71 | 77 | 83 | 89 | 95 | 101 | 107 | 113 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | allow_redefinition = False 3 | allow_untyped_globals = False 4 | check_untyped_defs = True 5 | disallow_incomplete_defs = True 6 | disallow_subclassing_any = True 7 | disallow_untyped_calls = True 8 | disallow_untyped_decorators = True 9 | disallow_untyped_defs = True 10 | follow_imports = silent 11 | ignore_missing_imports = False 12 | implicit_reexport = False 13 | no_implicit_optional = True 14 | pretty = True 15 | show_error_codes = True 16 | strict_equality = True 17 | warn_no_return = True 18 | warn_return_any = True 19 | warn_unreachable = True 20 | warn_unused_ignores = True 21 | -------------------------------------------------------------------------------- /newsfragments/+68766105.misc.rst: -------------------------------------------------------------------------------- 1 | Updated links after repository transfer 2 | -------------------------------------------------------------------------------- /newsfragments/+83bb8efb.misc.rst: -------------------------------------------------------------------------------- 1 | Adjust workflows for actions-reuse 3 2 | -------------------------------------------------------------------------------- /newsfragments/+d366fa9c.misc.rst: -------------------------------------------------------------------------------- 1 | Use pre-commit for maintaining code style and linting 2 | -------------------------------------------------------------------------------- /newsfragments/.gitignore: -------------------------------------------------------------------------------- 1 | !.gitignore 2 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "pytest-mysql" 3 | version = "3.1.0" 4 | description = "MySQL process and client fixtures for pytest" 5 | readme = "README.rst" 6 | keywords = ["tests", "pytest", "fixture", "mysql"] 7 | license = {file = "COPYING.lesser"} 8 | authors = [ 9 | {name = "Grzegorz Śliwiński", email = "fizyk+pypi@fizyk.dev"} 10 | ] 11 | classifiers = [ 12 | "Development Status :: 5 - Production/Stable", 13 | "Environment :: Web Environment", 14 | "Intended Audience :: Developers", 15 | "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)", 16 | "Natural Language :: English", 17 | "Operating System :: OS Independent", 18 | "Programming Language :: Python", 19 | "Programming Language :: Python :: 3", 20 | "Programming Language :: Python :: 3.9", 21 | "Programming Language :: Python :: 3.10", 22 | "Programming Language :: Python :: 3.11", 23 | "Programming Language :: Python :: 3.12", 24 | "Programming Language :: Python :: 3.13", 25 | "Programming Language :: Python :: 3 :: Only", 26 | "Topic :: Software Development :: Libraries :: Python Modules", 27 | "Topic :: Software Development :: Testing", 28 | "Framework :: Pytest", 29 | ] 30 | dependencies = [ 31 | "pytest >= 6.2", 32 | "port-for >= 0.6.0", 33 | "mirakuru", 34 | "pymysql", 35 | "packaging >= 23" 36 | ] 37 | requires-python = ">= 3.9" 38 | 39 | [project.urls] 40 | "Source" = "https://github.com/dbfixtures/pytest-mysql" 41 | "Bug Tracker" = "https://github.com/dbfixtures/pytest-mysql/issues" 42 | "Changelog" = "https://github.com/dbfixtures/pytest-mysql/blob/v3.1.0/CHANGES.rst" 43 | 44 | [project.entry-points."pytest11"] 45 | pytest_mysql = "pytest_mysql.plugin" 46 | 47 | [build-system] 48 | requires = ["setuptools >= 61.0.0", "wheel"] 49 | build-backend = "setuptools.build_meta" 50 | 51 | [tool.setuptools] 52 | zip-safe = true 53 | 54 | [tool.setuptools.packages.find] 55 | include = ["pytest_mysql*"] 56 | exclude = ["tests*"] 57 | namespaces = false 58 | 59 | [tool.pytest.ini_options] 60 | xfail_strict=true 61 | addopts = "--max-worker-restart=0 --showlocals --verbose --cov" 62 | testpaths = "tests" 63 | mysql_dbname = "pytestmysql" 64 | 65 | [tool.black] 66 | line-length = 100 67 | target-version = ['py39'] 68 | include = '.*\.pyi?$' 69 | 70 | [tool.ruff] 71 | line-length = 100 72 | select = [ 73 | "E", # pycodestyle 74 | "F", # pyflakes 75 | "I", # isort 76 | "D", # pydocstyle 77 | ] 78 | 79 | [tool.towncrier] 80 | directory = "newsfragments" 81 | single_file=true 82 | filename="CHANGES.rst" 83 | issue_format="`#{issue} `_" 84 | 85 | [tool.towncrier.fragment.feature] 86 | name = "Features" 87 | showcontent = true 88 | 89 | [tool.towncrier.fragment.bugfix] 90 | name = "Bugfixes" 91 | showcontent = true 92 | 93 | [tool.towncrier.fragment.break] 94 | name = "Breaking changes" 95 | showcontent = true 96 | 97 | [tool.towncrier.fragment.misc] 98 | name = "Miscellaneus" 99 | showcontent = false 100 | 101 | [tool.tbump] 102 | 103 | [tool.tbump.version] 104 | current = "3.1.0" 105 | 106 | # Example of a semver regexp. 107 | # Make sure this matches current_version before 108 | # using tbump 109 | regex = ''' 110 | (?P\d+) 111 | \. 112 | (?P\d+) 113 | \. 114 | (?P\d+) 115 | (\- 116 | (?P.+) 117 | )? 118 | ''' 119 | 120 | [tool.tbump.git] 121 | message_template = "Release {new_version}" 122 | tag_template = "v{new_version}" 123 | 124 | [[tool.tbump.field]] 125 | # the name of the field 126 | name = "extra" 127 | # the default value to use, if there is no match 128 | default = "" 129 | 130 | 131 | # For each file to patch, add a [[file]] config 132 | # section containing the path of the file, relative to the 133 | # tbump.toml location. 134 | [[tool.tbump.file]] 135 | src = "pytest_mysql/__init__.py" 136 | 137 | [[tool.tbump.file]] 138 | src = "pyproject.toml" 139 | search = 'version = "{current_version}"' 140 | 141 | [[tool.tbump.file]] 142 | src = "pyproject.toml" 143 | search = '"Changelog" = "https://github.com/dbfixtures/pytest-mysql/blob/v{current_version}/CHANGES.rst"' 144 | 145 | # You can specify a list of commands to 146 | # run after the files have been patched 147 | # and before the git commit is made 148 | 149 | [[tool.tbump.before_commit]] 150 | name = "Build changelog" 151 | cmd = "pipenv run towncrier build --version {new_version} --yes" 152 | 153 | # Or run some commands after the git tag and the branch 154 | # have been pushed: 155 | # [[tool.tbump.after_push]] 156 | # name = "publish" 157 | # cmd = "./publish.sh" 158 | -------------------------------------------------------------------------------- /pytest_mysql/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2016 by Clearcode 3 | # and associates (see AUTHORS). 4 | 5 | # This file is part of pytest-mysql. 6 | 7 | # pytest-mysql is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU Lesser General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | 12 | # pytest-mysql is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU Lesser General Public License for more details. 16 | 17 | # You should have received a copy of the GNU Lesser General Public License 18 | # along with pytest-mysql. If not, see . 19 | """Main module for pytest-mysql.""" 20 | __version__ = "3.1.0" 21 | -------------------------------------------------------------------------------- /pytest_mysql/config.py: -------------------------------------------------------------------------------- 1 | """Config module.""" 2 | 3 | from pathlib import Path 4 | from typing import Any, TypedDict 5 | 6 | from pytest import FixtureRequest 7 | 8 | 9 | class MySQLConfigType(TypedDict): 10 | """Configuration type dict.""" 11 | 12 | mysqld: Path 13 | mysqld_safe: Path 14 | admin: str 15 | host: str 16 | port: str 17 | user: str 18 | passwd: str 19 | dbname: str 20 | params: str 21 | logsdir: str 22 | install_db: str 23 | 24 | 25 | def get_config(request: FixtureRequest) -> MySQLConfigType: 26 | """Return a dictionary with config options.""" 27 | 28 | def get_conf_option(option: str) -> Any: 29 | option_name = "mysql_" + option 30 | return request.config.getoption(option_name) or request.config.getini(option_name) 31 | 32 | config: MySQLConfigType = { 33 | "mysqld": Path(get_conf_option("mysqld")), 34 | "mysqld_safe": Path(get_conf_option("mysqld_safe")), 35 | "admin": get_conf_option("admin"), 36 | "host": get_conf_option("host"), 37 | "port": get_conf_option("port"), 38 | "user": get_conf_option("user"), 39 | "passwd": get_conf_option("passwd"), 40 | "dbname": get_conf_option("dbname"), 41 | "params": get_conf_option("params"), 42 | "logsdir": get_conf_option("logsdir"), 43 | "install_db": get_conf_option("install_db"), 44 | } 45 | return config 46 | -------------------------------------------------------------------------------- /pytest_mysql/exceptions.py: -------------------------------------------------------------------------------- 1 | """Pytest MySQL's exceptions.""" 2 | 3 | 4 | class PytestMySQLException(Exception): 5 | """Base plguin's exceptions.""" 6 | 7 | 8 | class MySQLUnsupported(PytestMySQLException): 9 | """Exception raised when an unsupported MySQL has been encountered.""" 10 | 11 | 12 | class VersionNotDetected(PytestMySQLException): 13 | """Exception raised when exector could not detect mysqls' version.""" 14 | 15 | def __init__(self, output: str) -> None: 16 | """Create error message.""" 17 | super().__init__("Could not detect version in {}".format(output)) 18 | 19 | 20 | class SocketPathTooLong(PytestMySQLException): 21 | """Exception raised the socket path is over 103 chars. 22 | 23 | Raised on BSD/MacOS as Mysql will fail to start. 24 | """ 25 | 26 | 27 | class DatabaseExists(PytestMySQLException): 28 | """Raise this exception, when the database already exists.""" 29 | -------------------------------------------------------------------------------- /pytest_mysql/executor.py: -------------------------------------------------------------------------------- 1 | """Specified MySQL Executor.""" 2 | 3 | import platform 4 | import re 5 | import subprocess 6 | from pathlib import Path 7 | from typing import Any, Literal, Optional, Union 8 | 9 | from mirakuru import TCPExecutor 10 | from packaging.version import parse 11 | 12 | from pytest_mysql.exceptions import ( 13 | MySQLUnsupported, 14 | SocketPathTooLong, 15 | VersionNotDetected, 16 | ) 17 | 18 | 19 | class MySQLExecutor(TCPExecutor): 20 | """MySQL Executor for running MySQL server.""" 21 | 22 | VERSION_RE = re.compile(r"(?:[a-z_ ]+)(Ver)? (?P[\d.]+).*", re.I) 23 | IMPLEMENTATION_RE = re.compile(r".*MariaDB.*") 24 | 25 | def __init__( 26 | self, 27 | mysqld_safe: Path, 28 | mysqld: Path, 29 | admin_exec: str, 30 | logfile_path: str, 31 | params: str, 32 | base_directory: Path, 33 | user: str, 34 | host: str, 35 | port: int, 36 | timeout: int = 60, 37 | install_db: Optional[str] = None, 38 | ) -> None: 39 | """Specialised Executor to run and manage MySQL server process. 40 | 41 | :param mysqld_safe: path to mysqld_safe executable 42 | :param mysqld: path to mysqld executable 43 | :param admin_exec: path to mysqladmin executable 44 | :param logfile_path: where the server shoyld wrute it's logs 45 | :param params: string containing additional starting parameters 46 | :param base_directory: base directory where the temporary files, 47 | database files, socket and pid will be placed in. 48 | :param user: mysql username 49 | :param host: server's host 50 | :param port: server's port 51 | :param timeout: executor's timeout for start and stop actions 52 | :param install_db: 53 | """ 54 | self.mysqld_safe = mysqld_safe 55 | self.mysqld = mysqld 56 | self.install_db = install_db 57 | self.admin_exec = admin_exec 58 | self.base_directory = base_directory 59 | self.datadir = self.base_directory / f"mysqldata_{port}" 60 | self.datadir.mkdir() 61 | self.pidfile = self.base_directory / f"mysql-server.{port}.pid" 62 | self.unixsocket = str(self.base_directory / f"mysql.{port}.sock") 63 | self.logfile_path = logfile_path 64 | self.user = user 65 | self._initialised = False 66 | command = ( 67 | f"{self.mysqld_safe} " 68 | f"--datadir={self.datadir} " 69 | f"--pid-file={self.pidfile} " 70 | f"--port={port} " 71 | f"--user={self.user} " 72 | f"--socket={self.unixsocket} " 73 | f"--log-error={self.logfile_path} " 74 | f"--tmpdir={self.base_directory} " 75 | f"--skip-syslog {params}" 76 | ) 77 | super().__init__(command, host, port, timeout=timeout) 78 | 79 | def version(self) -> str: 80 | """Read MySQL's version.""" 81 | version_output = subprocess.check_output([self.mysqld, "--version"]).decode("utf-8") 82 | matches = self.VERSION_RE.search(version_output) 83 | if not matches: 84 | raise VersionNotDetected(version_output) 85 | return matches.groupdict()["version"] 86 | 87 | def implementation(self) -> Union[Literal["mariadb"], Literal["mysql"]]: 88 | """Detect MySQL Implementation.""" 89 | version_output = subprocess.check_output([self.mysqld, "--version"]).decode("utf-8") 90 | if self.IMPLEMENTATION_RE.search(version_output): 91 | return "mariadb" 92 | return "mysql" 93 | 94 | def initialize_mysqld(self) -> None: 95 | """Initialise mysql directory. 96 | 97 | #. Remove mysql directory if exist. 98 | #. `Initialize MySQL data directory 99 | `_ 100 | 101 | :param str mysql_init: mysql_init executable 102 | :param str datadir: path to datadir 103 | :param str base_directory: path to base_directory 104 | 105 | """ 106 | if self._initialised: 107 | return 108 | init_command = ( 109 | f"{self.mysqld} --initialize-insecure " 110 | f"--datadir={self.datadir} --tmpdir={self.base_directory} " 111 | f"--log-error={self.logfile_path}" 112 | ) 113 | subprocess.check_output(init_command, shell=True) 114 | self._initialised = True 115 | 116 | def initialise_mysql_db_install(self) -> None: 117 | """Initialise mysql directory for older MySQL installations or MariaDB. 118 | 119 | #. Remove mysql directory if exist. 120 | #. `Initialize MySQL data directory 121 | `_ 122 | 123 | :param str mysql_init: mysql_init executable 124 | :param str datadir: path to datadir 125 | :param str base_directory: path to base_directory 126 | 127 | """ 128 | if self._initialised: 129 | return 130 | init_command = ( 131 | f"{self.install_db} --user={self.user} " 132 | f"--datadir={self.datadir} --tmpdir={self.base_directory}" 133 | ) 134 | subprocess.check_output(init_command, shell=True) 135 | self._initialised = True 136 | 137 | def start(self) -> "MySQLExecutor": 138 | """Trigger initialisation during start.""" 139 | self._check_socket_path() 140 | 141 | implementation = self.implementation() 142 | if implementation == "mysql" and parse(self.version()) > parse("5.7.6"): 143 | self.initialize_mysqld() 144 | elif implementation in ["mysql", "mariadb"]: 145 | if self.install_db: 146 | self.initialise_mysql_db_install() 147 | else: 148 | raise MySQLUnsupported("mysqld_init path is missing.") 149 | else: 150 | raise MySQLUnsupported("Only MySQL and MariaDB servers are supported with MariaDB.") 151 | return super().start() 152 | 153 | def shutdown(self) -> None: 154 | """Send shutdown command to the server.""" 155 | shutdown_command = ( 156 | f"{self.admin_exec} --socket={self.unixsocket} " f"--user={self.user} shutdown" 157 | ) 158 | try: 159 | subprocess.check_output(shutdown_command, shell=True) 160 | except subprocess.CalledProcessError: 161 | # Fallback to using root user for shutdown 162 | shutdown_command = ( 163 | f"{self.admin_exec} --socket={self.unixsocket} " f"--user=root shutdown" 164 | ) 165 | subprocess.check_output(shutdown_command, shell=True) 166 | 167 | def stop(self, *args: Any, **kwargs: Any) -> "MySQLExecutor": 168 | """Stop the server.""" 169 | self.shutdown() 170 | return super().stop(*args, **kwargs) 171 | 172 | def _check_socket_path(self) -> None: 173 | if platform.system() in ["Darwin", "FreeBSD]"] and len(self.unixsocket) > 103: 174 | raise SocketPathTooLong( 175 | f"Socket path '{self.unixsocket}' is too long, " 176 | f"please pass ie. `--basetemp=/tmp/pytest_mysql` to pytest" 177 | ) 178 | -------------------------------------------------------------------------------- /pytest_mysql/executor_noop.py: -------------------------------------------------------------------------------- 1 | """Module containing Noop executor.""" 2 | 3 | from typing import Any, Literal 4 | 5 | 6 | class NoopMySQLExecutor: 7 | """Noop Executor. 8 | 9 | Used to mimic in necessary scope the MySQL executor inside fixtures. 10 | """ 11 | 12 | def __init__( 13 | self, 14 | user: str, 15 | host: str, 16 | port: int, 17 | ) -> None: 18 | """Initialize NoopMySQLExecutor.""" 19 | self.user = user 20 | self.host = host 21 | self.port = port 22 | self.unixsocket = None 23 | 24 | def running(self) -> Literal[True]: 25 | """Check if process is running.""" 26 | return True 27 | 28 | def start(self) -> None: 29 | """Do nothing starter.""" 30 | 31 | def __enter__(self) -> None: 32 | """Do nothing enter method.""" 33 | pass 34 | 35 | def __exit__(self, *args: Any, **kwargs: Any) -> None: 36 | """Do nothing exit method.""" 37 | pass 38 | -------------------------------------------------------------------------------- /pytest_mysql/factories/__init__.py: -------------------------------------------------------------------------------- 1 | """Factories module.""" 2 | 3 | from pytest_mysql.factories.client import mysql 4 | from pytest_mysql.factories.noprocess import mysql_noproc 5 | from pytest_mysql.factories.process import mysql_proc 6 | 7 | __all__ = ("mysql", "mysql_proc", "mysql_noproc") 8 | -------------------------------------------------------------------------------- /pytest_mysql/factories/client.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2013 by Clearcode 2 | # and associates (see AUTHORS). 3 | 4 | # This file is part of pytest-mysql. 5 | 6 | # pytest-mysql is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # pytest-mysql is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with pytest-mysql. If not, see . 18 | """Client fixture factory for MySQL database.""" 19 | from typing import Any, Callable, Dict, Generator, Optional, Union 20 | 21 | import pytest 22 | from _pytest.fixtures import FixtureRequest 23 | from pymysql import Connection, OperationalError, ProgrammingError 24 | 25 | from pytest_mysql.config import get_config 26 | from pytest_mysql.exceptions import DatabaseExists 27 | from pytest_mysql.executor import MySQLExecutor 28 | from pytest_mysql.executor_noop import NoopMySQLExecutor 29 | 30 | 31 | def mysql( 32 | process_fixture_name: str, 33 | passwd: Optional[str] = None, 34 | dbname: Optional[str] = None, 35 | charset: str = "utf8", 36 | collation: str = "utf8_general_ci", 37 | ) -> Callable[[FixtureRequest], Any]: 38 | """Client fixture factory for MySQL server. 39 | 40 | Factory. Create connection to mysql. If you want you can give a scope, 41 | default is 'session'. 42 | 43 | For charset and collation meaning, 44 | see `Database Character Set and Collation 45 | `_ 46 | 47 | :param str process_fixture_name: process fixture name 48 | :param str passwd: mysql server's password 49 | :param str dbname: database's name 50 | :param str charset: MySQL characterset to use by default 51 | for *tests* database 52 | :param str collation: MySQL collation to use by default 53 | for *tests* database 54 | 55 | :returns: function ``mysql_fixture`` with suit scope 56 | :rtype: func 57 | """ 58 | 59 | def _connect(connect_kwargs: Dict[str, Any], query_str: str, mysql_db: str) -> Connection: 60 | """Apply given query to a given MySQLdb connection.""" 61 | mysql_conn = Connection(**connect_kwargs) 62 | try: 63 | mysql_conn.query(query_str) 64 | except ProgrammingError as e: 65 | if "database exists" in str(e): 66 | raise DatabaseExists( 67 | f"Database {mysql_db} already exists. There's some test " 68 | f"configuration error. Either you start your own server " 69 | f"with the database name used in tests, or you use two " 70 | f"fixtures with the same database name on the same " 71 | f"process fixture." 72 | ) from e 73 | raise 74 | return mysql_conn 75 | 76 | @pytest.fixture 77 | def mysql_fixture( 78 | request: FixtureRequest, 79 | ) -> Generator[Connection, None, None]: 80 | """Client fixture for MySQL server. 81 | 82 | #. Get config. 83 | #. Try to import MySQLdb package. 84 | #. Connect to mysql server. 85 | #. Create database. 86 | #. Use proper database. 87 | #. Drop database after tests. 88 | 89 | :param request: fixture request object 90 | 91 | :returns: connection to database 92 | """ 93 | config = get_config(request) 94 | process: Union[NoopMySQLExecutor, MySQLExecutor] = request.getfixturevalue( 95 | process_fixture_name 96 | ) 97 | if not process.running(): 98 | process.start() 99 | 100 | mysql_user = process.user 101 | mysql_passwd = passwd or config["passwd"] 102 | mysql_db = dbname or config["dbname"] 103 | 104 | connection_kwargs: Dict[str, Any] = { 105 | "host": process.host, 106 | "user": mysql_user, 107 | "passwd": mysql_passwd, 108 | } 109 | if process.unixsocket: 110 | connection_kwargs["unix_socket"] = process.unixsocket 111 | else: 112 | connection_kwargs["port"] = process.port 113 | 114 | query_str = ( 115 | f"CREATE DATABASE `{mysql_db}` " 116 | f"DEFAULT CHARACTER SET {charset} " 117 | f"DEFAULT COLLATE {collation}" 118 | ) 119 | try: 120 | mysql_conn: Connection = _connect(connection_kwargs, query_str, mysql_db) 121 | except OperationalError: 122 | # Fallback to mysql connection with root user 123 | connection_kwargs["user"] = "root" 124 | mysql_conn = _connect(connection_kwargs, query_str, mysql_db) 125 | mysql_conn.query(f"USE `{mysql_db}`") 126 | yield mysql_conn 127 | 128 | # clean up after test that forgot to fetch selected data 129 | if not mysql_conn.open: 130 | mysql_conn = Connection(**connection_kwargs) 131 | try: 132 | with mysql_conn.cursor() as cursor: 133 | cursor.fetchall() 134 | except Exception as e: 135 | print(str(e)) 136 | query_drop_database = f"DROP DATABASE IF EXISTS `{mysql_db}`" 137 | mysql_conn.query(query_drop_database) 138 | mysql_conn.close() 139 | 140 | return mysql_fixture 141 | -------------------------------------------------------------------------------- /pytest_mysql/factories/noprocess.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2013 by Clearcode 2 | # and associates (see AUTHORS). 3 | 4 | # This file is part of pytest-mysql. 5 | 6 | # pytest-mysql is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # pytest-mysql is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with pytest-mysql. If not, see . 18 | """Process fixture factory for MySQL database.""" 19 | 20 | from typing import Callable, Generator, Optional 21 | 22 | import pytest 23 | from _pytest.fixtures import FixtureRequest 24 | 25 | from pytest_mysql.config import get_config 26 | from pytest_mysql.executor_noop import NoopMySQLExecutor 27 | 28 | 29 | def mysql_noproc( 30 | host: Optional[str] = None, 31 | port: Optional[int] = None, 32 | user: Optional[str] = None, 33 | ) -> Callable[[FixtureRequest], Generator[NoopMySQLExecutor, None, None]]: 34 | """Process fixture factory for MySQL server. 35 | 36 | :param str host: hostname 37 | :param int port: port name 38 | :param str user: user name 39 | :rtype: func 40 | :returns: function which makes a mysql process 41 | 42 | """ 43 | 44 | @pytest.fixture(scope="session") 45 | def mysql_noproc_fixture( 46 | request: FixtureRequest, 47 | ) -> Generator[NoopMySQLExecutor, None, None]: 48 | """Process fixture for MySQL server. 49 | 50 | #. Get config. 51 | 52 | :param request: fixture request object 53 | :rtype: pytest_dbfixtures.executors.TCPExecutor 54 | :returns: tcp executor 55 | 56 | """ 57 | config = get_config(request) 58 | mysql_port = int(port or config["port"] or 3306) 59 | mysql_host = host or config["host"] 60 | mysql_user = user or config["user"] or "root" 61 | 62 | mysql_executor = NoopMySQLExecutor( 63 | user=mysql_user, 64 | host=mysql_host, 65 | port=mysql_port, 66 | ) 67 | with mysql_executor: 68 | yield mysql_executor 69 | 70 | return mysql_noproc_fixture 71 | -------------------------------------------------------------------------------- /pytest_mysql/factories/process.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2013 by Clearcode 2 | # and associates (see AUTHORS). 3 | 4 | # This file is part of pytest-mysql. 5 | 6 | # pytest-mysql is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # pytest-mysql is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with pytest-mysql. If not, see . 18 | """Process fixture factory for MySQL database.""" 19 | 20 | from pathlib import Path 21 | from typing import Callable, Generator, List, Optional, Set, Tuple, Union 22 | from warnings import warn 23 | 24 | import pytest 25 | from port_for import get_port 26 | from pytest import FixtureRequest, TempPathFactory 27 | 28 | from pytest_mysql.config import get_config 29 | from pytest_mysql.executor import MySQLExecutor 30 | 31 | 32 | def mysql_proc( 33 | mysqld_exec: Optional[Path] = None, 34 | admin_executable: Optional[str] = None, 35 | mysqld_safe: Optional[Path] = None, 36 | host: Optional[str] = None, 37 | user: Optional[str] = None, 38 | port: Union[ 39 | None, 40 | str, 41 | int, 42 | Tuple[int, int], 43 | Set[int], 44 | List[str], 45 | List[int], 46 | List[Tuple[int, int]], 47 | List[Set[int]], 48 | List[Union[Set[int], Tuple[int, int]]], 49 | List[Union[str, int, Tuple[int, int], Set[int]]], 50 | ] = -1, 51 | params: Optional[str] = None, 52 | logs_prefix: str = "", 53 | install_db: Optional[str] = None, 54 | ) -> Callable[[FixtureRequest, TempPathFactory], Generator[MySQLExecutor, None, None]]: 55 | """Process fixture factory for MySQL server. 56 | 57 | :param mysqld_exec: path to mysql executable 58 | :param admin_executable: path to mysql_admin executable 59 | :param mysqld_safe: path to mysqld_safe executable 60 | :param host: hostname 61 | :param user: user name 62 | :param port: 63 | exact port (e.g. '8000', 8000) 64 | randomly selected port (None) - any random available port 65 | [(2000,3000)] or (2000,3000) - random available port from a given range 66 | [{4002,4003}] or {4002,4003} - random of 4002 or 4003 ports 67 | [(2000,3000), {4002,4003}] -random of given range and set 68 | :param params: additional command-line mysqld parameters 69 | :param logs_prefix: prefix for log filename 70 | :param install_db: path to legacy mysql_install_db script 71 | :returns: function which makes a mysql process 72 | """ 73 | 74 | @pytest.fixture(scope="session") 75 | def mysql_proc_fixture( 76 | request: FixtureRequest, tmp_path_factory: TempPathFactory 77 | ) -> Generator[MySQLExecutor, None, None]: 78 | """Process fixture for MySQL server. 79 | 80 | #. Get config. 81 | #. Initialize MySQL data directory 82 | #. `Start a mysqld server 83 | `_ 84 | #. Stop server and remove directory after tests. 85 | `See `_ 86 | 87 | :param FixtureRequest request: fixture request object 88 | :param tmp_path_factory: pytest fixture for temporary directories 89 | :rtype: pytest_dbfixtures.executors.TCPExecutor 90 | :returns: tcp executor 91 | 92 | """ 93 | config = get_config(request) 94 | mysql_mysqld = mysqld_exec or config["mysqld"] 95 | mysql_admin_exec = admin_executable or config["admin"] 96 | mysql_mysqld_safe = mysqld_safe or config["mysqld_safe"] 97 | mysql_port = get_port(port) or get_port(config["port"]) 98 | assert mysql_port 99 | mysql_host = host or config["host"] 100 | mysql_params = params or config["params"] 101 | mysql_install_db = install_db or config["install_db"] 102 | 103 | tmpdir = tmp_path_factory.mktemp(f"pytest-mysql-{request.fixturename}") 104 | 105 | if logs_prefix: 106 | warn( 107 | f"logfile_prefix factory argument is deprecated, " 108 | f"and will be dropped in future releases. All fixture related " 109 | f"data resides within {tmpdir}, and logs_prefix is only used, " 110 | f"if deprecated logsdir is configured", 111 | DeprecationWarning, 112 | ) 113 | 114 | logfile_path = tmpdir / f"mysql-server.{port}.log" 115 | logsdir = config["logsdir"] 116 | if logsdir: 117 | warn( 118 | f"mysql_logsdir and --mysql-logsdir config option is " 119 | f"deprecated, and will be dropped in future releases. " 120 | f"All fixture related data resides within {tmpdir}", 121 | DeprecationWarning, 122 | ) 123 | if logs_prefix: 124 | logfile_path = Path(logsdir) / f"{logs_prefix}mysql-server.{mysql_port}.log" 125 | 126 | mysql_executor = MySQLExecutor( 127 | mysqld_safe=mysql_mysqld_safe, 128 | mysqld=mysql_mysqld, 129 | admin_exec=mysql_admin_exec, 130 | logfile_path=str(logfile_path), 131 | base_directory=tmpdir, 132 | params=mysql_params, 133 | user=user or config["user"] or "root", 134 | host=mysql_host, 135 | port=mysql_port, 136 | install_db=mysql_install_db, 137 | ) 138 | with mysql_executor: 139 | yield mysql_executor 140 | 141 | return mysql_proc_fixture 142 | -------------------------------------------------------------------------------- /pytest_mysql/plugin.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2013 by Clearcode 2 | # and associates (see AUTHORS). 3 | 4 | # This file is part of pytest-mysql. 5 | 6 | # pytest-mysql is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # pytest-mysql is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with pytest-mysql. If not, see . 18 | """Plugin definition.""" 19 | 20 | from pytest import Parser 21 | 22 | from pytest_mysql import factories 23 | 24 | # pylint:disable=invalid-name 25 | _help_mysqld = "Path to MySQLd executable" 26 | _help_admin = "Path to MySQL's admin executable" 27 | _help_install_db = "Path to MySQL's legacy install_db script (also used in MariaDB)" 28 | _help_mysqld_safe = "Path to MySQL's init executable" 29 | _help_logsdir = "[DEPRECATED] Logs directory location" 30 | _help_host = "Host at which MySQL will accept connections" 31 | _help_port = "Port at which MySQL will accept connections" 32 | _help_user = "MySQL username" 33 | _help_passwd = "MySQL password" 34 | _help_dbname = "Test database name" 35 | _help_params = "Starting parameters for the MySQL" 36 | 37 | 38 | def pytest_addoption(parser: Parser) -> None: 39 | """Plugin configuration.""" 40 | parser.addini(name="mysql_mysqld", help=_help_mysqld, default="mysqld") 41 | 42 | parser.addini(name="mysql_mysqld_safe", help=_help_mysqld_safe, default="mysqld_safe") 43 | 44 | parser.addini(name="mysql_admin", help=_help_admin, default="mysqladmin") 45 | 46 | parser.addini( 47 | name="mysql_install_db", 48 | help=_help_install_db, 49 | default="mysql_install_db", 50 | ) 51 | 52 | parser.addini(name="mysql_host", help=_help_host, default="localhost") 53 | 54 | parser.addini( 55 | name="mysql_port", 56 | help=_help_port, 57 | default=None, 58 | ) 59 | 60 | parser.addini(name="mysql_user", help=_help_user, default="root") 61 | 62 | parser.addini(name="mysql_passwd", help=_help_passwd, default="") 63 | 64 | parser.addini(name="mysql_dbname", help=_help_dbname, default="test") 65 | 66 | parser.addini(name="mysql_params", help=_help_params, default="") 67 | 68 | parser.addini( 69 | name="mysql_logsdir", 70 | help=_help_logsdir, 71 | ) 72 | 73 | parser.addoption( 74 | "--mysql-mysqld", 75 | action="store", 76 | metavar="path", 77 | dest="mysql_mysqld", 78 | help=_help_mysqld, 79 | ) 80 | 81 | parser.addoption( 82 | "--mysql-mysqld-safe", 83 | action="store", 84 | metavar="path", 85 | dest="mysql_mysqld_safe", 86 | help=_help_mysqld_safe, 87 | ) 88 | 89 | parser.addoption( 90 | "--mysql-admin", 91 | action="store", 92 | metavar="path", 93 | dest="mysql_admin", 94 | help=_help_admin, 95 | ) 96 | 97 | parser.addoption( 98 | "--mysql-install-db", 99 | action="store", 100 | metavar="path", 101 | dest="mysql_install_db", 102 | help=_help_install_db, 103 | ) 104 | 105 | parser.addoption( 106 | "--mysql-host", 107 | action="store", 108 | dest="mysql_host", 109 | help=_help_host, 110 | ) 111 | 112 | parser.addoption("--mysql-port", action="store", dest="mysql_port", help=_help_port) 113 | 114 | parser.addoption("--mysql-user", action="store", dest="mysql_user", help=_help_user) 115 | 116 | parser.addoption("--mysql-passwd", action="store", dest="mysql_passwd", help=_help_passwd) 117 | 118 | parser.addoption("--mysql-dbname", action="store", dest="mysql_dbname", help=_help_dbname) 119 | 120 | parser.addoption("--mysql-params", action="store", dest="mysql_params", help=_help_params) 121 | 122 | parser.addoption( 123 | "--mysql-logsdir", 124 | action="store", 125 | metavar="path", 126 | dest="mysql_logsdir", 127 | help=_help_logsdir, 128 | ) 129 | 130 | 131 | mysql_proc = factories.mysql_proc() 132 | mysql_noproc = factories.mysql_noproc() 133 | mysql = factories.mysql("mysql_proc") 134 | 135 | __all__ = ("pytest_addoption", "mysql_proc", "mysql_noproc", "mysql") 136 | -------------------------------------------------------------------------------- /pytest_mysql/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbfixtures/pytest-mysql/3ff153229d7149efc829f679af597f375b2c2769/pytest_mysql/py.typed -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Main test module for pytest-mysql.""" 2 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | """Tests main conftest file.""" 2 | 3 | from pytest_mysql import factories 4 | from pytest_mysql.plugin import * # noqa: F403 5 | 6 | # pylint:disable=invalid-name 7 | mysql_proc2 = factories.mysql_proc(port=3308) 8 | mysql2 = factories.mysql("mysql_proc2", dbname="test-db") 9 | mysql_rand_proc = factories.mysql_proc(port=None) 10 | mysql_rand = factories.mysql("mysql_rand_proc") 11 | # pylint:enable=invalid-name 12 | -------------------------------------------------------------------------------- /tests/test_executor.py: -------------------------------------------------------------------------------- 1 | """Executor tests.""" 2 | 3 | from pathlib import Path 4 | from unittest.mock import patch 5 | 6 | import pytest 7 | from pytest import TempPathFactory 8 | 9 | from pytest_mysql.exceptions import MySQLUnsupported 10 | from pytest_mysql.executor import MySQLExecutor 11 | 12 | 13 | @pytest.mark.parametrize( 14 | "verstr, version", 15 | ( 16 | (b"mysql_install_db Ver 5.7.21, for Linux on x86_64", "5.7.21"), 17 | ( 18 | (b"mysqld Ver 5.7.21-0ubuntu0.17.10.1 " b"for Linux on x86_64 ((Ubuntu))"), 19 | "5.7.21", 20 | ), 21 | (b"mysql 5.5.55", "5.5.55"), 22 | ( 23 | ( 24 | b"mysqld Ver 10.1.30-MariaDB-0ubuntu0.17.10.1 " 25 | b"for debian-linux-gnu on x86_64 (Ubuntu 17.10)" 26 | ), 27 | "10.1.30", 28 | ), 29 | ( 30 | (b"mysqld Ver 8.0.12 for macos10.13 on x86_64 " b"(MySQL Community Server - GPL)"), 31 | "8.0.12", 32 | ), 33 | ((b"mysqld Ver 5.7.23 for osx10.13 on x86_64 (Homebrew)"), "5.7.23"), 34 | ((b"\nmysqld Ver 5.7.23 for osx10.13 on x86_64 (Homebrew)"), "5.7.23"), 35 | ), 36 | ) 37 | def test_version_check(verstr: bytes, version: str, tmp_path_factory: TempPathFactory) -> None: 38 | """Test executor's version property.""" 39 | executor = MySQLExecutor( 40 | mysqld_safe=Path(""), 41 | mysqld=Path(""), 42 | admin_exec="", 43 | logfile_path="", 44 | params="", 45 | base_directory=tmp_path_factory.mktemp("pytest-mysql"), 46 | user="", 47 | host="", 48 | port=8838, 49 | ) 50 | 51 | with patch("subprocess.check_output", lambda *args: verstr): 52 | assert version == executor.version() 53 | 54 | 55 | @pytest.mark.parametrize( 56 | "verstr, implementation", 57 | ( 58 | (b"mysql_install_db Ver 5.7.21, for Linux on x86_64", "mysql"), 59 | ( 60 | (b"mysqld Ver 5.7.21-0ubuntu0.17.10.1 " b"for Linux on x86_64 ((Ubuntu))"), 61 | "mysql", 62 | ), 63 | (b"mysql 5.5.55", "mysql"), 64 | ( 65 | ( 66 | b"mysqld Ver 10.1.30-MariaDB-0ubuntu0.17.10.1 " 67 | b"for debian-linux-gnu on x86_64 (Ubuntu 17.10)" 68 | ), 69 | "mariadb", 70 | ), 71 | (b"mysql 8.0.12", "mysql"), 72 | ( 73 | (b"Ver 8.0.12" b" for macos10.13 on x86_64 (MySQL Community Server - GPL)"), 74 | "mysql", 75 | ), 76 | (b"mysql 5.7.23", "mysql"), 77 | ( 78 | (b"mysqld Ver 5.7.23 " b"for osx10.13 on x86_64 (Homebrew)"), 79 | "mysql", 80 | ), 81 | ), 82 | ) 83 | def test_implementation( 84 | verstr: bytes, implementation: str, tmp_path_factory: TempPathFactory 85 | ) -> None: 86 | """Check detecting implementation.""" 87 | executor = MySQLExecutor( 88 | mysqld_safe=Path(""), 89 | mysqld=Path(""), 90 | admin_exec="", 91 | logfile_path="", 92 | params="", 93 | base_directory=tmp_path_factory.mktemp("pytest-mysql"), 94 | user="", 95 | host="", 96 | port=8838, 97 | ) 98 | 99 | with patch("subprocess.check_output", lambda *args: verstr): 100 | assert implementation == executor.implementation() 101 | 102 | 103 | @pytest.mark.parametrize( 104 | "verstr", 105 | ( 106 | b"mysql_install_db Ver 5.7.1, for Linux on x86_64", 107 | b"mysqld Ver 5.7.1-0ubuntu0.17.10.1 for Linux on x86_64 ((Ubuntu))", 108 | b"mysql 5.5.55", 109 | ( 110 | b"mysqld Ver 10.1.30-MariaDB-0ubuntu0.17.10.1 " 111 | b"for debian-linux-gnu on x86_64 (Ubuntu 17.10)" 112 | ), 113 | ), 114 | ) 115 | def test_exception_raised(verstr: bytes, tmp_path_factory: TempPathFactory) -> None: 116 | """Raise exception on not supported versions.""" 117 | executor = MySQLExecutor( 118 | mysqld_safe=Path(""), 119 | mysqld=Path(""), 120 | admin_exec="", 121 | logfile_path="", 122 | params="", 123 | base_directory=tmp_path_factory.mktemp("pytest-mysql"), 124 | user="", 125 | host="", 126 | port=8838, 127 | ) 128 | 129 | with ( 130 | patch("subprocess.check_output", lambda *args, **kwargs: verstr), 131 | pytest.raises(MySQLUnsupported), 132 | ): 133 | executor.start() 134 | -------------------------------------------------------------------------------- /tests/test_mysql.py: -------------------------------------------------------------------------------- 1 | """Actual tests for pytest-mysql.""" 2 | 3 | from pymysql import Connection 4 | 5 | from pytest_mysql.executor import MySQLExecutor 6 | 7 | QUERY = """CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), 8 | species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);""" 9 | 10 | 11 | def test_proc(mysql_proc: MySQLExecutor) -> None: 12 | """Check first, basic server fixture factory.""" 13 | assert mysql_proc.running() 14 | 15 | 16 | def test_mysql(mysql: Connection) -> None: 17 | """Check first, basic client fixture factory.""" 18 | cursor = mysql.cursor() 19 | cursor.execute(QUERY) 20 | mysql.commit() 21 | cursor.close() 22 | 23 | 24 | def test_mysql_test_without_cursor(mysql: Connection) -> None: 25 | """Run test without cursor and without fetching the data.""" 26 | mysql.query("SELECT VERSION();") 27 | 28 | 29 | def test_mysql_newfixture(mysql: Connection, mysql2: Connection) -> None: 30 | """More complext test with several mysql_processes.""" 31 | cursor = mysql.cursor() 32 | cursor.execute(QUERY) 33 | mysql.commit() 34 | cursor.close() 35 | 36 | cursor = mysql2.cursor() 37 | cursor.execute(QUERY) 38 | mysql2.commit() 39 | cursor.close() 40 | 41 | 42 | def test_random_port(mysql_rand: Connection) -> None: 43 | """Test if mysql fixture can be started on random port.""" 44 | mysql = mysql_rand 45 | mysql.cursor() 46 | -------------------------------------------------------------------------------- /tests/test_mysqlnoproc.py: -------------------------------------------------------------------------------- 1 | """MySQL tests that do not start mysql server.""" 2 | 3 | from pymysql import Connection 4 | 5 | from pytest_mysql import factories 6 | from tests.test_mysql import QUERY 7 | 8 | mysql_noproc2 = factories.mysql_noproc() 9 | mysqlnoproc_client = factories.mysql("mysql_noproc2") 10 | 11 | 12 | def test_mysql_noproc(mysqlnoproc_client: Connection) -> None: 13 | """Check if noproc fixture connects to the running mysql instance.""" 14 | cursor = mysqlnoproc_client.cursor() 15 | cursor.execute(QUERY) 16 | mysqlnoproc_client.commit() 17 | cursor.close() 18 | 19 | 20 | def test_mysql_noproc_closing_connection_not_throwing_exception( 21 | mysqlnoproc_client: Connection, 22 | ) -> None: 23 | """Check if closing the connection doesn't throw an exception. 24 | 25 | When cleaning the fixture. 26 | """ 27 | cursor = mysqlnoproc_client.cursor() 28 | cursor.execute(QUERY) 29 | mysqlnoproc_client.commit() 30 | cursor.close() 31 | mysqlnoproc_client.close() 32 | --------------------------------------------------------------------------------