conftest.py 23 KB

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