Tuesday, August 26, 2014

Automatization in Python testing GUI (Python paramiko, Python xlrd, Python FTP)

Моя задача была протестировать работу WEB GUI приложения которое распознает видео и делает снимки далее выводит список комбинаций найденных на снимках.

Видео файл - в котором показываются однорукие бандиты казино, распознаются видео остановки барабанов и комбинаций выпавших.

import xlrd
from tkinter import *
from tkinter import messagebox
import paramiko
import time

'''
Function help to destroy program window
'''
def quit(root):
    root.destroy()


'''
Start program, connection by SSH
'''
def startConnectToSSH(event):
    try:
        host = str(loginent1.get())
        user = str(loginent2.get())
        secret = str(loginent3.get())
        port = int(loginent4.get())
       
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=host, username=user, password=secret, port=port)
        quit(loginssh)
        print("Connect is done")

       
        class videoProcessingDisplay():
            '''
            Function for display in UI all information
            '''
            def insertOtchet(self, str3):
                tex1.insert(INSERT, str3, "a")
               
        class videoProcessingClass():
          
            '''
            Function for clear rezults display 
            '''
            def clearOtchetWindow(self, event):
                tex1.delete(1.0, END)
           
            '''
            Button check Connect to SSH 
            '''
            def checkConnecttoSSH(self, event):
                disp.insertOtchet("Wait please check connection")
                disp.insertOtchet("\n")
                try:
                    client.exec_command('ls')
                    disp.insertOtchet("Connection is active")
                    disp.insertOtchet("\n")
                except BaseException as e:
                    disp.insertOtchet("Connection restored, stay 1 min.")
                    disp.insertOtchet("\n")
                    client.connect(hostname=host, username=user, password=secret, port=port)
                    return 2
                return 1
           
            '''
            Auto check Connect to SSH, automated
            '''
            def autoCheckConnecttoSSH(self):
                disp.insertOtchet("Wait please auto check connection")
                disp.insertOtchet("\n")
                try:
                    client.exec_command('ls')
                    disp.insertOtchet("Connection is active")
                    disp.insertOtchet("\n")
                except BaseException as e:
                    disp.insertOtchet("Connection restored, stay 1 min.")
                    disp.insertOtchet("\n")
                    client.connect(hostname=host, username=user, password=secret, port=port)
                    return 2
                return 1
           
            '''
            Main function how compare 2 files, automated
            '''
            def nashaloSravneniya(self, event):
                def convertFromdoubleToString(str4):
                    arr3 = []
                    for i in str4:
                        if i == 1.0:
                            arr3.append("GR")
                        elif i == 2.0:
                            arr3.append("OR")
                        elif i == 3.0:
                            arr3.append("PL")
                        elif i == 4.0:
                            arr3.append("LE")
                        elif i == 5.0:
                            arr3.append("BE")
                        elif i == 6.0:
                            arr3.append("CH")
                        elif i == 7.0:
                            arr3.append("GR")
                        else:
                            print("Error in elements")
                            break
            #             print(arr3)   
                    return arr3
               
                '''
                function how compare 2 string for example and say if is error
                a = [GR    GR    GR    ME    ME    CH    ME    ME    PL    OR    LE    LE    CH    ME    ME]
                b = [LE    OR    OR    LE    LE    LE    BE    BE    BE    OR    OR    GR    PL    PL    CH]
                '''
               
                def sravnenieStrok(str1,str2):
                    arr1 = []
                    arr2 = []
               
                    for i in str1:
                        arr1.append(i.rstrip().replace(" ","").split(","))
                    for i2 in str2:
                        arr2.append(i2.rstrip().replace(" ","").split(","))
                    #proverka dlini strok
                    if len(arr1[0]) != len(arr2[0]):
                        disp.insertOtchet("Error: files has different reels configs, check files")
                   
                    #probegau po 15 znacheniyam strok i sravnivau ix   
                    i3 = 1
                    bads = 0
                    while i3 <= 15:
                        #print(arr1[i3], arr2[i3])
                        if arr1[i3] == arr2[i3]:
                            i3=i3+1
                        else:
                            i3=i3+1
                            bads=bads+1
                    disp.insertOtchet("Errors = {}" .format(bads))
                    disp.insertOtchet("\n")
                    return bads  
               
               
                choiseFomatFile = int(var.get())
                #print(choiseFomatFile)
                if choiseFomatFile == 0:
                    str5 = str(ent1.get())
                    str6 = str(ent2.get())
                    disp.insertOtchet("Choise csv format")
                   
                   
                    ins = open(str5, "r" )
                    testFileRows = []
                    for line in ins:
                        testFileRows.append(line.split(";"))
                    ins.close()
                   
                    ins1 = open(str6, "r" )
                    customerFileRows = []
                    for line1 in ins1:
                        customerFileRows.append(line1.split(";"))
                    ins1.close()
                   
                    try:
                        koefficentOfCorrection=0
               
                        for rownum in range(len(customerFileRows)):
                            numeraciyaStrok = ("Row =", rownum+1)
                            disp.insertOtchet(str(numeraciyaStrok))
                            disp.insertOtchet("\n")
                            if sravnenieStrok(testFileRows[rownum],customerFileRows[rownum+koefficentOfCorrection])>3:
                                disp.insertOtchet("String is very different, check comparing with next customer row")
                                disp.insertOtchet("\n")
                                if sravnenieStrok(testFileRows[rownum],customerFileRows[rownum+1])>3:
                                    disp.insertOtchet("Finaly, in test file row has many errors")
                                    disp.insertOtchet("\n")
                                else:
                                    koefficentOfCorrection=koefficentOfCorrection+1
                                    disp.insertOtchet("Timestamp is missed, to customer row number add 1 point. Correction = {}".format(koefficentOfCorrection))
                                    disp.insertOtchet("\n")
                               
                    except  AttributeError as err:
                        error = ("Error: {} break operation".format(err))
                        disp.insertOtchet("\n")
                        disp.insertOtchet(str(error))
                    except  IndexError as err1:
                        error1 = ("Number of timestamps is different in testing file and customer file")
                        disp.insertOtchet("\n")
                        disp.insertOtchet(str(error1))
                   
                else:
                    disp.insertOtchet("Choise xls format")
                    str5 = str(ent1.get())
                    str6 = str(ent2.get())
                    Testfile = ("Test file",   str5)
                    Customerfile = ("Customer file", str6)
               
                    disp.insertOtchet(str(Testfile))
                    disp.insertOtchet("\n")
                    disp.insertOtchet(str(Customerfile))
                    disp.insertOtchet("\n")
                   
               
                      
                    rbCustom = xlrd.open_workbook(str5,formatting_info=True)
                    sheet = rbCustom.sheet_by_index(0)
               
                    rbProgect = xlrd.open_workbook(str6,formatting_info=True)
                    sheetProgect = rbProgect.sheet_by_index(0)
            
                    '''
                    body of program, in opened both .xls files compare elements and do rezults table
                    '''
                   
                    try:
               
                        for rownum in range(sheet.nrows):
                            numeraciyaStrok = ("Row =", rownum+1)
                            disp.insertOtchet(str(numeraciyaStrok))
                            disp.insertOtchet("\n")
                            rowTest = sheet.row_values(rownum)
                            rowCustomer = sheetProgect.row_values(rownum)
                            sravnenieStrok(rowTest,rowCustomer)
                    except  AttributeError as err:
                        error = ("Error: {} break operation".format(err))
                        disp.insertOtchet("\n")
                        disp.insertOtchet(str(error))
           
           
            
            '''
            Command line client to server, button
            '''
            def testConnectBySSH(self, event):
                if self.autoCheckConnecttoSSH() == 1:
                    str6 = str(ent3.get())
                    disp.insertOtchet("\n")
                    stdin, stdout, stderr = client.exec_command(str6)
                    data = stdout.read() + stderr.read()
                    disp.insertOtchet(data)
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
            '''
            Send Digitizing.war to server, automated
            '''
            def testUploadFile(self):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Upload Digitizing.war to server")
                    disp.insertOtchet("\n")
                    ftp = client.open_sftp()
                    ftp.put('Digitizing.war', 'Digitizing.war')
                    ftp.close()
                    disp.insertOtchet("Ok, file copy from PC to server")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
           
            '''
            Download rezults from server button
            '''   
            def testDownloadFile(self,event):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Download rezults from server")
                    disp.insertOtchet("\n")
                    #cleapatra 10 min
                    stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=21&cols=5&rows=3\" --output-document=Cleapatra10min_x264.csv")
                    #cleapatra 1 min
                    #stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=22&cols=5&rows=3\" --output-document=Cleapatra1min_x264.csv")
                    time.sleep( 1 )
                    ftp = client.open_sftp()
                    #cleapatra 10 min
                    ftp.get('Cleapatra10min_x264.csv', 'Cleapatra10min_x264.csv')
                    #cleapatra 1 min
                    #ftp.get('Cleapatra1min_x264.csv', 'Cleapatra1min_x264.csv')
                    ftp.close()
                    disp.insertOtchet("Ok, file with rezults is comming to PC")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")

            '''
            Download rezults from server in automated scripts
            '''   
            def testDownloadFileAutomat(self):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Download rezults from server")
                    disp.insertOtchet("\n")
                    #cleapatra 10 min
                    stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=21&cols=5&rows=3\" --output-document=Cleapatra10min_x264.csv")
                    #cleapatra 1 min
                    #stdin, stdout, stderr = client.exec_command("wget \"http://192.168.10.221:8080/Digitizing/RawDataResponder?vid=22&cols=5&rows=3\" --output-document=Cleapatra1min_x264.csv")
                    time.sleep( 1 )
                    ftp = client.open_sftp()
                    #cleapatra 10 min
                    ftp.get('Cleapatra10min_x264.csv', 'Cleapatra10min_x264.csv')
                    #cleapatra 1 min
                    #ftp.get('Cleapatra1min_x264.csv', 'Cleapatra1min_x264.csv')
                    ftp.close()
                    disp.insertOtchet("Ok, file with rezults is comming to PC")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
           
            '''
            Get status of Video processing in server
            '''         
            def getStatusofVideoProcess(self):
                if self.autoCheckConnecttoSSH() == 1:
                    disp.insertOtchet("Get process = ")
                   
                    #cleopatra 1 min
                    #stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=getprocprogress&videoID=22\"")
                    #cleopatra 10 min
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=getprocprogress&videoID=21\"")
                               
                    data = stdout.read() + stderr.read()
                    pattern = r"progress\":([0-9]{1,3})"
                    regexp = re.compile(pattern)
                    s = regexp.findall(str(data))
                    znachenieVideoProcess = s[0]
                    disp.insertOtchet(znachenieVideoProcess)
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
                return znachenieVideoProcess
           
           
            '''
            Update new Build of VideoRecognization programon to Server
            ''' 
            def updateNewBuildofVideoRecognizationProgramonServer(self, event):
                if self.autoCheckConnecttoSSH() == 1:
                    time.sleep( 1 )
                    disp.insertOtchet("Process of updateing new build on server is start, remain 30 second")
                    disp.insertOtchet("\n")
                   
                    time.sleep( 1 )
                    stdin, stdout, stderr = client.exec_command("rm Digitizing.war")
                   
                    time.sleep( 1 )
                    main.testUploadFile()
                   
                    time.sleep( 5 )
            
                    stdin, stdout, stderr = client.exec_command("/opt/tomcat8/bin/shutdown.sh")
                   
                    time.sleep( 2 )
                   
                    stdin, stdout, stderr = client.exec_command("sudo rm -rf /opt/tomcat8/webapps/Digitizing")
                   
                    time.sleep( 5 )
                   
                    stdin, stdout, stderr = client.exec_command("cp Digitizing.war /opt/tomcat8/webapps/")
                   
                    time.sleep( 5 )
                   
                    stdin, stdout, stderr = client.exec_command("cd /opt/tomcat8/webapps/ && unzip Digitizing.war -d Digitizing")
                   
                    time.sleep( 10 )
                   
                    stdin, stdout, stderr = client.exec_command("/opt/tomcat8/bin/startup.sh")
                   
                    time.sleep( 5 )
                   
                    stdin, stdout, stderr = client.exec_command("sudo reboot")
            
                    disp.insertOtchet("\n")
                    disp.insertOtchet("Operation is well done")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
       
            '''
            Start process VideoRecognization on Server
            '''         
            def startProcessVideoRecognizationOnServer(self, event):
                if self.autoCheckConnecttoSSH() == 1:
                    time.sleep( 1 )
                   
                    disp.insertOtchet("Start process of video recognization on server")
                    print("Start process of video recognization on server")
                    disp.insertOtchet("\n")
                    time.sleep( 2 )
               
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=cleanup\"")
                    
                    disp.insertOtchet("Clean tables \n")
                    print("Clean tables")
                    time.sleep( 2 )
                    
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=inittables\"")
                    
                    disp.insertOtchet("Create tables \n")
                    print("Create tables")
                    time.sleep( 2 )
                   
                    stdin, stdout, stderr = client.exec_command("cd && rm Cleapatra10min_x264.csv")
                   
                    time.sleep( 1 )
                            
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=addproject&name=testVideo53&reels=2&description=Autotest\"")
                    
                    disp.insertOtchet("Create progect \n")
                    print("Create progect")
                    time.sleep( 2 )
       
                    #cleopatra 10 min
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=addvideo&fileName=Cleapatra10min_x264.mp4\"")           
                    #cleopatra 1 min
                    #stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=addvideo&fileName=Cleapatra1min_x264.mp4\"")
                    
                    disp.insertOtchet("Open file Cleapatra10min_x264.mp4 \n")
                    print("Open file Cleapatra10min_x264.mp4")
                    time.sleep( 2 )
                   
                    #cleopatra 10 min
                    stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=startvideoproc&videoID=21&timestamp=0&cols=5&rows=3&x1=0.10015649452269171&y1=0.3235908141962422&x2=0.917057902973396&y2=0.32150313152400833&x3=0.10485133020344288&y3=0.9728601252609603&x4=0.8998435054773083&y4=0.9624217118997912\"")
                    #cleopatra 1 min
                    #stdin, stdout, stderr = client.exec_command("curl \"http://192.168.10.221:8080/Digitizing/Commander?request=startvideoproc&videoID=22&timestamp=0&cols=5&rows=3&x1=0.10015649452269171&y1=0.3235908141962422&x2=0.917057902973396&y2=0.32150313152400833&x3=0.10485133020344288&y3=0.9728601252609603&x4=0.8998435054773083&y4=0.9624217118997912\"")
                    
                    disp.insertOtchet("Video proccesing is start \n")
                    print("Video proccesing is start")
                    time.sleep( 2 )
                   
                    b=0
                    while True:
                        print(b)
                        if ((int(self.getStatusofVideoProcess()) != 0) or b==1):
                            b=1
                            if ((int(self.getStatusofVideoProcess()) == 0 or int(self.getStatusofVideoProcess()) == 100) and b==1):
                                main.testDownloadFileAutomat()
                                print("Download rezults !")
                                break
                            else:
                                disp.insertOtchet("Wait please, process in progress = \n")
                                print("In progress = ", self.getStatusofVideoProcess(), "\n")
                                disp.insertOtchet(self.getStatusofVideoProcess())
                                time.sleep( 5 )
                        else:
                            disp.insertOtchet("Wait please, process in progress = \n")
                            print("Wait please, process in progress = ", self.getStatusofVideoProcess(), "\n")
                            disp.insertOtchet(self.getStatusofVideoProcess())
                            time.sleep( 2 )
           
                
            
                    disp.insertOtchet("Ok, file with rezults is comming to PC press button Compare combinations in files")
                else:
                    disp.insertOtchet("Check your connection")
                    disp.insertOtchet("\n")
                   
        disp = videoProcessingDisplay()
        main = videoProcessingClass()
        
        '''
        GUI of program
        '''
        user = Tk()
        user.title("Vuni combination tester")
        user.grid(100, 100, 300, 300)
       
        def handler():
            if messagebox.askyesno("Exit", "Exit from program") == True:
                client.close()
                quit(user)
        user.protocol("WM_DELETE_WINDOW", handler)
       
        lab1 = Label(user, text="Testing file name ", font="Arial 10")
        ent1 = Entry(user, width=40, bd=3, text="testing file")
        ent1.insert(0, "Cleapatra10min_x264.csv")
       
        lab2 = Label(user, text="Customer file name ", font="Arial 10")
        ent2 = Entry(user, width=40, bd=3, text="customer file")
        ent2.insert(0, "LastVariandCleapatra10min_x264.csv")
       
        ent3 = Entry(user, width=40, bd=3, text="command line")
        ent3.insert(0, "cp Digitizing.war /opt/tomcat8/webapps/")
       
        tex1 = Text(user,width=50, height=25, font="Verdana 12",wrap=WORD)
       
        but1 = Button(user, text="Compare combinations in files ", width=25, height=1, font="Verdana 12")
        but2 = Button(user, text="Command to server by SSH", width=25, height=1, font="Verdana 12")
        but3 = Button(user, text="Clear window", width=25, height=1, font="Verdana 12")
        but4 = Button(user, text="Upload new build to server 30 sec", width=25, height=1, font="Verdana 12")
        but5 = Button(user, text="Start process of video on server", width=25, height=1, font="Verdana 12")
        but6 = Button(user, text="Check connection to Server", width=25, height=1, font="Verdana 12")
        but7 = Button(user, text="Download rezults", width=25, height=1, font="Verdana 12")
       
        but1.bind("<Button-1>", main.nashaloSravneniya)
        but2.bind("<Button-1>", main.testConnectBySSH)
        but3.bind("<Button-1>", main.clearOtchetWindow)
        but4.bind("<Button-1>", main.updateNewBuildofVideoRecognizationProgramonServer)
        but5.bind("<Button-1>", main.startProcessVideoRecognizationOnServer)
        but6.bind("<Button-1>", main.checkConnecttoSSH)
        but7.bind("<Button-1>", main.testDownloadFile)
       
        var=IntVar()
        var.set(0)
        rad0 = Radiobutton(user,text="csv",
                  variable=var,value=0)
        rad1 = Radiobutton(user,text="xls",
                  variable=var,value=1)
       
        lab1.grid(row=1, column=0)
        ent1.grid(row=2, column=0)
        lab2.grid(row=3, column=0)
        ent2.grid(row=4, column=0)
        tex1.grid(row=0, column=1)
        ent3.grid(row=6, column=1)
       
        rad0.grid(row=5, column=1)
        rad1.grid(row=5, column=2)
       
        but1.grid(row=5, column=0)
        but2.grid(row=6, column=0)
        but3.grid(row=7, column=0)
        but4.grid(row=8, column=0)
        but5.grid(row=9, column=0)   
        but6.grid(row=0, column=0)
        but7.grid(row=10, column=0)
       
        user.mainloop()
       
    except TimeoutError and paramiko.ssh_exception.AuthenticationException:
        messagebox.showwarning("Error", "Connect to host is unavailible")
        quit(loginssh)
        #print("Connect to host is unavailible - {}".format(err))


'''
If user press button Cancel, exit program
'''
def exitProgramAborted(event):
    print("Cancel")
    loginssh.quit()

if __name__ == "__main__":
   
    loginssh = Tk()
    loginssh.title("Connect to Server by SSH")
    loginssh.grid(100, 100, 200, 200)
   
    loginlab1 = Label(loginssh, text="Server machine host ", font="Arial 10")
    loginent1 = Entry(loginssh, width=40, bd=3, text="192.168.10.221")
    loginent1.insert(0, "192.168.10.221")
   
    loginlab2 = Label(loginssh, text="User name", font="Arial 10")
    loginent2 = Entry(loginssh, width=40, bd=3, text="user")
    loginent2.insert(0, "user")
   
    loginlab3 = Label(loginssh, text="User password", font="Arial 10")
    loginent3 = Entry(loginssh, width=40, bd=3, text="userpass")
    loginent3.insert(0, "userpass")
   
    loginlab4 = Label(loginssh, text="Server port", font="Arial 10")
    loginent4 = Entry(loginssh, width=40, bd=3, text="22")
    loginent4.insert(0, "22")
   
    loginbut1 = Button(loginssh, text="Cancel", width=10, height=2, font="Verdana 12")
    loginbut2 = Button(loginssh, text="Connect", width=10, height=2, font="Verdana 12")
   
    loginlab1.grid(row=0, column=0)
    loginent1.grid(row=0, column=1)
    loginlab2.grid(row=1, column=0)
    loginent2.grid(row=1, column=1)
    loginlab3.grid(row=2, column=0)
    loginent3.grid(row=2, column=1)
    loginlab4.grid(row=3, column=0)
    loginent4.grid(row=3, column=1)
   
    loginbut1.bind("<Button-1>", exitProgramAborted)
    loginbut2.bind("<Button-1>", startConnectToSSH)
   
    loginbut1.grid(row=4, column=1)
    loginbut2.grid(row=4, column=2)
   
   
    loginssh.mainloop()

Tuesday, August 19, 2014

Bash linux how to parsing log file

Разрабатывая приставку видео, мне как тестеровщику автоматизатору понадобилось парсить лог файл и в красивом виде преподносить заказчику (Excel format)

Пример лог файла приставки описан ниже:


#!/bin/bash

int choise;

if [ "$1" == "" ]; then
        echo "check loag file"
        echo "true way to execute program ./makeotchet.sh LOG_file.log number_of_tests"
        exit
else if [ "$2" == "" ]; then 
        echo "check number of tests"                                                                                                                                                                                     
        echo "true way to execute program ./makeotchet.sh LOG_file.log number_of_tests"
        exit
     fi                                                                                                                                  

fi

echo "1 - Make file to othcet"
echo "2 - Make finaly otchet"
numberoftest="$2"
logfile="$1"

function makefiletootchet
{
        echo "wifi parsing"
        #first wifi adapter
        cat $logfile | grep -A 22  First | grep Upload > wifiupload1adapter.log
        cat $logfile | grep -A 22  First | grep Download > wifidownload1adapter.log
        #second wifi adapter
        cat $logfile | grep -A 22  Second | grep Upload > wifiupload2adapter.log
        cat $logfile | grep -A 22  Second | grep Download > wifidownload2adapter.log
        echo "eth parsing"
        cat $logfile | grep -A 16  eth0 | grep Upload > ethupload.log
        cat $logfile | grep -A 16  eth0 | grep Download > ethdownload.log
        echo "mem parsing"
        cat $logfile | grep MemFree > memlog.log
        cat $logfile | grep Cached > cashedlog.log
        echo "cpu parsing"
        cat $logfile | grep idle > cpulog.log
       
        echo "cpu generate rezult"
        awk '{ print $2 }' cpulog.log | sed 's/%//g' | sed 's/\./,/g' > rez_cpu_log_user.log
        awk '{ print $4 }' cpulog.log | sed 's/%//g' | sed 's/\./,/g' > rez_cpu_log_sys.log
        awk '{ print $8 }' cpulog.log | sed 's/%//g' | sed 's/\./,/g' > rez_cpu_log_free.log
       
        echo "wifi generate rezult"
        awk '{ print $11 }' wifiupload1adapter.log > rez_wifiuplod1adapter.log
        awk '{ print $11 }' wifidownload1adapter.log > rez_wifidown1adapter.log
        awk '{ print $11 }' wifiupload2adapter.log > rez_wifiuplod2adapter.log                                                                                                 
        awk '{ print $11 }' wifidownload2adapter.log > rez_wifidown2adapter.log
       
        echo "eth generate rezult"
        awk '{ print $11 }' ethupload.log > rez_ethuplod.log
        awk '{ print $11 }' ethdownload.log > rez_ethdown.log
       
        echo "memory generate rezult"
        awk '{ print $2 }' memlog.log > rez_memlog.log
        awk '{ print $2 }' cashedlog.log > rez_cashedlog.log
       
        exit   
}

function makefinalyotchet
{
       
        stroka=1
        echo "Start parsing"
        touch finalyothcet.csv
        echo "Memory;Cashed;Wifi_up1adapter;Wifi_down1adapter;Wifi_up2adapter;Wifi_down2adapter;CPU_free;CPU_sys;CPU_user;ETH_down;ETH_upl" > finalyothcet.csv
       
        for i in $(seq 1 $numberoftest); do

          nomerstroki=$stroka'p'
          fullzapis0=`sed -n -e $nomerstroki rez_memlog.log`
          fullzapis1=`sed -n -e $nomerstroki rez_cashedlog.log`
          fullzapis2=`sed -n -e $nomerstroki rez_wifiuplod1adapter.log`
          fullzapis3=`sed -n -e $nomerstroki rez_wifidown1adapter.log`
          fullzapis4=`sed -n -e $nomerstroki rez_wifiuplod2adapter.log`                                                                                                
          fullzapis5=`sed -n -e $nomerstroki rez_wifidown2adapter.log`   
          fullzapis6=`sed -n -e $nomerstroki rez_cpu_log_free.log`
          fullzapis7=`sed -n -e $nomerstroki rez_cpu_log_sys.log`
          fullzapis8=`sed -n -e $nomerstroki rez_cpu_log_user.log`
          fullzapis9=`sed -n -e $nomerstroki rez_ethdown.log`
          fullzapis10=`sed -n -e $nomerstroki rez_ethuplod.log`
         
          skoba=";"
          fullzapisfin="$fullzapis0$skoba$fullzapis1$skoba$fullzapis2$skoba$fullzapis3$skoba$fullzapis4$skoba$fullzapis5$skoba$fullzapis6$skoba$fullzapis7$skoba$fullzapis8$skoba$fullzapis9$skoba$fullzapis10$skoba"
          echo $fullzapisfin >> finalyothcet.csv
          stroka=$((stroka+1))
         done;
         
        echo "Make finaly otchet end"
       
        rm ethupload.log
        rm ethdownload.log
        rm memlog.log
        rm cpulog.log
        rm rez_cpu_log_user.log
        rm rez_cpu_log_sys.log
        rm rez_cpu_log_free.log
        rm wifiupload1adapter.log
        rm wifidownload1adapter.log
        rm wifiupload2adapter.log
        rm wifidownload2adapter.log
        rm rez_wifiuplod1adapter.log
        rm rez_wifidown1adapter.log
        rm rez_wifiuplod2adapter.log
        rm rez_wifidown2adapter.log
        rm rez_ethuplod.log
        rm rez_ethdown.log
        rm rez_cashedlog.log
        rm rez_memlog.log
        rm cashedlog.log
       
       
        exit
}

select choise in "1" "2";
 do

    echo you picked $choise
    if [ $choise == 1 ]; then
       echo "Your choise 1"
       makefiletootchet;
   
               
    else if [ $choise == 2 ]; then
        echo "Your choise 2"
        makefinalyotchet;
                             
        fi
   
    fi
    break;
 done

На выходе имею файл Excel -который парсит загрузку памяти, Wifi, Ethernet, CPU:
Memory;Cashed;Wifi_up1adapter;Wifi_down1adapter;Wifi_up2adapter;Wifi_down2adapter;CPU_free;CPU_sys;CPU_user;ETH_down;ETH_upl
49280;22236;23313;83,3;8,3;8,3;85040;50735
...
...

________________________EXAMPLE OF LOG FILE___________________________________
***** Start test 0 *****
MemFree:           49280 kB
Buffers:           17704 kB
CPU test begin
CPU:  8.3% usr  8.3% sys  0.0% nic 83.3% idle  0.0% io  0.0% irq  0.0% sirq
[7m  PID  PPID USER     STAT   VSZ %MEM CPU %CPU COMMAND [0m
17868 17861 root     S     3128  1.6   0  0.0 grep CPU
lan test
[network Thu Jan  1 00:00:50 PST 1970] iface = eth0; start time is 28847 ; timeout is 12
[network Thu Jan  1 00:00:51 PST 1970] ip_addr suuccessful; current time is 28851
[network Thu Jan  1 00:00:51 PST 1970] ping
PING 10.54.4.156 (10.54.4.156): 56 data bytes

--- 10.54.4.156 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 4.192/4.192/4.192 ms
[network Thu Jan  1 00:00:51 PST 1970] ping successful; current time is 28851
[network Thu Jan  1 00:00:51 PST 1970] iface_up: time = 4
[network Thu Jan  1 00:00:51 PST 1970] waiting for 17983 process...
[network Thu Jan  1 00:00:51 PST 1970] doing iperf to 10.54.4.156 ...
[network Thu Jan  1 00:00:55 PST 1970] Upload rate: 50735 kbps
[network Thu Jan  1 00:00:55 PST 1970] Download rate: 85040 kbps
[network Thu Jan  1 00:00:55 PST 1970] process finished
[network Thu Jan  1 00:00:55 PST 1970] iperf: unexpected_end = 28851
[network Thu Jan  1 00:00:55 PST 1970] iperf: current_time = 28855
[network Thu Jan  1 00:00:55 PST 1970] iperf: time = 4
[network] ethernet: Passed, 8 s (ifup: 4, iperf: 4)
[network] exit 0
LAN test begin
CPU:  0.0% usr  9.0% sys  0.0% nic 90.9% idle  0.0% io  0.0% irq  0.0% sirq
[7m  PID  PPID USER     STAT   VSZ %MEM CPU %CPU COMMAND [0m
18027 17861 root     S     3128  1.6   0  0.0 grep CPU
wifi test milan
[network Thu Jan  1 00:00:56 PST 1970] Searching for Wi-Fi USB device...
[network Thu Jan  1 00:00:56 PST 1970] Wi-Fi USB device found: 1
[network Thu Jan  1 00:01:01 PST 1970] Reenabling Ethernet (ip=192.168.1.1,gw=192.168.1.10)
[network Thu Jan  1 00:01:03 PST 1970] iface = wlan0; start time is 28856 ; timeout is 12
[network Thu Jan  1 00:01:03 PST 1970] ip_addr suuccessful; current time is 28863
[network Thu Jan  1 00:01:03 PST 1970] ping
PING 10.54.4.156 (10.54.4.156): 56 data bytes

--- 10.54.4.156 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 12.128/12.128/12.128 ms
[network Thu Jan  1 00:01:03 PST 1970] ping successful; current time is 28863
[network Thu Jan  1 00:01:03 PST 1970] iface_up: time = 7
[network Thu Jan  1 00:01:03 PST 1970] doing iperf to 10.54.4.156 ...
[network Thu Jan  1 00:01:03 PST 1970] waiting for 18172 process...
[network Thu Jan  1 00:01:07 PST 1970] Upload rate: 22236 kbps
[network Thu Jan  1 00:01:08 PST 1970] Download rate: 23313 kbps
[network Thu Jan  1 00:01:08 PST 1970] process finished
[network] wifi: ERROR: Slow download rate (23313)
[network Thu Jan  1 00:01:08 PST 1970] Shutting down wlan0 network interface
[network] exit 1
second test wifi begin
CPU:  0.0% usr  9.0% sys  0.0% nic 90.9% idle  0.0% io  0.0% irq  0.0% sirq
[7m  PID  PPID USER     STAT   VSZ %MEM CPU %CPU COMMAND [0m
18221 17861 root     S     3128  1.6   0  0.0 grep CPU
wifi test ap-lo-07
[network Thu Jan  1 00:01:09 PST 1970] Searching for Wi-Fi USB device...
[network Thu Jan  1 00:01:09 PST 1970] Wi-Fi USB device found: 1
[network Thu Jan  1 00:01:15 PST 1970] Reenabling Ethernet (ip=192.168.1.1,gw=192.168.1.10)
[network Thu Jan  1 00:01:17 PST 1970] iface = wlan0; start time is 28869 ; timeout is 12
[network Thu Jan  1 00:01:17 PST 1970] ip_addr suuccessful; current time is 28877
[network Thu Jan  1 00:01:17 PST 1970] ping
PING 10.54.4.156 (10.54.4.156): 56 data bytes

--- 10.54.4.156 ping statistics ---
1 packets transmitted, 0 packets received, 100% packet loss
[network Thu Jan  1 00:01:18 PST 1970] ping attempt failed; current time is 28878
PING 10.54.4.156 (10.54.4.156): 56 data bytes

--- 10.54.4.156 ping statistics ---
1 packets transmitted, 0 packets received, 100% packet loss
[network Thu Jan  1 00:01:19 PST 1970] ping attempt failed; current time is 28879
PING 10.54.4.156 (10.54.4.156): 56 data bytes

--- 10.54.4.156 ping statistics ---
1 packets transmitted, 0 packets received, 100% packet loss
[network Thu Jan  1 00:01:20 PST 1970] ping attempt failed; current time is 28880
[network Thu Jan  1 00:01:26 PST 1970] Reenabling Ethernet (ip=192.168.1.1,gw=192.168.1.10)
[network Thu Jan  1 00:01:27 PST 1970] iface = wlan0; start time is 28869 ; timeout is 12
[network Thu Jan  1 00:01:27 PST 1970] ip_addr suuccessful; current time is 28887
[network Thu Jan  1 00:01:27 PST 1970] ping
PING 10.54.4.156 (10.54.4.156): 56 data bytes

--- 10.54.4.156 ping statistics ---
1 packets transmitted, 0 packets received, 100% packet loss
[network Thu Jan  1 00:01:28 PST 1970] ping attempt failed; current time is 28888
[network] wifi: ERROR: iface_up_timeout (12) exceeded (ping).
[network Thu Jan  1 00:01:28 PST 1970] Shutting down wlan0 network interface
[network] exit 1
finaly test wifi begin
CPU:  8.3% usr  8.3% sys  0.0% nic 83.3% idle  0.0% io  0.0% irq  0.0% sirq
[7m  PID  PPID USER     STAT   VSZ %MEM CPU %CPU COMMAND [0m
18496 17861 root     S     3128  1.6   0  0.0 grep CPU
bad blok test
nandtype test
pcbasn set test
csn set test
pcbasn get test
csn get test
mac get test
edid test
7890
Format PCBASN-ok!
Writnig CSN
PCBASN save on the device!
usb test
led blue test
123456789012345
12345
Test nand type-ok!
[network Thu Jan  1 00:01:30 PST 1970] doing make_cksum /tmp/run/edid.txt ...
cat /tmp/run/start_firmware.log | grep Bad eraseblock
Test bad block-ok!
[network Thu Jan  1 00:01:30 PST 1970] 26196460391216 = 26196460391216
[network] : Passed
[network] exit 0
Start test board led time: 2000 msec frequency: 1 HZ.
00:26:AA:A3:6A:2A
led eth test
video test begin
Start test ETH led time: 2000 msec
CPU: 33.3% usr 66.6% sys  0.0% nic  0.0% idle  0.0% io  0.0% irq  0.0% sirq
[7m  PID  PPID USER     STAT   VSZ %MEM CPU %CPU COMMAND [0m
18649 17861 root     S     3128  1.6   0  0.0 grep CPU
hdmi test
Sleep 5 sec, otchet generating
Time for copy data to USB1:0m1.061s
[playback Thu Jan  1 00:01:34 PST 1970] Waiting for 10.54.4.156:/srv/nfs4/1MB.ts playback to start...
Copy to USB-ok!
[playback Thu Jan  1 00:01:34 PST 1970] srt:
Test main board led fail, time is out!
[playback Thu Jan  1 00:01:35 PST 1970] srt: <param name="playback_url" value="nfs://10.54.4.156:/srv/nfs4/1MB.ts"/>
[playback Thu Jan  1 00:01:35 PST 1970] Video start successfully!
Time for copy data from USB1:0m0.190s
ir test
Copy from USB-ok!
Start test IR time: 2 sec
Out: 0,  0xea15e608,  0
Test eth led fail, time is out!
Out: 0,  0xea15e608,  0
Out: 0,  0xea15e608,  0
Out: 0,  0xea15e608,  0
Test IR  fail, time is out!

Monday, August 18, 2014

Bash read line from file

Имеем файл например:
1
ф
2
к
4
е

Нужно прочитать все цифровые значения:

#!/bin/bash
stroka=1 #начиная с какой строки читаем, с первой нечетные, если со второй четные.
echo "Start parsing" >rezult.log

for i in {1..1500}; do   #сколько раз будем бегать по строкам     
   
   nomerstroki=$stroka'p'                     
   sed -n -e $nomerstroki $1 >> speed_rezult_$2.log
   stroka=$((stroka+2))
 done;

На выходе:
1
2
4

Thursday, February 6, 2014

Python unittest

Прочитав замечательную статью http://gahcep.github.io/blog/2013/02/10/qa-in-python-unittest/ для себя сделал пометки - может кому понадобятся, просто копируем в файл и компилируем смотрим результат.

import unittest
def setUpModule():
     #Инициализация переменных для всего модуля
     print ("In setUpModule()")
def tearDownModule():
     #Удаление всех переменных инициализированных в модуле
     print ("In tearDownModule()")
class BaseTestClass(unittest.TestCase):
     def test_add(self):
          #проверка того что внутри функции будет False
          self.assertFalse(10 > 20)
          #проверка того что внутри функции оба значения равны
          self.assertAlmostEqual(30, 30)
          #проверка того что первое значение больше второго
          self.assertGreater(120, 100)
          #проверка того что в первом масиве такие же как во втором
          first=[1,5,6]
          second=[5,6,1]
          self.assertCountEqual(first, second, 'msg')
          #проверка обих частей выражения на верность условий
          first=1
          second=2
          self.assertIs(first==1, second==2, 'msg')
          #проверка того что внутри функции будет True
          self.assertTrue(100 < 200, 'msg')
          #вызов исключительной ситуации найден еррор.
          #self.fail('all is bed')

class SecondClass(unittest.TestCase):
     #Задание переменных для класса тестов
     @staticmethod
     def setUpClass():
          print ("In setUpClass()")

     def setUp(self):
         #Задание переменной val для теста test_sub
         self.val = 220
         print ("In tearUp()")

     def test_sub(self):
          self.assertEquals(220, self.val)

     #Обнуление переменных для теста test_sub
     def tearDown(self):
          self.val
          print ("In tearDown()")

     #Обнуление переменных для класса тестов
     @staticmethod
     def tearDownClass():
          print ("In tearDownClass()")

 #Показаны все возможные ошибки возбуждаемые при проходе тестов
 class ThirdTestClass(unittest.TestCase):
    def test_ok(self):
        #Если тест проходит успешно
        self.assertEquals(210, 110 * 2 - 10)

    @unittest.skip('not supported')
    def test_skip(self):
        #Если тест помечен как - пропусить тест
        self.assertEquals(1000, 10 * 10 * 10)

    def test_fail(self):
        #Если тест заваливается
        self.assertEquals(420, 210 * 2.1)

    def test_error(self):
        #Если в тесте возникает ошибка
        raise ZeroDivisionError('Error! Division by zero')

    @unittest.expectedFailure
    def test_expected(self):
        #Если в тесте возникает ошибка которую програмист отловил с помошью try except
        raise ZeroDivisionError('Error! Division by zero')

unittest.main()


Short variant as I use this module

import unittest
import time
import Promwadserial


class Turin_Test(unittest.TestCase):

    def setUp(self):
        Promwadserial.try_connect_to_board(115200, 5)
        Promwadserial.sendCmd('root' + '\r\n')
        time.sleep(3)
        Promwadserial.sendCmd('root' + '\r\n')

    #@unittest.skip("skipping") 
def test_pwd(self):
        """pwd operation test""" 
        print("id: " + self.id())
        time.sleep(3)
        self.assertEqual(Promwadserial.sendCmd('pwd' + '\r\n'), ['/root'])


def suite():
    suite = unittest.TestSuite()
    suite.addTest(Turin_Test('test_pwd'))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())
    Promwadserial.Close_serial_board()

Thursday, August 8, 2013

Android CTS or Compatibility Test Suite

Установка на ПК программ для запуска утилиты CTS:

1. Закачать под конкретную платформу android тесты и утилиту CTS
http://source.android.com/compatibility/downloads.html
Чтоб заработала утилита CTS нужно установить ADB(Android Data Bridge)
http://developer.android.com/sdk/index.html
http://dl.google.com/android/adt/adt-bundle-linux-x86-20130729.zip
2. Распаковываем и прописываем для нашей системы место где лежит adb "/sdk/platform-tool"
export PATH=$PATH:/home/alexey1/Android/adt-bundle-linux-x86-20130729/sdk/platform-tool
3. Для запуска /android-cts/tools/cts-tradefed (CTS) нужна Java посмотрев сорцы по логике видим что тока на 1.6 версии запустится прогамма, не на какой более версии *(так начинается цирк и бубны):
JAVA_VERSION=$(java -version 2>&1 | head -n 1 | grep '[ "]1\.6[\. "$$]')
if [ "${JAVA_VERSION}" == "" ]; then
   echo "Wrong java version. 1.6 is required.
    3.1 Загружаем с сайта java:
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html
Development Kit 6u45 (javac)
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html#jdk-6u45-oth-JPR
Runtime Environment 6u45 (java)
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html#jre-6u45-oth-JPR
    3.2 Даем права для запуска скаченных бинарников
sudo chmod u+x jdk-6u45-linux-i586.bin
sudo chmod u+x jre-6u45-linux-i586.bin
Запускаем их
./jdk-6u45-linux-i586.bin
./jre-6u45-linux-i586.bin
    3.3 Прописываем в системе пути к Java:
sudo update-alternatives --install "/usr/bin/java" "java" "/home/alexey1/Android/jdk1.6/jdk1.6.0_45/bin/javac" 1
sudo update-alternatives --install "/usr/bin/java" "java" "/home/alexey1/Android/jdk1.6/jre1.6.0_45/bin/java" 1
Установка путей для системы:
sudo update-alternatives --set java /home/alexey1/Android/jdk1.6/jre1.6.0_45/bin/java
sudo update-alternatives --set javac /home/alexey1/Android/jdk1.6/jdk1.6.0_45/bin/javac
Если ругается на регистрацию javac not registered удаляем текушую символьную ссылку и в ручную создаем новую символьную ссылку
sudo rm /etc/alternatives/javac
sudo ln -s /home/alexey1/Android/jdk1.6/jdk1.6.0_45/bin/javac /etc/alternatives/javac



Настройка устроства для тестов:
This section is important as not following these instructions will lead to test timeouts/
failures:
1-4. Андройд версии (Android 4.0 and later) source.android.com
4. Убедится что установлены голосовые команды (Text To Speech files) проверить можно тут Settings > Speech synthesis > Install voice data before running CTS
tests. (или загрузитить с гуглмаркета)
5. Убедится что SD card подключена и она пустая. Warning:
CTS может модифицировать и удалить содержимое SD card подключенной к устройству.
лучше почистить содержимое (Settings > storage > Factory data reset).
7. Убедится в опции no lock pattern установленной на устростве (Settings > Security > Screen Lock should be 'None').
8. Убедится в опции "USB Debugging" development option is checked (Settings >
Developer options > USB debugging).Google Confidential
9. Убедится в опции Settings > Developer options > Stay Awake is checked
10. Убедится в опции Settings > Developer options > Allow mock locations is checked
11. Убедится в опции device is connected to a functioning Wi-Fi network (Settings > Wi-Fi)
12. Убедится в опции the device is at the home screen at the start of CTS (Press the home
button).
13. Когда запущены тесты на устростве недолжно быть запущено других задач и программ.
14. Не нажимать никаких кнопок и не касатся аппарата - это может послужить неправильным результатом теста
15. Необходимо подготовить устроство для тестов - загрузить модуль доступа на устроство:
1. adb install android-cts/repository/testcases/CtsDelegatingAccessibilityService.apk
2. Включить опцию появившуюся после инсталяции модуля Settings > Accessibility > Delegating Accessibility Service
16. Необходимо подготовить устроство для тестов - загрузить модуль аминистративного доступа: administration tests:
1. adb install android-cts/repository/testcases/CtsDeviceAdmin.apk
2. Включить опцию появившуюся после инсталяции модуля Settings > Security > Device Administrators >android.deviceadmin.cts.CtsDeviceAdmin* settings
17. Скопировать медиа файлы на устроство для проведения тестов (видео):
The CTS media stress tests require video clips to be on external storage (/sdcard).
Most of the clips are from Big Buck Bunny which is copyrighted by the Blender
Foundation ( http://www.bigbuckbunny.org) under the Creative Commons Attribution
3.0 license. The required space depends on the maximum video playback resolution
supported by the device. By default, 176x144 and 480x360 SHOULD be supported.
Note that the video playback capabilities of the device under test will be checked via
the android.media.CamcorderProfile APIs.
Here are the storage requirements by maximum video playback resolution:
● 480x360: 91.4MB
● 720x480: 151.9MB
● 1280x720: 401.6MB
● 920x1080: 1008.2MB
Иструкция как скопировать медиа данные на устроство:
1. Download the android-cts-media-X.Y.zip file from http://source.android.com/
compatibility/downloads.html and unzip it.
2. Connect the device to the computer and check that adb can connect to it.
3. cd to the unzipped folder.
4. chmod 544 copy_media.sh
5. Run copy_media.sh
○ To copy clips for just the default resolutions, run ./copy_media.sh.
Google Confidential
To copy clips up to a resolution of 720x480, run ./copy_media.sh 720x480.
If you are not sure about the maximum resolution, try 1920x1080 so that all
files are copied.
○ If there are multiple devices under adb, add -s serial option to the end.
For example, to copy up to 720x480 to device with serial 1234567, run
copy_media.sh 720x480 -s 1234567.
Или на прямую запустить копирование на устроство медиа контента(в моем примере я копирую для тестов под разрешение 480x360 все нарезки видео):
adb $adb_options push bbb_short/480x360 /mnt/sdcard/test/bbb_short/480x360
adb $adb_options push bbb_full/480x360 /mnt/sdcard/test/bbb_full/480x360



Использование CTS
Чтоб запустить тестирование необходимо на тестовом компьютере (ПК):
1. Убедится что устроство подключено к тестовому ПК через USB (adb -devices). Запустить CTS с консоли ПК.
$ adb start-server
$ ./android-cts/tools/cts-tradefed
2. Запустить прогон тестов по тест плану
cts-tf > run cts --plan Android

Все возможные команды и опции
Host:
  help: show this message
  help all: show the complete tradefed help
  exit: gracefully exit the cts console, waiting till all invocations are complete
Run:
  run cts --plan test_plan_name: run a test plan
  run cts --package/-p : run a CTS test package
  run cts --class/-c [--method/-m] : run a specific test class and/ormethod
  run cts --continue-session session_ID: run all not executed tests from a previous CTS session
  run cts [options] --serial/s device_ID: run CTS on specified device
  run cts [options] --shards number_of_shards: shard a CTS run into given number of independent chunks, to run on multiple devices inparallel
  run cts --help/--help-all: get more help on running CTS
List:
  l/list d/devices: list connected devices and their state
  l/list packages: list CTS test packages
  l/list p/plans: list CTS test plans
  l/list i/invocations: list invocations aka CTS test runs currentlyin progress
  l/list c/commands: list commands: aka CTS test run commands currently in the queue waiting to be allocated devices
  l/list r/results: list CTS results currently present in the repository
3. После каждого теста составляется отчет в форме XML то есть можно запустить через браузер и посмотреть результаты
/android-cts/repository/results

Tuesday, November 20, 2012

Python work with Flash drive

Задача:
1. Написать функцию которая записывает на Flash Disk в NAND определенную информацию( set_information_on_flash('/dev/sdb1', 'inputBuffer') )
2. Написать функцию которая считывает с Flash Disk файл определенную информацию(get_information_from_flash('/dev/sdb1', 'outputBuffer') )
3. Написать функцию которая сравнивает записанную информацию на Flash Disk в NAND с считанной информации с Flash Disk.(compare_information_in_out_file('outputBuffer','inputBuffer') )

#!/usr/bin/python

import commands
import re
import os
import csv

def main():

  set_information_on_flash('/dev/sdb1', 'inputBuffer')
  get_information_from_flash('/dev/sdb1', 'outputBuffer')
  compare_information_in_out_file('outputBuffer','inputBuffer')
 
def get_information_from_flash(devise, fileOutput):
    if os.path.exists('./%s' % (fileOutput)) == True:
        cmd = "dd if=%s of=%s bs=1 count=10 skip=1000" % (devise, fileOutput)
        output = commands.getoutput(cmd)
        print "Information getted"
    else:
        cmd = "touch ./%s" % (fileOutput)
        output = commands.getoutput(cmd)
        print "Please restart program, file %s is created" % (fileOutput)

def set_information_on_flash(devise, fileInput):
    if os.path.exists('./%s' % (fileInput)) == True:
        cmd = "dd if=%s of=%s bs=1 count=10 seek=1000 conv=notrunc" % (fileInput, devise)
        print cmd
        output = commands.getoutput(cmd)
        print "Information writed"
    else:
        cmd = "touch ./%s" % (fileInput)
        cmd1 = "echo 'AaBbCcDdEe' > ./%s" % (fileInput)
        output = commands.getoutput(cmd)
        output = commands.getoutput(cmd1)
        print "Please restart program, file %s is created" % (fileInput)

def compare_information_in_out_file(fileOutput,fileInput):
        fo = open(fileOutput, 'r')
        checkFile = fo.read(10)
        fo1 = open(fileInput, 'r')
        checkFile1 = fo1.read(10)
        print "Read from Outputfile = " + checkFile
        print "Read from Input file = " + checkFile1
        if checkFile != checkFile1:
            print "Reading is false"
        else:
            print "Reading is true both file is equal"
        fo.close()
        fo1.close()

if __name__ == '__main__':
  main()