├── .coveragerc ├── .download-redis.sh ├── .github ├── ISSUE_TEMPLATE.rst ├── PULL_REQUEST_TEMPLATE.rst ├── actions │ └── pytest │ │ └── action.yml ├── dependabot.yml └── workflows │ ├── automerge.yml │ ├── build.yml │ ├── pr-check.yml │ ├── pre-commit.yml │ ├── pypi.yml │ └── tests.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .rstcheck.cfg ├── CHANGES.rst ├── CONTRIBUTING.rst ├── COPYING ├── COPYING.lesser ├── MANIFEST.in ├── Pipfile ├── README.rst ├── logo.png ├── logo.svg ├── mypy.ini ├── newsfragments ├── +19db8f7e.misc.rst ├── +cb5e9b13.misc.rst ├── +fc669cf6.misc.rst └── .gitignore ├── pyproject.toml ├── pytest_redis ├── __init__.py ├── config.py ├── exception.py ├── executor │ ├── __init__.py │ ├── noop.py │ └── process.py ├── factories │ ├── __init__.py │ ├── client.py │ ├── noproc.py │ └── proc.py ├── plugin.py └── py.typed └── tests ├── __init__.py ├── conftest.py ├── test_executor.py └── test_redis.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | source = src/pytest_redis 3 | omit = */plugin.py 4 | -------------------------------------------------------------------------------- /.download-redis.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -v 2 | function download_redis { 3 | DOWNLOAD_PATH=$HOME/redis/redis-$2 4 | curl "$1" --output "$DOWNLOAD_PATH.tar.gz" 5 | if [ ! -f "$DOWNLOAD_PATH" ]; then 6 | mkdir "$DOWNLOAD_PATH" 7 | fi 8 | tar xzvf "$DOWNLOAD_PATH.tar.gz" --strip-components 1 -C "$DOWNLOAD_PATH" 9 | rm "$DOWNLOAD_PATH.tar.gz" 10 | (cd "$DOWNLOAD_PATH"; make) 11 | 12 | } 13 | 14 | if [ ! -f "$HOME/redis" ]; then 15 | mkdir $HOME/redis 16 | fi 17 | 18 | download_redis http://download.redis.io/releases/redis-7.4.1.tar.gz 7.4 19 | download_redis http://download.redis.io/releases/redis-7.2.6.tar.gz 7.2 20 | download_redis http://download.redis.io/releases/redis-6.2.16.tar.gz 6.2 21 | -------------------------------------------------------------------------------- /.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/actions/pytest/action.yml: -------------------------------------------------------------------------------- 1 | name: 'Pytest run' 2 | description: 'Run tests' 3 | inputs: 4 | python-version: # id of input 5 | description: 'Python version to use' 6 | required: true 7 | redis: 8 | description: 'Redis version' 9 | required: true 10 | codecov_token: 11 | description: Codecov Token 12 | required: true 13 | runs: 14 | using: "composite" 15 | steps: 16 | - name: Set up Python ${{ inputs.python-version }} 17 | uses: actions/setup-python@v3 18 | with: 19 | python-version: ${{ inputs.python-version }} 20 | - name: Cache Redis builds 21 | uses: actions/cache@v3 22 | with: 23 | path: ~/redis 24 | key: redis-${{ hashFiles('.download-redis.sh') }} 25 | - name: Get pip cache dir 26 | id: pip-cache 27 | shell: bash 28 | run: echo "dir=$(pip cache dir)" >> $GITHUB_OUTPUT 29 | - name: pip cache 30 | uses: actions/cache@v3 31 | with: 32 | path: ${{ steps.pip-cache.outputs.dir }} 33 | key: pip-${{ inputs.python-version }}-${{ hashFiles('requirements-*.txt') }} 34 | restore-keys: | 35 | pip-${{ matrix.python-version }}- 36 | - name: Run test on Redis ${{ inputs.redis }} 37 | uses: fizyk/actions-reuse/.github/actions/pipenv@v1.7.1 38 | with: 39 | python-version: ${{ matrix.python-version }} 40 | command: pytest -n 0 --cov-report=xml --redis-exec=$HOME/redis/redis-${{ inputs.redis }}/src/redis-server 41 | - name: Run xdist test on Redis ${{ inputs.redis }} 42 | uses: fizyk/actions-reuse/.github/actions/pipenv@v1.7.1 43 | with: 44 | python-version: ${{ matrix.python-version }} 45 | command: pytest -n 1 --cov-report=xml:coverage-xdist.xml --redis-exec=$HOME/redis/redis-${{ inputs.redis }}/src/redis-server 46 | - name: Upload coverage to Codecov 47 | uses: codecov/codecov-action@v3.0.0 48 | with: 49 | flags: linux,redis-${{ inputs.redis }} 50 | env_vars: OS, PYTHON 51 | fail_ci_if_error: false 52 | token: ${{ inputs.codecov_token }} 53 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 2 9 | - package-ecosystem: github-actions 10 | directory: "/" 11 | schedule: 12 | interval: weekly 13 | time: "04:00" 14 | open-pull-requests-limit: 2 15 | -------------------------------------------------------------------------------- /.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' 11 | - 'Test build package' 12 | 13 | jobs: 14 | automerge: 15 | uses: fizyk/actions-reuse/.github/workflows/shared-automerge.yml@v3.1.1 16 | secrets: 17 | app_id: ${{ secrets.MERGE_APP_ID }} 18 | private_key: ${{ secrets.MERGE_APP_PRIVATE_KEY }} 19 | -------------------------------------------------------------------------------- /.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.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | paths: 7 | - '**.py' 8 | - .github/workflows/tests.yml 9 | - requirements-test.txt 10 | pull_request: 11 | branches: [ main ] 12 | 13 | jobs: 14 | download_redis: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Cache Download and build Redis 19 | uses: actions/cache@v4 20 | with: 21 | path: ~/redis 22 | key: redis-${{ hashFiles('.download-redis.sh') }} 23 | - name: Download and build Redis 24 | run: ./.download-redis.sh 25 | tests_7_4: 26 | needs: [download_redis] 27 | runs-on: ubuntu-latest 28 | strategy: 29 | fail-fast: true 30 | matrix: 31 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", pypy-3.10] 32 | env: 33 | OS: ubuntu-latest 34 | PYTHON: ${{ matrix.python-version }} 35 | steps: 36 | - uses: actions/checkout@v4 37 | - uses: ./.github/actions/pytest 38 | with: 39 | python-version: ${{ matrix.python-version }} 40 | redis: "7.4" 41 | codecov_token: ${{ secrets.CODECOV_TOKEN }} 42 | tests_7_2: 43 | needs: [tests_7_4] 44 | runs-on: ubuntu-latest 45 | strategy: 46 | fail-fast: true 47 | matrix: 48 | python-version: ["3.10", "3.11", "3.12", "3.13", pypy-3.10] 49 | env: 50 | OS: ubuntu-latest 51 | PYTHON: ${{ matrix.python-version }} 52 | steps: 53 | - uses: actions/checkout@v4 54 | - uses: ./.github/actions/pytest 55 | with: 56 | python-version: ${{ matrix.python-version }} 57 | redis: "7.2" 58 | codecov_token: ${{ secrets.CODECOV_TOKEN }} 59 | tests_6_2: 60 | needs: [download_redis] 61 | runs-on: ubuntu-latest 62 | strategy: 63 | fail-fast: true 64 | matrix: 65 | python-version: ["3.10", "3.11", "3.12", "3.13", pypy-3.10] 66 | env: 67 | OS: ubuntu-latest 68 | PYTHON: ${{ matrix.python-version }} 69 | steps: 70 | - uses: actions/checkout@v4 71 | - uses: ./.github/actions/pytest 72 | with: 73 | python-version: ${{ matrix.python-version }} 74 | redis: "6.2" 75 | codecov_token: ${{ secrets.CODECOV_TOKEN }} 76 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | venv/ 3 | 4 | # C extensions 5 | *.so 6 | 7 | # Packages 8 | *.egg 9 | *.egg-info 10 | dist 11 | build 12 | eggs 13 | parts 14 | bin 15 | var 16 | sdist 17 | develop-eggs 18 | .installed.cfg 19 | lib 20 | lib64 21 | 22 | # Installer logs 23 | pip-log.txt 24 | Pipfile.lock 25 | 26 | # Unit test / coverage reports 27 | .coverage 28 | .tox 29 | nosetests.xml 30 | .cache/ 31 | .pytest_cache/ 32 | 33 | # Translations 34 | *.mo 35 | 36 | # Mr Developer 37 | .mr.developer.cfg 38 | .project 39 | .pydevproject 40 | .idea 41 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | CHANGELOG 2 | ========= 3 | 4 | .. towncrier release notes start 5 | 6 | 3.1.3 (2024-11-27) 7 | ================== 8 | 9 | Breaking changes 10 | ---------------- 11 | 12 | - Drop support for Python 3.8 13 | 14 | 15 | Features 16 | -------- 17 | 18 | - Mark support for python 3.13 19 | 20 | 21 | Miscellaneus 22 | ------------ 23 | 24 | - Dropped Redis 6.0 and 7.0 from CI 25 | Add Redis 7.4 into CI 26 | 27 | 28 | 3.1.2 (2024-06-19) 29 | ================== 30 | 31 | Bugfixes 32 | -------- 33 | 34 | - Fix compatibility with pytest < 8 (`#677 `__) 35 | 36 | 37 | 3.1.1 (2024-06-10) 38 | ================== 39 | 40 | Bugfixes 41 | -------- 42 | 43 | - Fixed redis factories module, where imports from submodule 44 | on the main `factories` level were removed by linter. (`#679 `__) 45 | 46 | 47 | 3.1.0 (2024-06-05) 48 | ================== 49 | 50 | Features 51 | -------- 52 | 53 | - Add '--redis-modules' command line option (or 'redis_modules' in .ini file) to specify comma-separated list of Redis extension modules to load (`#656 `__) 54 | - Support Python 3.12 (`#673 `__) 55 | 56 | 57 | Miscellaneus 58 | ------------ 59 | 60 | - Adjusted workflows for actions-reuse 2 (`#481 `__) 61 | - Migrate pydocstyle and pycodestyle to ruff. And use rstcheck to check rst files. (`#484 `__) 62 | - Update code formatting for black 24.1 (`#602 `__) 63 | - Drop Pipfile.lock from repository. 64 | Will rely on a cached in Pipeline or artifact. (`#604 `__) 65 | - Drop old install_py test step, that's supposed to install packages for caching purposes. (`#674 `__) 66 | - Test against Redis 7.2 (`#675 `__) 67 | 68 | 69 | 3.0.2 (2023-04-19) 70 | ================== 71 | 72 | Bugfixes 73 | -------- 74 | 75 | - Include py.typed in MANIFEST.in (`#471 `__) 76 | 77 | 78 | 3.0.1 (2023-03-27) 79 | ================== 80 | 81 | Bugfixes 82 | -------- 83 | 84 | - Fixed packaging LICENSE file. (`#453 `__) 85 | 86 | 87 | 3.0.0 (2023-03-24) 88 | ================== 89 | 90 | Breaking changes 91 | ---------------- 92 | 93 | - Dropped support for Python 3.7 (`#428 `__) 94 | 95 | 96 | Bugfixes 97 | -------- 98 | 99 | - NoopRedis fixture - used to connecto extenrally set up redis, now properly waits till it's ready to accept connections (`#388 `__) 100 | 101 | 102 | Features 103 | -------- 104 | 105 | - Use shutilo.where to find redis-server by default (`#374 `__) 106 | - Support for Redis 7 (`#391 `__) 107 | - Added username and password settings used to connect to the redis instances, set up both internally and externally. (`#404 `__) 108 | - Fully type pytest-redis (`#428 `__) 109 | - Support python 3.11 (`#437 `__) 110 | 111 | 112 | Miscellaneus 113 | ------------ 114 | 115 | - Added py.typed file (`#422 `__) 116 | - Added towncrier to manage newsfragment/CHANGELOG (`#424 `__) 117 | - Migrate dependency management to pipenv (`#425 `__) 118 | - Moved most of the project's packaging and configuration to pyproject.toml (`#426 `__) 119 | - Migrate automerge to a shared workflow based on application token management. (`#427 `__) 120 | - Added mypy checks for CI (`#428 `__) 121 | - Use tbump instead of bumpversion to manage release process (`#429 `__) 122 | - Remove Redis versions older nat 6.0.x from CI as they have reached EOL. (`#445 `__) 123 | - Removed the bit hidden ability to select over Redis/StrictRedis client for client fixture. 124 | For a long time both were same client already. (`#447 `__) 125 | - Split bigger code modules into smaller chunks. (`#452 `__) 126 | 127 | 128 | 2.4.0 129 | ===== 130 | 131 | Features 132 | -------- 133 | 134 | - Import FixtureRequest from pytest, not private _pytest. Require at least pytest 6.2 135 | - Replace tmpdir_factory with tmp_path_factory 136 | 137 | 138 | 2.3.0 139 | ===== 140 | 141 | Features 142 | -------- 143 | 144 | - Added datadir configuration that allows to modify the placement of a redis_proc generated files in the specific place. 145 | This helps overcome the issue with long tmp paths on macosx separately from the temporary path itself. 146 | 147 | 2.2.0 148 | ===== 149 | 150 | Features 151 | -------- 152 | 153 | - Configure redis to listen on specific hostname exclusively using `--bind` parameter. 154 | 155 | Misc 156 | ---- 157 | 158 | - rely on `get_port` functionality delivered by `port_for` 159 | 160 | 161 | 2.1.1 162 | ===== 163 | 164 | Misc 165 | ---- 166 | 167 | - Rise more informative error when the unixsocket is too long. Now the error 168 | will hint at solution how to overcome it. This might be issue especially on 169 | MacOS, where the default temp folder is already a long path 170 | 171 | 2.1.0 172 | ===== 173 | 174 | Features 175 | -------- 176 | 177 | - Rely on tmpdir_factory for handling tmpdirs. Now it's cleanup should 178 | be handled better without much of the leftovers dangling indefinitely 179 | in the tmp directory. 180 | - Store pidfile in fixture's temporary directory 181 | - Support only python 3.7 and up 182 | 183 | Backward incompatibilities 184 | -------------------------- 185 | 186 | - Dropped `--redis-logsdir` command line option, `redis_logsdir` ini file 187 | configuration option and `logsdir` fixture factory configuration option. 188 | Logs will be automatically placed in fixture's temporary directory. 189 | - Dropped `logs_prefix` argument from fixture factory argument 190 | 191 | 2.0.0 192 | ===== 193 | 194 | - [feature] ability to properly connect to already existing postgresql server using ``redis_nooproc`` fixture. 195 | - [enhancement] dropped support for python 2.7 196 | 197 | 1.3.2 198 | ===== 199 | 200 | - [bugfix] - close file descriptor when reading redis version (by brunsgaard) 201 | 202 | 1.3.1 203 | ===== 204 | 205 | - [bugfix] do not run redis explicitly with shell=True 206 | 207 | 1.3.0 208 | ===== 209 | 210 | - [enhancement] RedisExecutor now provides attribute with path to unixsocket 211 | - [enhancement] redis client fixture now connects to redis through unixsocket by default 212 | - [enhancement] Version check got moved to executor, to be run just before starting Redis Server 213 | - [feature] ability to configure decode_responses for redis client in command line, pytest.ini or factory argument. 214 | - [bugfix] set decode_responses to False, same as StrictRedis default 215 | - [enhancement] ability to change decode_responses value 216 | 217 | 1.2.1 218 | ===== 219 | 220 | - [bugfix] raise specific error in case the redis executable path has been misconfigured or does not exists 221 | 222 | 1.2.0 223 | ===== 224 | 225 | - [feature] ability to configure syslog-enabled for redis in command line, pytest.ini or factory argument. 226 | - [feature] ability to configure rdbchecksum for redis in command line, pytest.ini or factory argument. 227 | - [feature] ability to configure rdbcompression for redis in command line, pytest.ini or factory argument. 228 | - [ehnacement] - RedisExecutor handling parameters and their translation to redis values if needed. 229 | - [feature] ability to configure save option for redis in command line, pytest.ini or factory argument. 230 | 231 | 1.1.1 232 | ===== 233 | - [cleanup] removed path.py dependency 234 | 235 | 1.1.0 236 | ===== 237 | 238 | - [feature] - migrate usage of getfuncargvalue to getfixturevalue. require at least pytest 3.0.0 239 | 240 | 1.0.0 241 | ===== 242 | 243 | - [enhancements] removed the possibility to pass the custom config. No need to include one in package now. 244 | - [enhancements] command line, pytest.ini and fixture factory options for setting custom number of databases in redis 245 | - [enhancements] command line, pytest.ini and fixture factory options for redis log verbosity 246 | - [enhancements] command line, pytest.ini and fixture factory options for modifying connection timeout 247 | - [enhancements] command line and pytest.ini options for modifying executable 248 | - [enhancements] command line and pytest.ini options for modifying host 249 | - [enhancements] command line and pytest.ini options for modifying port 250 | - [enhancements] command line and pytest.ini options for modifying logs directory destination 251 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contribute to pytest-redis 2 | ========================== 3 | 4 | Thank you for taking time to contribute to pytest-redis! 5 | 6 | The following is a set of guidelines for contributing to pytest-redis. 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 pytest_redis/py.typed 2 | recursive-include src/pytest_redis *.py 3 | prune docs/build 4 | -------------------------------------------------------------------------------- /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 | redis = "==6.2.0" 11 | 12 | [dev-packages] 13 | towncrier = "==24.8.0" 14 | pytest-cov = "==6.1.1" 15 | pytest-xdist = "==3.7.0" 16 | mock = "==5.2.0" 17 | mypy = "==1.16.0" 18 | types-setuptools = "==80.9.0.20250529" 19 | types-mock = "==5.2.0.20250516" 20 | types-redis = "==4.6.0.20241004" 21 | tbump = "==6.11.0" 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://raw.githubusercontent.com/dbfixtures/pytest-redis/master/logo.png 2 | :width: 100px 3 | :height: 100px 4 | 5 | pytest-redis 6 | ============ 7 | 8 | .. image:: https://img.shields.io/pypi/v/pytest-redis.svg 9 | :target: https://pypi.python.org/pypi/pytest-redis/ 10 | :alt: Latest PyPI version 11 | 12 | .. image:: https://img.shields.io/pypi/wheel/pytest-redis.svg 13 | :target: https://pypi.python.org/pypi/pytest-redis/ 14 | :alt: Wheel Status 15 | 16 | .. image:: https://img.shields.io/pypi/pyversions/pytest-redis.svg 17 | :target: https://pypi.python.org/pypi/pytest-redis/ 18 | :alt: Supported Python Versions 19 | 20 | .. image:: https://img.shields.io/pypi/l/pytest-redis.svg 21 | :target: https://pypi.python.org/pypi/pytest-redis/ 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 Redis database. 28 | It allows you to specify additional fixtures for Redis process and client. 29 | 30 | How to use 31 | ========== 32 | 33 | Plugin contains three fixtures 34 | 35 | * **redisdb** - This is a redis client fixture. It constructs a redis client and cleans redis database after the test. 36 | It relies on redis_proc fixture, and as such the redis process is started at the very beginning of the first test 37 | using this fixture, and stopped after the last test finishes. 38 | * **redis_proc** - session scoped fixture, that starts Redis instance at it's first use and stops at the end of the tests. 39 | * **redis_nooproc** - a nooprocess fixture, that's connecting to already running redis 40 | 41 | Simply include one of these fixtures into your tests fixture list. 42 | 43 | .. code-block:: python 44 | 45 | # 46 | def test_redis(redisdb): 47 | """Check that it's actually working on redis database.""" 48 | redisdb.set('test1', 'test') 49 | redisdb.set('test2', 'test') 50 | 51 | my_functionality = MyRedisBasedComponent() 52 | my_functionality.do_something() 53 | assert my_functionality.did_something 54 | 55 | assert redisdb.get("did_it") == 1 56 | 57 | For the example above works like following: 58 | 59 | 1. pytest runs tests 60 | 2. redis_proc starts redis database server 61 | 3. redisdb creates client connection to the server 62 | 4. test itself runs and finishes 63 | 5. redisdb cleans up the redis 64 | 6. redis_proc stops server (if that was the last test using it) 65 | 7. pytest ends running tests 66 | 67 | You can also create additional redis client and process fixtures if you'd need to: 68 | 69 | 70 | .. code-block:: python 71 | 72 | from pytest_redis import factories 73 | 74 | redis_my_proc = factories.redis_proc(port=None) 75 | redis_my = factories.redisdb('redis_my_proc') 76 | 77 | def test_my_redis(redis_my): 78 | """Check that it's actually working on redis database.""" 79 | redis_my.set('test1', 'test') 80 | redis_my.set('test2', 'test') 81 | 82 | my_functionality = MyRedisBasedComponent() 83 | my_functionality.do_something() 84 | assert my_functionality.did_something 85 | 86 | assert redis_my.get("did_it") == 1 87 | 88 | .. note:: 89 | 90 | Each Redis process fixture can be configured in a different way than the others through the fixture factory arguments. 91 | 92 | 93 | Connecting to already existing redis database 94 | --------------------------------------------- 95 | 96 | Some projects are using already running redis servers (ie on docker instances). 97 | In order to connect to them, one would be using the ``redis_nooproc`` fixture. 98 | 99 | .. code-block:: python 100 | 101 | redis_external = factories.redisdb('redis_nooproc') 102 | 103 | def test_redis(redis_external): 104 | """Check that it's actually working on redis database.""" 105 | redis_external.set('test1', 'test') 106 | redis_external.set('test2', 'test') 107 | 108 | my_functionality = MyRedisBasedComponent() 109 | my_functionality.do_something() 110 | assert my_functionality.did_something 111 | 112 | assert redis_external.get("did_it") == 1 113 | 114 | Standard configuration options apply to it. Note that the `modules` configuration option 115 | has no effect with the ``redis_nooproc`` fixture, it is the responsibility of the already 116 | running redis server to be properly started with extension modules, if needed. 117 | 118 | By default the ``redis_nooproc`` fixture would connect to Redis 119 | instance using **6379** port attempting to make a successful socket 120 | connection within **15 seconds**. The fixture will block your test run 121 | within this timeout window. You can overwrite the timeout like so: 122 | 123 | 124 | .. code-block:: python 125 | 126 | # set the blocking wait to 5 seconds 127 | redis_external = factories.redis_noproc(timeout=5) 128 | 129 | def test_redis(redis_external): 130 | """Check that it's actually working on redis database.""" 131 | redis_external.set('test1', 'test') 132 | # etc etc 133 | 134 | These are the configuration options that are working on all levels with the ``redis_nooproc`` fixture: 135 | 136 | Configuration 137 | ============= 138 | 139 | You can define your settings in three ways, it's fixture factory argument, command line option and pytest.ini configuration option. 140 | You can pick which you prefer, but remember that these settings are handled in the following order: 141 | 142 | * ``Fixture factory argument`` 143 | * ``Command line option`` 144 | * ``Configuration option in your pytest.ini file`` 145 | 146 | .. list-table:: Configuration options 147 | :header-rows: 1 148 | 149 | * - Redis server option 150 | - Fixture factory argument 151 | - Command line option 152 | - pytest.ini option 153 | - Noop process fixture 154 | - Default 155 | * - executable 156 | - executable 157 | - --redis-exec 158 | - redis_exec 159 | - - 160 | - Look in PATH for redis-server via shutil.which 161 | * - host 162 | - host 163 | - --redis-host 164 | - redis_host 165 | - host 166 | - 127.0.0.1 167 | * - port 168 | - port 169 | - --redis-port 170 | - redis_port 171 | - port 172 | - random 173 | * - username 174 | - username 175 | - --redis-username 176 | - redis_username 177 | - username 178 | - None 179 | * - password 180 | - password 181 | - --redis-password 182 | - redis_password 183 | - password 184 | - None 185 | * - connection timeout 186 | - timeout 187 | - --redis-timeout 188 | - redis_timeout 189 | - - 190 | - 30 191 | * - number of databases 192 | - db_count 193 | - --redis-db-count 194 | - redis_db_count 195 | - - 196 | - 8 197 | * - Whether to enable logging to the system logger 198 | - syslog 199 | - --redis-syslog 200 | - redis_syslog 201 | - - 202 | - False 203 | * - Redis log verbosity level 204 | - loglevel 205 | - --redis-loglevel 206 | - redis_loglevel 207 | - - 208 | - notice 209 | * - Compress dump files 210 | - compress 211 | - --redis-compress 212 | - redis_compress 213 | - - 214 | - True 215 | * - Add checksum to RDB files 216 | - checksum 217 | - --redis-rdbcompress 218 | - redis_rdbchecksum 219 | - - 220 | - False 221 | * - Save configuration 222 | - save 223 | - --redis-save 224 | - redis_save 225 | - - 226 | - "" 227 | * - Redis test instance data directory path 228 | - datadir 229 | - --redis-datadir 230 | - redis_datadir 231 | - - 232 | - "" 233 | * - Redis test instance extension module(s) path 234 | - modules (list of paths) 235 | - --redis-modules (comma-separated string) 236 | - redis_modules (comma-separated string) 237 | - - 238 | - "" 239 | 240 | Example usage: 241 | 242 | * pass it as an argument in your own fixture 243 | 244 | .. code-block:: python 245 | 246 | redis_proc = factories.redis_proc(port=8888) 247 | 248 | * use ``--redis-port`` command line option when you run your tests 249 | 250 | .. code-block:: bash 251 | 252 | py.test tests --redis-port=8888 253 | 254 | 255 | * specify your port as ``redis_port`` in your ``pytest.ini`` file. 256 | 257 | To do so, put a line like the following under the ``[pytest]`` section of your ``pytest.ini``: 258 | 259 | .. code-block:: ini 260 | 261 | [pytest] 262 | redis_port = 8888 263 | 264 | Options below are for configuring redis client fixture. 265 | 266 | +---------------------+--------------------------+---------------------+-------------------+---------+ 267 | | Redis client option | Fixture factory argument | Command line option | pytest.ini option | Default | 268 | +=====================+==========================+=====================+===================+=========+ 269 | | decode_response | decode | --redis-decode | redis_decode | False | 270 | +---------------------+--------------------------+---------------------+-------------------+---------+ 271 | 272 | Release 273 | ======= 274 | 275 | Install pipenv and --dev dependencies first, Then run: 276 | 277 | .. code-block:: bash 278 | 279 | pipenv run tbump [NEW_VERSION] 280 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbfixtures/pytest-redis/75070aa0e3e808cfd3c9a8747c4aa8375e60e663/logo.png -------------------------------------------------------------------------------- /logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | 24 | 53 | 55 | 56 | 58 | image/svg+xml 59 | 61 | 62 | 63 | 64 | 65 | 70 | 73 | 76 | 79 | 84 | 89 | 94 | 99 | 104 | 109 | 114 | 119 | 124 | 129 | 135 | 140 | 146 | 152 | 157 | 162 | 168 | 173 | 178 | 183 | 188 | 193 | 198 | 199 | 200 | 201 | 202 | 203 | -------------------------------------------------------------------------------- /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/+19db8f7e.misc.rst: -------------------------------------------------------------------------------- 1 | Use pre-commit for maintaining code style and linting 2 | -------------------------------------------------------------------------------- /newsfragments/+cb5e9b13.misc.rst: -------------------------------------------------------------------------------- 1 | Adjust links after repository transfer 2 | -------------------------------------------------------------------------------- /newsfragments/+fc669cf6.misc.rst: -------------------------------------------------------------------------------- 1 | Adjust workflows for actions-reuse 3 2 | -------------------------------------------------------------------------------- /newsfragments/.gitignore: -------------------------------------------------------------------------------- 1 | !.gitignore 2 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "pytest-redis" 3 | version = "3.1.3" 4 | description = "Redis fixtures and fixture factories for Pytest." 5 | readme = "README.rst" 6 | keywords = ["tests", "pytest", "fixture", "redis"] 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 | "redis >= 3", 35 | ] 36 | requires-python = ">= 3.9" 37 | 38 | [project.urls] 39 | "Source" = "https://github.com/dbfixtures/pytest-redis" 40 | "Bug Tracker" = "https://github.com/dbfixtures/pytest-redis/issues" 41 | "Changelog" = "https://github.com/dbfixtures/pytest-redis/blob/v3.1.3/CHANGES.rst" 42 | 43 | [project.entry-points."pytest11"] 44 | pytest_redis = "pytest_redis.plugin" 45 | 46 | [build-system] 47 | requires = ["setuptools >= 61.0.0", "wheel"] 48 | build-backend = "setuptools.build_meta" 49 | 50 | [tool.setuptools] 51 | zip-safe = true 52 | 53 | [tool.setuptools.packages.find] 54 | include = ["pytest_redis*"] 55 | exclude = ["tests*"] 56 | namespaces = false 57 | 58 | [tool.pytest.ini_options] 59 | xfail_strict=true 60 | addopts = "--max-worker-restart=0 --showlocals --verbose --cov" 61 | testpaths = "tests" 62 | 63 | [tool.black] 64 | line-length = 100 65 | target-version = ['py39'] 66 | include = '.*\.pyi?$' 67 | 68 | [tool.ruff] 69 | # Decrease the maximum line length to 79 characters. 70 | line-length = 100 71 | lint.select = [ 72 | "E", # pycodestyle 73 | "F", # pyflakes 74 | "I", # isort 75 | "D", # pydocstyle 76 | ] 77 | 78 | [tool.rstcheck] 79 | report_level = "warning" 80 | 81 | [tool.towncrier] 82 | directory = "newsfragments" 83 | single_file=true 84 | filename="CHANGES.rst" 85 | issue_format="`#{issue} `__" 86 | 87 | [tool.towncrier.fragment.feature] 88 | name = "Features" 89 | showcontent = true 90 | 91 | [tool.towncrier.fragment.bugfix] 92 | name = "Bugfixes" 93 | showcontent = true 94 | 95 | [tool.towncrier.fragment.break] 96 | name = "Breaking changes" 97 | showcontent = true 98 | 99 | [tool.towncrier.fragment.misc] 100 | name = "Miscellaneus" 101 | showcontent = true 102 | 103 | [tool.tbump] 104 | # Uncomment this if your project is hosted on GitHub: 105 | # github_url = "https://github.com/dbfixtures/pytest-dynamodb/" 106 | 107 | [tool.tbump.version] 108 | current = "3.1.3" 109 | 110 | # Example of a semver regexp. 111 | # Make sure this matches current_version before 112 | # using tbump 113 | regex = ''' 114 | (?P\d+) 115 | \. 116 | (?P\d+) 117 | \. 118 | (?P\d+) 119 | (\- 120 | (?P.+) 121 | )? 122 | ''' 123 | 124 | [tool.tbump.git] 125 | message_template = "Release {new_version}" 126 | tag_template = "v{new_version}" 127 | 128 | [[tool.tbump.field]] 129 | # the name of the field 130 | name = "extra" 131 | # the default value to use, if there is no match 132 | default = "" 133 | 134 | 135 | # For each file to patch, add a [[file]] config 136 | # section containing the path of the file, relative to the 137 | # tbump.toml location. 138 | [[tool.tbump.file]] 139 | src = "pytest_redis/__init__.py" 140 | 141 | [[tool.tbump.file]] 142 | src = "pyproject.toml" 143 | search = 'version = "{current_version}"' 144 | 145 | [[tool.tbump.file]] 146 | src = "pyproject.toml" 147 | search = '"Changelog" = "https://github.com/dbfixtures/pytest-redis/blob/v{current_version}/CHANGES.rst"' 148 | 149 | # You can specify a list of commands to 150 | # run after the files have been patched 151 | # and before the git commit is made 152 | 153 | [[tool.tbump.before_commit]] 154 | name = "Build changelog" 155 | cmd = "pipenv run towncrier build --version {new_version} --yes" 156 | 157 | # Or run some commands after the git tag and the branch 158 | # have been pushed: 159 | # [[tool.tbump.after_push]] 160 | # name = "publish" 161 | # cmd = "./publish.sh" 162 | -------------------------------------------------------------------------------- /pytest_redis/__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-redis. 6 | 7 | # pytest-redis 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-redis 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-redis. If not, see . 19 | """Main module for pytest-redis.""" 20 | __version__ = "3.1.3" 21 | -------------------------------------------------------------------------------- /pytest_redis/config.py: -------------------------------------------------------------------------------- 1 | """Config loading helpers.""" 2 | 3 | from typing import Any, List, Optional, TypedDict 4 | 5 | from _pytest.fixtures import FixtureRequest 6 | 7 | 8 | class RedisConfigType(TypedDict): 9 | """Pytest redis config definition type.""" 10 | 11 | host: str 12 | port: Optional[int] 13 | username: str 14 | password: str 15 | exec: str 16 | timeout: int 17 | loglevel: str 18 | db_count: int 19 | save: str 20 | compression: bool 21 | rdbchecksum: bool 22 | syslog: bool 23 | decode: bool 24 | datadir: str 25 | modules: List[str] 26 | 27 | 28 | def get_config(request: FixtureRequest) -> RedisConfigType: 29 | """Return a dictionary with config options.""" 30 | 31 | def get_conf_option(option: str) -> Any: 32 | option_name = "redis_" + option 33 | return request.config.getoption(option_name) or request.config.getini(option_name) 34 | 35 | port = get_conf_option("port") 36 | if modules := get_conf_option("modules"): 37 | modules = modules.split(",") 38 | else: 39 | modules = [] 40 | config: RedisConfigType = { 41 | "host": get_conf_option("host"), 42 | "port": int(port) if port else None, 43 | "username": get_conf_option("username"), 44 | "password": get_conf_option("password"), 45 | "exec": get_conf_option("exec"), 46 | "timeout": int(get_conf_option("timeout")), 47 | "loglevel": get_conf_option("loglevel"), 48 | "db_count": int(get_conf_option("db_count")), 49 | "save": get_conf_option("save"), 50 | "compression": bool(get_conf_option("compression")), 51 | "rdbchecksum": bool(get_conf_option("rdbchecksum")), 52 | "syslog": bool(get_conf_option("syslog")), 53 | "decode": bool(get_conf_option("decode")), 54 | "datadir": get_conf_option("datadir"), 55 | "modules": modules, 56 | } 57 | return config 58 | -------------------------------------------------------------------------------- /pytest_redis/exception.py: -------------------------------------------------------------------------------- 1 | """Pytest-Redis exceptions.""" 2 | 3 | 4 | class RedisUnsupported(Exception): 5 | """Exception raised when redis<2.6 would be detected.""" 6 | 7 | 8 | class RedisMisconfigured(Exception): 9 | """Exception raised when the redis_exec points to non existing file.""" 10 | 11 | 12 | class UnixSocketTooLong(Exception): 13 | """Exception raised when unixsocket path is too long.""" 14 | -------------------------------------------------------------------------------- /pytest_redis/executor/__init__.py: -------------------------------------------------------------------------------- 1 | """Redis executor.""" 2 | 3 | from pytest_redis.executor.noop import NoopRedis 4 | from pytest_redis.executor.process import RedisExecutor 5 | 6 | __all__ = ("RedisExecutor", "NoopRedis") 7 | -------------------------------------------------------------------------------- /pytest_redis/executor/noop.py: -------------------------------------------------------------------------------- 1 | """Reddis class respsenting an instance started by a third party.""" 2 | 3 | import socket 4 | from typing import Optional 5 | 6 | from mirakuru import TCPExecutor 7 | 8 | 9 | class NoopRedis(TCPExecutor): 10 | """Reddis class respsenting an instance started by a third party.""" 11 | 12 | def __init__( 13 | self, 14 | host: str, 15 | port: int, 16 | username: Optional[str] = None, 17 | password: Optional[str] = None, 18 | unixsocket: Optional[str] = None, 19 | startup_timeout: int = 15, 20 | ) -> None: 21 | """Init method of NoopRedis. 22 | 23 | :param host: server's host 24 | :param port: server's port 25 | :param username: server's username 26 | :param password: server's password 27 | :param timeout: executor's timeout for start and stop actions 28 | """ 29 | self.host = host 30 | self.port = port 31 | self.username = username 32 | self.password = password 33 | # TODO: Can this be actually, arbitrary None? 34 | self.unixsocket = unixsocket 35 | self.timeout = startup_timeout 36 | super().__init__([], host, port, timeout=startup_timeout) 37 | 38 | def start(self) -> "NoopRedis": 39 | """Start is a NOOP.""" 40 | self._set_timeout() 41 | self.wait_for(self.redis_available) 42 | return self 43 | 44 | def redis_available(self) -> bool: 45 | """Return True if connecting to Redis is possible.""" 46 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 47 | try: 48 | s.settimeout(0.1) 49 | s.connect((self.host, self.port)) 50 | except (TimeoutError, ConnectionRefusedError): 51 | return False 52 | return True 53 | -------------------------------------------------------------------------------- /pytest_redis/executor/process.py: -------------------------------------------------------------------------------- 1 | """Redis executor.""" 2 | 3 | import os 4 | import platform 5 | import re 6 | from itertools import islice 7 | from pathlib import Path 8 | from tempfile import gettempdir 9 | from typing import Any, List, Literal, Optional 10 | 11 | from mirakuru import TCPExecutor 12 | from packaging.version import Version, parse 13 | 14 | from pytest_redis.exception import RedisMisconfigured, RedisUnsupported, UnixSocketTooLong 15 | 16 | MAX_UNIXSOCKET = 104 17 | if platform.system() == "Linux": 18 | MAX_UNIXSOCKET = 107 19 | 20 | 21 | def extract_version(text: str) -> Version: 22 | """Extract version number from the text. 23 | 24 | :param text: text that contains the version number 25 | """ 26 | matches = re.search(r"\d+(?:\.\d+)+", text) 27 | assert matches is not None 28 | return parse(matches.group(0)) 29 | 30 | 31 | class RedisExecutor(TCPExecutor): 32 | """Redis executor. 33 | 34 | Extended TCPExecutor to contain all required logic for parametrizing 35 | and properly constructing command to start redis-server. 36 | """ 37 | 38 | MIN_SUPPORTED_VERSION: Version = parse("2.6") 39 | """ 40 | Minimum required version of redis that is accepted by pytest-redis. 41 | """ 42 | 43 | def __init__( 44 | self, 45 | executable: str, 46 | databases: int, 47 | redis_timeout: int, 48 | loglevel: str, 49 | host: str, 50 | port: int, 51 | username: Optional[str] = None, 52 | password: Optional[str] = None, 53 | startup_timeout: int = 60, 54 | save: str = "", 55 | daemonize: str = "no", 56 | rdbcompression: bool = True, 57 | rdbchecksum: bool = False, 58 | syslog_enabled: bool = False, 59 | appendonly: str = "no", 60 | datadir: Optional[Path] = None, 61 | modules: Optional[List[str]] = None, 62 | ) -> None: # pylint:disable=too-many-locals 63 | """Init method of a RedisExecutor. 64 | 65 | :param executable: path to redis-server 66 | :param databases: number of databases 67 | :param redis_timeout: client's connection timeout 68 | :param loglevel: redis log verbosity level 69 | :param host: server's host 70 | :param port: server's port 71 | :param username: server's username 72 | :param password: server's password 73 | :param startup_timeout: executor's timeout for start and stop actions 74 | :param log_prefix: prefix for log filename 75 | :param save: redis save configuration setting 76 | :param daemonize: 77 | :param rdbcompression: Compress redis dump files 78 | :param rdbchecksum: Whether to add checksum to the rdb files 79 | :param syslog_enabled: Whether to enable logging 80 | to the system logger 81 | :param datadir: location where all the process files will be located 82 | :param appendonly: 83 | :param modules: list of paths of Redis extension modules to load 84 | """ 85 | if not datadir: 86 | datadir = Path(gettempdir()) 87 | self.unixsocket = str(datadir / f"redis.{port}.sock") 88 | self.executable = executable 89 | 90 | self.username = username 91 | self.password = password 92 | 93 | logfile_path = datadir / f"redis-server.{port}.log" 94 | pidfile_path = datadir / f"redis-server.{port}.pid" 95 | 96 | command = [ 97 | self.executable, 98 | "--daemonize", 99 | daemonize, 100 | "--rdbcompression", 101 | self._redis_bool(rdbcompression), 102 | "--rdbchecksum", 103 | self._redis_bool(rdbchecksum), 104 | "--appendonly", 105 | appendonly, 106 | "--databases", 107 | str(databases), 108 | "--timeout", 109 | str(redis_timeout), 110 | "--pidfile", 111 | str(pidfile_path), 112 | "--unixsocket", 113 | self.unixsocket, 114 | "--dbfilename", 115 | f"dump.{port}.rdb", 116 | "--logfile", 117 | str(logfile_path), 118 | "--loglevel", 119 | loglevel, 120 | "--syslog-enabled", 121 | self._redis_bool(syslog_enabled), 122 | "--bind", 123 | str(host), 124 | "--port", 125 | str(port), 126 | "--dir", 127 | str(datadir), 128 | ] 129 | if password: 130 | command.extend(["--requirepass", str(password)]) 131 | if save: 132 | if self.version < parse("7"): 133 | save_parts = save.split() 134 | assert all( 135 | (part.isdigit() for part in save_parts) 136 | ), "all save arguments should be numbers" 137 | assert ( 138 | len(save_parts) % 2 == 0 139 | ), "there should be even number of elements passed to save" 140 | for time, change in zip( 141 | islice(save_parts, 0, None, 2), islice(save_parts, 1, None, 2) 142 | ): 143 | command.extend([f"--save {time} {change}"]) 144 | else: 145 | command.extend([f"--save {save}"]) 146 | 147 | if modules: 148 | for module_path in modules: 149 | command.extend(["--loadmodule", module_path]) 150 | 151 | super().__init__(command, host, port, timeout=startup_timeout) 152 | 153 | @classmethod 154 | def _redis_bool(cls, value: Any) -> Literal["yes", "no"]: 155 | """Convert the boolean value to redis's yes/no. 156 | 157 | :param bool value: boolean value to convert 158 | :returns: yes for True, no for False 159 | :rtype: str 160 | """ 161 | return "yes" if value and value != "no" else "no" 162 | 163 | def start(self) -> "RedisExecutor": 164 | """Check supported version before starting.""" 165 | self._check_unixsocket_length() 166 | self._check_version() 167 | super().start() 168 | return self 169 | 170 | def _check_unixsocket_length(self) -> None: 171 | """Check unixsocket length.""" 172 | if len(self.unixsocket) > MAX_UNIXSOCKET: 173 | raise UnixSocketTooLong( 174 | f"Unix Socket path is longer than {MAX_UNIXSOCKET} " 175 | f"allowed on your system: {self.unixsocket}. " 176 | f"It's probably due to the temporary directory configuration. " 177 | f"You can configure that for python by changing TMPDIR envvar, " 178 | f"add for example `--basetemp=/tmp/pytest` to your pytest " 179 | f"command or add `addopts = --basetemp=/tmp/pytest` to your " 180 | f"pytest configuration file." 181 | ) 182 | 183 | @property 184 | def version(self) -> Any: 185 | """Return redis version.""" 186 | with os.popen(f"{self.executable} --version") as version_output: 187 | version_string = version_output.read() 188 | if not version_string: 189 | raise RedisMisconfigured( 190 | f"Bad path to redis_exec is given:" 191 | f" {self.executable} not exists or wrong program" 192 | ) 193 | 194 | return extract_version(version_string) 195 | 196 | def _check_version(self) -> None: 197 | """Check redises version if it's compatible.""" 198 | redis_version = self.version 199 | if redis_version < self.MIN_SUPPORTED_VERSION: 200 | raise RedisUnsupported( 201 | f"Your version of Redis is not supported. " 202 | f"Consider updating to Redis {self.MIN_SUPPORTED_VERSION} at least. " 203 | f"The currently installed version of Redis: {redis_version}." 204 | ) 205 | -------------------------------------------------------------------------------- /pytest_redis/factories/__init__.py: -------------------------------------------------------------------------------- 1 | """Redis fixture factories.""" 2 | 3 | from pytest_redis.factories.client import redisdb 4 | from pytest_redis.factories.noproc import redis_noproc 5 | from pytest_redis.factories.proc import redis_proc 6 | 7 | __all__ = ("redis_proc", "redis_noproc", "redisdb") 8 | -------------------------------------------------------------------------------- /pytest_redis/factories/client.py: -------------------------------------------------------------------------------- 1 | """Redis client fixture factory.""" 2 | 3 | from typing import Callable, Generator, Literal, Optional, Union 4 | 5 | import pytest 6 | import redis 7 | from _pytest.fixtures import FixtureRequest 8 | 9 | from pytest_redis.config import get_config 10 | from pytest_redis.executor import NoopRedis, RedisExecutor 11 | 12 | 13 | def redisdb( 14 | process_fixture_name: str, dbnum: int = 0, decode: Optional[bool] = None 15 | ) -> Callable[[FixtureRequest], Generator[redis.Redis, None, None]]: 16 | """Create connection fixture factory for pytest-redis. 17 | 18 | :param process_fixture_name: name of the process fixture 19 | :param dbnum: number of database to use 20 | :param decode: Client: to decode response or not. 21 | See redis.StrictRedis decode_reponse client parameter. 22 | :returns: function which makes a connection to redis 23 | """ 24 | 25 | @pytest.fixture 26 | def redisdb_factory(request: FixtureRequest) -> Generator[redis.Redis, None, None]: 27 | """Create connection for pytest-redis. 28 | 29 | #. Load required process fixture. 30 | #. Get redis module and config. 31 | #. Connect to redis. 32 | #. Flush database after tests. 33 | 34 | :param FixtureRequest request: fixture request object 35 | :rtype: redis.client.Redis 36 | :returns: Redis client 37 | """ 38 | proc_fixture: Union[NoopRedis, RedisExecutor] = request.getfixturevalue( 39 | process_fixture_name 40 | ) 41 | config = get_config(request) 42 | 43 | redis_host = proc_fixture.host 44 | redis_port = proc_fixture.port 45 | redis_username = proc_fixture.username 46 | redis_password = proc_fixture.password 47 | redis_db = dbnum 48 | decode_responses: Union[Literal[True], Literal[False]] = ( 49 | decode if decode is not None else config["decode"] 50 | ) 51 | 52 | redis_client = redis.Redis( 53 | redis_host, 54 | redis_port, 55 | redis_db, 56 | username=redis_username, 57 | password=redis_password, 58 | unix_socket_path=proc_fixture.unixsocket, 59 | decode_responses=decode_responses, 60 | ) 61 | 62 | yield redis_client 63 | redis_client.flushall() 64 | 65 | return redisdb_factory 66 | -------------------------------------------------------------------------------- /pytest_redis/factories/noproc.py: -------------------------------------------------------------------------------- 1 | """Redis noop fixture factory.""" 2 | 3 | from typing import Callable, Generator, Optional 4 | 5 | import pytest 6 | from _pytest.fixtures import FixtureRequest 7 | 8 | from pytest_redis.config import get_config 9 | from pytest_redis.executor import NoopRedis 10 | 11 | 12 | def redis_noproc( 13 | host: Optional[str] = None, 14 | port: Optional[int] = None, 15 | username: Optional[str] = None, 16 | password: Optional[str] = None, 17 | startup_timeout: int = 15, 18 | ) -> Callable[[FixtureRequest], Generator[NoopRedis, None, None]]: 19 | """Nooproc fixture factory for pytest-redis. 20 | 21 | :param host: hostname 22 | :param port: exact port (e.g. '8000', 8000) 23 | :param username: username used for authentication 24 | :param password: password used for authentication 25 | :param startup_timeout: Blocking wait until we give up connecting to Redis. 26 | :returns: function which makes a redis process 27 | """ 28 | 29 | @pytest.fixture(scope="session") 30 | def redis_nooproc_fixture(request: FixtureRequest) -> Generator[NoopRedis, None, None]: 31 | """Nooproc fixture for pytest-redis. 32 | 33 | Builds mock executor to run tests with 34 | 35 | :param FixtureRequest request: fixture request object 36 | :rtype: pytest_redis.executors.TCPExecutor 37 | :returns: tcp executor 38 | """ 39 | config = get_config(request) 40 | redis_noopexecutor = NoopRedis( 41 | host=host or config["host"], 42 | port=port or config["port"] or 6379, 43 | username=username or config["username"], 44 | password=password or config["password"], 45 | unixsocket=None, 46 | startup_timeout=startup_timeout, 47 | ) 48 | 49 | with redis_noopexecutor: 50 | yield redis_noopexecutor 51 | 52 | return redis_nooproc_fixture 53 | -------------------------------------------------------------------------------- /pytest_redis/factories/proc.py: -------------------------------------------------------------------------------- 1 | """Redis process fixture factory.""" 2 | 3 | from pathlib import Path 4 | from typing import Callable, Generator, List, Optional, Set, Tuple, Union 5 | 6 | import pytest 7 | from _pytest.fixtures import FixtureRequest 8 | from _pytest.tmpdir import TempPathFactory 9 | from port_for import get_port 10 | 11 | from pytest_redis.config import get_config 12 | from pytest_redis.executor import RedisExecutor 13 | 14 | 15 | def redis_proc( 16 | executable: Optional[str] = None, 17 | timeout: Optional[int] = None, 18 | host: Optional[str] = None, 19 | port: Union[ 20 | None, 21 | str, 22 | int, 23 | Tuple[int, int], 24 | Set[int], 25 | List[str], 26 | List[int], 27 | List[Tuple[int, int]], 28 | List[Set[int]], 29 | List[Union[Set[int], Tuple[int, int]]], 30 | List[Union[str, int, Tuple[int, int], Set[int]]], 31 | ] = -1, 32 | username: Optional[str] = None, 33 | password: Optional[str] = None, 34 | db_count: Optional[int] = None, 35 | save: Optional[str] = None, 36 | compression: Optional[bool] = None, 37 | checksum: Optional[bool] = None, 38 | syslog: Optional[bool] = None, 39 | loglevel: Optional[str] = None, 40 | datadir: Optional[str] = None, 41 | modules: Optional[List[str]] = None, 42 | ) -> Callable[[FixtureRequest, TempPathFactory], Generator[RedisExecutor, None, None]]: 43 | """Fixture factory for pytest-redis. 44 | 45 | :param executable: path to redis-server 46 | :param timeout: client's connection timeout 47 | :param host: hostname 48 | :param port: 49 | exact port (e.g. '8000', 8000) 50 | randomly selected port (None) - any random available port 51 | [(2000,3000)] or (2000,3000) - random available port from a given range 52 | [{4002,4003}] or {4002,4003} - random of 4002 or 4003 ports 53 | [(2000,3000), {4002,4003}] -random of given orange and set 54 | :param username: username 55 | :param password: password 56 | :param db_count: number of databases redis should have 57 | :param save: redis save configuration setting 58 | :param compression: Compress redis dump files 59 | :param checksum: Whether to add checksum to the rdb files 60 | :param syslog:Whether to enable logging to the system logger 61 | :param loglevel: redis log verbosity level. 62 | One of debug, verbose, notice or warning 63 | :param datadir: Path for redis data files, including the unix domain socket. 64 | If this is not configured, then a temporary directory is created and used 65 | instead. 66 | :param modules: list of paths of Redis extension modules to load 67 | :returns: function which makes a redis process 68 | """ 69 | 70 | @pytest.fixture(scope="session") 71 | def redis_proc_fixture( 72 | request: FixtureRequest, tmp_path_factory: TempPathFactory 73 | ) -> Generator[RedisExecutor, None, None]: 74 | """Fixture for pytest-redis. 75 | 76 | #. Get configs. 77 | #. Run redis process. 78 | #. Stop redis process after tests. 79 | 80 | :param request: fixture request object 81 | :param tmpdir_factory: 82 | :rtype: pytest_redis.executors.TCPExecutor 83 | :returns: tcp executor 84 | """ 85 | config = get_config(request) 86 | redis_exec = executable or config["exec"] 87 | rdbcompression: bool = config["compression"] if compression is None else compression 88 | rdbchecksum: bool = config["rdbchecksum"] if checksum is None else checksum 89 | 90 | if datadir: 91 | redis_datadir = Path(datadir) 92 | elif config["datadir"]: 93 | redis_datadir = Path(config["datadir"]) 94 | else: 95 | redis_datadir = tmp_path_factory.mktemp(f"pytest-redis-{request.fixturename}") 96 | 97 | redis_modules = modules or config["modules"] 98 | 99 | redis_port = get_port(port) or get_port(config["port"]) 100 | assert redis_port 101 | redis_executor = RedisExecutor( 102 | executable=redis_exec, 103 | databases=db_count or config["db_count"], 104 | redis_timeout=timeout or config["timeout"], 105 | loglevel=loglevel or config["loglevel"], 106 | rdbcompression=rdbcompression, 107 | rdbchecksum=rdbchecksum, 108 | syslog_enabled=syslog or config["syslog"], 109 | save=save or config["save"], 110 | host=host or config["host"], 111 | port=redis_port, 112 | username=username or config["username"], 113 | password=password or config["password"], 114 | startup_timeout=60, 115 | datadir=redis_datadir, 116 | modules=redis_modules, 117 | ) 118 | with redis_executor: 119 | yield redis_executor 120 | 121 | return redis_proc_fixture 122 | -------------------------------------------------------------------------------- /pytest_redis/plugin.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2013 by Clearcode 2 | # and associates (see AUTHORS). 3 | 4 | # This file is part of pytest-redis. 5 | 6 | # pytest-redis 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-redis 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-redis. If not, see . 18 | """Plugin configuration module for pytest-redis.""" 19 | from shutil import which 20 | 21 | from pytest import Parser 22 | 23 | import pytest_redis.factories.client 24 | import pytest_redis.factories.noproc 25 | import pytest_redis.factories.proc 26 | 27 | # pylint:disable=invalid-name 28 | _help_exec = "Redis server executable" 29 | _help_host = "Host at which Redis will accept connections" 30 | _help_port = "Port at which Redis will accept connections" 31 | _help_username = "Username used to authenticate to Redis" 32 | _help_password = "Password used to authenticate to Redis" 33 | _help_timeout = "Client's connection timeout in seconds" 34 | _help_loglevel = "Redis log verbosity level" 35 | _help_db_count = "Number of redis databases" 36 | _help_compress = "Turn on redis dump files compression." 37 | _help_rdbchecksum = "Whether to add checksum to the rdb files" 38 | _help_syslog = "Whether to enable logging to the system logger" 39 | _help_save = "Redis persistance frequency configuration - seconds keys" 40 | _help_decode = ( 41 | "Client: to decode response or not. " "See redis.StrictRedis decode_reponse client parameter." 42 | ) 43 | _help_datadir = "Directory where test Redis instance data files will be stored" 44 | _help_modules = "Comma separated list of paths to Redis extension modules to be loaded at startup" 45 | 46 | 47 | def pytest_addoption(parser: Parser) -> None: 48 | """Define configuration options.""" 49 | parser.addini(name="redis_exec", help=_help_exec, default=which("redis-server")) 50 | parser.addini(name="redis_host", help=_help_host, default="127.0.0.1") 51 | parser.addini( 52 | name="redis_port", 53 | help=_help_port, 54 | default=None, 55 | ) 56 | parser.addini( 57 | name="redis_username", 58 | help=_help_username, 59 | default=None, 60 | ) 61 | parser.addini( 62 | name="redis_password", 63 | help=_help_password, 64 | default=None, 65 | ) 66 | parser.addini( 67 | name="redis_timeout", 68 | help=_help_timeout, 69 | default=30, 70 | ) 71 | parser.addini( 72 | name="redis_loglevel", 73 | help=_help_loglevel, 74 | default="notice", 75 | ) 76 | parser.addini( 77 | name="redis_db_count", 78 | help=_help_db_count, 79 | default=8, 80 | ) 81 | parser.addini( 82 | name="redis_save", 83 | help=_help_save, 84 | default=None, 85 | ) 86 | parser.addini(name="redis_compression", type="bool", help=_help_compress) 87 | parser.addini(name="redis_rdbchecksum", type="bool", help=_help_rdbchecksum) 88 | parser.addini(name="redis_syslog", type="bool", help=_help_syslog) 89 | parser.addini(name="redis_decode", type="bool", help=_help_decode, default=False) 90 | parser.addini(name="redis_datadir", help=_help_datadir, default=None) 91 | parser.addini(name="redis_modules", help=_help_modules, default=None) 92 | 93 | parser.addoption( 94 | "--redis-exec", 95 | action="store", 96 | dest="redis_exec", 97 | help=_help_exec, 98 | ) 99 | parser.addoption( 100 | "--redis-host", 101 | action="store", 102 | dest="redis_host", 103 | help=_help_host, 104 | ) 105 | parser.addoption("--redis-port", action="store", dest="redis_port", help=_help_port) 106 | parser.addoption("--redis-username", action="store", dest="redis_username", help=_help_username) 107 | parser.addoption("--redis-password", action="store", dest="redis_password", help=_help_password) 108 | parser.addoption("--redis-timeout", action="store", dest="redis_timeout", help=_help_timeout) 109 | parser.addoption("--redis-loglevel", action="store", dest="redis_loglevel", help=_help_loglevel) 110 | parser.addoption("--redis-db-count", action="store", dest="redis_db_count", help=_help_db_count) 111 | parser.addoption("--redis-save", action="store", dest="redis_save", help=_help_save) 112 | parser.addoption( 113 | "--redis-compression", action="store_true", dest="redis_compression", help=_help_compress 114 | ) 115 | parser.addoption( 116 | "--redis-rdbchecksum", action="store_true", dest="redis_rdbchecksum", help=_help_rdbchecksum 117 | ) 118 | parser.addoption("--redis-syslog", action="store_true", dest="redis_syslog", help=_help_syslog) 119 | parser.addoption( 120 | "--redis-client-decode", action="store_true", dest="redis_decode", help=_help_decode 121 | ) 122 | parser.addoption("--redis-datadir", action="store", dest="redis_datadir", help=_help_datadir) 123 | parser.addoption("--redis-modules", action="store", dest="redis_modules", help=_help_modules) 124 | 125 | 126 | redis_proc = pytest_redis.factories.proc.redis_proc() 127 | redis_nooproc = pytest_redis.factories.noproc.redis_noproc() 128 | redisdb = pytest_redis.factories.client.redisdb("redis_proc") 129 | # pylint:enable=invalid-name 130 | -------------------------------------------------------------------------------- /pytest_redis/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbfixtures/pytest-redis/75070aa0e3e808cfd3c9a8747c4aa8375e60e663/pytest_redis/py.typed -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Test module for pytest-redis.""" 3 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | """Tests main conftest file.""" 2 | 3 | import warnings 4 | 5 | import pytest_redis.factories 6 | from pytest_redis.plugin import * # noqa: F403 7 | 8 | warnings.filterwarnings( 9 | "error", category=DeprecationWarning, module="(_pytest|pytest|redis|path|mirakuru).*" 10 | ) 11 | 12 | # pylint:disable=invalid-name 13 | redis_proc2 = pytest_redis.factories.redis_proc(port=6381) 14 | redis_nooproc2 = pytest_redis.factories.redis_noproc(port=6381, startup_timeout=1) 15 | redis_proc3 = pytest_redis.factories.redis_proc(port=6385, password="secretpassword") 16 | redis_nooproc3 = pytest_redis.factories.redis_noproc(port=6385, password="secretpassword") 17 | 18 | redisdb2 = pytest_redis.factories.redisdb("redis_proc2") 19 | redisdb2_noop = pytest_redis.factories.redisdb("redis_nooproc2") 20 | redisdb3 = pytest_redis.factories.redisdb("redis_proc3") 21 | redisdb3_noop = pytest_redis.factories.redisdb("redis_nooproc3") 22 | # pylint:enable=invalid-name 23 | -------------------------------------------------------------------------------- /tests/test_executor.py: -------------------------------------------------------------------------------- 1 | """Clean executor's tests.""" 2 | 3 | import socket 4 | from io import StringIO 5 | from typing import Any, Dict, Literal 6 | 7 | import pytest 8 | import redis 9 | from mirakuru.exceptions import ProcessExitedWithError, TimeoutExpired 10 | from mock import mock 11 | from packaging.version import parse 12 | from port_for import get_port 13 | from pytest import FixtureRequest, TempPathFactory 14 | 15 | from pytest_redis.config import get_config 16 | from pytest_redis.exception import RedisMisconfigured, RedisUnsupported, UnixSocketTooLong 17 | from pytest_redis.executor import ( 18 | NoopRedis, 19 | RedisExecutor, 20 | ) 21 | from pytest_redis.executor.process import extract_version 22 | 23 | 24 | @pytest.mark.parametrize( 25 | "parameter, config_option, value", 26 | ( 27 | ({"save": "900 1 300 10"}, "save", "900 1 300 10"), 28 | ({"save": "900 1"}, "save", "900 1"), 29 | ({"rdbcompression": True}, "rdbcompression", "yes"), 30 | ({"rdbcompression": False}, "rdbcompression", "no"), 31 | ({"rdbchecksum": True}, "rdbchecksum", "yes"), 32 | ({"rdbchecksum": False}, "rdbchecksum", "no"), 33 | ), 34 | ) 35 | def test_redis_exec_configuration( 36 | request: FixtureRequest, 37 | tmp_path_factory: TempPathFactory, 38 | parameter: Dict[str, Any], 39 | config_option: str, 40 | value: str, 41 | ) -> None: 42 | """Check if RedisExecutor properly processes configuration options. 43 | 44 | Improperly set options won't be set in redis, 45 | and we won't be able to read it out of redis. 46 | """ 47 | config = get_config(request) 48 | tmpdir = tmp_path_factory.mktemp("pytest-redis-test-test_redis_exec_configuration") 49 | redis_port = get_port(None) 50 | assert redis_port 51 | redis_exec = RedisExecutor( 52 | executable=config["exec"], 53 | databases=4, 54 | redis_timeout=config["timeout"], 55 | loglevel=config["loglevel"], 56 | port=redis_port, 57 | host=config["host"], 58 | startup_timeout=30, 59 | datadir=tmpdir, 60 | **parameter, 61 | ) 62 | with redis_exec: 63 | redis_client = redis.StrictRedis(redis_exec.host, redis_exec.port, 0) 64 | assert redis_client.config_get(config_option) == {config_option: value} 65 | 66 | 67 | @pytest.mark.parametrize( 68 | "syslog_enabled", 69 | (True, False), 70 | ) 71 | def test_redis_exec( 72 | request: FixtureRequest, tmp_path_factory: TempPathFactory, syslog_enabled: bool 73 | ) -> None: 74 | """Check if RedisExecutor properly starts with these configuration options. 75 | 76 | Incorrect options won't even start redis. 77 | """ 78 | config = get_config(request) 79 | tmpdir = tmp_path_factory.mktemp("pytest-redis-test-test_redis_exec") 80 | redis_port = get_port(None) 81 | assert redis_port 82 | redis_exec = RedisExecutor( 83 | executable=config["exec"], 84 | databases=4, 85 | redis_timeout=config["timeout"], 86 | loglevel=config["loglevel"], 87 | port=redis_port, 88 | host=config["host"], 89 | startup_timeout=30, 90 | datadir=tmpdir, 91 | syslog_enabled=syslog_enabled, 92 | ) 93 | with redis_exec: 94 | assert redis_exec.running() 95 | 96 | 97 | @pytest.mark.parametrize( 98 | "value, redis_value", 99 | ( 100 | (True, "yes"), 101 | (1, "yes"), 102 | ("str", "yes"), 103 | ("yes", "yes"), 104 | (False, "no"), 105 | (0, "no"), 106 | ("", "no"), 107 | ("no", "no"), 108 | ), 109 | ) 110 | def test_convert_bool(value: Any, redis_value: Literal["yes", "no"]) -> None: 111 | """Check correctness of the redis_bool method.""" 112 | # pylint:disable=protected-access 113 | assert RedisExecutor._redis_bool(value) == redis_value 114 | # pylint:enable=protected-access 115 | 116 | 117 | @pytest.mark.parametrize( 118 | "version", 119 | ( 120 | "Redis server version 2.4.14 (e9935407:0)", 121 | "Redis server version 2.4.13 (e0935407:0)" 122 | "Redis server version 2.5.0 (e9035407:0)" 123 | "Redis server version 2.3.10 (e9933407:0)", 124 | ), 125 | ) 126 | def test_old_redis_version( 127 | request: FixtureRequest, tmp_path_factory: TempPathFactory, version: str 128 | ) -> None: 129 | """Test how fixture behaves in case of old redis version.""" 130 | config = get_config(request) 131 | tmpdir = tmp_path_factory.mktemp("pytest-redis-test-test_old_redis_version") 132 | with mock.patch("os.popen", lambda *args: StringIO(version)): 133 | with pytest.raises(RedisUnsupported): 134 | redis_port = get_port(None) 135 | assert redis_port 136 | RedisExecutor( 137 | config["exec"], 138 | databases=4, 139 | redis_timeout=config["timeout"], 140 | loglevel=config["loglevel"], 141 | port=redis_port, 142 | host=config["host"], 143 | startup_timeout=30, 144 | datadir=tmpdir, 145 | ).start() 146 | 147 | 148 | def test_not_existing_redis(request: FixtureRequest, tmp_path_factory: TempPathFactory) -> None: 149 | """Check handling of misconfigured redis executable path.""" 150 | config = get_config(request) 151 | tmpdir = tmp_path_factory.mktemp("pytest-redis-test-test_not_existing_redis") 152 | with pytest.raises(RedisMisconfigured): 153 | redis_port = get_port(None) 154 | assert redis_port 155 | RedisExecutor( 156 | "/not/redis/here/redis-server", 157 | databases=4, 158 | redis_timeout=config["timeout"], 159 | loglevel=config["loglevel"], 160 | port=redis_port, 161 | host=config["host"], 162 | startup_timeout=30, 163 | datadir=tmpdir, 164 | ).start() 165 | 166 | 167 | def test_too_long_unixsocket(request: FixtureRequest, tmp_path_factory: TempPathFactory) -> None: 168 | """Check handling of misconfigured redis executable path.""" 169 | config = get_config(request) 170 | tmpdir = tmp_path_factory.mktemp("x" * 110) 171 | with pytest.raises(UnixSocketTooLong): 172 | redis_port = get_port(None) 173 | assert redis_port 174 | RedisExecutor( 175 | config["exec"], 176 | databases=4, 177 | redis_timeout=config["timeout"], 178 | loglevel=config["loglevel"], 179 | port=redis_port, 180 | host=config["host"], 181 | startup_timeout=30, 182 | datadir=tmpdir, 183 | ).start() 184 | 185 | 186 | @pytest.mark.parametrize( 187 | "text,result", 188 | [ 189 | ("Redis server version 2.4.14 (00000000:0)", "2.4.14"), 190 | ("Redis server v=2.6.13 sha=00000000:0 malloc=jemalloc-3.3.1 bits=64", "2.6.13"), 191 | ("1.2.5", "1.2.5"), 192 | ("Test2.0.5", "2.0.5"), 193 | ("2.0.5Test", "2.0.5"), 194 | ("m.n.a 2.4.14", "2.4.14"), 195 | ], 196 | ) 197 | def test_extract_version(text: str, result: str) -> None: 198 | """Check if the version extracction works correctly.""" 199 | assert extract_version(text) == parse(result) 200 | 201 | 202 | def test_extract_version_notfound() -> None: 203 | """Check error raised if version is not found.""" 204 | with pytest.raises(AssertionError): 205 | extract_version("Test") 206 | 207 | 208 | def test_noopredis_handles_timeout_when_waiting() -> None: 209 | """Test handling timeuts by NoopRedis.""" 210 | with mock.patch("pytest_redis.executor.noop.socket", spec=socket) as patched_socket: 211 | foo = patched_socket.socket.return_value 212 | socket_mock = foo.__enter__.return_value 213 | socket_mock.connect.side_effect = TimeoutError() 214 | noop_redis = NoopRedis(host="localhost", port=12345, startup_timeout=1) 215 | with pytest.raises(TimeoutExpired): 216 | noop_redis.start() 217 | 218 | assert not noop_redis.running() 219 | socket_mock.settimeout.assert_called_with(0.1) 220 | socket_mock.connect.assert_called() 221 | 222 | 223 | def test_redis_modules_option(request: FixtureRequest, tmp_path_factory: TempPathFactory) -> None: 224 | """Set 'module' keyword argument and check command line.""" 225 | config = get_config(request) 226 | tmpdir = tmp_path_factory.mktemp("pytest-redis-test-test_redis_exec_configuration") 227 | redis_port = get_port(None) 228 | assert redis_port 229 | 230 | redis_exec = RedisExecutor( 231 | executable=config["exec"], 232 | databases=4, 233 | redis_timeout=config["timeout"], 234 | loglevel=config["loglevel"], 235 | port=redis_port, 236 | host=config["host"], 237 | startup_timeout=30, 238 | datadir=tmpdir, 239 | modules=["nonexistent.so", "nonexistent2.so"], 240 | ) 241 | try: 242 | with pytest.raises( 243 | ProcessExitedWithError, match="--loadmodule nonexistent.so --loadmodule nonexistent2.so" 244 | ): 245 | redis_exec.start() 246 | 247 | logfilename = redis_exec.command_parts[redis_exec.command_parts.index("--logfile") + 1] 248 | with open(logfilename, "r") as logfile: 249 | logfile_text = logfile.read() 250 | assert ( 251 | "# Module nonexistent.so failed to load: nonexistent.so: cannot open shared object file" 252 | in logfile_text 253 | ) 254 | # cannot check for nonexistent2.so because Redis stops at first invalid module 255 | finally: 256 | redis_exec.stop() 257 | -------------------------------------------------------------------------------- /tests/test_redis.py: -------------------------------------------------------------------------------- 1 | """Module containing all tests for pytest-redis.""" 2 | 3 | from redis.client import Redis 4 | 5 | 6 | def test_redis(redisdb: Redis) -> None: 7 | """Check that it's actually working on redis database.""" 8 | redisdb.set("test1", "test") 9 | redisdb.set("test2", "test") 10 | 11 | test1 = redisdb.get("test1") 12 | assert test1 == b"test" 13 | 14 | test2 = redisdb.get("test2") 15 | assert test2 == b"test" 16 | 17 | 18 | def test_second_redis(redisdb: Redis, redisdb2: Redis) -> None: 19 | """Check that two redis prorcesses are separate ones.""" 20 | redisdb.set("test1", "test") 21 | redisdb.set("test2", "test") 22 | redisdb2.set("test1", "test_other") 23 | redisdb2.set("test2", "test_other") 24 | 25 | assert redisdb.get("test1") == b"test" 26 | assert redisdb.get("test2") == b"test" 27 | 28 | assert redisdb2.get("test1") == b"test_other" 29 | assert redisdb2.get("test2") == b"test_other" 30 | 31 | 32 | def test_external_redis(redisdb2: Redis, redisdb2_noop: Redis) -> None: 33 | """Check that nooproc connects to the same redis.""" 34 | redisdb2.set("test1", "test_other") 35 | redisdb2.set("test2", "test_other") 36 | 37 | assert redisdb2.get("test1") == b"test_other" 38 | assert redisdb2.get("test2") == b"test_other" 39 | 40 | assert redisdb2_noop.get("test1") == b"test_other" 41 | assert redisdb2_noop.get("test2") == b"test_other" 42 | 43 | 44 | def test_external_redis_auth(redisdb3: Redis, redisdb3_noop: Redis) -> None: 45 | """Check that nooproc connects to the same redis.""" 46 | redisdb3.set("test1", "test_other") 47 | redisdb3.set("test2", "test_other") 48 | 49 | assert redisdb3.get("test1") == b"test_other" 50 | assert redisdb3.get("test2") == b"test_other" 51 | 52 | assert redisdb3_noop.get("test1") == b"test_other" 53 | assert redisdb3_noop.get("test2") == b"test_other" 54 | --------------------------------------------------------------------------------