conftest.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. If one (and only one) container started from image nginxproxy/nginx-proxy:test
  299. or nginxproxy/docker-gen:latest is found, wait for its log to contain the substring "Watching docker events"
  300. """
  301. nginx_proxy_containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  302. docker_gen_containers = docker_client.containers.list(filters={"ancestor": "nginxproxy/docker-gen:latest"})
  303. container_name = "nginx-proxy"
  304. if len(nginx_proxy_containers) == 1:
  305. container = nginx_proxy_containers.pop()
  306. elif len(docker_gen_containers) == 1:
  307. container = docker_gen_containers.pop()
  308. container_name = "docker-gen"
  309. else:
  310. logging.debug("Either more than one or no nginx-proxy or docker-gen container found, skipping container readiness check")
  311. return
  312. for line in container.logs(stream=True):
  313. if b"Watching docker events" in line:
  314. logging.debug(f"{container_name} ready")
  315. break
  316. @pytest.fixture
  317. def docker_compose_files(request: FixtureRequest) -> List[str]:
  318. """Fixture returning the docker compose files to consider:
  319. If a YAML file exists with the same name as the test module (with the `.py` extension
  320. replaced with `.base.yml`, ie `test_foo.py`-> `test_foo.base.yml`) and in the same
  321. directory as the test module, use only that file.
  322. Otherwise, merge the following files in this order:
  323. - the `compose.base.yml` file in the parent `test` directory.
  324. - if present in the same directory as the test module, the `compose.base.override.yml` file.
  325. - the YAML file named after the current test module (ie `test_foo.py`-> `test_foo.yml`)
  326. Tests can override this fixture to specify a custom location.
  327. """
  328. compose_files: List[str] = []
  329. test_module_path = pathlib.Path(request.module.__file__).parent
  330. module_base_file = test_module_path.joinpath(f"{request.module.__name__}.base.yml")
  331. if module_base_file.is_file():
  332. return [module_base_file.as_posix()]
  333. global_base_file = test_module_path.parent.joinpath("compose.base.yml")
  334. if global_base_file.is_file():
  335. compose_files.append(global_base_file.as_posix())
  336. module_base_override_file = test_module_path.joinpath("compose.base.override.yml")
  337. if module_base_override_file.is_file():
  338. compose_files.append(module_base_override_file.as_posix())
  339. module_compose_file = test_module_path.joinpath(f"{request.module.__name__}.yml")
  340. if module_compose_file.is_file():
  341. compose_files.append(module_compose_file.as_posix())
  342. if not module_base_file.is_file() and not module_compose_file.is_file():
  343. logging.error(
  344. f"Could not find any docker compose file named '{module_base_file.name}' or '{module_compose_file.name}'"
  345. )
  346. logging.debug(f"using docker compose files {compose_files}")
  347. return compose_files
  348. def connect_to_network(network: Network) -> Optional[Network]:
  349. """
  350. If we are running from a container, connect our container to the given network
  351. :return: the name of the network we were connected to, or None
  352. """
  353. if PYTEST_RUNNING_IN_CONTAINER:
  354. try:
  355. my_container = docker_client.containers.get(test_container)
  356. except docker.errors.NotFound:
  357. logging.warning(f"container {test_container} not found")
  358. return None
  359. # figure out our container networks
  360. my_networks = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  361. # If the pytest container is using host networking, it cannot connect to container networks (not required with host network)
  362. if 'host' in my_networks:
  363. return None
  364. # Make sure our container is connected to the nginx-proxy's network,
  365. # but avoid connecting to `none` network (not valid) with `test_server-down` tests
  366. if network.name not in my_networks and network.name != 'none':
  367. try:
  368. logging.info(f"Connecting to docker network: {network.name}")
  369. network.connect(my_container)
  370. return network
  371. except docker.errors.APIError as e:
  372. logging.warning(f"Failed to connect to network {network.name}: {e}")
  373. return network # Ensure the network is still tracked for later removal
  374. return None
  375. def disconnect_from_network(network: Network = None):
  376. """
  377. If we are running from a container, disconnect our container from the given network.
  378. :param network: name of a docker network to disconnect from
  379. """
  380. if PYTEST_RUNNING_IN_CONTAINER and network is not None:
  381. try:
  382. my_container = docker_client.containers.get(test_container)
  383. except docker.errors.NotFound:
  384. logging.warning(f"container {test_container} not found")
  385. return
  386. # figure out our container networks
  387. my_networks_names = list(my_container.attrs["NetworkSettings"]["Networks"].keys())
  388. # disconnect our container from the given network
  389. if network.name in my_networks_names:
  390. logging.info(f"Disconnecting from network {network.name}")
  391. network.disconnect(my_container)
  392. def connect_to_all_networks() -> List[Network]:
  393. """
  394. If we are running from a container, connect our container to all current docker networks.
  395. :return: a list of networks we connected to
  396. """
  397. if not PYTEST_RUNNING_IN_CONTAINER:
  398. return []
  399. else:
  400. # find the list of docker networks
  401. networks = [network for network in docker_client.networks.list(greedy=True) if len(network.containers) > 0 and network.name != 'bridge']
  402. return [connect_to_network(network) for network in networks]
  403. class DockerComposer(contextlib.AbstractContextManager):
  404. def __init__(self):
  405. logging.debug("DockerComposer __init__")
  406. self._networks = None
  407. self._docker_compose_files = None
  408. self._project_name = None
  409. def __exit__(self, *exc_info):
  410. logging.debug("DockerComposer __exit__")
  411. self._down()
  412. def _down(self):
  413. logging.debug(f"DockerComposer _down {self._docker_compose_files} {self._project_name} {self._networks}")
  414. if self._docker_compose_files is None:
  415. logging.debug("docker_compose_files is None, nothing to cleanup")
  416. return
  417. if self._networks:
  418. for network in self._networks:
  419. disconnect_from_network(network)
  420. docker_compose_down(self._docker_compose_files, self._project_name)
  421. self._docker_compose_files = None
  422. self._project_name = None
  423. self._networks = []
  424. def compose(self, docker_compose_files: List[str], project_name: str):
  425. if docker_compose_files == self._docker_compose_files and project_name == self._project_name:
  426. logging.info(f"Skipping compose: {docker_compose_files} (already running under project {project_name})")
  427. return
  428. if docker_compose_files is None or project_name is None:
  429. logging.info(f"Skipping compose: no compose file specified")
  430. return
  431. self._down()
  432. self._docker_compose_files = docker_compose_files
  433. self._project_name = project_name
  434. logging.debug(f"DockerComposer compose {self._docker_compose_files} {self._project_name} {self._networks}")
  435. try:
  436. docker_compose_up(docker_compose_files, project_name)
  437. self._networks = connect_to_all_networks()
  438. wait_for_nginxproxy_to_be_ready()
  439. time.sleep(3) # give time to containers to be ready
  440. except KeyboardInterrupt:
  441. logging.warning("KeyboardInterrupt detected! Force cleanup...")
  442. self._down() # Ensure proper shutdown
  443. raise # Re-raise to allow pytest to exit cleanly
  444. except docker.errors.APIError as e:
  445. logging.error(f"Docker API error ({e.status_code}): {e.explanation}")
  446. logging.debug(f"Full error message: {str(e)}")
  447. self._down() # Ensure proper cleanup even on failure
  448. pytest.fail(f"Docker Compose setup failed due to Docker API error: {e.explanation}")
  449. except RuntimeError as e:
  450. logging.error(f"RuntimeEror encountered in: {project_name}")
  451. logging.debug(f"Full error message: {str(e)}")
  452. self._down() # Ensure proper cleanup even on failure
  453. pytest.fail(f"Docker Compose setup failed due to RuntimeError in: {project_name}")
  454. ###############################################################################
  455. #
  456. # Py.test fixtures
  457. #
  458. ###############################################################################
  459. @pytest.fixture(scope="module")
  460. def docker_composer() -> Iterator[DockerComposer]:
  461. with DockerComposer() as d:
  462. yield d
  463. @pytest.fixture
  464. def ca_root_certificate() -> str:
  465. return CA_ROOT_CERTIFICATE.as_posix()
  466. @pytest.fixture
  467. def monkey_patched_dns():
  468. original_dns_resolver = monkey_patch_urllib_dns_resolver()
  469. yield
  470. restore_urllib_dns_resolver(original_dns_resolver)
  471. @pytest.fixture
  472. def docker_compose(
  473. request: FixtureRequest,
  474. monkeypatch,
  475. monkey_patched_dns,
  476. docker_composer,
  477. docker_compose_files
  478. ) -> Iterator[DockerClient]:
  479. """
  480. Ensures containers necessary for the test module are started in a compose project,
  481. and set the environment variable `PYTEST_MODULE_PATH` to the test module's parent folder.
  482. A list of custom docker compose files path can be specified by overriding
  483. the `docker_compose_file` fixture.
  484. Also, in the case where pytest is running from a docker container, this fixture
  485. makes sure our container will be attached to all the docker networks.
  486. """
  487. pytest_module_path = pathlib.Path(request.module.__file__).parent
  488. monkeypatch.setenv("PYTEST_MODULE_PATH", pytest_module_path.as_posix())
  489. project_name = request.module.__name__
  490. docker_composer.compose(docker_compose_files, project_name)
  491. yield docker_client
  492. @pytest.fixture
  493. def nginxproxy() -> Iterator[RequestsForDocker]:
  494. """
  495. Provides the `nginxproxy` object that can be used in the same way the requests module is:
  496. r = nginxproxy.get("https://foo.com")
  497. The difference is that in case an HTTP requests has status code 404 or 502 (which mostly
  498. indicates that nginx has just reloaded), we retry up to 30 times the query.
  499. Also, the nginxproxy methods accept an additional keyword parameter: `ipv6` which forces requests
  500. made against containers to use the containers IPv6 address when set to `True`. If IPv6 is not
  501. supported by the system or docker, that particular test will be skipped.
  502. """
  503. yield RequestsForDocker()
  504. @pytest.fixture
  505. def acme_challenge_path() -> str:
  506. """
  507. Provides fake Let's Encrypt ACME challenge path used in certain tests
  508. """
  509. return ".well-known/acme-challenge/test-filename"
  510. ###############################################################################
  511. #
  512. # Py.test hooks
  513. #
  514. ###############################################################################
  515. # pytest hook to display additional stuff in test report
  516. def pytest_runtest_logreport(report):
  517. if report.failed:
  518. test_containers = docker_client.containers.list(all=True, filters={"ancestor": "nginxproxy/nginx-proxy:test"})
  519. for container in test_containers:
  520. report.longrepr.addsection('nginx-proxy logs', container.logs().decode())
  521. report.longrepr.addsection('nginx-proxy conf', get_nginx_conf_from_container(container).decode())
  522. # Py.test `incremental` marker, see http://stackoverflow.com/a/12579625/107049
  523. def pytest_runtest_makereport(item, call):
  524. if "incremental" in item.keywords:
  525. if call.excinfo is not None:
  526. parent = item.parent
  527. parent._previousfailed = item
  528. def pytest_runtest_setup(item):
  529. previousfailed = getattr(item.parent, "_previousfailed", None)
  530. if previousfailed is not None:
  531. pytest.xfail(f"previous test failed ({previousfailed.name})")
  532. ###############################################################################
  533. #
  534. # Check requirements
  535. #
  536. ###############################################################################
  537. try:
  538. docker_client.images.get('nginxproxy/nginx-proxy:test')
  539. except docker.errors.ImageNotFound:
  540. pytest.exit("The docker image 'nginxproxy/nginx-proxy:test' is missing")
  541. if Version(docker.__version__) < Version("5.0.0"):
  542. pytest.exit("This test suite is meant to work with the python docker module v5.0.0 or later")