api-bridgekeeper 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- api_bridgekeeper-0.1.0/LICENSE +201 -0
- api_bridgekeeper-0.1.0/PKG-INFO +96 -0
- api_bridgekeeper-0.1.0/README.md +79 -0
- api_bridgekeeper-0.1.0/api_bridgekeeper.egg-info/PKG-INFO +96 -0
- api_bridgekeeper-0.1.0/api_bridgekeeper.egg-info/SOURCES.txt +13 -0
- api_bridgekeeper-0.1.0/api_bridgekeeper.egg-info/dependency_links.txt +1 -0
- api_bridgekeeper-0.1.0/api_bridgekeeper.egg-info/requires.txt +7 -0
- api_bridgekeeper-0.1.0/api_bridgekeeper.egg-info/top_level.txt +1 -0
- api_bridgekeeper-0.1.0/bridgekeeper/__init__.py +4 -0
- api_bridgekeeper-0.1.0/bridgekeeper/checker.py +144 -0
- api_bridgekeeper-0.1.0/bridgekeeper/mocking.py +83 -0
- api_bridgekeeper-0.1.0/pyproject.toml +27 -0
- api_bridgekeeper-0.1.0/setup.cfg +4 -0
- api_bridgekeeper-0.1.0/tests/test_bridgekeeper.py +179 -0
- api_bridgekeeper-0.1.0/tests/test_mocking.py +68 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: api-bridgekeeper
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fail tests if APIs do not have input or output models
|
|
5
|
+
Author-email: Ashish Thomas Cherian <ufoundashish@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest; extra == "dev"
|
|
12
|
+
Requires-Dist: flask; extra == "dev"
|
|
13
|
+
Requires-Dist: fastapi; extra == "dev"
|
|
14
|
+
Requires-Dist: pydantic; extra == "dev"
|
|
15
|
+
Requires-Dist: mypy; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# Bridgekeeper
|
|
19
|
+
Fail tests if API's do not have input or output models
|
|
20
|
+
|
|
21
|
+
**Supports:**
|
|
22
|
+
- FastAPI
|
|
23
|
+
- Flask
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
You can use Bridgekeeper to validate your API endpoints and ensure they have explicitly typed input and output models.
|
|
28
|
+
|
|
29
|
+
### Basic Example
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from fastapi import FastAPI
|
|
33
|
+
from bridgekeeper import check_models
|
|
34
|
+
|
|
35
|
+
app = FastAPI()
|
|
36
|
+
|
|
37
|
+
@app.get("/items/{item_id}")
|
|
38
|
+
def read_item(item_id: int) -> dict:
|
|
39
|
+
return {"item_id": item_id}
|
|
40
|
+
|
|
41
|
+
# Run the checker against your initialized app
|
|
42
|
+
results = check_models(app)
|
|
43
|
+
|
|
44
|
+
# `results` will contain a list of endpoints missing type models
|
|
45
|
+
print(results)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Options
|
|
49
|
+
|
|
50
|
+
`check_models(app, allow_list=None, check_only=None)`
|
|
51
|
+
|
|
52
|
+
- **`allow_list` (list of strings, optional)**: A list of API paths to ignore (e.g., `["/health", "/metrics"]`). If an endpoint matches a path in the list, it is skipped.
|
|
53
|
+
- **`check_only` (literal string, optional)**: If you only want to validate inputs or outputs exclusively, pass `"request"` or `"response"`.
|
|
54
|
+
- **`allow_any` (boolean, optional)**: Defaults to `False`. When `False`, explicitly typing a parameter or return type as `typing.Any` is flagged as missing a strict model. Set to `True` if you want to allow `Any` as a valid type hint.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
results = check_models(
|
|
58
|
+
app,
|
|
59
|
+
allow_list=["/health"],
|
|
60
|
+
check_only="response", # Will strictly look for missing return types
|
|
61
|
+
allow_any=False # typing.Any will be rejected
|
|
62
|
+
)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Handling Complex Apps (Databases/Secrets)
|
|
66
|
+
|
|
67
|
+
If your FastAPI or Flask app connects to a database (like Postgres) or external service (like Redis) during initialization, trying to run `bridgekeeper` in a GitHub Action might crash when the app imports, before the tests even run.
|
|
68
|
+
|
|
69
|
+
Bridgekeeper provides generic mocking utilities to safely bypass these side effects. For highly complex apps where you don't want to list out every single dependency, you can use `auto_mock_missing=True` to seamlessly mock any module that isn't installed!
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from bridgekeeper import mock_modules, mock_env
|
|
73
|
+
|
|
74
|
+
# 1. Mock critical environment variables
|
|
75
|
+
mock_env({
|
|
76
|
+
"DATABASE_URL": "sqlite:///:memory:",
|
|
77
|
+
"SECRET_KEY": "dummy_secret_for_ci"
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
# 2. Automatically mock ANY missing dependency!
|
|
81
|
+
# This is extremely useful if you don't want to install heavy libraries (like SQLAlchemy, boto3, etc.)
|
|
82
|
+
# just to run a quick static analysis check.
|
|
83
|
+
mock_modules(auto_mock_missing=True)
|
|
84
|
+
|
|
85
|
+
# You can also explicitly mock specific modules with custom fakes:
|
|
86
|
+
# mock_modules({"app.core.db": PostgresTestDb}, auto_mock_missing=True)
|
|
87
|
+
|
|
88
|
+
# 3. Now it is safe to import the app
|
|
89
|
+
from myapp.main import app
|
|
90
|
+
from bridgekeeper import check_models
|
|
91
|
+
|
|
92
|
+
results = check_models(app)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Why the name bridgekeeper?
|
|
96
|
+
He guards the [Bridge of Death](https://montypython.fandom.com/wiki/Bridge_of_Death) and requires travelers to answer "questions three" before crossing safely.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Bridgekeeper
|
|
2
|
+
Fail tests if API's do not have input or output models
|
|
3
|
+
|
|
4
|
+
**Supports:**
|
|
5
|
+
- FastAPI
|
|
6
|
+
- Flask
|
|
7
|
+
|
|
8
|
+
## Usage
|
|
9
|
+
|
|
10
|
+
You can use Bridgekeeper to validate your API endpoints and ensure they have explicitly typed input and output models.
|
|
11
|
+
|
|
12
|
+
### Basic Example
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from fastapi import FastAPI
|
|
16
|
+
from bridgekeeper import check_models
|
|
17
|
+
|
|
18
|
+
app = FastAPI()
|
|
19
|
+
|
|
20
|
+
@app.get("/items/{item_id}")
|
|
21
|
+
def read_item(item_id: int) -> dict:
|
|
22
|
+
return {"item_id": item_id}
|
|
23
|
+
|
|
24
|
+
# Run the checker against your initialized app
|
|
25
|
+
results = check_models(app)
|
|
26
|
+
|
|
27
|
+
# `results` will contain a list of endpoints missing type models
|
|
28
|
+
print(results)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Options
|
|
32
|
+
|
|
33
|
+
`check_models(app, allow_list=None, check_only=None)`
|
|
34
|
+
|
|
35
|
+
- **`allow_list` (list of strings, optional)**: A list of API paths to ignore (e.g., `["/health", "/metrics"]`). If an endpoint matches a path in the list, it is skipped.
|
|
36
|
+
- **`check_only` (literal string, optional)**: If you only want to validate inputs or outputs exclusively, pass `"request"` or `"response"`.
|
|
37
|
+
- **`allow_any` (boolean, optional)**: Defaults to `False`. When `False`, explicitly typing a parameter or return type as `typing.Any` is flagged as missing a strict model. Set to `True` if you want to allow `Any` as a valid type hint.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
results = check_models(
|
|
41
|
+
app,
|
|
42
|
+
allow_list=["/health"],
|
|
43
|
+
check_only="response", # Will strictly look for missing return types
|
|
44
|
+
allow_any=False # typing.Any will be rejected
|
|
45
|
+
)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Handling Complex Apps (Databases/Secrets)
|
|
49
|
+
|
|
50
|
+
If your FastAPI or Flask app connects to a database (like Postgres) or external service (like Redis) during initialization, trying to run `bridgekeeper` in a GitHub Action might crash when the app imports, before the tests even run.
|
|
51
|
+
|
|
52
|
+
Bridgekeeper provides generic mocking utilities to safely bypass these side effects. For highly complex apps where you don't want to list out every single dependency, you can use `auto_mock_missing=True` to seamlessly mock any module that isn't installed!
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from bridgekeeper import mock_modules, mock_env
|
|
56
|
+
|
|
57
|
+
# 1. Mock critical environment variables
|
|
58
|
+
mock_env({
|
|
59
|
+
"DATABASE_URL": "sqlite:///:memory:",
|
|
60
|
+
"SECRET_KEY": "dummy_secret_for_ci"
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
# 2. Automatically mock ANY missing dependency!
|
|
64
|
+
# This is extremely useful if you don't want to install heavy libraries (like SQLAlchemy, boto3, etc.)
|
|
65
|
+
# just to run a quick static analysis check.
|
|
66
|
+
mock_modules(auto_mock_missing=True)
|
|
67
|
+
|
|
68
|
+
# You can also explicitly mock specific modules with custom fakes:
|
|
69
|
+
# mock_modules({"app.core.db": PostgresTestDb}, auto_mock_missing=True)
|
|
70
|
+
|
|
71
|
+
# 3. Now it is safe to import the app
|
|
72
|
+
from myapp.main import app
|
|
73
|
+
from bridgekeeper import check_models
|
|
74
|
+
|
|
75
|
+
results = check_models(app)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Why the name bridgekeeper?
|
|
79
|
+
He guards the [Bridge of Death](https://montypython.fandom.com/wiki/Bridge_of_Death) and requires travelers to answer "questions three" before crossing safely.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: api-bridgekeeper
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fail tests if APIs do not have input or output models
|
|
5
|
+
Author-email: Ashish Thomas Cherian <ufoundashish@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest; extra == "dev"
|
|
12
|
+
Requires-Dist: flask; extra == "dev"
|
|
13
|
+
Requires-Dist: fastapi; extra == "dev"
|
|
14
|
+
Requires-Dist: pydantic; extra == "dev"
|
|
15
|
+
Requires-Dist: mypy; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# Bridgekeeper
|
|
19
|
+
Fail tests if API's do not have input or output models
|
|
20
|
+
|
|
21
|
+
**Supports:**
|
|
22
|
+
- FastAPI
|
|
23
|
+
- Flask
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
You can use Bridgekeeper to validate your API endpoints and ensure they have explicitly typed input and output models.
|
|
28
|
+
|
|
29
|
+
### Basic Example
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from fastapi import FastAPI
|
|
33
|
+
from bridgekeeper import check_models
|
|
34
|
+
|
|
35
|
+
app = FastAPI()
|
|
36
|
+
|
|
37
|
+
@app.get("/items/{item_id}")
|
|
38
|
+
def read_item(item_id: int) -> dict:
|
|
39
|
+
return {"item_id": item_id}
|
|
40
|
+
|
|
41
|
+
# Run the checker against your initialized app
|
|
42
|
+
results = check_models(app)
|
|
43
|
+
|
|
44
|
+
# `results` will contain a list of endpoints missing type models
|
|
45
|
+
print(results)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Options
|
|
49
|
+
|
|
50
|
+
`check_models(app, allow_list=None, check_only=None)`
|
|
51
|
+
|
|
52
|
+
- **`allow_list` (list of strings, optional)**: A list of API paths to ignore (e.g., `["/health", "/metrics"]`). If an endpoint matches a path in the list, it is skipped.
|
|
53
|
+
- **`check_only` (literal string, optional)**: If you only want to validate inputs or outputs exclusively, pass `"request"` or `"response"`.
|
|
54
|
+
- **`allow_any` (boolean, optional)**: Defaults to `False`. When `False`, explicitly typing a parameter or return type as `typing.Any` is flagged as missing a strict model. Set to `True` if you want to allow `Any` as a valid type hint.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
results = check_models(
|
|
58
|
+
app,
|
|
59
|
+
allow_list=["/health"],
|
|
60
|
+
check_only="response", # Will strictly look for missing return types
|
|
61
|
+
allow_any=False # typing.Any will be rejected
|
|
62
|
+
)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Handling Complex Apps (Databases/Secrets)
|
|
66
|
+
|
|
67
|
+
If your FastAPI or Flask app connects to a database (like Postgres) or external service (like Redis) during initialization, trying to run `bridgekeeper` in a GitHub Action might crash when the app imports, before the tests even run.
|
|
68
|
+
|
|
69
|
+
Bridgekeeper provides generic mocking utilities to safely bypass these side effects. For highly complex apps where you don't want to list out every single dependency, you can use `auto_mock_missing=True` to seamlessly mock any module that isn't installed!
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from bridgekeeper import mock_modules, mock_env
|
|
73
|
+
|
|
74
|
+
# 1. Mock critical environment variables
|
|
75
|
+
mock_env({
|
|
76
|
+
"DATABASE_URL": "sqlite:///:memory:",
|
|
77
|
+
"SECRET_KEY": "dummy_secret_for_ci"
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
# 2. Automatically mock ANY missing dependency!
|
|
81
|
+
# This is extremely useful if you don't want to install heavy libraries (like SQLAlchemy, boto3, etc.)
|
|
82
|
+
# just to run a quick static analysis check.
|
|
83
|
+
mock_modules(auto_mock_missing=True)
|
|
84
|
+
|
|
85
|
+
# You can also explicitly mock specific modules with custom fakes:
|
|
86
|
+
# mock_modules({"app.core.db": PostgresTestDb}, auto_mock_missing=True)
|
|
87
|
+
|
|
88
|
+
# 3. Now it is safe to import the app
|
|
89
|
+
from myapp.main import app
|
|
90
|
+
from bridgekeeper import check_models
|
|
91
|
+
|
|
92
|
+
results = check_models(app)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Why the name bridgekeeper?
|
|
96
|
+
He guards the [Bridge of Death](https://montypython.fandom.com/wiki/Bridge_of_Death) and requires travelers to answer "questions three" before crossing safely.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
api_bridgekeeper.egg-info/PKG-INFO
|
|
5
|
+
api_bridgekeeper.egg-info/SOURCES.txt
|
|
6
|
+
api_bridgekeeper.egg-info/dependency_links.txt
|
|
7
|
+
api_bridgekeeper.egg-info/requires.txt
|
|
8
|
+
api_bridgekeeper.egg-info/top_level.txt
|
|
9
|
+
bridgekeeper/__init__.py
|
|
10
|
+
bridgekeeper/checker.py
|
|
11
|
+
bridgekeeper/mocking.py
|
|
12
|
+
tests/test_bridgekeeper.py
|
|
13
|
+
tests/test_mocking.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
bridgekeeper
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import os
|
|
3
|
+
import typing
|
|
4
|
+
from typing import Any, List, Dict, Optional, Literal, TypedDict, Callable
|
|
5
|
+
|
|
6
|
+
class MissingResult(TypedDict):
|
|
7
|
+
api: str
|
|
8
|
+
file: str
|
|
9
|
+
missing: List[str]
|
|
10
|
+
|
|
11
|
+
def _get_relative_path(func: Callable[..., Any]) -> str:
|
|
12
|
+
try:
|
|
13
|
+
# Unwrap standard decorators
|
|
14
|
+
func = inspect.unwrap(func)
|
|
15
|
+
# Unwrap functools.partial
|
|
16
|
+
if hasattr(func, 'func'):
|
|
17
|
+
func = func.func
|
|
18
|
+
abs_path = inspect.getfile(func)
|
|
19
|
+
return os.path.relpath(abs_path, os.getcwd())
|
|
20
|
+
except (TypeError, ValueError):
|
|
21
|
+
return "unknown"
|
|
22
|
+
|
|
23
|
+
def _check_missing(func: Callable[..., Any], allow_any: bool) -> List[str]:
|
|
24
|
+
missing: List[str] = []
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
# Unwrap function if it's wrapped (common in Flask decorators)
|
|
28
|
+
unwrapped_func = inspect.unwrap(func)
|
|
29
|
+
sig = inspect.signature(unwrapped_func)
|
|
30
|
+
except (ValueError, TypeError):
|
|
31
|
+
return []
|
|
32
|
+
|
|
33
|
+
# Check input types
|
|
34
|
+
missing_request = False
|
|
35
|
+
for param_name, param in sig.parameters.items():
|
|
36
|
+
if param_name in ('self', 'cls', 'request', 'response'):
|
|
37
|
+
continue
|
|
38
|
+
if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
|
|
39
|
+
continue
|
|
40
|
+
if param.annotation == inspect.Parameter.empty:
|
|
41
|
+
missing_request = True
|
|
42
|
+
break
|
|
43
|
+
if not allow_any and param.annotation is typing.Any:
|
|
44
|
+
missing_request = True
|
|
45
|
+
break
|
|
46
|
+
|
|
47
|
+
if missing_request:
|
|
48
|
+
missing.append("request")
|
|
49
|
+
|
|
50
|
+
# Check return type
|
|
51
|
+
if sig.return_annotation == inspect.Signature.empty:
|
|
52
|
+
missing.append("response")
|
|
53
|
+
elif not allow_any and sig.return_annotation is typing.Any:
|
|
54
|
+
missing.append("response")
|
|
55
|
+
|
|
56
|
+
return missing
|
|
57
|
+
|
|
58
|
+
def check_models(
|
|
59
|
+
app: Any,
|
|
60
|
+
allow_list: Optional[List[str]] = None,
|
|
61
|
+
check_only: Optional[Literal["request", "response"]] = None,
|
|
62
|
+
allow_any: bool = False
|
|
63
|
+
) -> List[MissingResult]:
|
|
64
|
+
"""
|
|
65
|
+
Checks if API routes have input (request) and output (response) type annotations.
|
|
66
|
+
|
|
67
|
+
:param app: The FastAPI or Flask application instance.
|
|
68
|
+
:param allow_list: A list of API paths to ignore (e.g., ["/health"]).
|
|
69
|
+
:param check_only: If specified, restricts the check to either "request" or "response" only.
|
|
70
|
+
:param allow_any: If False, endpoints using `typing.Any` for models will be flagged as missing.
|
|
71
|
+
:return: List of dictionaries with missing annotations.
|
|
72
|
+
"""
|
|
73
|
+
if allow_list is None:
|
|
74
|
+
allow_list = []
|
|
75
|
+
|
|
76
|
+
results: List[MissingResult] = []
|
|
77
|
+
|
|
78
|
+
def process_missing(api_path: str, func: Callable[..., Any], explicit_has_response: bool = False) -> None:
|
|
79
|
+
missing = _check_missing(func, allow_any)
|
|
80
|
+
|
|
81
|
+
if explicit_has_response and 'response' in missing:
|
|
82
|
+
missing.remove('response')
|
|
83
|
+
|
|
84
|
+
if check_only:
|
|
85
|
+
# Filter the missing list based on check_only
|
|
86
|
+
missing = [m for m in missing if m == check_only]
|
|
87
|
+
|
|
88
|
+
if missing:
|
|
89
|
+
results.append({
|
|
90
|
+
"api": api_path,
|
|
91
|
+
"file": _get_relative_path(func),
|
|
92
|
+
"missing": missing
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
if hasattr(app, 'url_map') and hasattr(app, 'view_functions'):
|
|
96
|
+
for rule in app.url_map.iter_rules():
|
|
97
|
+
api_path = rule.rule
|
|
98
|
+
if api_path in allow_list:
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
endpoint = rule.endpoint
|
|
102
|
+
if endpoint == 'static':
|
|
103
|
+
continue
|
|
104
|
+
|
|
105
|
+
view_func = app.view_functions.get(endpoint)
|
|
106
|
+
if not view_func:
|
|
107
|
+
continue
|
|
108
|
+
|
|
109
|
+
process_missing(api_path, view_func)
|
|
110
|
+
|
|
111
|
+
elif hasattr(app, 'routes'):
|
|
112
|
+
def _process_routes(routes, prefix=''):
|
|
113
|
+
for route in routes:
|
|
114
|
+
route_path = prefix + getattr(route, 'path', '')
|
|
115
|
+
|
|
116
|
+
# FastAPI / Starlette Mount or IncludedRouter
|
|
117
|
+
if hasattr(route, 'routes'):
|
|
118
|
+
_process_routes(route.routes, route_path)
|
|
119
|
+
continue
|
|
120
|
+
elif hasattr(route, 'app') and hasattr(route.app, 'routes'):
|
|
121
|
+
_process_routes(route.app.routes, route_path)
|
|
122
|
+
continue
|
|
123
|
+
elif hasattr(route, 'include_context') and hasattr(route, 'original_router') and hasattr(route.original_router, 'routes'):
|
|
124
|
+
included_prefix = getattr(route.include_context, 'prefix', '')
|
|
125
|
+
_process_routes(route.original_router.routes, prefix + included_prefix)
|
|
126
|
+
continue
|
|
127
|
+
elif hasattr(route, 'original_router') and hasattr(route.original_router, 'routes'):
|
|
128
|
+
_process_routes(route.original_router.routes, route_path)
|
|
129
|
+
continue
|
|
130
|
+
|
|
131
|
+
if not hasattr(route, 'endpoint'):
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
if route_path in allow_list:
|
|
135
|
+
continue
|
|
136
|
+
|
|
137
|
+
endpoint = getattr(route, 'endpoint')
|
|
138
|
+
has_response_model = getattr(route, 'response_model', None) is not None
|
|
139
|
+
|
|
140
|
+
process_missing(route_path, endpoint, explicit_has_response=has_response_model)
|
|
141
|
+
|
|
142
|
+
_process_routes(getattr(app, 'routes', []))
|
|
143
|
+
|
|
144
|
+
return results
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
from typing import Dict, List, Union, Any, Optional
|
|
4
|
+
from unittest.mock import MagicMock
|
|
5
|
+
from importlib.abc import MetaPathFinder, Loader
|
|
6
|
+
from importlib.machinery import ModuleSpec
|
|
7
|
+
|
|
8
|
+
class _MockLoader(Loader):
|
|
9
|
+
def __init__(self, mock_obj=None):
|
|
10
|
+
self.mock_obj = mock_obj
|
|
11
|
+
|
|
12
|
+
def create_module(self, spec):
|
|
13
|
+
if self.mock_obj is not None:
|
|
14
|
+
return self.mock_obj
|
|
15
|
+
m = MagicMock()
|
|
16
|
+
m.__path__ = []
|
|
17
|
+
m.__spec__ = None
|
|
18
|
+
m.__version__ = "1.0.0"
|
|
19
|
+
return m
|
|
20
|
+
|
|
21
|
+
def exec_module(self, module):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
class _MockFinder(MetaPathFinder):
|
|
25
|
+
def __init__(self, prefixes: List[str], custom_mocks: Dict[str, Any]):
|
|
26
|
+
self.prefixes = prefixes
|
|
27
|
+
self.custom_mocks = custom_mocks
|
|
28
|
+
|
|
29
|
+
def find_spec(self, fullname, path, target=None):
|
|
30
|
+
if fullname in self.custom_mocks:
|
|
31
|
+
return ModuleSpec(fullname, _MockLoader(self.custom_mocks[fullname]))
|
|
32
|
+
|
|
33
|
+
for prefix in self.prefixes:
|
|
34
|
+
if fullname == prefix or fullname.startswith(prefix + "."):
|
|
35
|
+
return ModuleSpec(fullname, _MockLoader())
|
|
36
|
+
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
class _FallbackMockFinder(MetaPathFinder):
|
|
40
|
+
"""
|
|
41
|
+
A fallback finder that returns a mock for any missing module.
|
|
42
|
+
Because it's appended to the end of sys.meta_path, it only catches
|
|
43
|
+
modules that genuinely failed to load via standard finders.
|
|
44
|
+
"""
|
|
45
|
+
def find_spec(self, fullname, path, target=None):
|
|
46
|
+
return ModuleSpec(fullname, _MockLoader())
|
|
47
|
+
|
|
48
|
+
def mock_modules(modules: Optional[Union[List[str], Dict[str, Any]]] = None, auto_mock_missing: bool = False) -> None:
|
|
49
|
+
"""
|
|
50
|
+
Mock heavy modules (like databases, redis, etc.) before importing the app.
|
|
51
|
+
Automatically intercepts submodules (e.g. mocking 'boto3' also mocks 'boto3.client').
|
|
52
|
+
|
|
53
|
+
:param modules: A list of module strings to mock automatically with MagicMock,
|
|
54
|
+
or a dictionary mapping module strings to custom mock objects.
|
|
55
|
+
:param auto_mock_missing: If True, appends a fallback finder that automatically
|
|
56
|
+
mocks ANY missing module.
|
|
57
|
+
"""
|
|
58
|
+
prefixes = []
|
|
59
|
+
custom_mocks = {}
|
|
60
|
+
|
|
61
|
+
if modules:
|
|
62
|
+
if isinstance(modules, list):
|
|
63
|
+
prefixes = modules
|
|
64
|
+
elif isinstance(modules, dict):
|
|
65
|
+
for k, v in modules.items():
|
|
66
|
+
if v is None:
|
|
67
|
+
prefixes.append(k)
|
|
68
|
+
else:
|
|
69
|
+
custom_mocks[k] = v
|
|
70
|
+
|
|
71
|
+
sys.meta_path.insert(0, _MockFinder(prefixes, custom_mocks))
|
|
72
|
+
|
|
73
|
+
if auto_mock_missing:
|
|
74
|
+
sys.meta_path.append(_FallbackMockFinder())
|
|
75
|
+
|
|
76
|
+
def mock_env(env_vars: Dict[str, str]) -> None:
|
|
77
|
+
"""
|
|
78
|
+
Mock environment variables before importing the app.
|
|
79
|
+
|
|
80
|
+
:param env_vars: A dictionary of environment variable keys and values.
|
|
81
|
+
"""
|
|
82
|
+
for key, value in env_vars.items():
|
|
83
|
+
os.environ[key] = value
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "api-bridgekeeper"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Fail tests if APIs do not have input or output models"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Ashish Thomas Cherian", email = "ufoundashish@gmail.com" }
|
|
14
|
+
]
|
|
15
|
+
dependencies = []
|
|
16
|
+
|
|
17
|
+
[project.optional-dependencies]
|
|
18
|
+
dev = [
|
|
19
|
+
"pytest",
|
|
20
|
+
"flask",
|
|
21
|
+
"fastapi",
|
|
22
|
+
"pydantic",
|
|
23
|
+
"mypy"
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import typing
|
|
3
|
+
from typing import Any, List, Dict
|
|
4
|
+
from bridgekeeper import check_models
|
|
5
|
+
from bridgekeeper.checker import MissingResult
|
|
6
|
+
|
|
7
|
+
# Mock FastAPI to avoid hard dependency in tests if missing
|
|
8
|
+
class MockAPIRoute:
|
|
9
|
+
def __init__(self, path: str, endpoint: typing.Callable[..., Any], response_model: typing.Optional[str] = None):
|
|
10
|
+
self.path = path
|
|
11
|
+
self.endpoint = endpoint
|
|
12
|
+
self.response_model = response_model
|
|
13
|
+
|
|
14
|
+
class MockFastAPI:
|
|
15
|
+
def __init__(self, routes: List[MockAPIRoute]):
|
|
16
|
+
self.routes = routes
|
|
17
|
+
|
|
18
|
+
# Mock Flask
|
|
19
|
+
class MockRule:
|
|
20
|
+
def __init__(self, rule: str, endpoint: str):
|
|
21
|
+
self.rule = rule
|
|
22
|
+
self.endpoint = endpoint
|
|
23
|
+
|
|
24
|
+
class MockUrlMap:
|
|
25
|
+
def __init__(self, rules: List[MockRule]):
|
|
26
|
+
self.rules = rules
|
|
27
|
+
def iter_rules(self) -> List[MockRule]:
|
|
28
|
+
return self.rules
|
|
29
|
+
|
|
30
|
+
class MockFlask:
|
|
31
|
+
def __init__(self, rules: List[MockRule], view_functions: Dict[str, typing.Callable[..., Any]]):
|
|
32
|
+
self.url_map = MockUrlMap(rules)
|
|
33
|
+
self.view_functions = view_functions
|
|
34
|
+
|
|
35
|
+
# Test functions
|
|
36
|
+
def perfect_func(item: str) -> str:
|
|
37
|
+
return item
|
|
38
|
+
|
|
39
|
+
def missing_return(item: str) -> Any:
|
|
40
|
+
return item
|
|
41
|
+
|
|
42
|
+
def missing_input(item: Any) -> str:
|
|
43
|
+
return str(item)
|
|
44
|
+
|
|
45
|
+
def missing_both(item: Any) -> Any:
|
|
46
|
+
return item
|
|
47
|
+
|
|
48
|
+
# We need to remove the return annotations for missing tests to trigger the logic.
|
|
49
|
+
# Python signatures are dynamic, let's redefine without hints.
|
|
50
|
+
def missing_return_real(item: str):
|
|
51
|
+
return item
|
|
52
|
+
|
|
53
|
+
def missing_input_real(item) -> str:
|
|
54
|
+
return item
|
|
55
|
+
|
|
56
|
+
def missing_both_real(item):
|
|
57
|
+
return item
|
|
58
|
+
|
|
59
|
+
def test_fastapi_checker() -> None:
|
|
60
|
+
routes = [
|
|
61
|
+
MockAPIRoute("/perfect", perfect_func),
|
|
62
|
+
MockAPIRoute("/missing_return", missing_return_real),
|
|
63
|
+
MockAPIRoute("/missing_input", missing_input_real),
|
|
64
|
+
MockAPIRoute("/missing_both", missing_both_real),
|
|
65
|
+
MockAPIRoute("/with_response_model", missing_return_real, response_model="SomeModel"),
|
|
66
|
+
]
|
|
67
|
+
app = MockFastAPI(routes)
|
|
68
|
+
|
|
69
|
+
results = check_models(app)
|
|
70
|
+
|
|
71
|
+
assert len(results) == 3
|
|
72
|
+
|
|
73
|
+
assert results[0]['api'] == "/missing_return"
|
|
74
|
+
assert results[0]['missing'] == ["response"]
|
|
75
|
+
|
|
76
|
+
assert results[1]['api'] == "/missing_input"
|
|
77
|
+
assert results[1]['missing'] == ["request"]
|
|
78
|
+
|
|
79
|
+
assert results[2]['api'] == "/missing_both"
|
|
80
|
+
assert set(results[2]['missing']) == {"request", "response"}
|
|
81
|
+
|
|
82
|
+
def test_fastapi_allow_list() -> None:
|
|
83
|
+
routes = [
|
|
84
|
+
MockAPIRoute("/missing_both", missing_both_real),
|
|
85
|
+
MockAPIRoute("/ignored", missing_both_real),
|
|
86
|
+
]
|
|
87
|
+
app = MockFastAPI(routes)
|
|
88
|
+
|
|
89
|
+
results = check_models(app, allow_list=["/ignored"])
|
|
90
|
+
assert len(results) == 1
|
|
91
|
+
assert results[0]['api'] == "/missing_both"
|
|
92
|
+
|
|
93
|
+
def test_fastapi_check_only_request() -> None:
|
|
94
|
+
routes = [
|
|
95
|
+
MockAPIRoute("/perfect", perfect_func),
|
|
96
|
+
MockAPIRoute("/missing_return", missing_return_real),
|
|
97
|
+
MockAPIRoute("/missing_input", missing_input_real),
|
|
98
|
+
MockAPIRoute("/missing_both", missing_both_real),
|
|
99
|
+
]
|
|
100
|
+
app = MockFastAPI(routes)
|
|
101
|
+
|
|
102
|
+
results = check_models(app, check_only="request")
|
|
103
|
+
|
|
104
|
+
# Missing return should be ignored now
|
|
105
|
+
assert len(results) == 2
|
|
106
|
+
|
|
107
|
+
assert results[0]['api'] == "/missing_input"
|
|
108
|
+
assert results[0]['missing'] == ["request"]
|
|
109
|
+
|
|
110
|
+
assert results[1]['api'] == "/missing_both"
|
|
111
|
+
assert results[1]['missing'] == ["request"]
|
|
112
|
+
|
|
113
|
+
def test_fastapi_check_only_response() -> None:
|
|
114
|
+
routes = [
|
|
115
|
+
MockAPIRoute("/perfect", perfect_func),
|
|
116
|
+
MockAPIRoute("/missing_return", missing_return_real),
|
|
117
|
+
MockAPIRoute("/missing_input", missing_input_real),
|
|
118
|
+
MockAPIRoute("/missing_both", missing_both_real),
|
|
119
|
+
]
|
|
120
|
+
app = MockFastAPI(routes)
|
|
121
|
+
|
|
122
|
+
results = check_models(app, check_only="response")
|
|
123
|
+
|
|
124
|
+
# Missing input should be ignored now
|
|
125
|
+
assert len(results) == 2
|
|
126
|
+
|
|
127
|
+
assert results[0]['api'] == "/missing_return"
|
|
128
|
+
assert results[0]['missing'] == ["response"]
|
|
129
|
+
|
|
130
|
+
assert results[1]['api'] == "/missing_both"
|
|
131
|
+
assert results[1]['missing'] == ["response"]
|
|
132
|
+
|
|
133
|
+
def test_flask_checker() -> None:
|
|
134
|
+
rules = [
|
|
135
|
+
MockRule("/perfect", "perfect_func"),
|
|
136
|
+
MockRule("/missing_return", "missing_return_real"),
|
|
137
|
+
MockRule("/static", "static"),
|
|
138
|
+
]
|
|
139
|
+
view_functions: Dict[str, typing.Callable[..., Any]] = {
|
|
140
|
+
"perfect_func": perfect_func,
|
|
141
|
+
"missing_return_real": missing_return_real,
|
|
142
|
+
"static": lambda: "static"
|
|
143
|
+
}
|
|
144
|
+
app = MockFlask(rules, view_functions)
|
|
145
|
+
|
|
146
|
+
results = check_models(app)
|
|
147
|
+
|
|
148
|
+
assert len(results) == 1
|
|
149
|
+
assert results[0]['api'] == "/missing_return"
|
|
150
|
+
assert results[0]['missing'] == ["response"]
|
|
151
|
+
|
|
152
|
+
def test_allow_any_false_by_default() -> None:
|
|
153
|
+
routes = [
|
|
154
|
+
MockAPIRoute("/missing_any_return", missing_return),
|
|
155
|
+
MockAPIRoute("/missing_any_input", missing_input),
|
|
156
|
+
MockAPIRoute("/missing_any_both", missing_both),
|
|
157
|
+
]
|
|
158
|
+
app = MockFastAPI(routes)
|
|
159
|
+
|
|
160
|
+
# allow_any defaults to False, so typing.Any should be flagged as missing
|
|
161
|
+
results = check_models(app)
|
|
162
|
+
|
|
163
|
+
assert len(results) == 3
|
|
164
|
+
assert results[0]['missing'] == ["response"]
|
|
165
|
+
assert results[1]['missing'] == ["request"]
|
|
166
|
+
assert set(results[2]['missing']) == {"request", "response"}
|
|
167
|
+
|
|
168
|
+
def test_allow_any_true() -> None:
|
|
169
|
+
routes = [
|
|
170
|
+
MockAPIRoute("/missing_any_return", missing_return),
|
|
171
|
+
MockAPIRoute("/missing_any_input", missing_input),
|
|
172
|
+
MockAPIRoute("/missing_any_both", missing_both),
|
|
173
|
+
]
|
|
174
|
+
app = MockFastAPI(routes)
|
|
175
|
+
|
|
176
|
+
# allow_any=True means typing.Any is accepted as a valid model
|
|
177
|
+
results = check_models(app, allow_any=True)
|
|
178
|
+
|
|
179
|
+
assert len(results) == 0
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
from unittest.mock import MagicMock
|
|
4
|
+
from bridgekeeper.mocking import mock_modules, mock_env
|
|
5
|
+
|
|
6
|
+
def test_mock_modules_list() -> None:
|
|
7
|
+
# Ensure module isn't loaded
|
|
8
|
+
if "dummy_module_1" in sys.modules:
|
|
9
|
+
del sys.modules["dummy_module_1"]
|
|
10
|
+
|
|
11
|
+
mock_modules(["dummy_module_1"])
|
|
12
|
+
|
|
13
|
+
import dummy_module_1 # type: ignore
|
|
14
|
+
assert "dummy_module_1" in sys.modules
|
|
15
|
+
assert isinstance(sys.modules["dummy_module_1"], MagicMock)
|
|
16
|
+
|
|
17
|
+
def test_mock_modules_dict() -> None:
|
|
18
|
+
if "dummy_module_2" in sys.modules:
|
|
19
|
+
del sys.modules["dummy_module_2"]
|
|
20
|
+
if "dummy_module_3" in sys.modules:
|
|
21
|
+
del sys.modules["dummy_module_3"]
|
|
22
|
+
|
|
23
|
+
custom_mock = object()
|
|
24
|
+
|
|
25
|
+
mock_modules({
|
|
26
|
+
"dummy_module_2": None, # Should be MagicMock
|
|
27
|
+
"dummy_module_3": custom_mock # Should be custom_mock
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
import dummy_module_2 # type: ignore
|
|
31
|
+
import dummy_module_3 # type: ignore
|
|
32
|
+
assert "dummy_module_2" in sys.modules
|
|
33
|
+
assert isinstance(sys.modules["dummy_module_2"], MagicMock)
|
|
34
|
+
|
|
35
|
+
assert "dummy_module_3" in sys.modules
|
|
36
|
+
assert sys.modules["dummy_module_3"] is custom_mock
|
|
37
|
+
|
|
38
|
+
def test_mock_env() -> None:
|
|
39
|
+
if "DUMMY_ENV_VAR" in os.environ:
|
|
40
|
+
del os.environ["DUMMY_ENV_VAR"]
|
|
41
|
+
|
|
42
|
+
mock_env({"DUMMY_ENV_VAR": "secret_value"})
|
|
43
|
+
|
|
44
|
+
assert os.environ.get("DUMMY_ENV_VAR") == "secret_value"
|
|
45
|
+
|
|
46
|
+
def test_auto_mock_missing() -> None:
|
|
47
|
+
# Ensure a truly non-existent module is not there
|
|
48
|
+
non_existent = "some_crazy_non_existent_module_name"
|
|
49
|
+
if non_existent in sys.modules:
|
|
50
|
+
del sys.modules[non_existent]
|
|
51
|
+
|
|
52
|
+
# Clear out the fallback mock finder if previous tests added it
|
|
53
|
+
sys.meta_path = [m for m in sys.meta_path if type(m).__name__ != '_FallbackMockFinder']
|
|
54
|
+
|
|
55
|
+
# Standard import should fail
|
|
56
|
+
try:
|
|
57
|
+
import some_crazy_non_existent_module_name # type: ignore
|
|
58
|
+
assert False, "Should have raised ImportError"
|
|
59
|
+
except ImportError:
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
# Now enable auto_mock_missing
|
|
63
|
+
mock_modules(auto_mock_missing=True)
|
|
64
|
+
|
|
65
|
+
# Standard import should now succeed and return a MagicMock!
|
|
66
|
+
import some_crazy_non_existent_module_name # type: ignore
|
|
67
|
+
assert "some_crazy_non_existent_module_name" in sys.modules
|
|
68
|
+
assert isinstance(sys.modules["some_crazy_non_existent_module_name"], MagicMock)
|