|
| 1 | +import io |
| 2 | +import tarfile |
| 3 | +import time |
| 4 | + |
| 5 | +import docker |
| 6 | +import pytest |
| 7 | +import requests |
| 8 | + |
| 9 | +from six import StringIO |
| 10 | + |
| 11 | +from kubernetes import config |
| 12 | +from openshift.helper import KubernetesObjectHelper |
| 13 | + |
| 14 | + |
| 15 | +@pytest.fixture(scope='session') |
| 16 | +def openshift_container(request): |
| 17 | + client = docker.from_env() |
| 18 | + # TODO: bind to a random host port |
| 19 | + image_name = 'openshift/origin:{}'.format(request.config.getoption('--openshift-version')) |
| 20 | + container = client.containers.run(image_name, 'start master', detach=True, |
| 21 | + ports={'8443/tcp': 8443}) |
| 22 | + |
| 23 | + try: |
| 24 | + # Wait for the container to no longer be in the created state before |
| 25 | + # continuing |
| 26 | + while container.status == u'created': |
| 27 | + time.sleep(0.2) |
| 28 | + container = client.containers.get(container.id) |
| 29 | + |
| 30 | + # Wait for the api server to be ready before continuing |
| 31 | + # TODO: actually we end on a 200 response |
| 32 | + for _ in range(10): |
| 33 | + try: |
| 34 | + resp = requests.head("https://localhost:8443/healthz/ready", verify=False) |
| 35 | + if resp.status_code == 200: |
| 36 | + break |
| 37 | + except requests.RequestException: |
| 38 | + pass |
| 39 | + |
| 40 | + time.sleep(1) |
| 41 | + |
| 42 | + # TODO: handle waiting for system policy to be fully configured better |
| 43 | + time.sleep(1) |
| 44 | + |
| 45 | + yield container |
| 46 | + finally: |
| 47 | + # Always remove the container |
| 48 | + container.remove(force=True) |
| 49 | + |
| 50 | + |
| 51 | +@pytest.fixture(scope='session') |
| 52 | +def kubeconfig(openshift_container, tmpdir_factory): |
| 53 | + # get_archive returns a stream of the tar archive containing the requested |
| 54 | + # files/directories, so we need use BytesIO as an intermediate step. |
| 55 | + tar_stream, _ = openshift_container.get_archive('/var/lib/origin/openshift.local.config/master/admin.kubeconfig') |
| 56 | + tar_obj = tarfile.open(fileobj=io.BytesIO(tar_stream.read())) |
| 57 | + kubeconfig_contents = tar_obj.extractfile('admin.kubeconfig').read() |
| 58 | + |
| 59 | + kubeconfig_file = tmpdir_factory.mktemp('kubeconfig').join('admin.kubeconfig') |
| 60 | + kubeconfig_file.write(kubeconfig_contents) |
| 61 | + yield kubeconfig_file |
| 62 | + |
| 63 | + |
| 64 | +@pytest.fixture() |
| 65 | +def k8s_helper(request, kubeconfig): |
| 66 | + print(request.module.__name__) |
| 67 | + _,api_version,resource = request.module.__name__.split('_', 2) |
| 68 | + k8s_helper = KubernetesObjectHelper(api_version, resource) |
| 69 | + k8s_helper.set_client_config({'kubeconfig': str(kubeconfig)}) |
| 70 | + config.kube_config.configuration.host='https://127.0.0.1:8443' |
| 71 | + yield k8s_helper |
0 commit comments