Package: pytest-docker-compose-v2
pytest-docker-compose-v2NOTE: This is a fork from thepytest-docker-composeproject which at the time of writing hasn't been updated in 2 years -- I depend on this so I'm taking a crack at running a -v2 fork, but I'm definitely willing to re-integrate any changes back to the original project. Currently the changes are pretty basic and includea PR that introduces support for docker compose v2, some package updates, and more superficial updates to align with personal preferences. Though I am making an effort to run the existing test suite, I have not tested this extensively.This package contains apytestplugin for integrating Docker Compose into your automated integration tests.Given a path to adocker-compose.ymlfile, it will automatically build the project at the start of the test run, bring the containers up before each test starts, and tear them down after each test ends.DependenciesMake sure you haveDockerinstalled.This plugin is automatically tested against the following software:Python 3.9, 3.10, 3.11 and 3.12pytest 7NOTE: This plugin isnotcompatible with Python 2.InstallationInstall the plugin using pip:pipinstallpytest-docker-compose-v2UsageFor performance reasons, the plugin is not enabled by default, so you must activate it manually in the tests that use it:pytest_plugins=["docker_compose"]SeeInstalling and Using Pluginsfor more information.To interact with Docker containers in your tests, use the following fixtures, these fixtures tell docker-compose to start all the services and then they can fetch the associated containers for use in a test:function_scoped_container_getterAn object that fetches containers of the Dockercompose.container.Containerobjects running during the test. The containers are fetched usingfunction_scoped_container_getter.get('service_name')These containers each have an extra attribute callednetwork_infoadded to them. This attribute has a list ofpytest_docker_compose.NetworkInfoobjects.This information can be used to configure API clients and other objects that will connect to services exposed by the Docker containers in your tests.NetworkInfois a container with the following fields:container_port: The port (and usually also protocol name) exposed
internally to the container.  You can use this value to find the correct
port for your test, when the container exposes multiple ports.hostname: The hostname (usually "localhost") to use when connecting to
the service from the host.host_port: The port number to use when connecting to the service from
the host.docker_projectThecompose.project.Projectobject that the containers are built from.
This fixture is generally only used internally by the plugin.Wider scoped fixturesTo use the following fixtures please readUse wider scoped fixturesclass_scoped_container_getter: Similar tofunction_scoped_container_getterjust with a wider scope.module_scoped_container_getter: Similar tofunction_scoped_container_getterjust with a wider scope.session_scoped_container_getter: Similar tofunction_scoped_container_getterjust with a wider scope.Waiting for Services to Come OnlineThe fixtures called[scope]_scoped_container_getterwill wait until every container is up before handing control over to the test.However, just because a container is up does not mean that the services running on it are ready to accept incoming requests yet!If your tests need to wait for a particular condition (for example, to wait for an HTTP health check endpoint to send back a 200 response), make sure that your fixtures account for this.Here's an example of a fixture calledwait_for_apithat waits for an HTTP service to come online before a test calledtest_read_and_writecan run.importpytestimportrequestsfromurllib.parseimporturljoinfromurllib3.util.retryimportRetryfromrequests.adaptersimportHTTPAdapterpytest_plugins=["docker_compose"]# Invoking this fixture: 'function_scoped_container_getter' starts all services@pytest.fixture(scope="function")defwait_for_api(function_scoped_container_getter):"""Wait for the api from my_api_service to become responsive"""request_session=requests.Session()retries=Retry(total=5,backoff_factor=0.1,status_forcelist=[500,502,503,504])request_session.mount('http://',HTTPAdapter(max_retries=retries))service=function_scoped_container_getter.get("my_api_service").network_info[0]api_url="http://%s:%s/"%(service.hostname,service.host_port)assertrequest_session.get(api_url)returnrequest_session,api_urldeftest_read_and_write(wait_for_api):"""The Api is now verified good to go and tests can interact with it"""request_session,api_url=wait_for_apidata_string='some_data'request_session.put('%sitems/2?data_string=%s'%(api_url,data_string))item=request_session.get(urljoin(api_url,'items/2')).json()assertitem['data']==data_stringrequest_session.delete(urljoin(api_url,'items/2'))Use wider scoped fixturesThefunction_scoped_container_getterfixture uses "function" scope, meaning that all of the containers are torn down after each individual test.This is done so that every test gets to run in a "clean" environment. However, this can potentially make a test suite take a very long time to complete.There are two options to make containers persist beyond a single test. The best way is to use the fixtures that are explicitly scoped to different scopes. There are three additional fixtures for this purpose:class_scoped_container_getter,module_scoped_container_getterandsession_scoped_container_getter. Notice that you need to be careful when using these! There are two main caveats to keep in mind:Manage your scope correctly, using 'module' scope and 'function' scope in one single file will throw an error! This is because the module scoped fixture will spin up the containers and then the function scoped fixture will try to spin up the containers again. Docker compose does not allow you to spin up containers twice.Clean up your environment after each test. Because the containers are not restarted their environments can carry the information from previous tests. Therefore you need to be very careful when designing your tests such that they leave the containers in the same state that it started in or you might run into difficult to understand behaviour.A second method to make containers persist beyond a single test is to supply the--use-running-containersflag to pytest like so:pytest--use-running-containersWith this flag,pytest-docker-composechecks that all containers are running
during the project creation. If they are not running a warning is given and
they are spun up anyways. They are then used for all the tests and NOT TORE
DOWN afterwards.This mode is best used in combination with the--docker-compose-no-buildflag since the newly build containers won't be used anyways. like so:pytest--docker-compose-no-build--use-running-containersIt is of course possible to add these options topytest.iniorpyproject.toml.Notice that for this mode the scoping of the fixtures becomes less important since the containers are fully persistent throughout all tests. I only recommend using this if your network takes excessively long to spin up/tear down. It should really be a last resort and you should probably look into speeding up your network instead of using this.Running Integration TestsUsepytestto run your tests as normal:pytestBy default, this will look for adocker-compose.ymlfile in the current
working directory.  You can specify a different file via the--docker-composeoption:pytest--docker-compose=/path/to/docker-compose.ymlDocker compose allows for specifying multiple compose files as describedin the docs. To specify more than one compose file, separate them with a,:pytest--docker-compose=/path/to/docker-compose.yml,/another/docker-compose.yml,/third/docker-compose.ymlTipAlternatively, you can specify this option in yourpytest.inifile:[pytest]addopts=--docker-compose=/path/to/docker-compose.ymlThe option will be ignored for tests that do not use this plugin.SeeConfiguration Optionsfor more information on using configuration
files to modify pytest behavior.Remove volumes after testsThere is another configuration option that will delete the volumes of containers after running.pytest--docker-compose-remove-volumesThis option will be ignored if the plugin is not used. Again, this option can also be added to thepytest.inifile.For more examples on how to use this plugin look at the testing suite of this plugin itself! It will give you some examples for configuringpyproject.tomland how to use the different fixtures to run docker containers.