2
0

conftest.py 25 KB

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