TerekhovaKate commented on code in PR #7400:
URL: https://github.com/apache/trafficcontrol/pull/7400#discussion_r1135819230


##########
traffic_ops/testing/api_contract/v4/conftest.py:
##########
@@ -0,0 +1,92 @@
+"""This module is used to create a Traffic Ops session 
+and to store prerequisite data for endpoints"""
+import json
+import logging
+import sys
+from random import randint
+from urllib.parse import urlparse
+import pytest
+from trafficops.tosession import TOSession
+
+# Create and configure logger
+logger = logging.getLogger()
+
+
+def pytest_addoption(parser):
+    """Passing in Traffic Ops Arguments [Username, Password, Url and Hostname] 
from Command Line"""
+    parser.addoption(
+        '--to_user', action='store', default='admin', help='User name for 
Traffic Ops Session'
+    )
+    parser.addoption(
+        '--to_password', action='store', default='twelve12', help='Password 
for Traffic Ops Session'
+    )
+    parser.addoption(
+        '--to_url', action='store', default='https://localhost/api', 
help='Traffic Ops URL'
+    )
+    parser.addoption(
+        '--hostname', action='store', default='localhost', help='Traffic Ops 
hostname'
+    )
+
+
[email protected](name="to_args")
+def to_data(pytestconfig):
+    """PyTest fixture to store Traffic ops Arguments passed from command 
line"""
+    args = {}
+    args['user'] = pytestconfig.getoption('--to_user')
+    args['password'] = pytestconfig.getoption('--to_password')
+    args['url'] = pytestconfig.getoption('--to_url')
+    args['hostname'] = pytestconfig.getoption('--hostname')
+    return args
+
+
[email protected](name="to_session")
+def to_login(to_args):
+    """PyTest Fixture to create a Traffic Ops session from Traffic Ops 
Arguments 
+    passed as command line arguments in to_args fixture in conftest"""
+    # Create a Traffic Ops V4 session and login
+    with open('to_data.json', encoding="utf-8", mode='r') as session_file:
+        data = json.load(session_file)
+        session_file.close()
+    session_data = data["test"]
+    api_version = session_data["api_version"]
+    port = session_data["port"]
+    if to_args["user"] is None:
+        logger.info(
+            "Traffic Ops session data were not passed from Command line Args")
+    else:
+        logger.info("Parsed Traffic ops session data from args %s", to_args)
+        session_data = to_args
+    to_url = urlparse(session_data["url"])
+    to_host = to_url.hostname
+    to_session = TOSession(host_ip=to_host, host_port=port,

Review Comment:
   to_session = TOSession(host_ip=to_host, host_port=port,
                               api_version=api_version, ssl=True, 
verify_cert=False)
        logger.info("Established Traffic Ops Session")
        # Login To TO_API
        to_session.login(session_data["user"], session_data["password"])
   
        if not to_session.logged_in:
            logger.error("Failure Logging into Traffic Ops")
            sys.exit(-1)
        else:
            logger.info("Successfully logged into Traffic Ops")
        return to_session
   i think we can use exceptions from from .restapi import LoginError, 
OperationError, api_request, RestApiSession



##########
traffic_ops/testing/api_contract/v4/conftest.py:
##########
@@ -0,0 +1,92 @@
+"""This module is used to create a Traffic Ops session 
+and to store prerequisite data for endpoints"""
+import json
+import logging
+import sys
+from random import randint
+from urllib.parse import urlparse
+import pytest
+from trafficops.tosession import TOSession
+
+# Create and configure logger
+logger = logging.getLogger()
+
+
+def pytest_addoption(parser):
+    """Passing in Traffic Ops Arguments [Username, Password, Url and Hostname] 
from Command Line"""
+    parser.addoption(
+        '--to_user', action='store', default='admin', help='User name for 
Traffic Ops Session'
+    )
+    parser.addoption(
+        '--to_password', action='store', default='twelve',  help='Password for 
Traffic Ops Session'
+    )
+    parser.addoption(
+        '--to_url', action='store', default='https://localhost/api', 
help='Traffic Ops URL'
+    )
+    parser.addoption(
+        '--hostname', action='store', default='localhost', help='Traffic Ops 
hostname'
+    )
+
+
[email protected](name="to_args")
+def to_data(pytestconfig):
+    """PyTest fixture to store Traffic ops Arguments passed from command 
line"""
+    args = {}
+    args['user'] = pytestconfig.getoption('--to_user')
+    args['password'] = pytestconfig.getoption('--to_password')
+    args['url'] = pytestconfig.getoption('--to_url')
+    args['hostname'] = pytestconfig.getoption('--hostname')
+    return args
+
+
[email protected](name="to_session")
+def to_login(to_args):
+    """PyTest Fixture to create a Traffic Ops session from Traffic Ops 
Arguments 
+    passed as command line arguments in to_args fixture in conftest"""
+    # Create a Traffic Ops V4 session and login
+    with open('to_data.json', encoding="utf-8", mode='r') as session_file:
+        data = json.load(session_file)
+        session_file.close()
+    session_data = data["test"]
+    api_version = session_data["api_version"]
+    port = session_data["port"]
+    if to_args["user"] is None:
+        logger.info(
+            "Traffic Ops session data were not passed from Command line Args")
+    else:
+        logger.info("Parsed Traffic ops session data from args %s", to_args)
+        session_data = to_args
+    to_url = urlparse(session_data["url"])
+    to_host = to_url.hostname
+    to_session = TOSession(host_ip=to_host, host_port=port,
+                           api_version=api_version, ssl=True, 
verify_cert=False)
+    logger.info("Established Traffic Ops Session")
+    # Login To TO_API
+    to_session.login(session_data["user"], session_data["password"])
+
+    if not to_session.logged_in:
+        logger.error("Failure Logging into Traffic Ops")
+        sys.exit(-1)
+    else:
+        logger.info("Successfully logged into Traffic Ops")
+    return to_session
+
+
[email protected]()
+def cdn_prereq(to_session, get_cdn_data):
+    """PyTest Fixture to create POST data for cdns endpoint"""
+
+    # Return new post data and post response from cdns POST request
+    data = get_cdn_data
+    data["name"] = data["name"][:4]+str(randint(0, 1000))
+    data["domainName"] = data["domainName"][:5] + str(randint(0, 1000))
+    logger.info("New cdn data to hit POST method %s", data)
+    # Hitting cdns POST methed
+    response = to_session.create_cdn(data=data)
+    try:
+        cdn_response = response[0]
+        prerequisite_data = [data, cdn_response]
+        return prerequisite_data
+    except IndexError:
+        logger.error("No CDN response data from cdns POST request")
+        return None

Review Comment:
   please verify with lint and flake 
   multiple return statements 
   better `@pytest.fixture()
    def cdn_prereq(to_session, get_cdn_data):
        """PyTest Fixture to create POST data for cdns endpoint"""
   
        # Return new post data and post response from cdns POST request
    
        get_cdn_data["name"] = get_cdn_data["name"][:4]+str(randint(0, 1000))
        get_cdn_data["domainName"] = get_cdn_data["domainName"][:5] + 
str(randint(0, 1000))
        logger.info("New cdn data to hit POST method %s", data)
        # Hitting cdns POST methed
        response = to_session.create_cdn(data=data)
        prerequisite_data = None
        try:
            cdn_response = response[0]
            prerequisite_data = [data, cdn_response]
         
        except IndexError:
            logger.error("No CDN response data from cdns POST request")
        return prerequisite_data`



##########
traffic_ops/testing/api_contract/v4/test_cdns.py:
##########
@@ -0,0 +1,64 @@
+"""Api Contract Test Case for cdns endpoint"""
+import json
+import logging
+import pytest
+
+# Create and configure logger
+logger = logging.getLogger()
+
+
[email protected](name="get_cdn_data")
+def get_cdn_prereq_data():
+    """PyTest Fixture to store prereq data for cdns endpoint"""
+    # Response keys for cdns endpoint
+    with open('prerequisite_data.json', encoding="utf-8", mode='r') as 
prereq_file:
+        data = json.load(prereq_file)
+    cdn_data = data["cdns"]
+    return cdn_data
+
+
+def test_get_cdn(to_session, get_cdn_data, cdn_prereq):
+    """Test step to validate keys from cdns endpoint response and POST method
+    :param to_session: Fixture to get Traffic ops session 
+    :type to_session: TOsession
+    :param get_cdn_data: Fixture to get cdn data from a prereq file
+    :type get_cdn_data: dict
+    :param cdn_prereq: Fixture to get sample cdn data and actual cdn response
+    :type cdn_prereq: list
+    """
+    # validate CDN keys from cdns get response
+    logger.info("Accessing Cdn endpoint through Traffic ops session")
+    cdn_name = cdn_prereq[0]["name"]
+    cdn_get_response = to_session.get_cdns(query_params={"name": 
str(cdn_name)})
+    try:
+        cdn_data = cdn_get_response[0]
+        cdn_keys = list(cdn_data[0].keys())
+        logger.info(
+            "CDN Keys from cdns endpoint response %s", cdn_keys)
+        # validate cdn values from prereq data in cdns get response
+        prereq_data = [cdn_prereq[0]['name'], cdn_prereq[0]
+                       ['domainName'], cdn_prereq[0]['dnssecEnabled']]
+        get_data = [cdn_data[0]['name'], cdn_data[0]
+                    ['domainName'], cdn_data[0]['dnssecEnabled']]
+        assert cdn_keys.sort() == list(get_cdn_data.keys()).sort()

Review Comment:
   we need a check for data type in json response. 
   https://docs.python.org/3/library/datatypes.html
   



##########
traffic_ops/testing/api_contract/v4/conftest.py:
##########
@@ -0,0 +1,100 @@
+"""This module is used to create a Traffic Ops session 
+and to store prerequisite data for endpoints"""
+import json
+import logging
+import sys
+from random import randint
+from urllib.parse import urlparse
+import pytest
+from trafficops.tosession import TOSession
+from trafficops.restapi import OperationError
+
+
+# Create and configure logger
+logger = logging.getLogger()
+
+
+def pytest_addoption(parser):
+    """Passing in Traffic Ops Arguments [Username, Password, Url and Hostname] 
from Command Line"""
+    parser.addoption(
+        '--to_user', action='store', default='admin', help='User name for 
Traffic Ops Session'
+    )
+    parser.addoption(
+        '--to_password', action='store', default='twelve12', help='Password 
for Traffic Ops Session'
+    )
+    parser.addoption(
+        '--to_url', action='store', default='https://localhost/api', 
help='Traffic Ops URL'
+    )
+    parser.addoption(
+        '--hostname', action='store', default='localhost', help='Traffic Ops 
hostname'
+    )
+
+
[email protected](name="to_args")
+def to_data(pytestconfig):
+    """PyTest fixture to store Traffic ops Arguments passed from command 
line"""
+    args = {}
+    args['user'] = pytestconfig.getoption('--to_user')
+    args['password'] = pytestconfig.getoption('--to_password')
+    args['url'] = pytestconfig.getoption('--to_url')
+    args['hostname'] = pytestconfig.getoption('--hostname')
+    return args
+
+
[email protected](name="to_session")
+def to_login(to_args):
+    """PyTest Fixture to create a Traffic Ops session from Traffic Ops 
Arguments 
+    passed as command line arguments in to_args fixture in conftest
+    :param to_args: Fixture to get Traffic ops session arguments
+    :type to_args: dict
+    """
+    # Create a Traffic Ops V4 session and login
+    with open('to_data.json', encoding="utf-8", mode='r') as session_file:

Review Comment:
   move  to fixture @pytest.fixture(name="to_args")
    def to_data(pytestconfig):
    logically this belongs to fulfilling data during test init 
   `with open('to_data.json', encoding="utf-8", mode='r') as session_file:
            data = json.load(session_file)
        session_data = data["test"]
        api_version = session_data["api_version"]
        port = session_data["port"]
        if to_args["user"] is None:
            logger.info(
                "Traffic Ops session data were not passed from Command line 
Args")
        else:
            logger.info("Parsed Traffic ops session data from args %s", to_args)
            session_data = to_args
        to_url = urlparse(session_data["url"])`



-- 
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