conftest.py 26 KB

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