コード例 #1
0
 def validate(self):
     json_file = self.__data_file
     json_data_obj = json.loads(json_file)  #open(json_file))
     try:
         validictory.validate(json_data_obj, self.__json_schema_obj)
         return True, ""
     except Exception as e:  #jsonschema.exceptions.ValidationError as extraInfo:
         #             logs.error(str(e))
         logs.debug("Schema File used is \"{}\"".format(
             self.__schema_file_name))
         return False, str(e)
コード例 #2
0
 def validate(self):
     self.__createSchemaTree()
     #extraInfo=""
     try:
         #with open(self.__report, 'r') as f:
         etree.fromstring(self.__report, self.__xml_parser)
         return True, ""
     except Exception as e:
         logs.error(str(e))
         logs.debug("Schema File used is \"{}\"".format(self.__schema_file))
         return False, str(e)
コード例 #3
0
    def markTestCasePassed(self, reportObj, valType, testCaseObj):
        self.__report = reportObj
        #         testCaseObj['status'] = 'PASS'
        dataDiction = testCaseObj.get(testCaseObj.keys()[0])
        #         dataDiction.update({'status':{'value':'PASS', 'visible': True}})
        dataDiction['status']['value'] = 'PASS'
        testCaseObj[testCaseObj.keys()[0]] = dataDiction

        self.__report.updatePassedTestCount(valType)
        self.__report.updateResult(valType, testCaseObj, 'Passed')
        if dataDiction.get('testLinkId').get('value') and Globals.TESTLINK:
            # print "Updating test link"
            self.updateTestLink(dataDiction)

        logs.debug("Total test Cases executed till now: " +
                   str(self.__report.getTestStats()[0]))
        logs.debug("Total test Cases Passed till now: " +
                   str(self.__report.getTestStats()[1]))
        logs.debug("Total test Cases Failed till now: " +
                   str(self.__report.getTestStats()[2]))
コード例 #4
0
    def markTestCaseFailed(self, reportObj, valType, testCaseObj):
        self.__report = reportObj
        #         print testCaseObj
        #         testCaseObj['status'] = 'FAIL'
        dataDiction = testCaseObj.get(testCaseObj.keys()[0])
        #         dataDiction.update({'status':{'value':'FAIL', 'visible': True, 'order': 0}})
        dataDiction['status']['value'] = 'FAIL'
        testCaseObj[testCaseObj.keys()[0]] = dataDiction

        self.__report.updateFailedTestCount(valType)
        self.__report.updateResult(valType, testCaseObj, 'Failed')
        if dataDiction.get('testLinkId').get('value') and Globals.TESTLINK:
            #             self.updateTestLink(testCaseObj['testLinkId'], "FAIL", reason=testCaseObj['description']['failReason'])
            self.updateTestLink(dataDiction)

        logs.debug("Total test Cases executed till now: " +
                   str(self.__report.getTestStats()[0]))
        logs.debug("Total test Cases Passed till now: " +
                   str(self.__report.getTestStats()[1]))
        logs.debug("Total test Cases Failed till now: " +
                   str(self.__report.getTestStats()[2]))
コード例 #5
0
    def getElementsSortedListByFieldName(self,
                                         response,
                                         field,
                                         URL='',
                                         sort=True,
                                         intValues=True,
                                         limit=None,
                                         lowerCase=False,
                                         removeEmptyValue=True,
                                         text='id=":',
                                         closetext='" version'):
        '''
        returns sorted list of elements from response
        Check if response is xml, json or csv.
        cut the response till the field is found, then take the other part and take out its value,
        again repeat this process and so on, keep storing all values in list and return as per parameter passed.
        '''
        if URL:
            self.__URL = URL
        else:
            self.__URL = response

        response = str(response).replace("'", "\"")
        csvFile = False
        if 'stix' in URL:
            pass

        elif self.is_xml(response) or '<?xml version=\"1.0\"' in response:
            text = "<" + field + ">"
            closetext = "</" + field + ">"
        elif self.is_json(self.__URL) or 'json' in self.__URL:
            text = "\"" + field + "\":"
            closetext = ","

        elif 'csv' in self.__URL or self.isResponseCsv(response):
            csvFile = True
            with (open("/tmp/temp.csv", 'w')) as f:
                f.write(response)
        else:
            logs.debug("Making default as json")
            text = "\"" + field + "\":"
            closetext = ","

        findList = []
        if csvFile:
            i = 1
            index = 0
            with (open("/tmp/temp.csv", 'r')) as f:
                for line in f:
                    line = self.removeExtraCommaFromCSV(line)
                    line = self.cleanResponse(line)
                    if i == 1:
                        #get the index for required field in list split by ","
                        array = line.split(",")
                        try:
                            index = list(array).index(field)
                            i += 1
                        except Exception as e:
                            logs.error(
                                "Required field {} not found in line: {}, returning empty array"
                                .format(field, line))
                            logs.error(str(e))
                            return []
                    else:
                        #then for that index take out the value in next coming rows
                        try:
                            value = line.split(",")[index]
                            if intValues:
                                findList.append(int(value))
                            elif lowerCase:
                                findList.append(str(value).lower().strip())
                            else:
                                findList.append(value.strip())
                        except:
                            pass
                f.close()

        else:
            string = response
            maximum = string.count(text)

            if limit < maximum and not limit == None:
                maximum = limit

            for temp in range(0, maximum):
                try:
                    tup = str(string).partition(text)
                    string = tup[2]
                    tup2 = string.partition(closetext)
                    if intValues:
                        findList.append(
                            int(str(tup2[0]).strip().replace("\"", "")))

                    elif lowerCase:
                        findList.append(
                            str(tup2[0]).replace("{", '').replace(
                                '[', '').replace(']',
                                                 '').replace('}', '').replace(
                                                     "\"", '').strip().lower())

                    else:
                        findList.append(
                            str(tup2[0]).replace("{", '').replace(
                                '[', '').replace(']',
                                                 '').replace('}', '').replace(
                                                     "\"", '').strip())
                except:
                    pass
        if removeEmptyValue:
            new = []
            # To remove empty values in a list
            for li in findList:
                if li:
                    new.append(li)
            findList = new

        if sort:
            findList = sorted(findList)

        return findList
コード例 #6
0
    def getURLResponse(self,
                       url,
                       requestType='GET',
                       headers=None,
                       body='',
                       verifyCert=False,
                       returnTimeTaken=False,
                       fileObjectDict=None,
                       responseIsFile=False,
                       responseHeaders=False,
                       **kwargs):
        '''
        give full URL to this like "http://google.com"
        ## kwargs arguments : 'updateHeaders' to allow update headers with Content-Type = application/json and 'certPath' which accepts certificate path from system.
        Returns variable responses, see argument list, first is response Code and other is response string and so on as 
        per arguments given
        => If u dont pass headers default will be 
            {'Content-Type':'application/json',
              'Accept' : 'application/json',
             }
        => If u dont want any headers to be passed or passed header should not be updated with 
            default value of Content-Type and Accept, pass 'updateHeaders=False' from your calling place of getURLResponse()
        
        If any thing more need to be given, pass that in headers, or if need to be overridden pass that too
        so if Accept should be text/xml, pass that in headers, it will be overridden.
        '''

        Globals.apiCount += 1
        logs.debug("Total API Hit Till Now {}".format(Globals.apiCount))
        finalHeaders = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        }
        if headers:
            if kwargs and kwargs.get('updateHeaders'):
                finalHeaders.update(headers)
                headers = finalHeaders
#         print "headers", headers

        certPath = kwargs.get('certPath')
        if certPath:
            print "using certificate Path '" + certPath + "' from certPath argument"
        logs.debug("Headers used for this query is {}".format(headers))

        try:
            logs.debug("Hitting {}".format(url))
            logs.debug("Post Data for this : {}".format(body))

            try:
                start = time.time()
                #                 self.flag = "request"
                #                 url = self.baseURL+url
                #                 url = "https://"+url if self.protocolHTTPS else "http://"+url
                if "post" in requestType.lower():
                    response = self.__request.post(
                        url,
                        data=body,
                        headers=headers,
                        verify=verifyCert,
                        cert=certPath,
                        files=fileObjectDict if fileObjectDict else None)

                elif "get" in requestType.lower():
                    response = self.__request.get(url,
                                                  headers=headers,
                                                  verify=verifyCert,
                                                  cert=certPath)

                elif "put" in requestType.lower():
                    response = self.__request.put(url,
                                                  data=body,
                                                  headers=headers,
                                                  verify=verifyCert,
                                                  cert=certPath)

                elif "delete" in requestType.lower():
                    response = self.__request.delete(url,
                                                     data=body,
                                                     headers=headers,
                                                     verify=verifyCert,
                                                     cert=certPath)

                elif "patch" in requestType.lower():
                    response = self.__request.patch(url,
                                                    data=body,
                                                    headers=headers,
                                                    verify=verifyCert,
                                                    cert=certPath)

                else:
                    return "Method Not supported in request module", "Method Not supported in request module", 000
                timeTaken = time.time() - start
                timeTaken = float("%.2f" % timeTaken)
                print "Got response for {} took {} seconds".format(
                    url,
                    time.time() - start)

                if responseIsFile:
                    filePath = os.path.join(os.getcwd(),
                                            "temp_" + str(int(time.time())))
                    with open(filePath, "a") as f:
                        f.write(response.content)

                    if returnTimeTaken:
                        return response.status_code, filePath, timeTaken
                    else:
                        return response.status_code, filePath

                if returnTimeTaken and not responseHeaders:
                    return response.status_code, response.content, timeTaken
                elif returnTimeTaken and responseHeaders:
                    return response.status_code, response.content, timeTaken, response.headers
                elif not returnTimeTaken and responseHeaders:
                    return response.status_code, response.content, response.headers
                else:
                    return response.status_code, response.content
            #http://stackoverflow.com/questions/8734617/python-django-badstatusline-error
            except BadStatusLine as e:
                logs.debug("Query {} took {} seconds".format(
                    url,
                    time.time() - start))
                self.__init__()
                logs.error("BAD STATUS LINE EXCEPTION OCCURRED" + str(e))
                logs.error(traceback.format_exc())
                if returnTimeTaken:
                    return "", "Bad Status Line Exception" + traceback.format_exc(
                    ), "NotCalculated"
                else:
                    return "", "Bad Status Line Exception" + traceback.format_exc(
                    )

        except Exception as e:
            logs.error(e)
            print(traceback.format_exc())
            if returnTimeTaken:
                return "Exception Occurred", traceback.format_exc(
                ), "Not Calculated"
            else:
                return "Exception Occurred", traceback.format_exc()