当前位置:网站首页>Play perfdogservice demo from scratch

Play perfdogservice demo from scratch

2020-11-10 14:21:56 Tencent wetest

1.Demo Folder

When downloading good PerfDogService The back folder looks like this .

The document states :

PerfDogService.exe: Service Startup file , You don't need to start it manually , The automation script starts the program automatically .
perfdog.proto: grpc Interface and protobuf Structure definition file
demo/python: python3 Of demo, Dependency Library grpcio and protobuf
demo/java: java Of demo, Dependency Library grpc-netty-shaded, grpc-protobuf, grpc-stub
PerfDogService.jar: Services depend on jar package

We don't care about the rest , Focus only on demo Folder ;
After deployment is Java and Python In two languages Demo, We will only analyze the transformation this time Python Of

Python Of Demo There are only three documents

Demo.py: The entry point of our program , At the same time, we mainly operate this file ;
perfdog_pb2.py: This file is generated by the protocol buffer compiler , That is, by perfdog.proto This file generates . Let's not modify it .
perfdog_pb2_grpc.py: This file is gRPC Python Protocol compiler plug-in generation , And don't modify it
Here is a brief introduction == Protocol buffer ==
A protocol buffer is a language independent , Platform independent data serialization structure mechanism ;
You only need to construct the data once , You can then use the generated special source code to easily write and read structured data in a variety of data streams in various languages ;

Do you use python Language , You work hard with python A bunch of dictionaries have been defined Class Or something , You want to use it for old Li next door , But Lao Li used java ah , At this time, Xiao Wang next door also needs to use , But Xiao Wang used C++ ah , Languages can't call directly . At this time, through the protocol buffer mechanism , First compile your data to generate a special source code , Lao Li and Xiao Wang can call this source code .

2.Demo.py File parsing

In fact, there is only one Run function , And the official notes are clear , Let's take a brief look at it

0 To 3 There's nothing to say , Is to evoke PerfDogService service , A connection is established with the server through a token , among stub There are many other ways to connect

Now look at step four

deviceEventIterator Here's an iteratable object , It stores all the current connected devices , for example Android La ,Ios, Simulator, etc ; 

What we use most is device, Here's the model under test uid, Name, etc . there uid Is the unique identification of the currently connected device , If you install it ADB, You can enter it at the console ADB devices Check your current connected device information , Such as this :

5 It's actually starting to initialize the device
6 Is to start getting all installed applications of the device under test , The application is saved in apps In this object , This is also an iterative object ,
iteration apps You can get every app, And each app Name , Package name , edition ,Icon, Is it a system App,subVersion wait .

The first 7 Step here is actually to obtain the hardware information of the device under test , For example CPU, model , Android version and so on

The first 8 Step here to select the performance data indicators to be collected , I've added one more here CPU Core The usage rate of
The first 9 We're ready to collect performance data

Collecting performance data information is actually done by multithreading , therefore Sleep(20) It's collecting 20s The data of

10 and 11 It's to add comments for different periods of time

The first 12 Step is two operations
1. Upload the entire data to the cloud
2. Export chapter 5 Seconds to 20 Seconds of data to local , The export path can be changed by itself (outputDirectory)

13 Finally stop testing , But the process didn't stop , If you start Perfdog client , This error may be displayed .

Go now Kill Drop this java Just go into the city .

3.Demo Simple modification

Because of my personal needs 1 I don't want every configuration to be modified by a line of code ,2 It is to pave the way for building a custom cloud performance test platform in the future , So simply modify the code : Source code not deleted , It's just that the comments are missing , Convenient for comparison ;
1. Extract common configuration
2. You need to configure the corresponding equipment to be tested in advance
3. You need to configure the test in advance APP( To configure APP Name )
4. Just upload one piece of data to the cloud ,
5. Data saved locally will not be intercepted for a certain period of time .

# -*- coding: utf-8 -*-
import subprocess
import time
import traceback

import grpc
import perfdog_pb2_grpc
import perfdog_pb2
import threading
class Config():
    PERFDOGSERVER_PATH=r'C:UsersAdministratorDesktopperfdogPerfDogService.exe' #PerfDogService The path of 
    TOKEN='XXXXXXXXXXXXXXXXXXXX '#token
    DEVICES_UID="813QEDTE228ZK" # Phone serial number to be tested 
    APP_NAME=" The weather " # What needs to be tested app name 
    TEST_TIMER=11 # Test duration required 
    LABEL="this is a label" #label Content 
    NOTE="this is a note" #note Content 
    CASENAME=" Weather test data " # Use case description  , Data with the same use case name will be covered 
    SAVEDATA_BEGINTIME=1 # Start time of export to local data ( second )
    SAVEDATA_ENDTIME=20 # End time of export to local data ( second )
    OUTPUT="F:perfdog_service_output" # The directory where the export file is saved ,
    SAVEDATA_TYPE=perfdog_pb2.EXPORT_TO_JSON # The type saved in the export file ,

#  First run demo Before you need to pass pip install grpcio(1.23.0) and protobuf(3.10.0)
def run():
    try:
        #  Start in code PerfDogService Or start it manually PerfDogService
        print("0. start-up PerfDogService")
        # 1.************************** fill PerfDogService The path of 
        perfDogService = subprocess.Popen(Config.PERFDOGSERVER_PATH)
        #  wait for PerfDogService To start over 
        time.sleep(5)
        print("1. adopt ip And port to PerfDog Service")
        options = [('grpc.max_receive_message_length', 100 * 1024 * 1024)]
        channel = grpc.insecure_channel('127.0.0.1:23456', options=options)
        print("2. Create a new one stub, Through this stub Object can call all the interfaces provided by the server ")
        stub = perfdog_pb2_grpc.PerfDogServiceStub(channel)
        print("3. Log in with a token , The token can be applied on the official website ")
        userInfo = stub.loginWithToken(perfdog_pb2.Token(token=Config.TOKEN))
        print("UserInfo:n", userInfo)
        print("4. Start the device monitor to monitor the device , Each time the device is plugged in and removed, a DeviceEvent")
        deviceEventIterator = stub.startDeviceMonitor(perfdog_pb2.Empty())
        for deviceEvent in deviceEventIterator:
            #  from DeviceEvent Get to the device object ,device Object will be used in later interfaces 
            device = deviceEvent.device

            print(" At present devices: ",device," **** ",deviceEvent)
            # time.sleep(20000)
            if deviceEvent.eventType == perfdog_pb2.ADD and device.uid==Config.DEVICES_UID:
                print(" equipment [%s:%s] Insert n" % (device.uid, perfdog_pb2.DEVICE_CONTYPE.Name(device.conType)))
                #  Each phone will return two conType Different device objects (USB And WIFI Of ), If it's a survey line , Take the USB object 
                if device.conType == perfdog_pb2.USB:
                    print("5. Initialization equipment [%s:%s]n" % (device.uid, perfdog_pb2.DEVICE_CONTYPE.Name(device.conType)))
                    stub.initDevice(device)
                    print("6. obtain app list ")
                    appList = stub.getAppList(device)
                    #
                    apps = appList.app
                    app_index = 0
                    for app in apps:
                        print('%s: %s->%s' % (app_index, app.label, app.packageName))
                        if app.label==Config.APP_NAME:
                            app_select=app_index
                            break
                        else:
                            app_index += 1
                            app_select=None
                    if app_select is None:app_select = int(input(" Input not installed APP, Please select to test App: "))

                    app = apps[app_select]

                    print("7. Get device details ")
                    deviceInfo = stub.getDeviceInfo(device)
                    print("8. Turn on the performance data item ")
                    stub.enablePerfDataType(
                        perfdog_pb2.EnablePerfDataTypeReq(device=device, type=perfdog_pb2.NETWORK_USAGE))
                    stub.enablePerfDataType(
                        perfdog_pb2.EnablePerfDataTypeReq(device=device, type=perfdog_pb2.NORMALIZED_CPU_CORE_USAGE))



                    print("9. Start collecting [%s:%s] Performance data for n" % (app.label, app.packageName))
                    print(stub.startTestApp(perfdog_pb2.StartTestAppReq(device=device, app=app)))

                    req = perfdog_pb2.OpenPerfDataStreamReq(device=device)
                    perfDataIterator = stub.openPerfDataStream(req)

                    def perf_data_process():
                        for perfData in perfDataIterator:
                            print(perfData)

                    threading.Thread(target=perf_data_process).start()
                    #  Collect some data 
                    time.sleep(Config.TEST_TIMER)
                    print("10. Set up label")
                    stub.setLabel(perfdog_pb2.SetLabelReq(device=device, label="I am a label"))
                    time.sleep(3)
                    print("11. Add annotations ")
                    stub.addNote(perfdog_pb2.AddNoteReq(device=device, time=5000, note="I am a note"))
                    print("12. Upload and export all data ")
                    saveResult = stub.saveData(perfdog_pb2.SaveDataReq(
                        device=device,
                        caseName=Config.CASENAME,  # web On case and excel Name 
                        uploadToServer=True,  #  Upload to perfdog The server 
                        exportToFile=True,  #  Save to local 
                        outputDirectory=Config.OUTPUT,
                        dataExportFormat=Config.SAVEDATA_TYPE
                    ))

                    print(" Save results :n", saveResult)
                    # print("12. Upload and export page 5 Seconds to 20 Second data ")
                    # stub.saveData(perfdog_pb2.SaveDataReq(
                    #     device=device,
                    #     beginTime=5000,  #  Specify the start time 
                    #     endTime=20000,  #  Specify the end time 
                    #     caseName="case2",  # web On case and excel Name 
                    #     uploadToServer=True,  #  Upload to perfdog The server 
                    #     exportToFile=True,  #  Save to local 
                    #     outputDirectory="F:perfdog_service_output",
                    #     dataExportFormat=perfdog_pb2.EXPORT_TO_EXCEL
                    # ))
                    print("13. Stop test ")
                    stub.stopTest(perfdog_pb2.StopTestReq(device=device))
                    print("over")
                    break
                elif deviceEvent.eventType == perfdog_pb2.REMOVE:
                    print(" equipment [%s:%s] remove n" % (device.uid, perfdog_pb2.DEVICE_CONTYPE.Name(device.conType)))
    except Exception as e:
                traceback.print_exc()

if __name__ == '__main__':
    run()
#

Performance testing technology exchange group :720150565

see PerfDog details :https://perfdog.qq.com/?ADTAG...

版权声明
本文为[Tencent wetest]所创,转载请带上原文链接,感谢