Python uses pyqt to write interface tools

The previous article introduced the use of python’s own tkinter package to write tools with interfaces.

This article introduces the use of pyqt to develop test tools.

The advantage of tkinter is that python comes with it, which is easy to use (but the handwritten controls are complicated), and the layout and placement are not intuitive and easy, because it is positioned by pixel coordinates, and it takes a long time to develop the interface. pyqt is a third-party gui development tool, and is currently recognized as the best client interface development tool on python, because the control is manually dragged and dropped by qt designer, and it is very simple to adjust the color, font size and other styles without going to the code level To write a lot of interface code, what you see is what you get.

To learn pyqt, you need to install these files. pyqt is a third-party python package, eric is a qt design interface, and sip needs to be used when packaging tools.

After installing the environment, double-click to run the eric4.bat file (my version is eric4)

In the interface after running the eric4.bat file, click the designer icon to enter the qt design view

This picture is the qt designer interface

Just drag and drop the components in the control list on the left to the ui. After the layout is completed and the interface is satisfactory, click Save File As in the menu bar to save it as a ui file. The file suffix is .ui by default.

Use the cmd command to convert the .ui file to a .py file, the command is

pyuic4 -o syui.py suoyouxiangmu.ui

The front is the name of the py file, and the back is the file name of the ui saved just now. After executing this command, you will see that there is an additional file called syui.py in the folder.

Open the file, you can see the general content of the file, the screenshot is as follows

If you want to display the interface of the py file converted from ui, you need to add code

However, it is strongly recommended not to write this way. Do not write the tool’s function code and the py code obtained by ui conversion in one file, because when developing tools, you may often use the adjustment interface to continuously convert ui into py code. If the code is written here file, the function code written before will be overwritten, and write the code in the red box and the function code of the descendants in another file.

The syntax for binding a function to a button in pyqt is mainwindow.pushButton_2.clicked.connect(function)

Here are some ways to get the value of the control and assign the default value to the control

mainwindow.lineEdit.setText((u”zg extra abc”)) #Assign a value to the input box

mainwindow.textEdit.setPlainText(”) #Assign a value to texedit

mainwindow.comboBox.setCurrentIndex(2) #Assign a value to the drop-down box

mainwindow.checkBox.setChecked(1) #Assign value to the checkbox checkbox, you can fill in True or False or 0, 1< /em>

print unicode(QString(mainwindow.lineEdit.text())) #Get the value of the input box<br>unicode(QString(mainwindow.textEdit.toPlainText()))#Get the value of textedit<br>print unicode(QString(mainwindow.comboBox.currentText()))#Get the value of the drop-down box<br><br>print mainwindow.comboBox.currentIndex() #Get the index of the drop-down box<br>if mainwindow.checkBox.isChecked()==True Get the value of the checkbox checkbox

You can write the function code as you want, which is no different from ordinary pure script code. If the background script function is written in advance, it only takes a little time to add it to the interface. It should be noted that some functions with relatively long execution time, such as cyclic requests, or the response time of the interface are very long, and Qthread sub-threads are needed, otherwise, using ordinary functions will freeze the client interface for a period of time until the function runs Finish.

Let’s show a few tools I made using pyqt. These tools of mine are all displayed in the console on the left side of the interface. It is very convenient to see the running results in one interface. There is no need to operate on the interface and then go to the python ide console to see the results.

This tool is a tool for base64 encoding or decoding of strings, because the interface of our company is to pass the base64 encoded string of json to the background, and then perform base64 encoding in the background. When doing tests, base64 is often sent The encrypted string, if you don’t decrypt it, you can’t understand the meaning and function of the request. If you grab the login interface package of our company project, you will be completely at a loss, because most of the web is captured and you can see username:xxxxx password:xxxxx yanzhenma:xxxxx. Our company needs base64 decoding before it can I can see the key-value pairs, so I made a tool for this reason; although there are a lot of transcoding websites on the Internet, it is not convenient to open a webpage every time I use it. This tool uses the base64 package that comes with python. Otherwise, I write the code to convert base64 myself, and I don’t know what the encoding rules of base64 are.

This tool is an interface test, which performs get and post requests, similar to postman’s function and jmeter’s interface test function. The tool has processed cookies in the background code, and only needs to execute the login interface once before operating other interfaces. The second post added a base64 check, mainly to consider the versatility of the tool. Unchecking base64 is suitable for most companies. If our company does not check, the background cannot encrypt a string that is not base64 encrypted Performing base64 decoding will of course return an error status code. The tool is made using reqeusts. This tool uses Qthread, otherwise the interface will be stuck when encountering an interface with a large response time.

This tool uses the client to replace the functions that should have been completed by the app. A normal test is to use a tool to generate a QR code image from a character string in txt, and then use the app to scan the QR code. If the ratio of the child code to the parent code is 20 to 1, you need to scan each time to generate a QR code and then scan it with the app. At one time, it takes about 10 minutes to complete a process. The tool is to directly assign the txt20 line substring at one time, then copy a parent code string to the input box, click to confirm the association, the background will automatically divide the URL of 20 subcodes, and take out the code value in the URL. This place mainly uses The regular expression divides 20 subcode values, and then posts them to the server according to the format of the interface parameters. The whole process can be completed in 20 seconds. It’s very fast. This app cannot use appium due to the need to scan the code. Using the interface to replace the app’s functions saves a lot of time for testing business processes.

Of course, the method of this tool can only be associated again and again. Later, because of new requirements, I used a pure script to read two notepads, each with 20,000 lines, and read them at one time. After the content of the two notepads, the specified rows are automatically associated with each other multiple times. If the ratio is 20:1, and 20,000 code values are associated, an interface can return to the interface in 0.2 seconds, and it will take a few minutes to use single-threaded requests. .

This tool is part of the app function of the test project. It aggregates the functions of multiple interfaces of the app into one interface to assist testing, such as testing the SMS function of the alarm. It takes 2 minutes to fill in various forms with the app, but only 2 seconds with the tool Bell, because a large number of default parameters are processed in the background.

This tool is a tool for detecting the running status of online server services. It can continuously detect whether the return of each interface is normal, whether the database status is normal, and whether the web server is abnormal. You only need to set the specified time to automatically detect in a loop, and write the request of each command every day to a log log. Once there is an exception, the captured exception will be sent to the relevant e-mailer, and the request for each command every day will be written into a log log, and a text message will be sent to the relevant personnel to avoid the problem without knowing it. Among them, the mail uses the mail function of python’s smtlib, and the text message is to make PHP an interface for sending text messages. I only need to post the relevant content to PHP according to the specified format, and then I can send text messages to notify everyone.

This tool was made in the form of windows service before, and the service was installed in the windows service to run silently, but this client method is not required to be highly controllable.

This tool is a function for a friend who needs to run cmd commands without cmd. The subprocess is used, the code is relatively short and the code is posted here.

import subprocess
ui.lineEdit_14.setText((u"ping 127.0.0.1"))
ui.lineEdit_15.setText((u"https://180.42.98.2/uniform/user-login.action"))

class CmdThread(QThread):
    _signal = pyqtSignal(str)
    def __int__(self):
        super(CmdThread, self).__init__()

    def run(self):
        cmd_str=unicode(QString(ui.lineEdit_14.text()))
        The cmd command sent by print u'\
 is: ', cmd_str
        try:
            ot=subprocess.check_output(cmd_str, shell=True)

            print ot.decode('gbk').encode('utf8')
        except Exception, e:
            print e
        print '*********************************************'

cmdThread = CmdThread()
cmdThread._signal.connect(chuli) #####cmd Some commands will consume a lot of time, you need to use Qthread, chuli is a function, link the black console on the right
def cmd():
    cmdThread. start()

This tool is posted by Baidu. The specific implementation code has been introduced in another Baidu reply blog. Since this account was bought from Taobao, and when debugging the code, Baidu has permanently banned the reply function, so the returned Not errcode0, 220012 means that the account has been disabled to reply to posts.

Finally, introduce the packaging code of the pyqt tool, and use py2exe to package it into an exe client. run in cmd

python setup.py py2exe --includes sip can be packaged. 
 1 #coding=utf-8
 2 from distutils.core import setup
 3 import py2exe
 4 import globs
 5
 6 #python setup.py py2exe --includes sip icon to manually copy the picture to the dist folder
 7
 8 setup(
 9 # targets to build
10 windows = [{<!-- -->"script":"dysyui.py", "icon_resources": [(1, "logo1.ico")]} ],
11 options = { "py2exe":{<!-- -->"dll_excludes":["MSVCP90.dll"],"bundle_files": 3,}},
12 data_files = [("imageformats",glob.glob("C:\Python27\Lib\site-packages\PyQt4\plugins\imageformats\*.dll"))]
13)

Well, that’s all for pyqt.

syntaxbug.com © 2021 All Rights Reserved.