conftest.py 24 KB

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