├── .circleci └── config.yml ├── .gitignore ├── .tool-versions ├── CHANGES.md ├── LICENSE.txt ├── MANIFEST.in ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── requirements.txt ├── setup.py ├── src └── lovely │ ├── __init__.py │ └── pytest │ ├── __init__.py │ └── docker │ ├── __init__.py │ └── compose.py └── tests ├── conftest.py ├── docker-compose.yml ├── test_checker.py └── test_hello.py /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | jobs: 4 | test: 5 | machine: 6 | image: ubuntu-2204:2024.02.7 7 | environment: 8 | TZ: Europe/Zurich 9 | steps: 10 | - run: 11 | name: Install Python 3.11.7 12 | command: | 13 | pyenv install 3.11.7 14 | pyenv global 3.11.7 15 | - checkout 16 | - restore_cache: 17 | name: restore gradle cache 18 | key: lovely-pytest-docker-gradle-{{ checksum "gradle/wrapper/gradle-wrapper.properties" }}-{{ checksum "build.gradle.kts" }} 19 | - restore_cache: 20 | name: restore pip cache 21 | key: lovely-pytest-docker-pip-{{ checksum "requirements.txt" }} 22 | - run: 23 | name: Python version 24 | command: python3 --version 25 | - run: 26 | name: Bootstrap Gradle 27 | command: ./gradlew --version 28 | - run: 29 | name: Python venv + dependencies 30 | command: ./gradlew --console=plain dev 31 | - save_cache: 32 | name: save pip cache 33 | # use a key to update cache content 34 | key: lovely-pytest-docker-pip-{{ checksum "requirements.txt" }} 35 | paths: 36 | - "~/.cache/pip" 37 | - save_cache: 38 | name: save gradle cache 39 | key: lovely-pytest-docker-gradle-{{ checksum "gradle/wrapper/gradle-wrapper.properties" }}-{{ checksum "build.gradle.kts" }} 40 | paths: 41 | - "~/.gradle/caches/" 42 | - "~/.gradle/wrapper/" 43 | - run: 44 | command: ./gradlew test 45 | 46 | workflows: 47 | test: 48 | jobs: 49 | - test: 50 | context: 51 | - github-credentials 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /v/ 2 | .gradle/ 3 | *.py[co] 4 | *.egg 5 | *.egg-info 6 | .DS\_Store 7 | .cache/ 8 | dist/ 9 | __pycache__/ 10 | .idea/ 11 | *.iml 12 | /build/ 13 | VERSION.txt 14 | -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | python 3.11.9 2 | -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | # Changes for Lovely Pytest Docker 2 | 3 | ## 2024-09-02 / 1.0.0 4 | 5 | ### Feature 6 | 7 | - use "docker compose" instead of "docker-compose" to start services 8 | 9 | ### Breaking 10 | 11 | - stop support for Python 2.7 12 | 13 | ### Development 14 | 15 | - update Gradle & Python & dependencies 16 | - use CircleCI instead of Travis 17 | 18 | ## 2022-12-22 / 0.3.1 19 | 20 | - make auto generated project names compatible with docker-compose 2.5 21 | 22 | ## 2021-12-22 / 0.3.0 23 | 24 | - add support for `docker-compose stop` 25 | - allow to set the timeout and retry interval when waiting for services 26 | - added explicit dependency to six, which is no more required in newer pytest versions 27 | 28 | ## 2021-08-05 / 0.2.1 29 | 30 | - explicitly set the project-directory in compose executors to allow older 31 | compose versions to find ".env" files 32 | see https://docs.docker.com/compose/environment-variables/#the-env-file 33 | 34 | ## 2020-10-06 / 0.2.0 35 | 36 | - added url_checker method to create an url_checker for a specific path 37 | 38 | ## 2019-08-27 / 0.1.0 39 | 40 | - added ``docker_services_project_name`` fixture in order to override the container 41 | name prefix for started services. 42 | 43 | ## 2019-01-22 / 0.0.5 44 | 45 | - python 2 runtime compatibility 46 | 47 | ## 2018-12-20 / 0.0.4 48 | 49 | - make docker_ip a fixture to make it possible to override it per project 50 | 51 | ## 2018-01-21 / 0.0.3 52 | 53 | - fixed wrong error handling when polling for docker up state 54 | 55 | ## 2018-01-10 / 0.0.2 56 | 57 | - added exec method in Services class 58 | - added possibility to use custom checker for wait_for_service method 59 | 60 | ## 2018-01-09 / 0.0.1 61 | 62 | - initial version 63 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include VERSION.txt 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lovely Pytest Docker 2 | 3 | [![PyPI](https://img.shields.io/pypi/v/lovely-pytest-docker)](https://pypi.org/project/lovely-pytest-docker/) 4 | [![PyPI](https://img.shields.io/pypi/pyversions/lovely-pytest-docker)](https://pypi.org/project/lovely-pytest-docker/) 5 | [![Build Status](https://app.travis-ci.com/lovelysystems/lovely-pytest-docker.svg?branch=master)](https://app.travis-ci.com/lovelysystems/lovely-pytest-docker) 6 | 7 | Create simple Pytest_ fixtures for writing integration tests based on Docker 8 | containers. The framework provides a service class to start and stop containers 9 | based Docker Compose. Each single container can be started individually. 10 | 11 | Some parts of this package are taken from 12 | https://github.com/AndreLouisCaron/pytest-docker 13 | 14 | ## Usage with Pytest 15 | 16 | The docker compose file should contain all desired containers and the ports 17 | should be exposed. In the following example we want to start the app to test 18 | and a SQL database (Crate). Let's assume there is a ``Dockerfile`` for the app 19 | in the same folder as the docker compose file. 20 | 21 | ```yaml 22 | 23 | 24 | version: "3" 25 | services: 26 | app: 27 | build: . 28 | ports: 29 | - "8080" 30 | depends_on: 31 | - "crate" 32 | 33 | crate: 34 | image: crate:latest 35 | ports: 36 | - "4200" 37 | ``` 38 | 39 | In the ``conftest.py`` file we can declare the docker fixtures for each service 40 | we want to be able to start in the tests. 41 | 42 | ```python 43 | 44 | import pytest 45 | 46 | @pytest.fixture(scope='session') 47 | def docker_app(docker_services): 48 | docker_services.start('app') 49 | public_port = docker_services.wait_for_service("app", 8080) 50 | url = "http://{docker_services.docker_ip}:{public_port}".format(**locals()) 51 | return url 52 | 53 | @pytest.fixture(scope='session') 54 | def docker_crate(docker_services): 55 | docker_services.start('crate') 56 | public_port = docker_services.wait_for_service("crate", 4200) 57 | dsn = "{docker_services.docker_ip}:{public_port}".format(**locals()) 58 | return dsn 59 | ``` 60 | 61 | By default the fixture will look for the ``docker-compose.yml`` file in the 62 | ``tests`` subfolder of the path where ``pytest.ini`` resides (or the project's 63 | root directory if no ini file is given - as in the tests example). In many 64 | cases you will want to override the location for the docker compose files. Just 65 | overwrite the ``docker_compose_files`` fixture in your ``conftest.py`` file. 66 | 67 | ```python 68 | @pytest.fixture(scope='session') 69 | def docker_compose_files(pytestconfig): 70 | """Get the docker-compose.yml absolute path. 71 | Override this fixture in your tests if you need a custom location. 72 | """ 73 | return [ 74 | project_path('docker', 'docker-compose.yml'), 75 | ] 76 | ``` 77 | 78 | In your test file declare the fixtures you want to use: 79 | 80 | ```python 81 | def test_something(docker_app, docker_crate): 82 | # e.g. initialize database 83 | ... 84 | # test something (e.g. request to docker_app) 85 | ... 86 | ``` 87 | 88 | A working configuration and test example can be found in the ``tests`` folder 89 | of this package. 90 | 91 | ## Execution in Docker Container 92 | 93 | It's possible to execute a command inside one of the Docker containers. Use 94 | the ``exec`` method of the ``docker_services`` fixture:: 95 | 96 | ```python 97 | def test_execute(docker_services): 98 | # the first argument is the service name of the compose file, 99 | # the following arguments build the command to run 100 | res = docker_services.execute('crate', 'ls', '-a') 101 | ``` 102 | 103 | ## Stopping a Docker Container 104 | 105 | It's possible to stop single Docker containers. Use 106 | the ``stop`` method of the ``docker_services`` fixture:: 107 | 108 | def test_stop(docker_services): 109 | # the first argument is the service name of the compose file, 110 | # the following arguments build the command to run 111 | res = docker_services.stop('crate') 112 | 113 | ## Wait for Service 114 | 115 | The ``wait_for_service`` method of the service module checks whether the 116 | docker service is really started. By default it makes a HTTP GET request to the 117 | server's ``/`` endpoint. The service will retry to check until a timeout of 118 | 30 seconds has passed. 119 | 120 | ### Custom Service Checker 121 | 122 | Some services may work differently and require a custom checker. 123 | 124 | Create a custom service checker function which receives the IP address and the 125 | port as parameters:: 126 | 127 | ```python 128 | def custom_service_checker(ip_address, port): 129 | # if service is ready 130 | return True 131 | # otherwise return False 132 | ``` 133 | 134 | In the fixture provide the custom service checker function as ``check_service`` 135 | parameter to the ``wait_for_service`` method:: 136 | 137 | ```python 138 | @pytest.fixture(scope='session') 139 | def docker_custom_service(docker_services): 140 | docker_services.start('custom_service') 141 | public_port = docker_services.wait_for_service( 142 | "app", 143 | 8080, 144 | check_server=custom_service_checker 145 | ) 146 | url = "http://{docker_services.docker_ip}:{public_port}".format(**locals()) 147 | return url 148 | ``` 149 | 150 | To use another request path with the default checker the `url_checker` method 151 | can be used to create a `check_url` method for another path:: 152 | 153 | ```python 154 | docker_services.wait_for_service( 155 | "app", 156 | 8080, 157 | check_server=url_checker('/probe_status'), 158 | ) 159 | ``` 160 | 161 | ## Run Tests 162 | 163 | Tests are held in the ``tests`` directory. Running tests is done via the 164 | [pytest](http://doc.pytest.org) package with:: 165 | 166 | ```shell 167 | ./gradlew pytest 168 | ``` 169 | 170 | ## Publish a new Version 171 | 172 | Use gradle to build and twine to upload like this: 173 | 174 | ```shell 175 | ./gradlew sdist 176 | twine upload build/sdist/lovely-pytest-docker-.tar.gz 177 | ``` 178 | 179 | Note: twine needs to be installed by othher means (e.g. ``pip install twine``) 180 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | base 3 | id("com.lovelysystems.gradle") version ("1.14.2") 4 | } 5 | 6 | lovely { 7 | gitProject() 8 | pythonProject("python3.11") 9 | } 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lovelysystems/lovely-pytest-docker/36c446e562858a30c8adfc0814ae86af92d290e2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.11 3 | # by the following command: 4 | # 5 | # pip-compile --output-file=requirements.txt setup.py 6 | # 7 | iniconfig==2.0.0 8 | # via pytest 9 | packaging==24.1 10 | # via pytest 11 | pluggy==1.5.0 12 | # via pytest 13 | pytest==8.3.2 14 | # via lovely-pytest-docker (setup.py) 15 | six==1.16.0 16 | # via lovely-pytest-docker (setup.py) 17 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from setuptools import setup, find_packages 4 | 5 | here = os.path.abspath(os.path.dirname(__file__)) 6 | readme = open(os.path.join(here, 'README.md')).read() 7 | 8 | requires = [ 9 | 'pytest', 10 | 'six' 11 | ] 12 | 13 | 14 | def get_version(): 15 | p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "VERSION.txt") 16 | with open(p) as f: 17 | return f.read().strip() 18 | 19 | 20 | setup( 21 | name='lovely-pytest-docker', 22 | version=get_version(), 23 | description='Pytest testing utilities with docker containers.', 24 | long_description=readme, 25 | long_description_content_type="text/markdown", 26 | classifiers=[ 27 | "Programming Language :: Python :: 3", 28 | ], 29 | author='Lovely Systems', 30 | author_email='office@lovelysystems.com', 31 | url='https://github.com/lovelysystems/lovely-pytest-docker', 32 | keywords='pytest testing docker compose', 33 | namespace_packages=['lovely'], 34 | packages=find_packages('src'), 35 | package_dir={'': 'src'}, 36 | zip_safe=False, 37 | include_package_data=True, 38 | install_requires=requires, 39 | entry_points={ 40 | 'pytest11': [ 41 | 'lovely_pytest_docker = lovely.pytest.docker.compose', 42 | ], 43 | }, 44 | ) 45 | -------------------------------------------------------------------------------- /src/lovely/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | __import__('pkg_resources').declare_namespace(__name__) 3 | except ImportError: 4 | pass 5 | -------------------------------------------------------------------------------- /src/lovely/pytest/__init__.py: -------------------------------------------------------------------------------- 1 | class Test(object): 2 | pass 3 | -------------------------------------------------------------------------------- /src/lovely/pytest/docker/__init__.py: -------------------------------------------------------------------------------- 1 | from .compose import url_checker 2 | 3 | __all__ = ( 4 | url_checker, 5 | ) 6 | -------------------------------------------------------------------------------- /src/lovely/pytest/docker/compose.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import os 3 | import pytest 4 | import re 5 | import subprocess 6 | import time 7 | import timeit 8 | from six.moves.urllib.error import HTTPError 9 | from six.moves.urllib.request import urlopen 10 | 11 | 12 | def check_url(docker_ip, public_port, path='/'): 13 | """Check if a service is reachable. 14 | 15 | Makes a simple GET request to path of the HTTP endpoint. Service is 16 | available if returned status code is < 500. 17 | """ 18 | url = 'http://{}:{}{}'.format(docker_ip, public_port, path) 19 | try: 20 | r = urlopen(url) 21 | return r.code < 500 22 | except HTTPError as e: 23 | # If service returns e.g. a 404 it's ok 24 | return e.code < 500 25 | except Exception: 26 | # Possible service not yet started 27 | return False 28 | 29 | 30 | def url_checker(path): 31 | """Create a check_url method for a specific path 32 | """ 33 | return functools.partial(check_url, path=path) 34 | 35 | 36 | def execute(command, success_codes=(0,)): 37 | """Run a shell command.""" 38 | try: 39 | output = subprocess.check_output( 40 | command, 41 | stderr=subprocess.STDOUT, 42 | shell=False, 43 | ) 44 | status = 0 45 | except subprocess.CalledProcessError as error: 46 | output = error.output or b'' 47 | status = error.returncode 48 | command = error.cmd 49 | output = output.decode('utf-8') 50 | if status not in success_codes: 51 | raise Exception( 52 | 'Command %r returned %d: """%s""".' % (command, status, output) 53 | ) 54 | return output 55 | 56 | 57 | class Services(object): 58 | """A class which encapsulates services from docker compose definition. 59 | 60 | This code is partly taken from 61 | https://github.com/AndreLouisCaron/pytest-docker 62 | """ 63 | 64 | def __init__(self, compose_files, docker_ip, project_name='pytest'): 65 | self._docker_compose = DockerComposeExecutor( 66 | compose_files, project_name 67 | ) 68 | self._services = {} 69 | self.docker_ip = docker_ip 70 | 71 | def start(self, *services): 72 | """Ensures that the given services are started via docker compose. 73 | 74 | :param services: the names of the services as defined in compose file 75 | """ 76 | self._docker_compose.execute('up', '--build', '-d', *services) 77 | 78 | 79 | def stop(self, *services): 80 | """Ensures that the given services are stopped via docker compose. 81 | 82 | :param services: the names of the services as defined in compose file 83 | """ 84 | self._docker_compose.execute('stop', *services) 85 | 86 | 87 | def execute(self, service, *cmd): 88 | """Execute a command inside a docker container. 89 | 90 | :param service: the name of the service as defined in compose file 91 | :param cmd: list of command parts to execute 92 | """ 93 | return self._docker_compose.execute('exec', '-T', service, *cmd) 94 | 95 | def wait_for_service(self, service, private_port, check_server=check_url, timeout=30.0, pause=0.1): 96 | """ 97 | Waits for the given service to response to a http GET. 98 | 99 | :param service: the service name as defined in the docker compose file 100 | :param private_port: the private port as defined in docker compose file 101 | :param check_server: optional function to check if the server is ready 102 | (default check method makes GET request to '/' 103 | of HTTP endpoint) 104 | :param timeout: maximum time to wait for the service in seconds 105 | :param pause: time in seconds to wait between retries 106 | 107 | :return: the public port of the service exposed to host system if any 108 | """ 109 | public_port = self.port_for(service, private_port) 110 | self.wait_until_responsive( 111 | timeout=timeout, 112 | pause=pause, 113 | check=lambda: check_server(self.docker_ip, public_port), 114 | ) 115 | return public_port 116 | 117 | def shutdown(self): 118 | self._docker_compose.execute('down', '-v') 119 | 120 | def port_for(self, service, port): 121 | """Get the effective bind port for a service.""" 122 | 123 | # Lookup in the cache. 124 | cache = self._services.get(service, {}).get(port, None) 125 | if cache is not None: 126 | return cache 127 | 128 | output = self._docker_compose.execute( 129 | 'port', service, str(port) 130 | ) 131 | endpoint = output.strip() 132 | if not endpoint: 133 | raise ValueError( 134 | 'Could not detect port for "%s:%d".' % (service, port) 135 | ) 136 | 137 | # Usually, the IP address here is 0.0.0.0, so we don't use it. 138 | match = int(endpoint.split(':', 1)[1]) 139 | 140 | # Store it in cache in case we request it multiple times. 141 | self._services.setdefault(service, {})[port] = match 142 | 143 | return match 144 | 145 | @staticmethod 146 | def wait_until_responsive(check, timeout, pause, 147 | clock=timeit.default_timer): 148 | """Wait until a service is responsive.""" 149 | 150 | ref = clock() 151 | now = ref 152 | while (now - ref) < timeout: 153 | if check(): 154 | return 155 | time.sleep(pause) 156 | now = clock() 157 | 158 | raise Exception( 159 | 'Timeout reached while waiting on service!' 160 | ) 161 | 162 | 163 | class DockerComposeExecutor(object): 164 | def __init__(self, compose_files, project_name): 165 | self._compose_files = compose_files 166 | self._project_name = project_name 167 | self.project_directory = os.path.dirname(os.path.realpath(compose_files[0])) 168 | 169 | def execute(self, *subcommand): 170 | command = ["docker", "compose", "--project-directory", self.project_directory] 171 | for compose_file in self._compose_files: 172 | command.append('-f') 173 | command.append(compose_file) 174 | command.append('-p') 175 | command.append(self._project_name) 176 | command += subcommand 177 | return execute(command) 178 | 179 | 180 | @pytest.fixture(scope='session') 181 | def docker_ip(): 182 | """Determine IP address for TCP connections to Docker containers.""" 183 | 184 | # When talking to the Docker daemon via a UNIX socket, route all TCP 185 | # traffic to docker containers via the TCP loopback interface. 186 | docker_host = os.environ.get('DOCKER_HOST', '').strip() 187 | if not docker_host: 188 | return '127.0.0.1' 189 | 190 | match = re.match('^tcp://(.+?):\d+$', docker_host) 191 | if not match: 192 | raise ValueError( 193 | 'Invalid value for DOCKER_HOST: "%s".' % (docker_host,) 194 | ) 195 | return match.group(1) 196 | 197 | 198 | @pytest.fixture(scope='session') 199 | def docker_compose_files(pytestconfig): 200 | """Get the docker-compose.yml absolute path. 201 | Override this fixture in your tests if you need a custom location. 202 | """ 203 | return [ 204 | os.path.join(str(pytestconfig.rootdir), 'tests', 'docker-compose.yml') 205 | ] 206 | 207 | 208 | @pytest.fixture(scope='session') 209 | def docker_services_project_name(pytestconfig): 210 | """ 211 | Create unique project name for docker compose based on the pytestconfig root directory. 212 | Characters prohibited by Docker compose project names are replaced with hyphens. 213 | """ 214 | slug = re.sub(r'[^a-z0-9]+', '-', str(pytestconfig.rootdir).lower()) 215 | project_name = "pytest{}".format(slug) 216 | return project_name 217 | 218 | 219 | @pytest.fixture(scope='session') 220 | def docker_services(request, docker_compose_files, docker_ip, docker_services_project_name): 221 | """Provide the docker services as a pytest fixture. 222 | 223 | The services will be stopped after all tests are run. 224 | """ 225 | keep_alive = request.config.getoption("--keepalive", False) 226 | services = Services( 227 | docker_compose_files, 228 | docker_ip, 229 | docker_services_project_name 230 | ) 231 | yield services 232 | if not keep_alive: 233 | services.shutdown() 234 | 235 | 236 | def pytest_addoption(parser): 237 | """Add custom options to pytest. 238 | 239 | Add the --keepalive option for pytest. 240 | """ 241 | parser.addoption("--keepalive", "-K", action="store_true", 242 | default=False, help="Keep docker containers alive") 243 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.fixture(scope='session') 5 | def docker_hello_world(docker_services): 6 | """Fixture for the specific Hello World container. 7 | 8 | Depends on the `docker_services` fixture and returns the public url for the 9 | docker container's service. 10 | """ 11 | docker_services.start('hello') 12 | public_port = docker_services.wait_for_service("hello", 8080) 13 | url = "http://{docker_services.docker_ip}:{public_port}".format(**locals()) 14 | return url 15 | 16 | 17 | @pytest.fixture(scope='session') 18 | def docker_hello_world2(docker_services): 19 | """Fixture for the second Hello World container. 20 | 21 | Depends on the `docker_services` fixture and returns the public url for the 22 | docker container's service. 23 | """ 24 | docker_services.start('hello2') 25 | public_port = docker_services.wait_for_service("hello2", 8080) 26 | url = "http://{docker_services.docker_ip}:{public_port}".format(**locals()) 27 | return url 28 | 29 | 30 | @pytest.fixture(scope='session') 31 | def docker_services_project_name(): 32 | return "lovely-pytest-docker" 33 | -------------------------------------------------------------------------------- /tests/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | hello: 4 | image: jfxs/hello-world 5 | ports: 6 | - "8080" 7 | hello2: 8 | image: jfxs/hello-world 9 | ports: 10 | - "8080" 11 | -------------------------------------------------------------------------------- /tests/test_checker.py: -------------------------------------------------------------------------------- 1 | from lovely.pytest.docker import url_checker 2 | 3 | 4 | def test_url_checker(): 5 | f = url_checker('/probe_status') 6 | assert f is not None 7 | assert f.args == () 8 | assert f.keywords['path'] == '/probe_status' 9 | -------------------------------------------------------------------------------- /tests/test_hello.py: -------------------------------------------------------------------------------- 1 | from six.moves.urllib.request import urlopen 2 | import time 3 | 4 | 5 | def test_hello_world(docker_hello_world): 6 | """Test if the container is reachable. 7 | 8 | The docker_hello_world fixture is used, so the container will start on test 9 | startup. Do a request to the docker service and read the body. 10 | """ 11 | res = urlopen(docker_hello_world).read() 12 | assert b'The Hello world page' in res 13 | 14 | 15 | def test_single_container(docker_hello_world, docker_services): 16 | """Test if only the requested containers are started. 17 | 18 | The container for hello2 is never started as the fixture is not used.s 19 | """ 20 | res = docker_services._docker_compose.execute("ps") 21 | assert 'hello' in res 22 | assert 'hello2' not in res 23 | 24 | 25 | def test_stop_single_container(docker_hello_world, docker_hello_world2, docker_services): 26 | """Test if only the requested containers are stope. 27 | 28 | The container for hello2 is started by the fixture and stopped via function. 29 | """ 30 | res = docker_services._docker_compose.execute("ps") 31 | assert 'hello' in res 32 | assert 'hello2' in res 33 | docker_services.stop("hello2") 34 | res = docker_services._docker_compose.execute('ps', '--services', '--filter', 'status=running') 35 | assert 'hello2' not in res 36 | docker_services.start("hello2") 37 | res = docker_services._docker_compose.execute('ps', '--services', '--filter', 'status=running') 38 | assert 'hello2' in res 39 | 40 | 41 | def test_execute(docker_services): 42 | """Test the exec method. 43 | 44 | The exec method executes a command inside a docker command. 45 | """ 46 | res = docker_services.execute('hello', 'ls', '-a') 47 | assert res.startswith('.\n..\n.dockerenv\n') 48 | 49 | 50 | # counter 51 | custom_checker_called = 0 52 | 53 | 54 | def custom_checker(ip_address, port): 55 | global custom_checker_called 56 | if custom_checker_called > 1: 57 | return True 58 | custom_checker_called += 1 59 | return False 60 | 61 | 62 | def test_custom_checker(docker_services): 63 | """Test a custom checker in the wait_for_service method.""" 64 | 65 | docker_services.wait_for_service("hello", 8080, check_server=custom_checker) 66 | assert custom_checker_called > 1 67 | 68 | 69 | def test_custom_docker_service_project_name(docker_hello_world, docker_services): 70 | """Test a custom project name for docker services. 71 | 72 | Project name can be defined as fixture in conftest.py 73 | """ 74 | res = docker_services._docker_compose.execute("ps") 75 | assert 'lovely-pytest-docker' in res 76 | --------------------------------------------------------------------------------