-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathtest_01_provider_fastapi.py
230 lines (182 loc) · 7.33 KB
/
test_01_provider_fastapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""
Test the FastAPI provider with Pact.
This module tests the FastAPI provider defined in `src/fastapi.py` against the
mock consumer. The mock consumer is set up by Pact and will replay the requests
defined by the consumers. Pact will then validate that the provider responds
with the expected responses.
The provider will be expected to be in a given state in order to respond to
certain requests. For example, when fetching a user's information, the provider
will need to have a user with the given ID in the database. In order to avoid
side effects, the provider's database calls are mocked out using functionalities
from `unittest.mock`.
In order to set the provider into the correct state, this test module defines an
additional endpoint on the provider, in this case `/_pact/provider_states`.
Calls to this endpoint mock the relevant database calls to set the provider into
the correct state.
A good resource for understanding the provider tests is the [Pact Provider
Test](https://docs.pact.io/5-minute-getting-started-guide#scope-of-a-provider-pact-test)
section of the Pact documentation.
"""
from __future__ import annotations
import time
from datetime import datetime, timezone
from multiprocessing import Process
from typing import TYPE_CHECKING, Any, Optional
from unittest.mock import MagicMock
import pytest
import uvicorn
from pydantic import BaseModel
from yarl import URL
from examples.src.fastapi import User, app
from pact import Verifier # type: ignore[import-untyped]
if TYPE_CHECKING:
from collections.abc import Generator
PROVIDER_URL = URL("http://localhost:8080")
class ProviderState(BaseModel):
"""Define the provider state."""
consumer: str
state: str
@app.post("/_pact/provider_states")
async def mock_pact_provider_states(
state: ProviderState,
) -> dict[str, Optional[str]]:
"""
Define the provider state.
For Pact to be able to correctly test compliance with the contract, the
internal state of the provider needs to be set up correctly. Naively, this
would be achieved by setting up the database with the correct data for the
test, but this can be slow and error-prone. Instead this is best achieved by
mocking the relevant calls to the database so as to avoid any side effects.
For Pact to be able to correctly get the provider into the correct state,
this function is used to define an additional endpoint on the provider. This
endpoint is called by Pact before each test to ensure that the provider is
in the correct state.
"""
mapping = {
"user 123 doesn't exist": mock_user_123_doesnt_exist,
"user 123 exists": mock_user_123_exists,
"create user 124": mock_post_request_to_create_user,
"delete the user 124": mock_delete_request_to_delete_user,
}
mapping[state.state]()
return {"result": f"{state} set"}
def run_server() -> None:
"""
Run the FastAPI server.
This function is required to run the FastAPI server in a separate process. A
lambda cannot be used as the target of a `multiprocessing.Process` as it
cannot be pickled.
"""
host = PROVIDER_URL.host if PROVIDER_URL.host else "localhost"
port = PROVIDER_URL.port if PROVIDER_URL.port else 8080
uvicorn.run(app, host=host, port=port)
@pytest.fixture(scope="module")
def verifier() -> Generator[Verifier, Any, None]:
"""Set up the Pact verifier."""
proc = Process(target=run_server, daemon=True)
verifier = Verifier(
provider="UserProvider",
provider_base_url=str(PROVIDER_URL),
)
proc.start()
time.sleep(2)
yield verifier
proc.kill()
def mock_user_123_doesnt_exist() -> None:
"""Mock the database for the user 123 doesn't exist state."""
import examples.src.fastapi
examples.src.fastapi.FAKE_DB = MagicMock()
examples.src.fastapi.FAKE_DB.get.return_value = None
def mock_user_123_exists() -> None:
"""
Mock the database for the user 123 exists state.
You may notice that the return value here differs from the consumer's
expected response. This is because the consumer's expected response is
guided by what the consumer uses.
By using consumer-driven contracts and testing the provider against the
consumer's contract, we can ensure that the provider is what the consumer
needs. This allows the provider to safely evolve their API (by both adding
and removing fields) without fear of breaking the interactions with the
consumers.
"""
import examples.src.fastapi
mock_db = MagicMock()
mock_db.get.return_value = User(
id=123,
name="Verna Hampton",
email="[email protected]",
created_on=datetime.now(tz=timezone.utc),
ip_address="10.1.2.3",
hobbies=["hiking", "swimming"],
admin=False,
)
examples.src.fastapi.FAKE_DB = mock_db
def mock_post_request_to_create_user() -> None:
"""
Mock the database for the post request to create a user.
"""
import examples.src.fastapi
local_db: dict[int, User] = {}
def local_setitem(key: int, value: User) -> None:
local_db[key] = value
def local_getitem(key: int) -> User:
return local_db[key]
mock_db = MagicMock()
mock_db.__len__.return_value = 124
mock_db.__setitem__.side_effect = local_setitem
mock_db.__getitem__.side_effect = local_getitem
examples.src.fastapi.FAKE_DB = mock_db
def mock_delete_request_to_delete_user() -> None:
"""
Mock the database for the delete request to delete a user.
"""
import examples.src.fastapi
local_db = {
123: User(
id=123,
name="Verna Hampton",
email="[email protected]",
created_on=datetime.now(tz=timezone.utc),
ip_address="10.1.2.3",
hobbies=["hiking", "swimming"],
admin=False,
),
124: User(
id=124,
name="Jane Doe",
email="[email protected]",
created_on=datetime.now(tz=timezone.utc),
ip_address="10.1.2.5",
hobbies=["running", "dancing"],
admin=False,
),
}
def local_delitem(key: int) -> None:
del local_db[key]
def local_contains(key: int) -> bool:
return key in local_db
mock_db = MagicMock()
mock_db.__delitem__.side_effect = local_delitem
mock_db.__contains__.side_effect = local_contains
examples.src.fastapi.FAKE_DB = mock_db
def test_against_broker(broker: URL, verifier: Verifier) -> None:
"""
Test the provider against the broker.
The broker will be used to retrieve the contract, and the provider will be
tested against the contract.
As Pact is a consumer-driven, the provider is tested against the contract
defined by the consumer. The consumer defines the expected request to and
response from the provider.
For an example of the consumer's contract, see the consumer's tests.
"""
code, _ = verifier.verify_with_broker(
broker_url=str(broker),
# Despite the auth being set in the broker URL, we still need to pass
# the username and password to the verify_with_broker method.
broker_username=broker.user,
broker_password=broker.password,
publish_version="0.0.0",
publish_verification_results=True,
provider_states_setup_url=str(PROVIDER_URL / "_pact" / "provider_states"),
)
assert code == 0