Beispiel #1
0
 def add_test(self):
     from model import Test
     for i in range(3):
         test = Test()
         test.name='fengxin'
         self.session.add(test)
         self.session.commit()
def prepareTestList(files, subdir):
    testList = []
    for file in files:
        filePath = os.path.join(subdir, file)
        if (filePath.endswith('.xml')):
            document = ET.parse(filePath)
            root = document.getroot()
            for testcase in root.findall('testcase'):
                name = testcase.attrib['name']
                duration = testcase.attrib['time']
                failure = testcase.find('failure')

                regex = re.compile("([a-zA-Z]+)_([a-zA-Z]+)_([0-9]+)")
                match = regex.match(str(name))
                testId = "_".join(match.groups())
                uid = match.group(3)
                steps = getStepsForTest(testId, subdir)

                if failure is None:
                    test = Test(name, uid, duration, "", steps, False)
                    testList.append(test)
                else:
                    test = Test(name, uid, duration, failure.text[:200], steps,
                                True)
                    testList.append(test)

    return testList
def add_test(input_subject, input_grade, input_picture, input_description,
             input_solution, input_username):
    print("tring to add!!!!!!!!!!!!!!!!!!!!!!!!!")

    test_object = Test(subject=input_subject,
                       grade=input_grade,
                       picture=input_picture,
                       solution=input_solution,
                       username=input_username,
                       description=input_description)
    session.add(test_object)
    session.commit()
Beispiel #4
0
def ObtenerDatos(filename):
    resultado = TestRun()
    trx_file = open(filename, 'r')
    xml_temp = open(TEMP_FILE_NAME, 'w')
    for line in trx_file:
        xml_temp.write(line.replace('&#', ''))
    trx_file.close()
    xml_temp.close()
    xmldoc = minidom.parse(TEMP_FILE_NAME)

    try:

        # Obtencion de datos del Test Run

        testrun = xmldoc.getElementsByTagName("TestRun")[0]
        resultado.id_testrun = testrun.attributes["id"].value
        resultado.nombre_maquina_testrun = testrun.attributes["name"].value
        resultado.nombre_usuario_testrun = testrun.attributes["runUser"].value

        tiempos = testrun.getElementsByTagName("Times")[0]
        resultado.creacion_testrun = parseTIME(tiempos.attributes["creation"].value)
        resultado.finalizacion_testrun = parseTIME(tiempos.attributes["finish"].value)
        resultado.encolado_testrun = parseTIME(tiempos.attributes["queuing"].value)
        resultado.inicio_testrun = parseTIME(tiempos.attributes["start"].value)

        configuraciones = testrun.getElementsByTagName("TestSettings")[0]
        resultado.id_configuraciones = configuraciones.attributes["id"]
        resultado.nombre_configuraciones = configuraciones.attributes["name"]
        deployado = configuraciones.getElementsByTagName("Deployment")[0]
        resultado.deployado = deployado.attributes["runDeploymentRoot"].value

        resumen = testrun.getElementsByTagName("ResultSummary")[0]
        resultado.resultado = resumen.attributes["outcome"].value
        numeros = resumen.getElementsByTagName("Counters")[0]
        resultado.abortados = numeros.attributes["aborted"].value
        resultado.completos = numeros.attributes["completed"].value
        resultado.desconectados = numeros.attributes["disconnected"].value
        resultado.errores = numeros.attributes["error"].value
        resultado.ejecutados = numeros.attributes["executed"].value
        resultado.fallidos = numeros.attributes["failed"].value
        resultado.en_progreso = numeros.attributes["inProgress"].value
        resultado.inconclusos = numeros.attributes["inconclusive"].value
        resultado.no_ejecutados = numeros.attributes["notExecuted"].value
        resultado.no_ejecutables = numeros.attributes["notRunnable"].value
        resultado.pasados = numeros.attributes["passed"].value
        resultado.pasados_abortados = numeros.attributes["passedButRunAborted"].value
        resultado.pendientes = numeros.attributes["pending"].value
        resultado.timeout = numeros.attributes["timeout"].value
        resultado.total = numeros.attributes["total"].value
        resultado.alertas = numeros.attributes["warning"].value

        # Obtencion de datos los Test
        lista_unit_test_result = testrun.getElementsByTagName("UnitTestResult")
        lista_unit_test = testrun.getElementsByTagName("UnitTest")
        lista_test_entry = testrun.getElementsByTagName("TestEntry")

        if not len(lista_unit_test_result) == len(lista_unit_test) == len(lista_test_entry):
            raise Exception("Incongruencia en cantidad de Test")

        cantidad = len(lista_unit_test_result)
        lista_clases = []

        for indice_test in range(0, cantidad):
            test = Test()
            unit_test_result = lista_unit_test_result[indice_test]
            unit_test = lista_unit_test[indice_test]
            test_entry = lista_test_entry[indice_test]
            if not (
                unit_test_result.attributes["testId"].value ==
                unit_test.attributes["id"].value ==
                test_entry.attributes["testId"].value
               ):
                    raise Exception("Incongruencia en ID de Test")

            # Obtencion de datos del Test

            test.id = unit_test_result.attributes["testId"].value
            test.computadora_test = unit_test_result.attributes["computerName"].value
            test.duracion = parseTIMEDELTA(unit_test_result.attributes["duration"].value)
            test.fin = parseTIME(unit_test_result.attributes["endTime"].value)
            test.id_ejecucion = unit_test_result.attributes["executionId"].value
            test.resultado = unit_test_result.attributes["outcome"].value
            test.resultado_id = unit_test_result.attributes["relativeResultsDirectory"].value
            test.inicio = parseTIME(unit_test_result.attributes["startTime"].value)
            test.id_lista = unit_test_result.attributes["testListId"].value
            test.nombre_test = unit_test_result.attributes["testName"].value
            test.tipo_test = unit_test_result.attributes["testType"].value
            metodo_test = unit_test.getElementsByTagName("TestMethod")[0]
            test.clase_test = metodo_test.attributes["className"].value.split(".")[-1]
            lista_clases.append(test.clase_test)

            if (len(unit_test_result.getElementsByTagName("Output")) > 0):
                msj = unit_test_result.getElementsByTagName("Message")[0]
                test.mensaje = msj.childNodes[0].nodeValue
                error = unit_test_result.getElementsByTagName("StackTrace")[0]
                test.error = error.childNodes[0].nodeValue
            else:
                test.mensaje = None
                test.error = None

            test.completar(TEST_EXITOSO_TEXTO)
            resultado.tests.append(test)

        lista_listas_test = testrun.getElementsByTagName("TestList")

        if len(lista_listas_test) > 0:
            for lista_test in lista_listas_test:
                lista = ListaTest()
                lista.id_lista = lista_test.attributes["id"].value
                lista.nombre_lista = lista_test.attributes["name"].value
                lista.tests = filter(lambda t: t.id_lista == lista.id_lista, resultado.tests)

                lista.completar()
                resultado.listas_test.append(lista)

        if len(lista_clases) > 0:
            for clase_test in lista_clases:
                clase = ClaseTest()
                clase.nombre_clase = clase_test
                clase.tests = filter(lambda t: t.clase_test == clase_test, resultado.tests)
                clase.completar()
                resultado.clases_test.append(clase)

    except Exception as e:
        raise e
    finally:
        # Limpieza de temporales
        if os.path.isfile(TEMP_FILE_NAME):
            os.remove(TEMP_FILE_NAME)

    resultado.completar()
    return resultado
Beispiel #5
0
    def test(self):
        for x in self.urls:
            test = Test()
            print("calling: " + x)
            try:
                r = requests.get(url=x)

                if r.status_code < 300:
                    test.set_message("Success with status code " +
                                     str(r.status_code))
                    test.set_result("Success")
                elif r.status_code < 400:
                    test.set_message("Redirect with status code " +
                                     str(r.status_code))
                    test.set_result("failed")
                elif r.status_code < 500:
                    test.set_message("Bad request with status code " +
                                     str(r.status_code))
                    test.set_result("failed")
                else:
                    test.set_message(
                        "internal server error with status code " +
                        str(r.status_code))
                    test.set_result("failed")
            except requests.exceptions.ConnectionError as e:
                test.set_message("connection failed")
            self.testResults.append(test)
Beispiel #6
0
# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__ = "jingyi"
__date__ = "$2015-5-4 7:10:34$"

if __name__ == "__main__":
    import model.Test as run
    run.main()
    def runTest(self):
        print("\n############## Running telnet tests ################\n")
        for connection in self.conns:
            test = Test()
            test.set_test_method("Telnet socket connect test")
            ip = connection
            port = self.conns[connection]
            print("\n####### connecting to " + ip + " : " + str(port) +
                  " ########\n")
            try:
                tn = telnetlib.Telnet(ip, port)
                print(tn.read_all())
                test.set_message("Successfully connected to: " + connection +
                                 ":" + conns[connection])
                test.set_result("Success")
                tn.close()

            except TimeoutError as e:
                test.set_message("Failed to connect to: " + connection + ":" +
                                 str(conns[connection]) + " with error \n" +
                                 "Time Out Error error({0}): {1}".format(
                                     e.errno, e.strerror))
                test.set_result("failed")
                print("Time Out Error error({0}): {1}".format(
                    e.errno, e.strerror))
            self.testResults.append(test)
Beispiel #8
0
    except:
        pass
    else:
        for pkg in packages:
            pip.main(["install", pkg])
        os.remove(pkgfile)

    from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
    from sklearn.svm import SVC
    from sklearn.tree import DecisionTreeClassifier
    from model import Test
    import warnings

    with warnings.catch_warnings():

        warnings.simplefilter("ignore")

        model = Test(testing_file="labeled")

        model.RandomSelection()
        model.PreBuiltModel(estimator=RandomForestClassifier(n_estimators=35))
        model.PreBuiltModel(estimator=SVC(C=10.0,
                                          gamma=.001,
                                          probability=True,
                                          decision_function_shape="ovr"))
        model.BinaryEnsemble(base_estimator=DecisionTreeClassifier())
        model.BinaryEnsemble(base_estimator=SVC(C=10.0,
                                                gamma=.001,
                                                probability=True,
                                                decision_function_shape="ovr"))
    def post(self):
        post = simplejson.loads(self.request.body)

        phoneKey = None
        deviceKey = None
        brandKey = None
        benchmarkKey = None

        phoneID = None
        device = None
        brand = None
        totalScore = None
        testResults = []
        
        # get post data
        try:
            phoneID = post["phoneid"]
            device = post["device"]    
            brand = post["brand"]
            totalScore = int(post["total_score"])
            testResults = post["results"]
        except KeyError:
            self.error(404)
        
        if phoneID is not None and device is not None and brand is not None and totalScore is not None and testResults: 
            query = Phone.all()
            query.filter("phoneid =", phoneID)
            results = query.fetch(1)
            
            # get phone key
            if query.count(1) > 0:
                phoneKey = results[0].key() 
            else:
                phoneKey = Phone(
                    phoneid = phoneID
                ).put()

            query = Device.all()
            query.filter("name =", device)
            results = query.fetch(1)

            # get device key
            if query.count(1) > 0:
                deviceKey = results[0].key()
            else:       
                query = Brand.all()
                query.filter("brandname =", brand)
                results = query.fetch(1)
                
                # get brand key
                if query.count(1) > 0:
                     brandKey = results[0].key()
                else:
                    # add brand
                    brandKey = Brand(
                        brandname = brand
                    ).put()

                # add device
                deviceKey = Device(
                    brandkey = Key(brandKey),
                    name = device
                ).put()
                
            # new benchmark           
            if phoneKey is not None and deviceKey is not None:
                benchmarkKey = Benchmark(
                    phonekey = phoneKey,
                    devicekey = deviceKey,
                    total_score = totalScore
                ).put()

                if benchmarkKey is not None:                    
                    for result in testResults:
                        test = None
                        testKey = None
                        
                        try:
                            test = result["test"]
                        except KeyError:
                            self.error(404)


                        # get test key
                        query = Test.all()
                        query.filter("name =", test)
                        results = query.fetch(1)
                        
                        # get phone key
                        if query.count(1) > 0:
                            testKey = results[0].key() 

                        score = None
                        successful = None

                        try:                        
                            score = int(result["score"])
                            successful = bool(result["successful"])
                        except KeyError:
                            self.error(404)                          

                        if testKey is not None and score is not None and successful is not None:
                            # put test result
                            testResultKey = TestResult(
                                benchmarkkey = benchmarkKey,
                                testkey = testKey,
                                score = score,
                                successful = successful
                            ).put()
                            if not testResultKey:
                                self.error(405)
                                break;
                        else:
                            self.error(404)
                else:
                    self.error(404)
            else:
                self.error(404)
        else:
            self.error(404)
Beispiel #10
0
 def runTest(self):
     for connection in self.conns:
         test = Test()
         test.set_test_method("ping")
         resp = ""
         ip = connection
         try:
             op = subprocess.check_output(["ping", ip, "-n", "3"])
             x = str(op)
             y = x.split("\\r\\n")
             for i in y:
                 if not ('b\'' in i) and not ("'" in i):
                     resp += i + "\n"
             test.set_message(resp)
             test.set_result("Success")
             self.testResults.append(test)
         except subprocess.CalledProcessError as e:
             print(e)
             test.set_message("Request failed")
             test.set_result("failed")
             self.testResults.append(test)