conftest.py 24 KB

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