conftest.py 25 KB

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