ocket8888 commented on code in PR #7424:
URL: https://github.com/apache/trafficcontrol/pull/7424#discussion_r1156367600


##########
traffic_ops/testing/api_contract/v4/test_cachegroups.py:
##########
@@ -0,0 +1,109 @@
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""API Contract Test Case for cachegroup endpoint."""
+import logging
+import pytest
+import requests
+
+from trafficops.tosession import TOSession
+
+# Create and configure logger
+logger = logging.getLogger()
+
+primitive = bool | int | float | str | None
+
[email protected]('request_template_data', ["cachegroup"], 
indirect=True)
+def test_cachegroup_contract(to_session: TOSession, request_template_data:
+       list[dict[str, object] | list[object] | primitive],
+       response_template_data: list[dict[str, object] | list[object] | 
primitive],
+       cachegroup_post_data: dict[str, object]) -> None:
+       """
+       Test step to validate keys, values and data types from cachegroup 
endpoint
+       response.
+       :param to_session: Fixture to get Traffic Ops session.
+       :param request_template_data: Fixture to get request template data from 
a prerequisites file.
+       :param response_template_data: Fixture to get response template data 
from a prerequisites file.
+       :param cachegroup_post_data: Fixture to get sample cachegroup data and 
actual cachegroup response.
+       """
+       # validate CDN keys from cdns get response
+       logger.info("Accessing /cachegroup endpoint through Traffic ops 
session.")
+
+       cachegroup = request_template_data[0]
+       if not isinstance(cachegroup, dict):
+               raise TypeError("malformed cachegroup in prerequisite data; not 
an object")
+
+       cachegroup_name = cachegroup.get("name")
+       if not isinstance(cachegroup_name, str):
+               raise TypeError("malformed cachegroup in prerequisite data; 
'name' not a string")
+
+       cachegroup_get_response: tuple[
+               dict[str, object] | list[dict[str, object] | list[object] | 
primitive] | primitive,
+               requests.Response
+       ] = to_session.get_cachegroups(query_params={"name": 
str(cachegroup_name)})
+       try:
+               cachegroup_data = cachegroup_get_response[0]
+               if not isinstance(cachegroup_data, list):
+                       raise TypeError("malformed API response; 'response' 
property not an array")
+
+               first_cachegroup = cachegroup_data[0]
+               if not isinstance(first_cachegroup, dict):
+                       raise TypeError("malformed API response; first Cache 
group in response is not an object")
+               cachegroup_keys = set(first_cachegroup.keys())
+
+               logger.info("Cache group Keys from cachegroup endpoint response 
%s", cachegroup_keys)
+               response_template = 
response_template_data.get("cachegroup").get("properties")

Review Comment:
   According to your function's call signature, `response_template_data` is a 
`list`, which has no `get` method. So either this line is wrong (probably not 
because tests pass), or the call signature is wrong (much more likely.



##########
traffic_ops/testing/api_contract/v4/conftest.py:
##########
@@ -336,3 +406,68 @@ def cdn_post_data(to_session: TOSession, cdn_prereq_data: 
list[JSONData]) -> dic
        except IndexError:
                logger.error("No CDN response data from cdns POST request.")
                sys.exit(1)
+
+
[email protected]()
+def cachegroup_post_data(to_session: TOSession, request_template_data: 
list[JSONData]
+                        ) -> dict[str, object]:
+       """
+       PyTest Fixture to create POST data for cachegroup endpoint.
+
+       :param to_session: Fixture to get Traffic Ops session.
+       :param request_template_data: Fixture to get Cachegroup data from a 
prerequisites file.
+       :returns: Sample POST data and the actual API response.
+       """
+       try:
+               cachegroup = request_template_data[0]
+       except IndexError as e:
+               raise TypeError(
+                       "malformed prerequisite data; no Cache group present in 
'cachegroup' array property") from e
+
+       if not isinstance(cachegroup, dict):
+               raise TypeError(
+                       f"malformed prerequisite data; Cache group must be 
objects, not '{type(cachegroup)}'")
+
+       # Return new post data and post response from cachegroups POST request
+       randstr = str(randint(0, 1000))
+       try:
+               name = cachegroup["name"]
+               if not isinstance(name, str):
+                       raise TypeError(f"name must be str, not '{type(name)}'")
+               cachegroup["name"] = name[:4] + randstr
+               short_name = cachegroup["shortName"]
+               if not isinstance(short_name, str):
+                       raise TypeError(f"shortName must be str, not 
'{type(short_name)}")
+               cachegroup["shortName"] = short_name[:5] + randstr
+       except KeyError as e:
+               raise TypeError(f"missing Cache group property '{e.args[0]}'") 
from e
+       # Hitting types GET method to access typeID for cachegroup POST data
+       type_get_response: tuple[
+               dict[str, object] | list[dict[str, object] | list[object] | 
primitive] | primitive,
+               requests.Response
+       ] = to_session.get_types(query_params={"useInTable": "cachegroup"})
+       try:
+               type_data = type_get_response[0]
+               if not isinstance(type_data, list):
+                       raise TypeError("malformed API response; 'response' 
property not an array")
+               first_type = type_data[0]
+               if not isinstance(first_type, dict):
+                       raise TypeError("malformed API response; first Type in 
response is not an object")
+               cachegroup["typeId"] = first_type["id"]
+               type_id = cachegroup["typeId"]
+               logger.info("extracted %s from %s", type_id, type_get_response)
+       except KeyError as e:
+               raise TypeError(f"missing Type property '{e.args[0]}'") from e
+
+       logger.info("New cachegroup data to hit POST method %s", 
request_template_data)
+       # Hitting cachegroup POST method
+       response: tuple[JSONData, requests.Response] = 
to_session.create_cachegroups(data=cachegroup)
+       try:
+               resp_obj = response[0]
+               if not isinstance(resp_obj, dict):
+                       raise TypeError("malformed API response; cache group is 
not an object")
+               return resp_obj
+       except IndexError:
+               logger.error("No Cache group response data from cdns POST 
request.")
+               sys.exit(1)
+

Review Comment:
   There's an extra trailing newline here, and it's the only reason Pylint 
gives your code less than a perfect score.



##########
traffic_ops/testing/api_contract/v4/test_cachegroups.py:
##########
@@ -0,0 +1,109 @@
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""API Contract Test Case for cachegroup endpoint."""
+import logging
+import pytest
+import requests
+
+from trafficops.tosession import TOSession
+
+# Create and configure logger
+logger = logging.getLogger()
+
+primitive = bool | int | float | str | None
+
[email protected]('request_template_data', ["cachegroup"], 
indirect=True)
+def test_cachegroup_contract(to_session: TOSession, request_template_data:
+       list[dict[str, object] | list[object] | primitive],
+       response_template_data: list[dict[str, object] | list[object] | 
primitive],
+       cachegroup_post_data: dict[str, object]) -> None:
+       """
+       Test step to validate keys, values and data types from cachegroup 
endpoint
+       response.
+       :param to_session: Fixture to get Traffic Ops session.
+       :param request_template_data: Fixture to get request template data from 
a prerequisites file.
+       :param response_template_data: Fixture to get response template data 
from a prerequisites file.
+       :param cachegroup_post_data: Fixture to get sample cachegroup data and 
actual cachegroup response.
+       """
+       # validate CDN keys from cdns get response
+       logger.info("Accessing /cachegroup endpoint through Traffic ops 
session.")
+
+       cachegroup = request_template_data[0]
+       if not isinstance(cachegroup, dict):
+               raise TypeError("malformed cachegroup in prerequisite data; not 
an object")
+
+       cachegroup_name = cachegroup.get("name")
+       if not isinstance(cachegroup_name, str):
+               raise TypeError("malformed cachegroup in prerequisite data; 
'name' not a string")
+
+       cachegroup_get_response: tuple[
+               dict[str, object] | list[dict[str, object] | list[object] | 
primitive] | primitive,
+               requests.Response
+       ] = to_session.get_cachegroups(query_params={"name": 
str(cachegroup_name)})
+       try:
+               cachegroup_data = cachegroup_get_response[0]
+               if not isinstance(cachegroup_data, list):
+                       raise TypeError("malformed API response; 'response' 
property not an array")
+
+               first_cachegroup = cachegroup_data[0]
+               if not isinstance(first_cachegroup, dict):
+                       raise TypeError("malformed API response; first Cache 
group in response is not an object")
+               cachegroup_keys = set(first_cachegroup.keys())
+
+               logger.info("Cache group Keys from cachegroup endpoint response 
%s", cachegroup_keys)
+               response_template = 
response_template_data.get("cachegroup").get("properties")
+               # validate cachegroup values from prereq data in cachegroup get 
response.
+               prereq_values = [
+                       cachegroup_post_data["name"],
+                       cachegroup_post_data["shortName"],
+                       cachegroup_post_data["fallbackToClosest"],
+                       cachegroup_post_data["typeId"]
+               ]
+               get_values = [
+                       first_cachegroup["name"],
+               first_cachegroup["shortName"],
+               first_cachegroup["fallbackToClosest"],
+                   first_cachegroup["typeId"]

Review Comment:
   The reason this looks off is because you indented the first line 
(`first_cachegroup["name"]`, line 75) with tabs and then the others with a 
mixture of tabs and spaces.
   
   You don't need to change that; if the linter's happy then so am I. I just 
noticed a discussion about it, so I figured I'd point it out.



##########
traffic_control/clients/python/pylint.rc:
##########
@@ -429,6 +429,12 @@ max-branches=15
 # Maximum number of statements in function / method body.
 max-statements=80
 
+# Maximum number of locals for function / method body
+max-locals=25
+
+# Maximum number of arguments for function / method
+max-args=10
+

Review Comment:
   Why add these? Was there a default value that was causing your code to not 
pass the linter?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to