Skip to content

Commit

Permalink
Merge pull request #44 from MarketSquare/39_add_option_to_mark_option…
Browse files Browse the repository at this point in the history
…al_parameters_as_mandatory

add option to mark optional parameters as mandatory
  • Loading branch information
robinmackaij authored Dec 4, 2024
2 parents f9d7377 + 5ff7ef3 commit b0990b7
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 8 deletions.
9 changes: 4 additions & 5 deletions src/OpenApiLibCore/dto_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ class PropertyValueConstraint(ResourceRelation):
invalid_value: Any = NOT_SET
invalid_value_error_code: int = 422
error_code: int = 422
treat_as_mandatory: bool = False


@dataclass
Expand Down Expand Up @@ -210,15 +211,13 @@ def get_invalidated_data(
if status_code == invalid_property_default_code:
# add all properties defined in the schema, including optional properties
property_names.extend((schema["properties"].keys()))
# remove duplicates
property_names = list(set(property_names))
if not property_names:
raise ValueError(
f"No property can be invalidated to cause status_code {status_code}"
)
# shuffle the property_names so different properties on the Dto are invalidated
# when rerunning the test
shuffle(property_names)
# Remove duplicates, then shuffle the property_names so different properties on
# the Dto are invalidated when rerunning the test.
shuffle(list(set(property_names)))
for property_name in property_names:
# if possible, invalidate a constraint but send otherwise valid data
id_dependencies = [
Expand Down
28 changes: 27 additions & 1 deletion src/OpenApiLibCore/openapi_libcore.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,15 @@ def headers_that_can_be_invalidated(self) -> Set[str]:

def get_required_properties_dict(self) -> Dict[str, Any]:
"""Get the json-compatible dto data containing only the required properties."""
required_properties = self.dto_schema.get("required", [])
relations = self.dto.get_relations()
mandatory_properties = [
relation.property_name
for relation in relations
if getattr(relation, "treat_as_mandatory", False)
]
required_properties: List[str] = self.dto_schema.get("required", [])
required_properties.extend(mandatory_properties)

required_properties_dict: Dict[str, Any] = {}
for key, value in (self.dto.as_dict()).items():
if key in required_properties:
Expand Down Expand Up @@ -414,16 +422,34 @@ def get_minimal_body_dict(self) -> Dict[str, Any]:

def get_required_params(self) -> Dict[str, str]:
"""Get the params dict containing only the required query parameters."""
relations = self.dto.get_parameter_relations()
mandatory_properties = [
relation.property_name
for relation in relations
if getattr(relation, "treat_as_mandatory", False)
]
mandatory_parameters = [p for p in mandatory_properties if p in self.parameters]

required_parameters = [
p.get("name") for p in self.parameters if p.get("required")
]
required_parameters.extend(mandatory_parameters)
return {k: v for k, v in self.params.items() if k in required_parameters}

def get_required_headers(self) -> Dict[str, str]:
"""Get the headers dict containing only the required headers."""
relations = self.dto.get_parameter_relations()
mandatory_properties = [
relation.property_name
for relation in relations
if getattr(relation, "treat_as_mandatory", False)
]
mandatory_parameters = [p for p in mandatory_properties if p in self.parameters]

required_parameters = [
p.get("name") for p in self.parameters if p.get("required")
]
required_parameters.extend(mandatory_parameters)
return {k: v for k, v in self.headers.items() if k in required_parameters}


Expand Down
3 changes: 2 additions & 1 deletion tests/libcore/suites/test_get_invalidated_parameters.robot
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,11 @@ Test Get Invalidated Parameters Adds Optional Parameter If Not Provided
${headers}= Set Variable ${invalidated[1]}
Length Should Be ${headers} 1

Test Get Invalidated Parameters Adds Optional Parameter If treat_as_mandatory Is True
${request_data}= Get Request Data endpoint=/energy_label/{zipcode}/{home_number} method=get
Evaluate ${request_data.params.clear()} is None
${invalidated}= Get Invalidated Parameters
... status_code=422
... request_data=${request_data}
${extension}= Set Variable ${invalidated[0].get("extension")}
Length Should Be ${extension} 0
Length Should Be ${extension} 20
3 changes: 2 additions & 1 deletion tests/libcore/suites/test_request_data_class.robot
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ Test Get Required Properties Dict
Should Contain ${request_data.dto.as_dict()} parttime_day
Should Not Be Empty ${request_data.dto.name}
${required_properties}= Set Variable ${request_data.get_required_properties_dict()}
Should Not Contain ${required_properties} parttime_day
Should Contain ${required_properties} name
# parttime_day is configured with treat_as_mandatory=True
Should Contain ${required_properties} parttime_day

Test Get Required Params
${request_data}= Get Request Data endpoint=/available_employees method=get
Expand Down
16 changes: 16 additions & 0 deletions tests/user_implemented/custom_user_mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ def get_relations() -> List[Relation]:
invalid_value_error_code=403,
error_code=422,
),
PropertyValueConstraint(
property_name="parttime_day",
values=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
treat_as_mandatory=True,
)
]
return relations

Expand All @@ -88,6 +93,17 @@ def get_relations() -> List[Relation]:
]
return relations

@staticmethod
def get_parameter_relations() -> List[Relation]:
relations: List[Relation] = [
PropertyValueConstraint(
property_name="extension",
values=["E", "boven", "A4.1"],
treat_as_mandatory=True,
)
]
return relations


class MessageDto(Dto):
@staticmethod
Expand Down

0 comments on commit b0990b7

Please sign in to comment.