basic introduction
There are many data-driven forms. We can parameterize by defining variables, or by defining arrays and dictionaries, or by reading files (txt\csv\xml). . The following briefly introduces how to read txt and csv formats. XML seems to be used less in the test process (maybe my test is not rich enough, and I will also introduce how to read xml when I have time).
Actual operation
First, read the txt format
Regarding the reading of txt format files, I will not repeat them here. You can refer to this article on three ways to read files in Python . Emphasize the format. Note that when we store data, in order to facilitate subsequent reading of the required data, we must use a special symbol to distinguish the meaning of each different data. For example, if we need to test the two fields "username" and "password", we need to construct data about these two fields in the txt file.
Three sets of test data are created here, which are separated by ",", and then we use the "split" method to separate the data according to "," according to the read data, and then take the data and store it in a variable for use. Of course, this special symbol is customized according to your own preferences. Of course, it is best to use a symbol that is convenient and easy to remember.
Second, read csv format
If you need to test a set of data including user name, age, gender, email and other information, it is a bit inconvenient to use txt at this time. We can use to create a csv format file, read it using the reader() method of the csv module, and then traverse the data in the file through a for loop.
1. Traverse each row of data
Code:
# -*- coding: utf-8 -*-
'''
@author: April_Chou
@time: 2018/4/16 20:54
'''
import csv
user_file = csv.reader(open('D:/WorkSpace2/seleniumTest/4/info.csv','r'))
for linein user_file:
print(line)
result:
['name', 'age', 'student number']
['Python', '3', '1']
['Java', '4', '2']
['Ruby', '5', '3']
2. Get a column of data
Code:
# -*- coding: utf-8 -*-
'''
@author: April_Chou
@time: 2018/4/16 20:54
'''
import csv
user_file = csv.reader(open('D:/WorkSpace2/seleniumTest/4/info.csv','r'))
for linein user_file:
print(line[0])
result:
Name
Python
Java
Ruby
Third, read the xml format
Sometimes the read data format is irregular, for example, when configuring an xml file to configure the URL, browser, login user name and password of the automation script, etc., you need to read the xml file. First import the minidom module of xml to process the XML file, then use the parse() method to open an XML file, and documentElement is used to get the only root element of the XML file.