How to implement data-driven interface automation testing using Python!

This article mainly introduces you to the relevant information on how to use Python to implement data-driven interface automated testing. The article introduces it in great detail through sample code. It has certain reference learning value for everyone to learn or use python. Friends who need it can come here Let’s take a look together

Foreword

During the interface testing process, we often use CSV reading operations. This article mainly explains how to write and read CSV in Python3. Not much to say below, let’s take a look at the detailed introduction.

1. Demand

A certain API, GET method, three parameters: token, mobile, and email

  • token is required
  • mobile,email 1 item is required
  • mobile is the mobile phone number, email is the email format

2. Plan

For the above API, when doing interface testing, the number of test cases required will often be as many as 10+. At this time, it may be more appropriate to use a data-driven approach to write common content into the configuration file.

Here we consider pre-saving the API, parameters, and expected results in a formatted CSV, using the csv component to read the URL, parameters, and expected results from the CSV. The Requests component initiates a request and compares the response results with the expected results. Finally, write the comparison results to the result CSV.

The process is as shown below?

3. Implementation

1. Before loading the code, install the following components:

  • csv read and write CSV files
  • json
  • requests initiates a request and obtains the response result
  • unittest test case scheduling
Now I have also found a lot of test friends and created a communication group to share technology, sharing a lot of technical documents and video tutorials we collected.
If you don’t want to experience the feeling of not being able to find resources when self-study, having no one to answer your questions, and persisting for a few days before giving up.
You can join us to communicate. And there are many technical experts who have made certain achievements in automation, performance, security, test development, etc.
Share their experience, and also share many live lectures and technical salons
You can learn for free! Focus on it! Open source! ! !
QQ group number: 110685036

2. data.csv (this example selects some use cases)

3. reader_CSV function code example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

twenty one

twenty two

twenty three

twenty four

25

26

27

28

29

30

31

32

import csv

import json

import requests

import time

import unittest

def readCSV(self,filename):

'''

:param filename: the data file to be read

:return: [{data1},{data2}...]

'''

datas = []

try:

#Read data files using DictReader to facilitate conversion to and from json

with open(filename,'r') as csvfile:

#Convert the data read from the file into dictionary list format

reader = csv.DictReader(csvfile)

for row in reader:

data = {}

data['id'] = row['id']

data['url'] = row['url']

data['token'] = str(row['token'])

data['mobile'] = row['mobile']

data['email'] = row['email']

data['expect'] = json.dumps (row['expect']) \

if isinstance(row['expect'], dict) \

else row['expect'] #If expect If what is read is not json, its original value will be used, otherwise it will be converted to json format and saved in the result

datas.append(data)

return datas

#If the file cannot be found, return empty datas

except FileNotFoundError:

print("The file does not exist",filename)

return datas

4. request_URL function example (including GET request and POST request methods)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

twenty one

twenty two

def get_request(self,url,params):

'''

General calling GET interface method

:param url:string interface path

:param params:{"":"","":""} Parameters that need to be passed in

:return: response response body

'''

print("Calling API...")

r = requests.get(url,params=params)

print(r.text)

return r

def post_request(self,url,params):

'''

General calling POST interface method

:param url: string interface path

:param params: {"":"","":""} Parameters that need to be passed in

:return:response response body

'''

print("Calling API...")

r = requests.post(url,params=json. dumps(params)) #post method must be converted into json format using json.dumps()

print(r.text)

return r

5. Example of assert_Result function

1

2

3

4

5

6

7

8

9

def assertResult(self,except_value,real_value):

'''

Verify whether the sample string contains the specified string

:param except_value: string specified string

:param real_value: string sample string

:return: Boolean If the sample contains the specified string, it returns True, otherwise it returns False

'''

ifsuccess = except_value in str (real_value)

return ifsuccess

6. Write_CSV function example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

def writeCSV(self,filename,results):

'''

Write the specified content into the csv file

:param filename: string The name of the file to be written

:param results: [{data1},{data2},...] written content

:return: None

'''

print("Write file:",filename)

#Write files using DictWriter

with open(filename,'w + ') as csvfile:

headers="id,url,token,mobile,email,expect,real_value,assert_value".split(",")

writer = csv.DictWriter(csvfile,fieldnames=headers)

#Write header

writer.writeheader()

#Write data

if results.__len__() > 0 :

for result in results:

writer.writerow(result)

csvfile.close()

7. Test_interface1 function example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

twenty one

twenty two

twenty three

twenty four

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

def test_interface1(self):

#Specify the name of the data file to be read

data_file = "../data/data.csv"

#Specify the name of the data file generated by the final result

result_file = "../data/result_{}.csv". code>format(str(time.time()).split(".\ ")[0])

#Read data from the specified file

datas = self.readCSV(data_file)

#If the data file has content, call the interface, otherwise the test will end directly

if datas.__len__() > 0:

results =[]

#Get each line in the data file

for testcase in datas:

result = {}

result["id"] = testcase["id"]

result["url"] = testcase["url"]

result["token"] = testcase["token"]

result["mobile"] = testcase["mobile"]

result["email"] = testcase["email"]

result["expect"] = testcase["expect"]

#Assembly parameters

params = {

"token":result["token"],

"mobile":result["mobile"],

"email":result["email"]

}

#Call the API interface and get the response result

real_value = self.get_request(result["url\ "],params)

#Call the assert method to check whether the expected result exists in the response result

assert_value = self.assertResult(result["expect\ "],real_value.text)

result["real_value"] = real_value.text

result["assert_value"] = assert_value

#Get all fields in each row as well as actual results and verification results

results.append(result)

#After executing all records, write all results to result.csv

self.writeCSV(result_file,results) #Write csv file

print("Test ends")

8. result_1523956055.csv (please ignore the test results in this example)

Summary

Python encapsulates many methods, and the development speed is relatively fast for testing. If the interface automation test adopts the data-driven method of CSV management, using csv + requests is one of the tools that cannot be missed in test development.

Okay, that’s all the content of this article!!!

Finally, I would like to thank everyone who has read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software testing interview document

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeWeb crawlerSelenium388365 people are learning the system