conftest.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. import contextlib
  2. import logging
  3. import os
  4. import pathlib
  5. import platform
  6. import re
  7. import shlex
  8. import socket
  9. import subprocess
  10. import time
  11. from collections.abc import Callable
  12. from io import StringIO
  13. from typing import Iterator, List, Optional, Any
  14. import backoff
  15. import docker.errors
  16. import pytest
  17. import requests
  18. from _pytest.fixtures import FixtureRequest
  19. from docker import DockerClient
  20. from docker.models.containers import Container
  21. from docker.models.networks import Network
  22. from packaging.version import Version
  23. from requests import Response
  24. from urllib3.util.connection import HAS_IPV6
  25. logging.basicConfig(level=logging.INFO)
  26. logging.getLogger('backoff').setLevel(logging.INFO)
  27. logging.getLogger('DNS').setLevel(logging.DEBUG)
  28. logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARN)
  29. CA_ROOT_CERTIFICATE = pathlib.Path(__file__).parent.joinpath("certs/ca-root.crt")
  30. PYTEST_RUNNING_IN_CONTAINER = os.environ.get('PYTEST_RUNNING_IN_CONTAINER') == "1"
  31. FORCE_CONTAINER_IPV6 = False # ugly global state to consider containers' IPv6 address instead of IPv4
  32. DOCKER_COMPOSE = os.environ.get('DOCKER_COMPOSE', 'docker compose')
  33. docker_client = docker.from_env()
  34. # Name of pytest container to reference if it's being used for running tests
  35. test_container = 'nginx-proxy-pytest'
  36. ###############################################################################
  37. #
  38. # utilities
  39. #
  40. ###############################################################################
  41. @contextlib.contextmanager
  42. def ipv6(force_ipv6: bool = True):
  43. """
  44. Meant to be used as a context manager to force IPv6 sockets:
  45. with ipv6():
  46. nginxproxy.get("http://something.nginx-proxy.example") # force use of IPv6
  47. with ipv6(False):
  48. nginxproxy.get("http://something.nginx-proxy.example") # legacy behavior
  49. """
  50. global FORCE_CONTAINER_IPV6
  51. FORCE_CONTAINER_IPV6 = force_ipv6
  52. yield
  53. FORCE_CONTAINER_IPV6 = False
  54. class RequestsForDocker:
  55. """
  56. Proxy for calling methods of the requests module.
  57. When an HTTP response failed due to HTTP Error 404 or 502, retry a few times.
  58. Provides method `get_conf` to extract the nginx-proxy configuration content.
  59. """
  60. def __init__(self):
  61. self.session = requests.Session()
  62. if CA_ROOT_CERTIFICATE.is_file():
  63. self.session.verify = CA_ROOT_CERTIFICATE.as_posix()
  64. @staticmethod
  65. def get_nginx_proxy_container() -> Container:
  66. """
  67. Return list of containers
  68. """
  69. nginx_proxy_containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  70. if len(nginx_proxy_containers) > 1:
  71. pytest.fail("Too many running nginxproxy/nginx-proxy:test containers", pytrace=False)
  72. elif len(nginx_proxy_containers) == 0:
  73. pytest.fail("No running nginxproxy/nginx-proxy:test container", pytrace=False)
  74. return nginx_proxy_containers.pop()
  75. def get_conf(self) -> bytes:
  76. """
  77. Return the nginx config file
  78. """
  79. nginx_proxy_container = self.get_nginx_proxy_container()
  80. return get_nginx_conf_from_container(nginx_proxy_container)
  81. def get_ip(self) -> str:
  82. """
  83. Return the nginx container ip address
  84. """
  85. nginx_proxy_container = self.get_nginx_proxy_container()
  86. return container_ip(nginx_proxy_container)
  87. def _with_backoff(self, method_name: str, predicate: Callable[[Any], bool], *args, **kwargs) -> Response:
  88. """Apply backoff retry logic to any session HTTP method."""
  89. with ipv6(kwargs.pop('ipv6', False)):
  90. @backoff.on_predicate(backoff.constant, predicate, interval=.25, max_tries=20)
  91. def _request(*_args, **_kwargs):
  92. return getattr(self.session, method_name)(*_args, **_kwargs)
  93. return _request(*args, **kwargs)
  94. def get_unknown_host(self, *args, **kwargs) -> Response:
  95. return self._with_backoff(
  96. 'get',
  97. lambda r: r.status_code != 503 or r.headers.get("X-Powered-By") != "nginx-proxy",
  98. *args,
  99. **kwargs
  100. )
  101. def get(self, *args, **kwargs) -> Response:
  102. return self._with_backoff('get', lambda r: r.status_code in (404, 502), *args, **kwargs)
  103. def post(self, *args, **kwargs) -> Response:
  104. return self._with_backoff('post', lambda r: r.status_code in (404, 502), *args, **kwargs)
  105. def put(self, *args, **kwargs) -> Response:
  106. return self._with_backoff('put', lambda r: r.status_code in (404, 502), *args, **kwargs)
  107. def head(self, *args, **kwargs) -> Response:
  108. return self._with_backoff('head', lambda r: r.status_code in (404, 502), *args, **kwargs)
  109. def delete(self, *args, **kwargs) -> Response:
  110. return self._with_backoff('delete', lambda r: r.status_code in (404, 502), *args, **kwargs)
  111. def options(self, *args, **kwargs) -> Response:
  112. return self._with_backoff('options', lambda r: r.status_code in (404, 502), *args, **kwargs)
  113. def __getattr__(self, name):
  114. return getattr(requests, name)
  115. def container_ip(container: Container) -> str:
  116. """
  117. return the IP address of a container.
  118. If the global FORCE_CONTAINER_IPV6 flag is set, return the IPv6 address
  119. """
  120. global FORCE_CONTAINER_IPV6
  121. if FORCE_CONTAINER_IPV6:
  122. if not HAS_IPV6:
  123. pytest.skip("This system does not support IPv6")
  124. ip = container_ipv6(container)
  125. if ip == '':
  126. pytest.skip(f"Container {container.name} has no IPv6 address")
  127. else:
  128. return ip
  129. else:
  130. net_info = container.attrs["NetworkSettings"]["Networks"]
  131. if "bridge" in net_info:
  132. return net_info["bridge"]["IPAddress"]
  133. # container is running in host network mode
  134. if "host" in net_info:
  135. return "127.0.0.1"
  136. # not default bridge network, fallback on first network defined
  137. network_name = list(net_info.keys())[0]
  138. return net_info[network_name]["IPAddress"]
  139. def container_ipv6(container: Container) -> str:
  140. """
  141. return the IPv6 address of a container.
  142. """
  143. net_info = container.attrs["NetworkSettings"]["Networks"]
  144. if "bridge" in net_info:
  145. return net_info["bridge"]["GlobalIPv6Address"]
  146. # container is running in host network mode
  147. if "host" in net_info:
  148. return "::1"
  149. # not default bridge network, fallback on first network defined
  150. network_name = list(net_info.keys())[0]
  151. return net_info[network_name]["GlobalIPv6Address"]
  152. def nginx_proxy_dns_resolver(domain_name: str) -> Optional[str]:
  153. """
  154. if "nginx-proxy" if found in host, return the ip address of the docker container
  155. issued from the docker image nginxproxy/nginx-proxy:test or nginx:latest.
  156. :return: IP or None
  157. """
  158. log = logging.getLogger('DNS')
  159. log.debug(f"nginx_proxy_dns_resolver({domain_name!r})")
  160. if 'nginx-proxy' in domain_name:
  161. nginxproxy_containers = docker_client.containers.list(filters={"status": "running", "ancestor": "nginxproxy/nginx-proxy:test"})
  162. nginx_containers = docker_client.containers.list(filters={"status": "running", "ancestor": "nginx:latest"})
  163. if len(nginxproxy_containers) == 0 and len(nginx_containers) == 0:
  164. log.warning(f"no running container found from image nginxproxy/nginx-proxy:test or nginx:latest while resolving {domain_name!r}")
  165. exited_nginxproxy_containers = docker_client.containers.list(filters={"status": "exited", "ancestor": "nginxproxy/nginx-proxy:test"})
  166. exited_nginx_containers = docker_client.containers.list(filters={"status": "exited", "ancestor": "nginx:latest"})
  167. if len(exited_nginxproxy_containers) > 0:
  168. exited_nginxproxy_container_logs = exited_nginxproxy_containers[0].logs()
  169. log.warning(f"nginxproxy/nginx-proxy:test container might have exited unexpectedly. Container logs: " + "\n" + exited_nginxproxy_container_logs.decode())
  170. if len(exited_nginx_containers) > 0:
  171. exited_nginx_container_logs = exited_nginx_containers[0].logs()
  172. log.warning(f"nginx:latest container might have exited unexpectedly. Container logs: " + "\n" + exited_nginx_container_logs.decode())
  173. return None
  174. container = None
  175. container_type = "nginx-proxy"
  176. if len(nginxproxy_containers) >= 1:
  177. container = nginxproxy_containers[0]
  178. if len(nginx_containers) >= 1:
  179. container = nginx_containers[0]
  180. container_type = "nginx"
  181. ip = container_ip(container)
  182. log.info(f"resolving domain name {domain_name!r} as IP address {ip} of {container_type} container {container.name}")
  183. return ip
  184. return None
  185. def docker_container_dns_resolver(domain_name: str) -> Optional[str]:
  186. """
  187. if domain name is of the form "XXX.container.docker" or "anything.XXX.container.docker",
  188. return the ip address of the docker container named XXX.
  189. :return: IP or None
  190. """
  191. log = logging.getLogger('DNS')
  192. log.debug(f"docker_container_dns_resolver({domain_name!r})")
  193. match = re.search(r'(^|.+\.)(?P<container>[^.]+)\.container\.docker$', domain_name)
  194. if not match:
  195. log.debug(f"{domain_name!r} does not match")
  196. return None
  197. container_name = match.group('container')
  198. log.debug(f"looking for container {container_name!r}")
  199. try:
  200. container = docker_client.containers.get(container_name)
  201. except docker.errors.NotFound:
  202. log.warning(f"container named {container_name!r} not found while resolving {domain_name!r}")
  203. return None
  204. log.debug(f"container {container.name!r} found ({container.short_id})")
  205. ip = container_ip(container)
  206. log.info(f"resolving domain name {domain_name!r} as IP address {ip} of container {container.name}")
  207. return ip
  208. def monkey_patch_urllib_dns_resolver():
  209. """
  210. Alter the behavior of the urllib DNS resolver so that any domain name
  211. containing substring 'nginx-proxy' will resolve to the IP address
  212. of the container created from image 'nginxproxy/nginx-proxy:test',
  213. or to 127.0.0.1 on Darwin.
  214. see https://docs.docker.com/desktop/features/networking/#i-want-to-connect-to-a-container-from-the-host
  215. """
  216. prv_getaddrinfo = socket.getaddrinfo
  217. dns_cache = {}
  218. def new_getaddrinfo(*args):
  219. logging.getLogger('DNS').debug(f"resolving domain name {repr(args)}")
  220. _args = list(args)
  221. # Fail early when querying IP directly, and it is forced ipv6 when not supported,
  222. # Otherwise a pytest container not using the host network fails to pass `test_raw-ip-vhost`.
  223. if FORCE_CONTAINER_IPV6 and not HAS_IPV6:
  224. pytest.skip("This system does not support IPv6")
  225. # custom DNS resolvers
  226. ip = None
  227. # Docker Desktop can't route traffic directly to Linux containers.
  228. if platform.system() == "Darwin":
  229. ip = "127.0.0.1"
  230. if ip is None:
  231. ip = nginx_proxy_dns_resolver(args[0])
  232. if ip is None:
  233. ip = docker_container_dns_resolver(args[0])
  234. if ip is not None:
  235. _args[0] = ip
  236. # call on original DNS resolver, with eventually the original host changed to the wanted IP address
  237. try:
  238. return dns_cache[tuple(_args)]
  239. except KeyError:
  240. res = prv_getaddrinfo(*_args)
  241. dns_cache[tuple(_args)] = res
  242. return res
  243. socket.getaddrinfo = new_getaddrinfo
  244. return prv_getaddrinfo
  245. def restore_urllib_dns_resolver(getaddrinfo_func):
  246. socket.getaddrinfo = getaddrinfo_func
  247. def get_nginx_conf_from_container(container: Container) -> bytes:
  248. """
  249. return the nginx /etc/nginx/conf.d/default.conf file content from a container
  250. """
  251. import tarfile
  252. from io import BytesIO
  253. strm_generator, stat = container.get_archive('/etc/nginx/conf.d/default.conf')
  254. strm_fileobj = BytesIO(b"".join(strm_generator))
  255. with tarfile.open(fileobj=strm_fileobj) as tf:
  256. conffile = tf.extractfile('default.conf')
  257. return conffile.read()
  258. def __prepare_and_execute_compose_cmd(compose_files: List[str], project_name: str, cmd: str):
  259. """
  260. Prepare and execute the Docker Compose command with the provided compose files and project name.
  261. """
  262. compose_cmd = StringIO()
  263. compose_cmd.write(DOCKER_COMPOSE)
  264. compose_cmd.write(f" --project-name {project_name}")
  265. for compose_file in compose_files:
  266. compose_cmd.write(f" --file {compose_file}")
  267. compose_cmd.write(f" {cmd}")
  268. try:
  269. subprocess.check_output(shlex.split(compose_cmd.getvalue()), stderr=subprocess.STDOUT)
  270. logging.info(f"Executed '{compose_cmd.getvalue()}'")
  271. except subprocess.CalledProcessError as e:
  272. logging.error(f"Error while running '{compose_cmd.getvalue()}'")
  273. def docker_compose_up(compose_files: List[str], project_name: str):
  274. """
  275. Execute compose up --detach with the provided compose files and project name.
  276. """
  277. if compose_files is None or len(compose_files) == 0:
  278. pytest.fail(f"No compose file passed to docker_compose_up", pytrace=False)
  279. __prepare_and_execute_compose_cmd(compose_files, project_name, cmd="up --detach")
  280. def docker_compose_down(compose_files: List[str], project_name: str):
  281. """
  282. Execute compose down --volumes with the provided compose files and project name.
  283. """
  284. if compose_files is None or len(compose_files) == 0:
  285. pytest.fail(f"No compose file passed to docker_compose_up", pytrace=False)
  286. __prepare_and_execute_compose_cmd(compose_files, project_name, cmd="down --volumes")
  287. def wait_for_nginxproxy_to_be_ready():
  288. """
  289. Wait for logs of running containers started from image nginxproxy/nginx-proxy:test and/or
  290. nginxproxy/docker-gen:latest to contain the substring "Watching docker events"
  291. """
  292. nginx_proxy_containers = docker_client.containers.list(filters={"status": "running", "ancestor": "nginxproxy/nginx-proxy:test"})
  293. docker_gen_containers = docker_client.containers.list(filters={"status": "running", "ancestor": "nginxproxy/docker-gen:latest"})
  294. containers = nginx_proxy_containers + docker_gen_containers
  295. for container in containers:
  296. logging.debug(f"waiting for container {container.name} to be ready")
  297. for line in container.logs(stream=True):
  298. if b"Watching docker events" in line:
  299. logging.debug(f"{container.name} ready")
  300. break
  301. @pytest.fixture
  302. def docker_compose_files(request: FixtureRequest) -> List[str]:
  303. """Fixture returning the docker compose files to consider:
  304. If a YAML file exists with the same name as the test module (with the `.py` extension
  305. replaced with `.base.yml`, ie `test_foo.py`-> `test_foo.base.yml`) and in the same
  306. directory as the test module, use only that file.
  307. Otherwise, merge the following files in this order:
  308. - the `compose.base.yml` file in the parent `test` directory.
  309. - if present in the same directory as the test module, the `compose.base.override.yml` file.
  310. - the YAML file named after the current test module (ie `test_foo.py`-> `test_foo.yml`)
  311. Tests can override this fixture to specify a custom location.
  312. """
  313. compose_files: List[str] = []
  314. test_module_path = pathlib.Path(request.module.__file__).parent
  315. module_base_file = test_module_path.joinpath(f"{request.module.__name__}.base.yml")
  316. if module_base_file.is_file():
  317. return [module_base_file.as_posix()]
  318. global_base_file = test_module_path.parent.joinpath("compose.base.yml")
  319. if global_base_file.is_file():
  320. compose_files.append(global_base_file.as_posix())
  321. module_base_override_file = test_module_path.joinpath("compose.base.override.yml")
  322. if module_base_override_file.is_file():
  323. compose_files.append(module_base_override_file.as_posix())
  324. module_compose_file = test_module_path.joinpath(f"{request.module.__name__}.yml")
  325. if module_compose_file.is_file():
  326. compose_files.append(module_compose_file.as_posix())
  327. if not module_base_file.is_file() and not module_compose_file.is_file():
  328. logging.error(
  329. f"Could not find any docker compose file named '{module_base_file.name}' or '{module_compose_file.name}'"
  330. )
  331. logging.debug(f"using docker compose files {compose_files}")
  332. return compose_files
  333. def connect_to_network(network: Network) -> Optional[Network]:
  334. """
  335. If we are running from a container, connect our container to the given network
  336. :return: the name of the network we were connected to, or None
  337. """
  338. if PYTEST_RUNNING_IN_CONTAINER:
  339. try:
  340. my_container = docker_client.containers.get(test_container)
  341. except docker.errors.NotFound:
  342. logging.warning(f"container {test_container} not found")
  343. return None
  344. # figure out our container networks
  345. my_networks = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  346. # If the pytest container is using host networking, it cannot connect to container networks (not required with host network)
  347. if 'host' in my_networks:
  348. return None
  349. # Make sure our container is connected to the nginx-proxy's network,
  350. # but avoid connecting to `none` network (not valid) with `test_server-down` tests
  351. if network.name not in my_networks and network.name != 'none':
  352. try:
  353. logging.info(f"Connecting to docker network: {network.name}")
  354. network.connect(my_container)
  355. return network
  356. except docker.errors.APIError as e:
  357. logging.warning(f"Failed to connect to network {network.name}: {e}")
  358. return network # Ensure the network is still tracked for later removal
  359. return None
  360. def disconnect_from_network(network: Network = None):
  361. """
  362. If we are running from a container, disconnect our container from the given network.
  363. :param network: name of a docker network to disconnect from
  364. """
  365. if PYTEST_RUNNING_IN_CONTAINER and network is not None:
  366. try:
  367. my_container = docker_client.containers.get(test_container)
  368. except docker.errors.NotFound:
  369. logging.warning(f"container {test_container} not found")
  370. return
  371. # figure out our container networks
  372. my_networks_names = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  373. # disconnect our container from the given network
  374. if network.name in my_networks_names:
  375. logging.info(f"Disconnecting from network {network.name}")
  376. network.disconnect(my_container)
  377. def connect_to_all_networks() -> List[Network]:
  378. """
  379. If we are running from a container, connect our container to all current docker networks.
  380. :return: a list of networks we connected to
  381. """
  382. if not PYTEST_RUNNING_IN_CONTAINER:
  383. return []
  384. else:
  385. # find the list of docker networks
  386. networks = [network for network in docker_client.networks.list(greedy=True) if len(network.containers) > 0 and network.name != 'bridge']
  387. return [connect_to_network(network) for network in networks]
  388. class DockerComposer(contextlib.AbstractContextManager):
  389. def __init__(self):
  390. logging.debug("DockerComposer __init__")
  391. self._networks = None
  392. self._docker_compose_files = None
  393. self._project_name = None
  394. def __exit__(self, *exc_info):
  395. logging.debug("DockerComposer __exit__")
  396. self._down()
  397. def _down(self):
  398. logging.debug(f"DockerComposer _down {self._docker_compose_files} {self._project_name} {self._networks}")
  399. if self._docker_compose_files is None:
  400. logging.debug("docker_compose_files is None, nothing to cleanup")
  401. return
  402. if self._networks:
  403. for network in self._networks:
  404. disconnect_from_network(network)
  405. docker_compose_down(self._docker_compose_files, self._project_name)
  406. self._docker_compose_files = None
  407. self._project_name = None
  408. self._networks = []
  409. def compose(self, docker_compose_files: List[str], project_name: str):
  410. if docker_compose_files == self._docker_compose_files and project_name == self._project_name:
  411. logging.info(f"Skipping compose: {docker_compose_files} (already running under project {project_name})")
  412. return
  413. if docker_compose_files is None or project_name is None:
  414. logging.info(f"Skipping compose: no compose file specified")
  415. return
  416. self._down()
  417. self._docker_compose_files = docker_compose_files
  418. self._project_name = project_name
  419. logging.debug(f"DockerComposer compose {self._docker_compose_files} {self._project_name} {self._networks}")
  420. try:
  421. docker_compose_up(docker_compose_files, project_name)
  422. self._networks = connect_to_all_networks()
  423. wait_for_nginxproxy_to_be_ready()
  424. time.sleep(3) # give time to containers to be ready
  425. except KeyboardInterrupt:
  426. logging.warning("KeyboardInterrupt detected! Force cleanup...")
  427. self._down() # Ensure proper shutdown
  428. raise # Re-raise to allow pytest to exit cleanly
  429. except docker.errors.APIError as e:
  430. logging.error(f"Docker API error ({e.status_code}): {e.explanation}")
  431. logging.debug(f"Full error message: {str(e)}")
  432. self._down() # Ensure proper cleanup even on failure
  433. pytest.fail(f"Docker Compose setup failed due to Docker API error: {e.explanation}")
  434. except RuntimeError as e:
  435. logging.error(f"RuntimeEror encountered in: {project_name}")
  436. logging.debug(f"Full error message: {str(e)}")
  437. self._down() # Ensure proper cleanup even on failure
  438. pytest.fail(f"Docker Compose setup failed due to RuntimeError in: {project_name}")
  439. ###############################################################################
  440. #
  441. # Py.test fixtures
  442. #
  443. ###############################################################################
  444. @pytest.fixture(scope="module")
  445. def docker_composer() -> Iterator[DockerComposer]:
  446. with DockerComposer() as d:
  447. yield d
  448. @pytest.fixture
  449. def ca_root_certificate() -> str:
  450. return CA_ROOT_CERTIFICATE.as_posix()
  451. @pytest.fixture
  452. def monkey_patched_dns():
  453. original_dns_resolver = monkey_patch_urllib_dns_resolver()
  454. yield
  455. restore_urllib_dns_resolver(original_dns_resolver)
  456. @pytest.fixture
  457. def docker_compose(
  458. request: FixtureRequest,
  459. monkeypatch,
  460. monkey_patched_dns,
  461. docker_composer,
  462. docker_compose_files
  463. ) -> Iterator[DockerClient]:
  464. """
  465. Ensures containers necessary for the test module are started in a compose project,
  466. and set the environment variable `PYTEST_MODULE_PATH` to the test module's parent folder.
  467. A list of custom docker compose files path can be specified by overriding
  468. the `docker_compose_file` fixture.
  469. Also, in the case where pytest is running from a docker container, this fixture
  470. makes sure our container will be attached to all the docker networks.
  471. """
  472. pytest_module_path = pathlib.Path(request.module.__file__).parent
  473. monkeypatch.setenv("PYTEST_MODULE_PATH", pytest_module_path.as_posix())
  474. project_name = request.module.__name__
  475. docker_composer.compose(docker_compose_files, project_name)
  476. yield docker_client
  477. @pytest.fixture
  478. def nginxproxy() -> Iterator[RequestsForDocker]:
  479. """
  480. Provides the `nginxproxy` object that can be used in the same way the requests module is:
  481. r = nginxproxy.get("https://foo.com")
  482. The difference is that in case an HTTP requests has status code 404 or 502 (which mostly
  483. indicates that nginx has just reloaded), we retry up to 30 times the query.
  484. Also, the nginxproxy methods accept an additional keyword parameter: `ipv6` which forces requests
  485. made against containers to use the containers IPv6 address when set to `True`. If IPv6 is not
  486. supported by the system or docker, that particular test will be skipped.
  487. """
  488. yield RequestsForDocker()
  489. @pytest.fixture
  490. def acme_challenge_path() -> str:
  491. """
  492. Provides fake Let's Encrypt ACME challenge path used in certain tests
  493. """
  494. return ".well-known/acme-challenge/test-filename"
  495. ###############################################################################
  496. #
  497. # Py.test hooks
  498. #
  499. ###############################################################################
  500. # pytest hook to display additional stuff in test report
  501. def pytest_runtest_logreport(report):
  502. if report.failed:
  503. test_containers = docker_client.containers.list(all=True, filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  504. for container in test_containers:
  505. report.longrepr.addsection('nginx-proxy logs', container.logs().decode())
  506. report.longrepr.addsection('nginx-proxy conf', get_nginx_conf_from_container(container).decode())
  507. # Py.test `incremental` marker, see http://stackoverflow.com/a/12579625/107049
  508. def pytest_runtest_makereport(item, call):
  509. if "incremental" in item.keywords:
  510. if call.excinfo is not None:
  511. parent = item.parent
  512. parent._previousfailed = item
  513. def pytest_runtest_setup(item):
  514. previousfailed = getattr(item.parent, "_previousfailed", None)
  515. if previousfailed is not None:
  516. pytest.xfail(f"previous test failed ({previousfailed.name})")
  517. ###############################################################################
  518. #
  519. # Check requirements
  520. #
  521. ###############################################################################
  522. try:
  523. docker_client.images.get('nginxproxy/nginx-proxy:test')
  524. except docker.errors.ImageNotFound:
  525. pytest.exit("The docker image 'nginxproxy/nginx-proxy:test' is missing")
  526. if Version(docker.__version__) < Version("5.0.0"):
  527. pytest.exit("This test suite is meant to work with the python docker module v5.0.0 or later")