Exemplo n.º 1
0
def download_from_bytes(content_case):
    c = content_case.case_params
    bytes_url = content_case.get_mature_url()
    bytes_params = c["request_params_func"](content_case)
    content_case.append_audit("Bytes URL: " + bytes_url)
    content_case.append_audit("Params: " + str(sanitize_dict(bytes_params)))
    bytes_response = requests.get(
        bytes_url, params=bytes_params, headers=content_case.headers,
        allow_redirects=True)
    return bytes_response.content
Exemplo n.º 2
0
def download_from_ticket(content_case):

    c = content_case.case_params

    ticket_url = content_case.get_mature_url()
    ticket_params = c["request_params_func"](content_case)

    content_case.append_audit("Ticket URL: " + ticket_url)
    content_case.append_audit("Params: " + str(sanitize_dict(ticket_params)))
    ticket_response = requests.get(
        ticket_url, params=ticket_params, headers=content_case.headers,
        allow_redirects=True)

    ticket_json = json.loads(ticket_response.content)

    matrix_url = ticket_json["url"]
    matrix_headers = ticket_json["headers"] \
                     if "headers" in ticket_json.keys() \
                     else {}
    
    matrix_response = requests.get(
        matrix_url, headers=matrix_headers, allow_redirects=True)
    return matrix_response.content
    def set_test_status(self, url, response):
        """Sets test status and messages based on response
        
        After making the API request, this method parses the response object
        and cross-references with the expected output (JSON schema, status code,
        etc). Test results are marked pass/fail/skip, and associated messages
        are added. The 3 steps of validating a single test case are as follows:
        1) validate content type/media type, 2) validate response status code,
        3) validate response body matches correct JSON schema

        Args:
            url (str): requested url
            params (dict): key-value mapping of supplied parameters
            response (Response): response object from the request
        """

        # apply_params = self.test.kwargs["apply_params"]

        if self.status != -1:
            self.append_audit("Request: " + url)
            self.append_audit("Params: " + str(sanitize_dict(self.params)))
            self.append_audit("Headers: " + str(sanitize_dict(self.headers)))
            # only add response body if JSON format is expected
            if self.is_json:
                if re.compile("json").search(response.headers["Content-Type"]):
                    self.append_audit("Response Body: " + response.text)

            try:
                # Validation 1, Content-Type, Media Type validation
                # check response content type is in accepted media types
                response_media_type = self.__get_response_media_type(response)
                if not response_media_type in set(self.media_types):
                    raise tse.MediaTypeException(
                        "Response Content-Type '%s'" % response_media_type +
                        " not in request accepted media types: " +
                        str(self.media_types))

                # Validation 2, Status Code match validation
                # if response code matches expected, validate against JSON
                # schema
                if response.status_code not in self.exp_status:
                    raise tse.StatusCodeException(
                        "Response status code: %s" %
                        str(response.status_code) +
                        " not in expected status code(s): " +
                        str(sorted(list(self.exp_status))))

                # Validation 3, JSON Schema Validation
                # if JSON schema matches response body, test succeeds
                # if a JSON object can't be parsed from the response body,
                # then catch this error and assign exception

                # if JSON object/dict cannot be parsed from the response body,
                # raise a TestStatusException

                # if endpoint not expected to return JSON (is_json == False),
                # skip this step
                if self.is_json:
                    response_json = None
                    try:
                        response_json = response.json()
                    except ValueError as e:
                        raise tse.JsonParseException(
                            "Error parsing JSON from response")

                    if self.schema_func:
                        self.schema_file = self.case_params["schema_func"](
                            self.runner, self.test, self.params)

                    sv = SchemaValidator(self.schema_file)
                    validation_result = sv.validate_instance(response_json)
                    self.set_status(validation_result["status"])

                    if validation_result["status"] == -1:
                        raise tse.SchemaValidationException(
                            validation_result["message"])
                else:
                    self.set_status(1)

                # update the test runner with settings (supported filters,
                # supported formats) retrieved from the server in the response
                if self.server_settings_update_func:
                    self.server_settings_update_func(
                        self.runner, self.test.kwargs["obj_type"],
                        response_json)

            except tse.TestStatusException as e:
                self.set_status(-1)
                self.set_error_message(str(e))
                self.append_audit("Exception of class %s encountered" %
                                  (str(e.__class__.__name__)))
                self.append_audit("Exception Message: " + str(e))
Exemplo n.º 4
0
    def wrapper(content_case):
        """Inner function returned by the decorator function

        Arguments:
            content_case (ContentCase): content case object for test case
        
        Returns:
            (dict): test case result
        """

        # assign url and request params
        result = {"status": 1, "message": ""}
        url = content_case.get_mature_url()
        c = content_case.case_params
        request_params = {}
        if "request_params_func" in c.keys():
            request_params = c["request_params_func"](content_case)

        try:
            content_case.append_audit("Request URL: " + url)
            content_case.append_audit("Request Headers:" +
                                      str(sanitize_dict(content_case.headers)))
            content_case.append_audit("Request Params: " + str(request_params))

            # make the request for expression object, and get the download URL
            # from the "URL" property
            # write the file content to a temporary file for subsequent
            # content checking
            response = requests.get(url,
                                    headers=content_case.headers,
                                    params=request_params)

            if re.compile("json").search(response.headers["Content-Type"]):
                content_case.append_audit("Response Body: " +
                                          str(response.text))
            download_url = c["download_url"](response)
            content_case.append_audit("Matrix Download URL: " + download_url)
            r = requests.get(download_url,
                             headers=content_case.headers,
                             allow_redirects=True)

            if os.path.exists(c["tempfile"]):
                os.remove(c["tempfile"])

            file_write = open(c["tempfile"], 'wb')
            file_write.write(r.content)
            file_write.close()

            # get the attribute handler based on object type and file format
            obj_type = content_case.test.kwargs["obj_type"]
            server_settings = content_case.runner.retrieved_server_settings
            fmt = server_settings[obj_type]["exp_format"]
            attribute_handler = ATTRIBUTE_HANDLERS[obj_type][fmt](
                c["tempfile"])
            content_case.set_attribute_handler(attribute_handler)

            # execute the inner function
            result = function(content_case)

        # if any exception is encountered in the above process, the test fails
        # and the reason should be displayed in the report
        except Exception as e:
            result["status"] = -1
            content_case.set_error_message(
                "Error parsing expression json and " + "download url: " +
                str(e))
            content_case.append_audit(str(e))

        return result