conftest.py 25 KB

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