|
2 | 2 | # Permissions are hereby granted under the terms of the MIT License:
|
3 | 3 | # https://opensource.org/licenses/MIT.
|
4 | 4 |
|
| 5 | +import contextlib |
| 6 | +import functools |
5 | 7 | import os
|
6 | 8 | import subprocess
|
7 | 9 | import sys
|
|
10 | 12 | import urllib
|
11 | 13 | import urllib.error
|
12 | 14 | import urllib.request
|
| 15 | +from typing import Callable |
13 | 16 |
|
14 | 17 | import moto.server
|
15 | 18 |
|
|
18 | 21 | MOTOSERVER_PATH = moto.server.__file__
|
19 | 22 | MOTOSERVER_ARGS = [sys.executable, MOTOSERVER_PATH]
|
20 | 23 |
|
| 24 | +# Mocked AWS environment variables for Moto. |
| 25 | +MOTOSERVER_ENV = { |
| 26 | + "AWS_ACCESS_KEY_ID": "testing", |
| 27 | + "AWS_SECRET_ACCESS_KEY": "testing", |
| 28 | + "AWS_SECURITY_TOKEN": "testing", |
| 29 | + "AWS_SESSION_TOKEN": "testing", |
| 30 | + "AWS_DEFAULT_REGION": "us-east-1", |
| 31 | + "AWS_ENDPOINT_URL_S3": MOTO_SERVER_ENDPOINT_URL, |
| 32 | +} |
| 33 | + |
21 | 34 |
|
22 | 35 | class S3Test(unittest.TestCase):
|
23 |
| - _moto_server = None |
| 36 | + _stop_moto_server = None |
24 | 37 |
|
25 | 38 | @classmethod
|
26 | 39 | def setUpClass(cls) -> None:
|
27 | 40 | super().setUpClass()
|
28 |
| - |
29 |
| - """Mocked AWS Credentials for moto.""" |
30 |
| - os.environ["AWS_ACCESS_KEY_ID"] = "testing" |
31 |
| - os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" |
32 |
| - os.environ["AWS_SECURITY_TOKEN"] = "testing" |
33 |
| - os.environ["AWS_SESSION_TOKEN"] = "testing" |
34 |
| - os.environ["AWS_DEFAULT_REGION"] = "us-east-1" |
35 |
| - |
36 |
| - cls._moto_server = subprocess.Popen(MOTOSERVER_ARGS) |
37 |
| - t0 = time.perf_counter() |
38 |
| - running = False |
39 |
| - while not running and time.perf_counter() - t0 < 60.0: |
40 |
| - try: |
41 |
| - with urllib.request.urlopen(MOTO_SERVER_ENDPOINT_URL, timeout=1.0): |
42 |
| - running = True |
43 |
| - print( |
44 |
| - f"moto_server started after {round(1000 * (time.perf_counter() - t0))} ms" |
45 |
| - ) |
46 |
| - |
47 |
| - except urllib.error.URLError as e: |
48 |
| - pass |
49 |
| - if not running: |
50 |
| - raise Exception( |
51 |
| - f"Failed to start moto server after {round(1000 * (time.perf_counter() - t0))} ms" |
52 |
| - ) |
| 41 | + cls._stop_moto_server = _start_moto_server() |
53 | 42 |
|
54 | 43 | def setUp(self) -> None:
|
55 |
| - # see https://github.com/spulec/moto/issues/2288 |
56 |
| - urllib.request.urlopen( |
57 |
| - urllib.request.Request( |
58 |
| - MOTO_SERVER_ENDPOINT_URL + "/moto-api/reset", method="POST" |
59 |
| - ) |
60 |
| - ) |
| 44 | + _reset_moto_server() |
61 | 45 |
|
62 | 46 | @classmethod
|
63 | 47 | def tearDownClass(cls) -> None:
|
64 |
| - cls._moto_server.kill() |
| 48 | + cls._stop_moto_server() |
65 | 49 | super().tearDownClass()
|
| 50 | + |
| 51 | + |
| 52 | +def s3_test(timeout: float = 60.0, ping_timeout: float = 1.0): |
| 53 | + """A decorator to run individual tests with a Moto S3 server. |
| 54 | +
|
| 55 | + The decorated tests receives the Moto Server's endpoint URL. |
| 56 | +
|
| 57 | + Args: |
| 58 | + timeout: |
| 59 | + Total time in seconds it may take to start the server. |
| 60 | + Raises if time is exceeded. |
| 61 | + ping_timeout: |
| 62 | + Timeout for individual ping requests trying to access the |
| 63 | + started moto server. |
| 64 | + The total number of pings is ``int(timeout / ping_timeout)``. |
| 65 | + """ |
| 66 | + |
| 67 | + def decorator(test_func): |
| 68 | + @functools.wraps(test_func) |
| 69 | + def wrapper(*args, **kwargs): |
| 70 | + stop_moto_server = _start_moto_server(timeout, ping_timeout) |
| 71 | + try: |
| 72 | + return test_func(*args, endpoint_url=MOTO_SERVER_ENDPOINT_URL, **kwargs) |
| 73 | + finally: |
| 74 | + stop_moto_server() |
| 75 | + |
| 76 | + return wrapper |
| 77 | + |
| 78 | + return decorator |
| 79 | + |
| 80 | + |
| 81 | +@contextlib.contextmanager |
| 82 | +def s3_test_server(timeout: float = 60.0, ping_timeout: float = 1.0) -> str: |
| 83 | + """A context manager that starts a Moto S3 server for testing. |
| 84 | +
|
| 85 | + Args: |
| 86 | + timeout: |
| 87 | + Total time in seconds it may take to start the server. |
| 88 | + Raises if time is exceeded. |
| 89 | + ping_timeout: |
| 90 | + Timeout for individual ping requests trying to access the |
| 91 | + started moto server. |
| 92 | + The total number of pings is ``int(timeout / ping_timeout)``. |
| 93 | +
|
| 94 | + Returns: |
| 95 | + The server's endpoint URL |
| 96 | +
|
| 97 | + Raises: |
| 98 | + Exception: If the server could not be started or |
| 99 | + if the service is not available after after |
| 100 | + *timeout* seconds. |
| 101 | + """ |
| 102 | + stop_moto_server = _start_moto_server(timeout=timeout, ping_timeout=ping_timeout) |
| 103 | + try: |
| 104 | + _reset_moto_server() |
| 105 | + yield MOTO_SERVER_ENDPOINT_URL |
| 106 | + finally: |
| 107 | + stop_moto_server() |
| 108 | + |
| 109 | + |
| 110 | +def _start_moto_server( |
| 111 | + timeout: float = 60.0, ping_timeout: float = 1.0 |
| 112 | +) -> Callable[[], None]: |
| 113 | + """Start a Moto S3 server for testing. |
| 114 | +
|
| 115 | + Args: |
| 116 | + timeout: |
| 117 | + Total time in seconds it may take to start the server. |
| 118 | + Raises if time is exceeded. |
| 119 | + ping_timeout: |
| 120 | + Timeout for individual ping requests trying to access the |
| 121 | + started moto server. |
| 122 | + The total number of pings is ``int(timeout / ping_timeout)``. |
| 123 | +
|
| 124 | + Returns: |
| 125 | + A function that stops the server and restores the environment. |
| 126 | +
|
| 127 | + Raises: |
| 128 | + Exception: If the server could not be started or |
| 129 | + if the service is not available after |
| 130 | + *timeout* seconds. |
| 131 | + """ |
| 132 | + |
| 133 | + prev_env: dict[str, str | None] = { |
| 134 | + k: os.environ.get(k) for k, v in MOTOSERVER_ENV.items() |
| 135 | + } |
| 136 | + os.environ.update(MOTOSERVER_ENV) |
| 137 | + |
| 138 | + moto_server = subprocess.Popen(MOTOSERVER_ARGS) |
| 139 | + t0 = time.perf_counter() |
| 140 | + running = False |
| 141 | + while not running and time.perf_counter() - t0 < timeout: |
| 142 | + try: |
| 143 | + with urllib.request.urlopen(MOTO_SERVER_ENDPOINT_URL, timeout=ping_timeout): |
| 144 | + running = True |
| 145 | + print( |
| 146 | + f"moto_server started after" |
| 147 | + f" {round(1000 * (time.perf_counter() - t0))} ms" |
| 148 | + ) |
| 149 | + |
| 150 | + except urllib.error.URLError: |
| 151 | + pass |
| 152 | + if not running: |
| 153 | + raise Exception( |
| 154 | + f"Failed to start moto server" |
| 155 | + f" after {round(1000 * (time.perf_counter() - t0))} ms" |
| 156 | + ) |
| 157 | + |
| 158 | + def stop_moto_server(): |
| 159 | + try: |
| 160 | + moto_server.kill() |
| 161 | + finally: |
| 162 | + # Restore environment variables |
| 163 | + for k, v in prev_env.items(): |
| 164 | + if v is None: |
| 165 | + del os.environ[k] |
| 166 | + else: |
| 167 | + os.environ[k] = v |
| 168 | + |
| 169 | + return stop_moto_server |
| 170 | + |
| 171 | + |
| 172 | +def _reset_moto_server(): |
| 173 | + # see https://github.com/spulec/moto/issues/2288 |
| 174 | + urllib.request.urlopen( |
| 175 | + urllib.request.Request( |
| 176 | + MOTO_SERVER_ENDPOINT_URL + "/moto-api/reset", method="POST" |
| 177 | + ) |
| 178 | + ) |
0 commit comments