1717# You should have received a copy of the GNU Lesser General Public License
1818# along with python-transip. If not, see <https://www.gnu.org/licenses/>.
1919
20- from typing import Any
20+ from typing import Any , List , Dict
2121import json
2222import os
2323import responses # type: ignore
2424
2525
26- def load_fixture (path ) -> Any :
27- """Load a JSON fixture from the fixtures directory."""
28- fixtures : str = os .path .join (
29- os .path .dirname (os .path .realpath (__file__ )),
30- "fixtures"
31- )
32- with open (os .path .join (fixtures , path )) as fixture :
33- return json .load (fixture )
34-
35-
3626def load_responses_fixture (path ) -> None :
3727 """Load a JSON fixture containing all the API response examples."""
3828
39- def get_responses_method (method : str ) -> str :
40- """
29+ def _load_json_fixtures (path : str ) -> List [Dict [str , Any ]]:
30+ """Load JSON fixtures from file."""
31+ cwd : str = os .path .dirname (os .path .realpath (__file__ ))
32+ fixtures : str = os .path .join (os .path .join (cwd , 'fixtures' ), path )
33+ with open (fixtures ) as fixture :
34+ return json .load (fixture )
35+
36+ def _get_responses_method (method : str ) -> str :
37+ """Returns the responses method based upon the supplied method.
38+
39+ Args:
40+ method (str): The response method.
41+
4142 Raises:
4243 ValueError: if the specified method is invalid.
4344 """
@@ -54,17 +55,27 @@ def get_responses_method(method: str) -> str:
5455 return responses .PATCH
5556 raise ValueError (f"Unable to find method '{ method } ' in responses" )
5657
57- fixture = load_fixture (path )
58- for response in fixture :
59- match = []
60- if response .get ("match_json" ):
61- match .append (responses .json_params_matcher (response ["match_json" ]))
58+ fixtures : List [Dict [str , Any ]] = _load_json_fixtures (path )
59+ for fixture in fixtures :
60+ # Add the matchers for the request parameters or JSON body
61+ matchers : List [Any ] = []
62+ if fixture .get ('match_json_params' ):
63+ matchers .append (
64+ responses .json_params_matcher (fixture ['match_json_params' ])
65+ )
66+ if fixture .get ('match_urlencoded_params' ):
67+ matchers .append (
68+ responses .urlencoded_params_matcher (
69+ fixture ['match_urlencoded_params' ]
70+ )
71+ )
6272
73+ # Register the mocked response
6374 responses .add (
64- get_responses_method ( response ["method" ]),
65- url = response ["url" ],
66- json = response .get ("json" ),
67- status = response ["status" ],
68- content_type = response .get ("content_type" , "application/json" ),
69- match = match
70- )
75+ _get_responses_method ( fixture ["method" ]),
76+ url = fixture ["url" ],
77+ json = fixture .get ("json" ),
78+ status = fixture ["status" ],
79+ content_type = fixture .get ("content_type" , "application/json" ),
80+ match = matchers
81+ )
0 commit comments