|
| 1 | +from pathlib import Path |
1 | 2 | import subprocess |
2 | 3 | import pytest |
3 | 4 |
|
4 | | -from .util import random_string, find_free_port, docker_run, get_local_ip, wait_for_port |
| 5 | +import redis |
| 6 | + |
| 7 | +from .util import random_string, find_free_port, docker_run, wait_for_port |
5 | 8 |
|
6 | 9 |
|
7 | 10 | @pytest.fixture |
8 | | -def redis_port(): |
9 | | - container_name = "cog-test-redis-" + random_string(10) |
| 11 | +def docker_network(): |
| 12 | + name = "cog-test-" + random_string(10) |
| 13 | + subprocess.run(["docker", "network", "create", name]) |
| 14 | + yield name |
| 15 | + subprocess.run(["docker", "network", "rm", name]) |
| 16 | + |
| 17 | + |
| 18 | +@pytest.fixture |
| 19 | +def redis_port(docker_network): |
| 20 | + """Start a redis server inside the Docker network. |
| 21 | + Inside the network, it is available at redis:6379 |
| 22 | + Outside the network, it is available at localhost:redis_port |
| 23 | + """ |
10 | 24 | port = find_free_port() |
11 | 25 | with docker_run( |
12 | 26 | "redis", |
13 | | - name=container_name, |
| 27 | + net_alias="redis", |
| 28 | + network=docker_network, |
14 | 29 | publish=[{"host": port, "container": 6379}], |
15 | 30 | detach=True, |
16 | 31 | ): |
17 | | - wait_for_port(get_local_ip(), port) |
| 32 | + wait_for_port("localhost", port) |
18 | 33 | yield port |
19 | 34 |
|
20 | 35 |
|
| 36 | +@pytest.fixture |
| 37 | +def redis_client(redis_port): |
| 38 | + yield redis.Redis("localhost", redis_port) |
| 39 | + |
| 40 | + |
21 | 41 | @pytest.fixture |
22 | 42 | def docker_image(): |
23 | 43 | image = "cog-test-" + random_string(10) |
24 | 44 | yield image |
25 | 45 | subprocess.run(["docker", "rmi", "-f", image], check=False) |
| 46 | + |
| 47 | + |
| 48 | +@pytest.fixture |
| 49 | +def upload_server_image(): |
| 50 | + """ |
| 51 | + Build the upload server once for the test run. The image doesn't change. |
| 52 | + """ |
| 53 | + subprocess.run( |
| 54 | + ["docker", "build", "-t", "cog-test-upload-server", "."], |
| 55 | + cwd=Path(__file__).parent.parent / "upload_server", |
| 56 | + check=True, |
| 57 | + ) |
| 58 | + return "cog-test-upload-server" |
| 59 | + |
| 60 | + |
| 61 | +@pytest.fixture |
| 62 | +def upload_server(docker_network, upload_server_image, tmpdir_factory): |
| 63 | + """ |
| 64 | + Run a server that can be used to upload and download files from. |
| 65 | +
|
| 66 | + It is accessible at http://upload-server:5000 inside the network. The thing returned is the path for uploads. |
| 67 | + """ |
| 68 | + tmpdir = tmpdir_factory.mktemp("uploads") |
| 69 | + with docker_run( |
| 70 | + upload_server_image, |
| 71 | + net_alias="upload-server", |
| 72 | + network=docker_network, |
| 73 | + volumes=["-v", f"{tmpdir}:/uploads"], |
| 74 | + detach=True, |
| 75 | + ): |
| 76 | + yield tmpdir |
0 commit comments