|
| 1 | +import functools |
| 2 | +import os |
| 3 | +from urllib.request import urlopen |
| 4 | + |
| 5 | +import pytest |
| 6 | +import re |
| 7 | +import subprocess |
| 8 | +import time |
| 9 | +import timeit |
| 10 | + |
| 11 | +from requests import HTTPError |
| 12 | + |
| 13 | + |
| 14 | +def check_url(docker_ip, public_port, path="/"): |
| 15 | + """Check if a service is reachable. |
| 16 | +
|
| 17 | + Makes a simple GET request to path of the HTTP endpoint. Service is |
| 18 | + available if returned status code is < 500. |
| 19 | + """ |
| 20 | + url = "http://{}:{}{}".format(docker_ip, public_port, path) |
| 21 | + try: |
| 22 | + r = urlopen(url) |
| 23 | + return r.code < 500 |
| 24 | + except HTTPError as e: |
| 25 | + # If service returns e.g. a 404 it's ok |
| 26 | + return e.code < 500 |
| 27 | + except Exception: |
| 28 | + # Possible service not yet started |
| 29 | + return False |
| 30 | + |
| 31 | + |
| 32 | +def execute(command, success_codes=(0,)): |
| 33 | + """Run a shell command.""" |
| 34 | + try: |
| 35 | + output = subprocess.check_output( |
| 36 | + command, |
| 37 | + stderr=subprocess.STDOUT, |
| 38 | + shell=False, |
| 39 | + ) |
| 40 | + status = 0 |
| 41 | + except subprocess.CalledProcessError as error: |
| 42 | + output = error.output or b"" |
| 43 | + status = error.returncode |
| 44 | + command = error.cmd |
| 45 | + output = output.decode("utf-8") |
| 46 | + if status not in success_codes: |
| 47 | + raise Exception('Command %r returned %d: """%s""".' % (command, status, output)) |
| 48 | + return output |
| 49 | + |
| 50 | + |
| 51 | +class Services(object): |
| 52 | + """A class which encapsulates services from docker compose definition. |
| 53 | +
|
| 54 | + This code is partly taken from |
| 55 | + https://github.com/AndreLouisCaron/pytest-docker |
| 56 | + """ |
| 57 | + |
| 58 | + def __init__(self, compose_files, docker_ip, project_name="pytest"): |
| 59 | + self._docker_compose = DockerComposeExecutor(compose_files, project_name) |
| 60 | + self._services = {} |
| 61 | + self.docker_ip = docker_ip |
| 62 | + |
| 63 | + def start(self, *services): |
| 64 | + """Ensures that the given services are started via docker compose. |
| 65 | +
|
| 66 | + :param services: the names of the services as defined in compose file |
| 67 | + """ |
| 68 | + self._docker_compose.execute("up", "--build", "-d", *services) |
| 69 | + |
| 70 | + def stop(self, *services): |
| 71 | + """Ensures that the given services are stopped via docker compose. |
| 72 | +
|
| 73 | + :param services: the names of the services as defined in compose file |
| 74 | + """ |
| 75 | + self._docker_compose.execute("stop", *services) |
| 76 | + |
| 77 | + def execute(self, service, *cmd): |
| 78 | + """Execute a command inside a docker container. |
| 79 | +
|
| 80 | + :param service: the name of the service as defined in compose file |
| 81 | + :param cmd: list of command parts to execute |
| 82 | + """ |
| 83 | + return self._docker_compose.execute("exec", "-T", service, *cmd) |
| 84 | + |
| 85 | + def wait_for_service( |
| 86 | + self, service, private_port, check_server=check_url, timeout=30.0, pause=0.1 |
| 87 | + ): |
| 88 | + """ |
| 89 | + Waits for the given service to response to a http GET. |
| 90 | +
|
| 91 | + :param service: the service name as defined in the docker compose file |
| 92 | + :param private_port: the private port as defined in docker compose file |
| 93 | + :param check_server: optional function to check if the server is ready |
| 94 | + (default check method makes GET request to '/' |
| 95 | + of HTTP endpoint) |
| 96 | + :param timeout: maximum time to wait for the service in seconds |
| 97 | + :param pause: time in seconds to wait between retries |
| 98 | +
|
| 99 | + :return: the public port of the service exposed to host system if any |
| 100 | + """ |
| 101 | + public_port = self.port_for(service, private_port) |
| 102 | + self.wait_until_responsive( |
| 103 | + timeout=timeout, |
| 104 | + pause=pause, |
| 105 | + check=lambda: check_server(self.docker_ip, public_port), |
| 106 | + ) |
| 107 | + return public_port |
| 108 | + |
| 109 | + def shutdown(self): |
| 110 | + self._docker_compose.execute("down", "-v") |
| 111 | + |
| 112 | + def port_for(self, service, port): |
| 113 | + """Get the effective bind port for a service.""" |
| 114 | + |
| 115 | + # Lookup in the cache. |
| 116 | + cache = self._services.get(service, {}).get(port, None) |
| 117 | + if cache is not None: |
| 118 | + return cache |
| 119 | + |
| 120 | + output = self._docker_compose.execute("port", service, str(port)) |
| 121 | + endpoint = output.strip() |
| 122 | + if not endpoint: |
| 123 | + raise ValueError('Could not detect port for "%s:%d".' % (service, port)) |
| 124 | + |
| 125 | + # Usually, the IP address here is 0.0.0.0, so we don't use it. |
| 126 | + match = int(endpoint.split(":", 1)[1]) |
| 127 | + |
| 128 | + # Store it in cache in case we request it multiple times. |
| 129 | + self._services.setdefault(service, {})[port] = match |
| 130 | + |
| 131 | + return match |
| 132 | + |
| 133 | + @staticmethod |
| 134 | + def wait_until_responsive(check, timeout, pause, clock=timeit.default_timer): |
| 135 | + """Wait until a service is responsive.""" |
| 136 | + |
| 137 | + ref = clock() |
| 138 | + now = ref |
| 139 | + while (now - ref) < timeout: |
| 140 | + if check(): |
| 141 | + return |
| 142 | + time.sleep(pause) |
| 143 | + now = clock() |
| 144 | + |
| 145 | + raise Exception("Timeout reached while waiting on service!") |
| 146 | + |
| 147 | + |
| 148 | +class DockerComposeExecutor(object): |
| 149 | + def __init__(self, compose_files, project_name): |
| 150 | + self._compose_files = compose_files |
| 151 | + self._project_name = project_name |
| 152 | + self.project_directory = os.path.dirname(os.path.realpath(compose_files[0])) |
| 153 | + |
| 154 | + def execute(self, *subcommand): |
| 155 | + command = ["docker", "compose"] |
| 156 | + for compose_file in self._compose_files: |
| 157 | + command.append("-f") |
| 158 | + command.append(compose_file) |
| 159 | + command.append("-p") |
| 160 | + command.append(self._project_name) |
| 161 | + command += subcommand |
| 162 | + return execute(command) |
0 commit comments