conftest.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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 io import StringIO
  12. from typing import Iterator, List, Optional
  13. import backoff
  14. import docker.errors
  15. import pytest
  16. import requests
  17. from _pytest.fixtures import FixtureRequest
  18. from docker import DockerClient
  19. from docker.models.containers import Container
  20. from docker.models.networks import Network
  21. from packaging.version import Version
  22. from requests import Response
  23. from urllib3.util.connection import HAS_IPV6
  24. logging.basicConfig(level=logging.INFO)
  25. logging.getLogger('backoff').setLevel(logging.INFO)
  26. logging.getLogger('DNS').setLevel(logging.DEBUG)
  27. logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARN)
  28. CA_ROOT_CERTIFICATE = pathlib.Path(__file__).parent.joinpath("certs/ca-root.crt")
  29. PYTEST_RUNNING_IN_CONTAINER = os.environ.get('PYTEST_RUNNING_IN_CONTAINER') == "1"
  30. FORCE_CONTAINER_IPV6 = False # ugly global state to consider containers' IPv6 address instead of IPv4
  31. DOCKER_COMPOSE = os.environ.get('DOCKER_COMPOSE', 'docker compose')
  32. docker_client = docker.from_env()
  33. # Name of pytest container to reference if it's being used for running tests
  34. test_container = 'nginx-proxy-pytest'
  35. ###############################################################################
  36. #
  37. # utilities
  38. #
  39. ###############################################################################
  40. @contextlib.contextmanager
  41. def ipv6(force_ipv6: bool = True):
  42. """
  43. Meant to be used as a context manager to force IPv6 sockets:
  44. with ipv6():
  45. nginxproxy.get("http://something.nginx-proxy.example") # force use of IPv6
  46. with ipv6(False):
  47. nginxproxy.get("http://something.nginx-proxy.example") # legacy behavior
  48. """
  49. global FORCE_CONTAINER_IPV6
  50. FORCE_CONTAINER_IPV6 = force_ipv6
  51. yield
  52. FORCE_CONTAINER_IPV6 = False
  53. class RequestsForDocker:
  54. """
  55. Proxy for calling methods of the requests module.
  56. When an HTTP response failed due to HTTP Error 404 or 502, retry a few times.
  57. Provides method `get_conf` to extract the nginx-proxy configuration content.
  58. """
  59. def __init__(self):
  60. self.session = requests.Session()
  61. if CA_ROOT_CERTIFICATE.is_file():
  62. self.session.verify = CA_ROOT_CERTIFICATE.as_posix()
  63. @staticmethod
  64. def get_nginx_proxy_container() -> Container:
  65. """
  66. Return list of containers
  67. """
  68. nginx_proxy_containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  69. if len(nginx_proxy_containers) > 1:
  70. pytest.fail("Too many running nginxproxy/nginx-proxy:test containers", pytrace=False)
  71. elif len(nginx_proxy_containers) == 0:
  72. pytest.fail("No running nginxproxy/nginx-proxy:test container", pytrace=False)
  73. return nginx_proxy_containers.pop()
  74. def get_conf(self) -> bytes:
  75. """
  76. Return the nginx config file
  77. """
  78. nginx_proxy_container = self.get_nginx_proxy_container()
  79. return get_nginx_conf_from_container(nginx_proxy_container)
  80. def get_ip(self) -> str:
  81. """
  82. Return the nginx container ip address
  83. """
  84. nginx_proxy_container = self.get_nginx_proxy_container()
  85. return container_ip(nginx_proxy_container)
  86. def get(self, *args, **kwargs) -> Response:
  87. with ipv6(kwargs.pop('ipv6', False)):
  88. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  89. def _get(*_args, **_kwargs):
  90. return self.session.get(*_args, **_kwargs)
  91. return _get(*args, **kwargs)
  92. def post(self, *args, **kwargs) -> Response:
  93. with ipv6(kwargs.pop('ipv6', False)):
  94. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  95. def _post(*_args, **_kwargs):
  96. return self.session.post(*_args, **_kwargs)
  97. return _post(*args, **kwargs)
  98. def put(self, *args, **kwargs) -> Response:
  99. with ipv6(kwargs.pop('ipv6', False)):
  100. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  101. def _put(*_args, **_kwargs):
  102. return self.session.put(*_args, **_kwargs)
  103. return _put(*args, **kwargs)
  104. def head(self, *args, **kwargs) -> Response:
  105. with ipv6(kwargs.pop('ipv6', False)):
  106. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  107. def _head(*_args, **_kwargs):
  108. return self.session.head(*_args, **_kwargs)
  109. return _head(*args, **kwargs)
  110. def delete(self, *args, **kwargs) -> Response:
  111. with ipv6(kwargs.pop('ipv6', False)):
  112. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  113. def _delete(*_args, **_kwargs):
  114. return self.session.delete(*_args, **_kwargs)
  115. return _delete(*args, **kwargs)
  116. def options(self, *args, **kwargs) -> Response:
  117. with ipv6(kwargs.pop('ipv6', False)):
  118. @backoff.on_predicate(backoff.constant, lambda r: r.status_code in (404, 502), interval=.3, max_tries=30, jitter=None)
  119. def _options(*_args, **_kwargs):
  120. return self.session.options(*_args, **_kwargs)
  121. return _options(*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 runninf 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 running container started from image nginxproxy/nginx-proxy:test
  299. and nginxproxy/docker-gen:latest logs 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. for line in container.logs(stream=True):
  306. if b"Watching docker events" in line:
  307. logging.debug(f"container {container.name} is ready")
  308. break
  309. @pytest.fixture
  310. def docker_compose_files(request: FixtureRequest) -> List[str]:
  311. """Fixture returning the docker compose files to consider:
  312. If a YAML file exists with the same name as the test module (with the `.py` extension
  313. replaced with `.base.yml`, ie `test_foo.py`-> `test_foo.base.yml`) and in the same
  314. directory as the test module, use only that file.
  315. Otherwise, merge the following files in this order:
  316. - the `compose.base.yml` file in the parent `test` directory.
  317. - if present in the same directory as the test module, the `compose.base.override.yml` file.
  318. - the YAML file named after the current test module (ie `test_foo.py`-> `test_foo.yml`)
  319. Tests can override this fixture to specify a custom location.
  320. """
  321. compose_files: List[str] = []
  322. test_module_path = pathlib.Path(request.module.__file__).parent
  323. module_base_file = test_module_path.joinpath(f"{request.module.__name__}.base.yml")
  324. if module_base_file.is_file():
  325. return [module_base_file.as_posix()]
  326. global_base_file = test_module_path.parent.joinpath("compose.base.yml")
  327. if global_base_file.is_file():
  328. compose_files.append(global_base_file.as_posix())
  329. module_base_override_file = test_module_path.joinpath("compose.base.override.yml")
  330. if module_base_override_file.is_file():
  331. compose_files.append(module_base_override_file.as_posix())
  332. module_compose_file = test_module_path.joinpath(f"{request.module.__name__}.yml")
  333. if module_compose_file.is_file():
  334. compose_files.append(module_compose_file.as_posix())
  335. if not module_base_file.is_file() and not module_compose_file.is_file():
  336. logging.error(
  337. f"Could not find any docker compose file named '{module_base_file.name}' or '{module_compose_file.name}'"
  338. )
  339. logging.debug(f"using docker compose files {compose_files}")
  340. return compose_files
  341. def connect_to_network(network: Network) -> Optional[Network]:
  342. """
  343. If we are running from a container, connect our container to the given network
  344. :return: the name of the network we were connected to, or None
  345. """
  346. if PYTEST_RUNNING_IN_CONTAINER:
  347. try:
  348. my_container = docker_client.containers.get(test_container)
  349. except docker.errors.NotFound:
  350. logging.warning(f"container {test_container} not found")
  351. return None
  352. # figure out our container networks
  353. my_networks = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  354. # If the pytest container is using host networking, it cannot connect to container networks (not required with host network)
  355. if 'host' in my_networks:
  356. return None
  357. # Make sure our container is connected to the nginx-proxy's network,
  358. # but avoid connecting to `none` network (not valid) with `test_server-down` tests
  359. if network.name not in my_networks and network.name != 'none':
  360. try:
  361. logging.info(f"Connecting to docker network: {network.name}")
  362. network.connect(my_container)
  363. return network
  364. except docker.errors.APIError as e:
  365. logging.warning(f"Failed to connect to network {network.name}: {e}")
  366. return network # Ensure the network is still tracked for later removal
  367. return None
  368. def disconnect_from_network(network: Network = None):
  369. """
  370. If we are running from a container, disconnect our container from the given network.
  371. :param network: name of a docker network to disconnect from
  372. """
  373. if PYTEST_RUNNING_IN_CONTAINER and network is not None:
  374. try:
  375. my_container = docker_client.containers.get(test_container)
  376. except docker.errors.NotFound:
  377. logging.warning(f"container {test_container} not found")
  378. return
  379. # figure out our container networks
  380. my_networks_names = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  381. # disconnect our container from the given network
  382. if network.name in my_networks_names:
  383. logging.info(f"Disconnecting from network {network.name}")
  384. network.disconnect(my_container)
  385. def connect_to_all_networks() -> List[Network]:
  386. """
  387. If we are running from a container, connect our container to all current docker networks.
  388. :return: a list of networks we connected to
  389. """
  390. if not PYTEST_RUNNING_IN_CONTAINER:
  391. return []
  392. else:
  393. # find the list of docker networks
  394. networks = [network for network in docker_client.networks.list(greedy=True) if len(network.containers) > 0 and network.name != 'bridge']
  395. return [connect_to_network(network) for network in networks]
  396. class DockerComposer(contextlib.AbstractContextManager):
  397. def __init__(self):
  398. logging.debug("DockerComposer __init__")
  399. self._networks = None
  400. self._docker_compose_files = None
  401. self._project_name = None
  402. def __exit__(self, *exc_info):
  403. logging.debug("DockerComposer __exit__")
  404. self._down()
  405. def _down(self):
  406. logging.debug(f"DockerComposer _down {self._docker_compose_files} {self._project_name} {self._networks}")
  407. if self._docker_compose_files is None:
  408. logging.debug("docker_compose_files is None, nothing to cleanup")
  409. return
  410. if self._networks:
  411. for network in self._networks:
  412. disconnect_from_network(network)
  413. docker_compose_down(self._docker_compose_files, self._project_name)
  414. self._docker_compose_files = None
  415. self._project_name = None
  416. self._networks = []
  417. def compose(self, docker_compose_files: List[str], project_name: str):
  418. if docker_compose_files == self._docker_compose_files and project_name == self._project_name:
  419. logging.info(f"Skipping compose: {docker_compose_files} (already running under project {project_name})")
  420. return
  421. if docker_compose_files is None or project_name is None:
  422. logging.info(f"Skipping compose: no compose file specified")
  423. return
  424. self._down()
  425. self._docker_compose_files = docker_compose_files
  426. self._project_name = project_name
  427. logging.debug(f"DockerComposer compose {self._docker_compose_files} {self._project_name} {self._networks}")
  428. try:
  429. docker_compose_up(docker_compose_files, project_name)
  430. self._networks = connect_to_all_networks()
  431. wait_for_nginxproxy_to_be_ready()
  432. except KeyboardInterrupt:
  433. logging.warning("KeyboardInterrupt detected! Force cleanup...")
  434. self._down() # Ensure proper shutdown
  435. raise # Re-raise to allow pytest to exit cleanly
  436. except docker.errors.APIError as e:
  437. logging.error(f"Docker API error ({e.status_code}): {e.explanation}")
  438. logging.debug(f"Full error message: {str(e)}")
  439. self._down() # Ensure proper cleanup even on failure
  440. pytest.fail(f"Docker Compose setup failed due to Docker API error: {e.explanation}")
  441. except RuntimeError as e:
  442. logging.error(f"RuntimeEror encountered in: {project_name}")
  443. logging.debug(f"Full error message: {str(e)}")
  444. self._down() # Ensure proper cleanup even on failure
  445. pytest.fail(f"Docker Compose setup failed due to RuntimeError in: {project_name}")
  446. ###############################################################################
  447. #
  448. # Py.test fixtures
  449. #
  450. ###############################################################################
  451. @pytest.fixture(scope="module")
  452. def docker_composer() -> Iterator[DockerComposer]:
  453. with DockerComposer() as d:
  454. yield d
  455. @pytest.fixture
  456. def ca_root_certificate() -> str:
  457. return CA_ROOT_CERTIFICATE.as_posix()
  458. @pytest.fixture
  459. def monkey_patched_dns():
  460. original_dns_resolver = monkey_patch_urllib_dns_resolver()
  461. yield
  462. restore_urllib_dns_resolver(original_dns_resolver)
  463. @pytest.fixture
  464. def docker_compose(
  465. request: FixtureRequest,
  466. monkeypatch,
  467. monkey_patched_dns,
  468. docker_composer,
  469. docker_compose_files
  470. ) -> Iterator[DockerClient]:
  471. """
  472. Ensures containers necessary for the test module are started in a compose project,
  473. and set the environment variable `PYTEST_MODULE_PATH` to the test module's parent folder.
  474. A list of custom docker compose files path can be specified by overriding
  475. the `docker_compose_file` fixture.
  476. Also, in the case where pytest is running from a docker container, this fixture
  477. makes sure our container will be attached to all the docker networks.
  478. """
  479. pytest_module_path = pathlib.Path(request.module.__file__).parent
  480. monkeypatch.setenv("PYTEST_MODULE_PATH", pytest_module_path.as_posix())
  481. project_name = request.module.__name__
  482. docker_composer.compose(docker_compose_files, project_name)
  483. yield docker_client
  484. @pytest.fixture
  485. def nginxproxy() -> Iterator[RequestsForDocker]:
  486. """
  487. Provides the `nginxproxy` object that can be used in the same way the requests module is:
  488. r = nginxproxy.get("https://foo.com")
  489. The difference is that in case an HTTP requests has status code 404 or 502 (which mostly
  490. indicates that nginx has just reloaded), we retry up to 30 times the query.
  491. Also, the nginxproxy methods accept an additional keyword parameter: `ipv6` which forces requests
  492. made against containers to use the containers IPv6 address when set to `True`. If IPv6 is not
  493. supported by the system or docker, that particular test will be skipped.
  494. """
  495. yield RequestsForDocker()
  496. @pytest.fixture
  497. def acme_challenge_path() -> str:
  498. """
  499. Provides fake Let's Encrypt ACME challenge path used in certain tests
  500. """
  501. return ".well-known/acme-challenge/test-filename"
  502. ###############################################################################
  503. #
  504. # Py.test hooks
  505. #
  506. ###############################################################################
  507. # pytest hook to display additional stuff in test report
  508. def pytest_runtest_logreport(report):
  509. if report.failed:
  510. test_containers = docker_client.containers.list(all=True, filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  511. for container in test_containers:
  512. report.longrepr.addsection('nginx-proxy logs', container.logs().decode())
  513. report.longrepr.addsection('nginx-proxy conf', get_nginx_conf_from_container(container).decode())
  514. # Py.test `incremental` marker, see http://stackoverflow.com/a/12579625/107049
  515. def pytest_runtest_makereport(item, call):
  516. if "incremental" in item.keywords:
  517. if call.excinfo is not None:
  518. parent = item.parent
  519. parent._previousfailed = item
  520. def pytest_runtest_setup(item):
  521. previousfailed = getattr(item.parent, "_previousfailed", None)
  522. if previousfailed is not None:
  523. pytest.xfail(f"previous test failed ({previousfailed.name})")
  524. ###############################################################################
  525. #
  526. # Check requirements
  527. #
  528. ###############################################################################
  529. try:
  530. docker_client.images.get('nginxproxy/nginx-proxy:test')
  531. except docker.errors.ImageNotFound:
  532. pytest.exit("The docker image 'nginxproxy/nginx-proxy:test' is missing")
  533. if Version(docker.__version__) < Version("5.0.0"):
  534. pytest.exit("This test suite is meant to work with the python docker module v5.0.0 or later")