PKddM`ޚpytest_docker_tools/__init__.py''' An opionated set of helpers for defining Docker integration test environments with py.test fixtures. ''' from .factories import build, container, fetch, network, volume __version__ = '0.0.9' __all__ = [ 'build', 'container', 'fetch', 'network', 'volume', ] PK`MK__pytest_docker_tools/builder.pyimport textwrap from .templates import find_fixtures_in_params, resolve_fixtures_in_params def build_fixture_function(callable, scope, wrapper_class, kwargs): name = callable.__name__ docstring = getattr(callable, '__doc__', '').format(**kwargs) fixtures = find_fixtures_in_params(kwargs).union(set(('request', 'docker_client'))) fixtures_str = ','.join(fixtures) template = textwrap.dedent(f''' import pytest @pytest.fixture(scope=scope) def {name}({fixtures_str}): \'\'\' {docstring} \'\'\' real_kwargs = resolve_fixtures_in_params(request, kwargs) return _{name}(request, docker_client, wrapper_class=wrapper_class, **real_kwargs) ''') globals = { 'resolve_fixtures_in_params': resolve_fixtures_in_params, f'_{name}': callable, 'kwargs': kwargs, 'scope': scope, 'wrapper_class': wrapper_class, } exec(template, globals) return globals[name] def fixture_factory(scope='function'): wrapper_class = None def inner(callable): def factory(*, scope=scope, wrapper_class=wrapper_class, **kwargs): return build_fixture_function(callable, scope, wrapper_class, kwargs) factory.__name__ = callable.__name__ factory.__doc__ = getattr(callable, '__doc__', '') return factory return inner PKnL]%pytest_docker_tools/plugin.pyimport docker import pytest from .wrappers import Container @pytest.fixture(scope='session') def docker_client(request): ''' A Docker client configured from environment variables ''' return docker.from_env() @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): ''' This hook allows Docker containers to contribute their logs to the py.test report. ''' outcome = yield rep = outcome.get_result() if not rep.failed: return if 'request' not in item.funcargs: return for name, fixturedef in item.funcargs['request']._fixture_defs.items(): if not hasattr(fixturedef, 'cached_result'): continue fixture = fixturedef.cached_result[0] if isinstance(fixture, Container): rep.sections.append(( name + ': ' + fixture.name, fixture.logs(), )) PKnLs~33 pytest_docker_tools/templates.py''' # Template handling Fixture factories can take static strings: ```python redis = container( image='redis:latest', ) ``` But that is not useful when building multiple containers that need to reference one another or you need to parameterize the fixture. This module provides two facilities: The ability to reference fixtures using python string template notation and the ability to know what fixtures this will fetch in at test collection (and generation) time. For example: ``` def test_simple_resolve(request): # These are parameters declared at import time - they can be reevaluated in the context of multiple tests kwargs = { 'somekey': ['{pytestconfig.getoption("verbose")}'], } # This can be used in a fixture factory to fill in the templates resolved = resolve_fixtures_in_params(request, kwargs) # And then the test can access them pytestconfig = request.getfixturevalue('pytestconfig') assert resolved['somekey'][0] == str(pytestconfig.getoption("verbose")) } ``` In order to make fixtures generated by a fixture factory more seamless we need to know a fixtures dependencies at collection time. We have a helper to find them: def test_simple_find(): # These are parameters declared at import time - they can be reevaluated in the context of multiple tests kwargs = { 'somekey': ['{pytestconfig.getoption("verbose")}'], } dependencies = find_fixtures_in_params(kwargs) assert dependencies = set('pytestconfig') ''' import inspect from string import Formatter __all__ = [ 'find_fixtures_in_params', 'resolve_fixtures_in_params', ] class FixtureFormatter(Formatter): def __init__(self, request): self.request = request def get_value(self, key, args, kwargs): return self.request.getfixturevalue(key) class Renderer(object): def __init__(self, request): self.request = request def visit_value(self, val): if isinstance(val, str): return FixtureFormatter(self.request).format(val) elif callable(val): return val(*[self.request.getfixturevalue(f) for f in inspect.getargspec(val)[0]]) return val def visit_list(self, val): return [self.visit(v) for v in val] def visit_dict(self, mapping): return {self.visit(k): self.visit(v) for (k, v) in mapping.items()} def visit(self, value): if isinstance(value, dict): return self.visit_dict(value) elif isinstance(value, list): return self.visit_list(value) elif value: return self.visit_value(value) class FixtureFinder(object): def visit_value(self, val): if isinstance(val, str): for literal_text, format_spec, conversion, _ in Formatter().parse(val): if format_spec: yield format_spec.split('.')[0].split('[')[0] elif callable(val): yield from inspect.getargspec(val)[0] def visit_list(self, val): for v in val: yield from self.visit(v) def visit_dict(self, mapping): for k, v in mapping.items(): yield from self.visit(k) yield from self.visit(v) def visit(self, value): if isinstance(value, dict): yield from self.visit_dict(value) elif isinstance(value, list): yield from self.visit_list(value) elif value: yield from self.visit_value(value) def find_fixtures_in_params(value): ''' Walk an object and identify fixtures references in templates in strings. ''' finder = FixtureFinder() return set(finder.visit(value)) def resolve_fixtures_in_params(request, value): ''' Walk an object and resolve fixture values referenced in template strings. ''' renderer = Renderer(request) return renderer.visit(value) PKnL`͵pytest_docker_tools/utils.pyimport sys import time def wait_for_callable(message, callable, timeout=30): ''' Runs a callable once a second until it returns True or we hit the timeout. ''' sys.stdout.write(message) try: for i in range(timeout): sys.stdout.write('.') sys.stdout.flush() if callable(): return time.sleep(1) finally: sys.stdout.write('\n') raise RuntimeError('Timeout exceeded') PKnL./pytest_docker_tools/contexts/scratch/Dockerfile# For volume seeding we want a near-empty volune, You can't 'docker create scratch' # and you can have an iamge with just `FROM scratch`. FROM scratch CMD ["/bin/sh"] PKnL)pytest_docker_tools/factories/__init__.pyfrom .build import build from .container import container from .fetch import fetch from .network import network from .volume import volume __all__ = [ 'build', 'container', 'fetch', 'network', 'volume', ] PK`MOm&pytest_docker_tools/factories/build.pyimport sys from pytest_docker_tools.builder import fixture_factory @fixture_factory(scope='session') def build(request, docker_client, wrapper_class, **kwargs): ''' Docker image: built from "{path}" ''' # The docker build command now defaults to --rm=true, but docker-py doesnt # Let's do what docker build does by default kwargs.setdefault('rm', True) sys.stdout.write(f'Building {kwargs["path"]}') try: image, logs = docker_client.images.build(**kwargs) for line in logs: sys.stdout.write('.') sys.stdout.flush() finally: sys.stdout.write('\n') # request.addfinalizer(lambda: docker_client.images.remove(image.id)) wrapper_class = wrapper_class or (lambda image: image) return wrapper_class(image) PK`M"CM*pytest_docker_tools/factories/container.pyfrom pytest_docker_tools.builder import fixture_factory from pytest_docker_tools.utils import wait_for_callable from pytest_docker_tools.wrappers import Container @fixture_factory() def container(request, docker_client, wrapper_class, **kwargs): ''' Docker container: image={image} ''' kwargs.update({'detach': True}) raw_container = docker_client.containers.run(**kwargs) request.addfinalizer(lambda: raw_container.remove(force=True) and raw_container.wait(timeout=10)) wrapper_class = wrapper_class or Container container = wrapper_class(raw_container) wait_for_callable('Waiting for container to be ready', container.ready) return container PK`ML"&pytest_docker_tools/factories/fetch.pyimport sys from pytest_docker_tools.builder import fixture_factory @fixture_factory(scope='session') def fetch(request, docker_client, wrapper_class, **kwargs): ''' Docker image: Fetched from {repository} ''' sys.stdout.write(f'Fetching {kwargs["repository"]}\n') image = docker_client.images.pull(**kwargs) # request.addfinalizer(lambda: docker_client.images.remove(image.id)) wrapper_class = wrapper_class or (lambda image: image) return wrapper_class(image) PK`M{u(pytest_docker_tools/factories/network.pyimport uuid from pytest_docker_tools.builder import fixture_factory @fixture_factory() def network(request, docker_client, wrapper_class, **kwargs): ''' Docker network ''' name = kwargs.pop('name', 'pytest-{uuid}').format(uuid=str(uuid.uuid4())) print(f'Creating network {name}') network = docker_client.networks.create(name, **kwargs) request.addfinalizer(lambda: network.remove()) wrapper_class = wrapper_class or (lambda network: network) return wrapper_class(network) PK`Mc'pytest_docker_tools/factories/volume.pyimport io import os import tarfile import uuid from pytest_docker_tools.builder import fixture_factory def _populate_volume(docker_client, volume, seeds): fp = io.BytesIO() tf = tarfile.open(mode="w:gz", fileobj=fp) for path, contents in seeds.items(): ti = tarfile.TarInfo(path) if contents is None: ti.type = tarfile.DIRTYPE tf.addfile(ti) else: ti.size = len(contents) tf.addfile(ti, io.BytesIO(contents)) tf.close() fp.seek(0) image, logs = docker_client.images.build( path=os.path.join(os.path.dirname(__file__), '..', 'contexts/scratch'), rm=True, ) list(logs) container = docker_client.containers.create( image=image.id, volumes={ f'{volume.name}': {'bind': '/data'}, }, ) try: container.put_archive('/data', fp) finally: container.remove(force=True) @fixture_factory() def volume(request, docker_client, wrapper_class, **kwargs): ''' Docker volume ''' name = kwargs.pop('name', 'pytest-{uuid}').format(uuid=str(uuid.uuid4())) seeds = kwargs.pop('initial_content', {}) print(f'Creating volume {name}') volume = docker_client.volumes.create(name, **kwargs) request.addfinalizer(lambda: volume.remove(True)) if seeds: _populate_volume(docker_client, volume, seeds) wrapper_class = wrapper_class or (lambda volume: volume) return wrapper_class(volume) PKnL'kBB(pytest_docker_tools/wrappers/__init__.pyfrom .container import Container __all__ = [ 'Container', ] PK`M/o)pytest_docker_tools/wrappers/container.py''' This module contains a wrapper that adds some helpers to a Docker Container object that are useful for integration testing. ''' import io import tarfile class _Map(object): def __init__(self, container): self._container = container def values(self): return [self[k] for k in self.keys()] def items(self): return [(k, self[k]) for k in self.keys()] def __iter__(self): return iter(self.keys()) class IpMap(_Map): @property def primary(self): return next(iter(self.values())) def keys(self): return self._container.attrs['NetworkSettings']['Networks'].keys() def __getitem__(self, key): if not isinstance(key, str): key = key.name networks = self._container.attrs['NetworkSettings']['Networks'] if key not in networks: raise KeyError(f'Unknown network: {key}') return networks[key]['IPAddress'] class PortMap(_Map): def __init__(self, container): self._container = container def keys(self): return self._container.attrs['NetworkSettings']['Ports'].keys() def __getitem__(self, key): ports = self._container.attrs['NetworkSettings']['Ports'] if key not in ports: raise KeyError(f'Unknown port: {key}') if not ports[key]: return [] return [int(p['HostPort']) for p in ports[key]] class Container(object): def __init__(self, container): self._container = container self.ips = IpMap(container) self.ports = PortMap(container) def ready(self): self._container.reload() if self.status == 'exited': raise RuntimeError(f'Container {self.name} has already exited before we noticed it was ready') if self.status != 'running': return False networks = self._container.attrs['NetworkSettings']['Networks'] for name, network in networks.items(): if not network['IPAddress']: return False # If a user has exposed a port then wait for LISTEN socket to show up in netstat ports = self._container.attrs['NetworkSettings']['Ports'] for port, listeners in ports.items(): if not listeners: continue port, proto = port.split('/') assert proto in ('tcp', 'udp') if proto == 'tcp' and port not in self.get_open_tcp_ports(): return False if proto == 'udp' and port not in self.get_open_udp_ports(): return False return True @property def attrs(self): return self._container.attrs @property def id(self): return self._container.id @property def name(self): return self._container.name @property def env(self): kv_pairs = map(lambda v: v.split('=', 1), self._container.attrs['Config']['Env']) return {k: v for k, v in kv_pairs} @property def status(self): return self._container.status def reload(self): return self._container.reload() def kill(self, signal=None): return self._container.kill(signal) def remove(self, *args, **kwargs): raise RuntimeError('Do not remove this container manually. It will be removed automatically by py.test after the test finishes.') def logs(self): return self._container.logs().decode('utf-8') def get_files(self, path): ''' Retrieve files from a container at a given path. This is meant for extracting log files from a container where it is not using the docker logging capabilities. ''' archive_iter, _ = self._container.get_archive(path) archive_stream = io.BytesIO() [archive_stream.write(chunk) for chunk in archive_iter] archive_stream.seek(0) archive = tarfile.TarFile(fileobj=archive_stream) files = {} for info in archive.getmembers(): if not info.isfile(): files[info.name] = None continue reader = archive.extractfile(info.name) files[info.name] = reader.read() return files def get_text(self, path): text = {} for path, bytes in self.get_files(path).items(): if bytes is None: text[path] = None continue text[path] = bytes.decode('utf-8') def get_open_tcp_ports(self): ''' Gets all TCP sockets in the LISTEN state ''' netstat = self._container.exec_run('cat /proc/net/tcp')[1].decode('utf-8').strip() ports = [] for line in netstat.split('\n'): # Not interested in empty lines if not line: continue line = line.split() # Only interested in listen sockets if line[3] != '0A': continue ports.append(str(int(line[1].split(':', 1)[1], 16))) return ports def get_open_udp_ports(self): ''' Gets all UDP sockets in the LISTEN state ''' netstat = self._container.exec_run('cat /proc/net/udp')[1].decode('utf-8').strip() ports = [] for line in netstat.split('\n'): # Not interested in empty lines if not line: continue line = line.split() # Only interested in listen sockets if line[3] != '0A': continue ports.append(str(int(line[1].split(':', 1)[1], 16))) return ports PK!HG^(44pytest_docker_tools-0.0.9.dist-info/entry_points.txt.,I-.14JON-/)#䔦gqqPK!HNO)pytest_docker_tools-0.0.9.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,zd&Y)r$[)T&UrPK!H4?>pc,pytest_docker_tools-0.0.9.dist-info/METADATA=T&u{PΊfr]zrUD2ikk?T*++ܯhdq|,>{[8gu s$#Y,Zf$zCqjUW=Тޒ>8UUpbi%YZp mKXPq)RN-lR^+u4RL'>c ,iv௔g–I*prx'JaRR̎ bYn. 1l jH] ʔ48L7mG̯ZK%giNa.u&kRL-Ҩxg&3 Y۔9`,[VEQER\_vdD.-Q%O<%R|VLU`"y'eDf(Y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pyPKnL./]pytest_docker_tools/contexts/scratch/DockerfilePKnL)Rpytest_docker_tools/factories/__init__.pyPK`MOm&|pytest_docker_tools/factories/build.pyPK`M"CM*!pytest_docker_tools/factories/container.pyPK`ML"&$pytest_docker_tools/factories/fetch.pyPK`M{u('pytest_docker_tools/factories/network.pyPK`Mc'@)pytest_docker_tools/factories/volume.pyPKnL'kBB(c/pytest_docker_tools/wrappers/__init__.pyPK`M/o)/pytest_docker_tools/wrappers/container.pyPK!HG^(44Fpytest_docker_tools-0.0.9.dist-info/entry_points.txtPK!HNO)Fpytest_docker_tools-0.0.9.dist-info/WHEELPK!H4?>pc,-Gpytest_docker_tools-0.0.9.dist-info/METADATAPK!H"Qlu*apytest_docker_tools-0.0.9.dist-info/RECORDPKe