Beispiel #1
0
def test_filters():
    random_label_value = random_name()

    containers_with_labels = []

    for _ in range(3):
        containers_with_labels.append(
            docker.run(
                "busybox",
                ["sleep", "infinity"],
                remove=True,
                detach=True,
                labels=dict(dodo=random_label_value),
            ))

    containers_with_wrong_labels = []
    for _ in range(3):
        containers_with_wrong_labels.append(
            docker.run(
                "busybox",
                ["sleep", "infinity"],
                remove=True,
                detach=True,
                labels=dict(dodo="something"),
            ))

    expected_containers_with_labels = docker.container.list(filters=dict(
        label=f"dodo={random_label_value}"))

    assert set(expected_containers_with_labels) == set(containers_with_labels)

    for container in containers_with_labels + containers_with_wrong_labels:
        container.kill()
def test_clone():
    some_volume = docker.volume.create()
    docker.run(
        "busybox",
        [
            "sh",
            "-c",
            "mkdir -p /volume/subdir/subdir2 && touch /volume/subdir/subdir2/dodo.txt",
        ],
        remove=True,
        volumes=[(some_volume, "/volume")],
    )

    new_volume = docker.volume.clone(some_volume)
    files = docker.run(
        "busybox",
        [
            "sh",
            "-c",
            "ls /volume/subdir/subdir2",
        ],
        remove=True,
        volumes=[(new_volume, "/volume")],
    )
    assert files == "dodo.txt"
Beispiel #3
0
def test_run_volumes():
    volume_name = random_name()
    docker.run(
        "busybox",
        ["touch", "/some/path/dodo"],
        volumes=[(volume_name, "/some/path")],
        remove=True,
    )
    docker.volume.remove(volume_name)
Beispiel #4
0
 def __init_memory(self, loc):
     try:
         docker.run("redis",
                    volumes=[(loc + "/", '/data')],
                    publish=[(self.port, 6379)],
                    detach=True,
                    name='Prophet-Memory')
     except:
         docker.start('Prophet-Memory')
         print('Prophet is alive')
Beispiel #5
0
def test_wait_multiple_container_random_exit_order():
    cont_1 = docker.run("busybox", ["sh", "-c", "sleep 4 && exit 8"],
                        detach=True)
    cont_2 = docker.run("busybox", ["sh", "-c", "sleep 2 && exit 10"],
                        detach=True)

    with cont_1, cont_2:
        exit_codes = docker.wait([cont_1, cont_2])

    assert exit_codes == [8, 10]
def test_copy_to_volume(tmp_path):
    some_volume = docker.volume.create()
    docker.run(
        "busybox",
        ["touch", "/volume/dodo.txt"],
        remove=True,
        volumes=[(some_volume, "/volume")],
    )

    docker.volume.copy((some_volume, "dodo.txt"), tmp_path)
    assert (tmp_path / "dodo.txt").exists()
Beispiel #7
0
def init_tts():
    global TEXT_TO_SPEECH, TTS_PORT
    try:
        docker.run(TEXT_TO_SPEECH,
                   detach=True,
                   networks=['host'],
                   name='Prophets-Voice')
        print("TTS started in port {}".format(TTS_PORT))
    except Exception as e:
        docker.start('Prophets-Voice')
        print("TTS Already running")
Beispiel #8
0
def init_stt():
    global SPEECH_TO_TEXT, STT_PORT
    try:
        docker.run(SPEECH_TO_TEXT,
                   detach=True,
                   publish=[(STT_PORT, 5000)],
                   name='Prophets-Ears')
        print("STT started in port {}".format(STT_PORT))
    except:
        docker.start('Prophets-Ears')
        print('STT already running')
def test_volume_drivers():
    some_volume = docker.volume.create(
        driver="local",
        options=dict(type="tmpfs", device="tmpfs", o="size=100m,uid=1000"),
    )
    docker.run(
        "busybox",
        ["touch", "/dodo/dada"],
        volumes=[(some_volume, "/dodo")],
        remove=True,
    )
    docker.volume.remove(some_volume)
def test_context_manager():
    with pytest.raises(DockerException):
        with docker.network.create(random_name()) as my_net:
            docker.run(
                "busybox",
                ["ping", "idonotexistatall.com"],
                networks=[my_net],
                remove=True,
            )
            # an exception will be raised because the container will fail
            # but the network will be removed anyway.

    assert my_net not in docker.network.list()
Beispiel #11
0
def test_prune_prunes_container():
    stopped_container = docker.run("hello-world", remove=False, detach=True)
    running_container = docker.run(
        "ubuntu", ["sleep", "infinity"], remove=False, detach=True
    )

    assert stopped_container in docker.container.list(all=True)
    assert running_container in docker.container.list()

    docker.system.prune()

    assert stopped_container not in docker.container.list(all=True)
    assert running_container in docker.container.list()
    docker.container.remove(running_container, force=True)
Beispiel #12
0
def test_prune_prunes_volumes():
    some_volume = docker.volume.create(driver="local")
    docker.run(
        "ubuntu",
        ["touch", "/dodo/dada"],
        volumes=[(some_volume, "/dodo")],
        remove=False,
    )
    assert some_volume in docker.volume.list()

    docker.system.prune()
    assert some_volume in docker.volume.list()

    docker.system.prune(volumes=True)
    assert some_volume not in docker.volume.list()
Beispiel #13
0
def test_copy_to_volume_subdirectory(tmp_path):
    some_volume = docker.volume.create()
    docker.run(
        "busybox",
        [
            "sh",
            "-c",
            "mkdir -p /volume/subdir/subdir2 && touch /volume/subdir/subdir2/dodo.txt",
        ],
        remove=True,
        volumes=[(some_volume, "/volume")],
    )

    docker.volume.copy((some_volume, "subdir/subdir2"), tmp_path)
    assert (tmp_path / "subdir2/dodo.txt").exists()
Beispiel #14
0
def test_wait_single_container():
    cont_1 = docker.run("busybox", ["sh", "-c", "sleep 2 && exit 8"],
                        detach=True)
    with cont_1:
        exit_code = docker.wait(cont_1)

    assert exit_code == 8
Beispiel #15
0
def test_execute():
    my_container = docker.run("busybox:1", ["sleep", "infinity"],
                              detach=True,
                              remove=True)
    exec_result = docker.execute(my_container, ["echo", "dodo"])
    assert exec_result == "dodo"
    docker.kill(my_container)
def test_client(report_dir: Path, request: Any) -> None:
    try:
        print("Starting autobahn-testsuite server")
        autobahn_container = docker.run(
            detach=True,
            image="autobahn-testsuite",
            name="autobahn",
            publish=[(9001, 9001)],
            remove=True,
            volumes=[
                (f"{request.fspath.dirname}/client", "/config"),
                (f"{report_dir}", "/reports"),
            ],
        )
        print("Running aiohttp test client")
        client = subprocess.Popen(
            ["wait-for-it", "-s", "localhost:9001", "--"] + [sys.executable] +
            ["tests/autobahn/client/client.py"])
        client.wait()
    finally:
        print("Stopping client and server")
        client.terminate()
        client.wait()
        autobahn_container.stop()

    failed_messages = get_failed_tests(f"{report_dir}/clients", "aiohttp")

    assert not failed_messages, "\n".join("\n\t".join(
        f"{field}: {msg[field]}"
        for field in ("case", "description", "expectation", "expected",
                      "received")) for msg in failed_messages)
def _docker_registry(login=True):
    encrypted_password = docker.run(
        "mhenry07/apache2-utils",
        ["htpasswd", "-Bbn", "my_user", "my_password"],
        remove=True,
    )
    with tempfile.TemporaryDirectory() as tmp_path:
        tmp_path = Path(tmp_path)
        htpasswd_file = tmp_path / "htpasswd"
        htpasswd_file.write_text(encrypted_password)
        registry = docker.container.create(
            "registry:2",
            remove=True,
            envs=dict(
                REGISTRY_AUTH="htpasswd",
                REGISTRY_AUTH_HTPASSWD_REALM="Registry Realm",
                REGISTRY_AUTH_HTPASSWD_PATH="/tmp/htpasswd",
            ),
            publish=[(5000, 5000)],
        )
        with registry:
            registry.copy_to(htpasswd_file, "/tmp/htpasswd")
            registry.start()
            time.sleep(1.5)
            if login:
                docker.login("localhost:5000",
                             username="******",
                             password="******")
            yield "localhost:5000"
Beispiel #18
0
def test_simple_logs_stream_stdout_and_stderr():
    with docker.run("busybox:1", ["sh", "-c", ">&2 echo dodo && echo dudu"],
                    detach=True) as c:
        time.sleep(0.3)
        output = list(docker.container.logs(c, stream=True))

        # the order of stderr and stdout is not guaranteed.
        assert set(output) == {("stderr", b"dodo\n"), ("stdout", b"dudu\n")}
Beispiel #19
0
def test_restart():
    cmd = ["sleep", "infinity"]
    containers = [docker.run("busybox:1", cmd, detach=True) for _ in range(3)]
    docker.kill(containers)

    docker.restart(containers)
    for container in containers:
        assert container.state.running
Beispiel #20
0
def test_export_file(tmp_path):
    dest = tmp_path / "dodo.tar"
    with docker.run("ubuntu", ["sleep", "infinity"], detach=True,
                    remove=True) as c:
        c.export(dest)

    assert dest.exists()
    assert dest.stat().st_size > 10_000
Beispiel #21
0
def test_exec_privilged_flag():
    with docker.run("ubuntu:18.04", ["sleep", "infinity"],
                    detach=True,
                    remove=True) as c:
        c.execute(["apt-get", "update"])
        c.execute(["apt-get", "install", "-y", "iproute2"])
        c.execute(["ip", "link", "add", "dummy0", "type", "dummy"],
                  privileged=True)
        c.execute(["ip", "link", "delete", "dummy0"], privileged=True)
Beispiel #22
0
def test_exec_env_file(tmp_path):

    env_file = tmp_path / "variables.env"
    env_file.write_text("DODO=dada\n")

    with docker.run("ubuntu", ["sleep", "infinity"], detach=True,
                    remove=True) as c:
        result = c.execute(["bash", "-c", "echo $DODO"], env_files=[env_file])
    assert result == "dada"
Beispiel #23
0
def test_execute_stream():
    my_container = docker.run("busybox:1", ["sleep", "infinity"],
                              detach=True,
                              remove=True)
    exec_result = list(
        docker.execute(my_container, ["sh", "-c", ">&2 echo dodo"],
                       stream=True))
    assert exec_result == [("stderr", b"dodo\n")]
    docker.kill(my_container)
Beispiel #24
0
def test_docker_stats():
    with docker.run("busybox", ["sleep", "infinity"],
                    detach=True,
                    stop_timeout=1) as container:
        for stat in docker.stats():
            if stat.container_id == container.id:
                break
        assert stat.container_name == container.name
        assert stat.cpu_percentage <= 5
        assert stat.memory_used <= 100_000_000
Beispiel #25
0
def test_same_stream_run_create_start():
    python_code = """
import sys
sys.stdout.write("everything is fine\\n\\nhello world")
sys.stderr.write("Something is wrong!")
    """
    image = build_image_running(python_code)
    output_run = set(docker.run(image, remove=True, stream=True))
    container = docker.container.create(image, remove=True)
    output_create = set(container.start(attach=True, stream=True))
    assert output_run == output_create
Beispiel #26
0
def test_remove_anonymous_volume_too():
    container = docker.run("postgres:9.6.20-alpine", detach=True)

    volume_id = container.mounts[0].name
    volume = docker.volume.inspect(volume_id)

    with container:
        pass

    assert volume not in docker.volume.list()
    assert container not in docker.ps(all=True)
Beispiel #27
0
def test_container_run_with_random_port():
    with docker.run(
            "ubuntu",
        ["sleep", "infinity"],
            publish=[(90, )],
            remove=True,
            detach=True,
            stop_timeout=1,
    ) as container:
        assert container.network_settings.ports["90/tcp"][0][
            "HostPort"] is not None
Beispiel #28
0
def test_context_manager():
    container_name = random_name()
    with pytest.raises(ArithmeticError):
        with docker.run("busybox:1", ["sleep", "infinity"],
                        detach=True,
                        name=container_name):
            raise ArithmeticError

    assert container_name not in [
        x.name for x in docker.container.list(all=True)
    ]
Beispiel #29
0
def test_pause_unpause():
    container = docker.run("busybox", ["ping", "www.google.com"],
                           detach=True,
                           remove=True)

    with container:
        assert container.state.running
        container.pause()
        assert container.state.paused
        container.unpause()
        assert not container.state.paused
        assert container.state.running
Beispiel #30
0
def test_diff():
    my_container = docker.run("busybox:1", ["sleep", "infinity"],
                              detach=True,
                              remove=True)

    docker.execute(my_container, ["mkdir", "/some_path"])
    docker.execute(my_container, ["touch", "/some_file"])
    docker.execute(my_container, ["rm", "-rf", "/tmp"])

    diff = docker.diff(my_container)
    assert diff == {"/some_path": "A", "/some_file": "A", "/tmp": "D"}
    docker.kill(my_container)