Skip to content

Commit

Permalink
feat: improve validate string to return closest payload type possible
Browse files Browse the repository at this point in the history
  • Loading branch information
gcharest authored Sep 17, 2024
1 parent e292fa3 commit 8283f9b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
6 changes: 4 additions & 2 deletions app/models/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,12 @@ def validate_string_payload_type(payload: str) -> tuple:
]
model_params = model_utils.get_dict_of_parameters_from_models(known_models)

max_matches = 0
for model, params in model_params.items():
if model_utils.is_parameter_in_model(params, payload_dict):
matches = model_utils.has_parameters_in_model(params, payload_dict)
if matches > max_matches:
max_matches = matches
payload_type = model
break

if payload_type:
return payload_type, payload_dict
Expand Down
29 changes: 27 additions & 2 deletions app/tests/models/test_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,12 +239,37 @@ def test_validate_string_payload_type_valid_json(
"TestModel": ["type"],
"TestModel2": ["type2"],
}
model_utils_mock.is_parameter_in_model.side_effect = [False, True]
model_utils_mock.has_parameters_in_model.side_effect = [0, 1, 0]
assert webhooks.validate_string_payload_type('{"type": "test"}') == (
"TestModel",
{"type": "test"},
)
assert model_utils_mock.is_parameter_in_model.call_count == 2
assert model_utils_mock.has_parameters_in_model.call_count == 3


@patch("models.webhooks.model_utils")
def test_validate_string_payload_same_params_in_multiple_models_returns_first_found(
model_utils_mock, caplog
):
model_utils_mock.get_dict_of_parameters_from_models.return_value = {
"WrongModel": ["test"],
"TestModel": ["type", "type2"],
"TestModel2": ["type2"],
"TestModel3": ["type"],
}
model_utils_mock.has_parameters_in_model.side_effect = [0, 2, 0, 1]
response = webhooks.validate_string_payload_type(
'{"type": "test", "type2": "test"}'
)
assert response == (
"TestModel",
{"type": "test", "type2": "test"},
)
assert response != (
"TestModel3",
{"type": "test"},
)
assert model_utils_mock.has_parameters_in_model.call_count == 4


def test_validate_string_payload_type_error_loading_json(caplog):
Expand Down

0 comments on commit 8283f9b

Please sign in to comment.