Interface automation test learning and use

Introduction to Interface Automation Testing

1. Concept

Interface test: It is to test the interface between systems or components, mainly to verify the exchange, transmission and control management process of data.

                  and mutual logical dependencies.

Automated testing: It is a process of transforming human-driven testing behavior into machine execution.

Interface automated testing: It is a process in which programs or tools replace manual and automatic testing of interfaces.

2. Implementation method

  • Use interface testing tools to achieve, such as: JMeter, Postman, etc.
  • Implemented by writing code (using requests, sessions)

3. Lack of interface testing tools

  • The test data is not well controlled
  • Inconvenient to test encrypted interface
  • Poor expandability

Requests library

1. What is the requests library

1.1 Introduction

The Requests library is written in Python, based on urllib, and adopts the Apache2 Licensed open source HTTP library; compared with the urllib library, the Requests library is more convenient, can save us a lot of work, and fully meet the HTTP testing requirements;

2.2 Installation

pip install requests

2. Send request

Using requests to send network requests is very simple, just call the method corresponding to the HTTP request type.

Common HTTP request methods: GET, POST, PUT, DELETE, HEAD, OPTIONS

2.1 GET request

import requests

response = requests.get("http://www.baidu.com")

The return value response of the request method is the Response object, and we can get all the response information we want from this object.

2.2 POST request

response = requests.post(url, data=None, json=None)
    """
    :param url: 请求的URL
    :param data: (可选) 要发送到请求体中的字典、元组、字节或文件对象
    :param json: (可选) 要发送到请求体中的JSON数据
    :rtype: requests.Response
    """

import requests

response = requests.post("http://www.baidu.com", data={"key": "value"})

The difference between extended data and json:
data: dictionary object
json: json string
Tips:
      1. In python, a dictionary object is the same as a json string, but the background format is different.
How to convert a dictionary object to a json string?
      1. Import json
      2. json.dumps (dictionary object) # convert json string


The difference between response data json() and text:
        json(): return type dictionary, you can get the response value through the key name
        text: the returned type is string, you can’t get the response value through the key name
        Prompt: the common point is long both like dictionaries 

2.3 Other request types

Other HTTP request types, such as: PUT, DELETE, HEAD, and OPTIONS.

import requests

response = requests.put("http://www.baidu.com", data={"key": "value"})
response = requests.delete("http://www.baidu.com")
response = requests.head("http://www.baidu.com")
response = requests.options("http://www.baidu.com")

3. Pass URL parameters

If you need to pass data in the query string of the URL, you can use the params parameter to define, and the parameters passed by params can be strings or dictionaries.

import requests

response = requests.get("http://www.baidu.com", params="kw=python")
print(response.url) # http://www.baidu.com/?kw=python

params = {"k1": "v1", "k2": ["v2", "v3"]}
response = requests.get("http://www.baidu.com", params=params)
print(response.url) # http://www.baidu.com/?k1=v1&k2=v2&k2=v3

4. Response content

The return value response of the request method is the Response object, and we can get all the response information we want from this object.

response.status_code     状态码
response.url             请求url
response.encoding        查看响应头部字符编码
response.headers         头信息
response.cookies         cookie信息
response.text            文本形式的响应内容
response.content         字节形式的响应内容
response.json()          JSON形式的响应内容

JSON response content

If the content of the request response is data in JSON format, you can directly call the response.json() method to obtain the data, because the built-in JSON decoder in requests helps us process JSON data.

response = requests.get("http://www.baidu.com")
json_data = response.json()

response.json() throws an exception if JSON decoding fails

5. Custom request header

If you need to add request header data to the request, you only need to pass a dictionary type of data to the headers parameter.

headers = {"key": "value"}
response = requests.get("http://www.baidu.com", headers=headers)

6、Cookie

Role: distinguish the same request client

Obtain the cookie data in the response information:

response = requests.get("http://www.baidu.com")
print(response.cookies)

To add cookie data when sending a request, you can use the cookies parameter:

requests.get("http://www.baidu.com", cookies={"c1": "v1"})

principle:

7、Session

Function: session can automatically save the cookies information generated by the server, and automatically attach it to the next request.

In requests, the session object is a very commonly used object. This object represents a user session: from the time when the client browser connects to the server, to when the client browser disconnects from the server.

create session object

session = requests.Session()

After getting the session object, you can call the method in the object to send the request

session.get()
session.post()
session.delete()
session.put()

Integrate UnitTest

Integrate the interface test script into the UnitTest unit test framework, and use the function of UnitTest to run the interface test cases.

Framework construction:

import unittest
import requests


# 新建类 继承unittest.TestCase
class TPShopLogin(unittest.TestCase):
    # setUp
    def setUp(self):
        pass

    # tearDown
    def tearDown(self):
        pass

    # 测试方法
    def test(self):
        pass



if __name__ == '__main__':
    unittest.main()

case analysis:

Requirement: Use the human resource management project to complete the interface test for the login function

URL: http://ihrm2-test.itheima.net

Use case design:

 Code:

# 导包 unittest_test requests
import unittest
import requests


# 新建类 继承unittest.TestCase
class TPShopLogin(unittest.TestCase):
    def setUp(self):
        # 获取session对象
        self.session = requests.session()
        # 登陆url
        self.url_login = "http://ihrm2-test.itheima.net/api/sys/login"

    def tearDown(self):
        # 关闭session
        self.session.close()

    # 测试方法 登陆成功
    def test_login_success(self):
        # 请求头
        headers = {"Content-Type": "application/json"}
        # 请求登陆(为了过审把password加了s)
        json_data = {"mobile": "13800000002", "passwords": "123456"}    
        r = self.session.post(self.url_login, json=json_data, headers=headers)
        # 断言判断是否登录成功
        try:
            self.assertEqual(r.json()["message"], "操作成功!")
        except AssertionError as e:
            print(e)

    # 测试方法,用户名错误
    def test_login_error_mobile_err(self):
        # 请求头
        headers = {"Content-Type": "application/json"}
        # 请求登陆(为了过审把password加了s)
        json_data = {"mobile": "", "passwords": "123456"}
        r = self.session.post(self.url_login, json=json_data, headers=headers)
        # 断言判断是否登录失败
        try:
            self.assertEqual(r.json()["message"], "用户名或密码错误")
        except AssertionError as e:
            print(e)

    # 测试方法,密码错误
    def test_login_error_password_err(self):
        # 请求头
        headers = {"Content-Type": "application/json"}
        # 请求登陆(为了过审把password加了s)
        json_data = {"mobile": "13800000002", "passwords": ""}
        r = self.session.post(self.url_login, json=json_data, headers=headers)
        # 断言判断是否登录失败
        try:
            self.assertEqual(r.json()["message"], "用户名或密码错误")
        except AssertionError as e:
            print(e)


if __name__ == '__main__':
    unittest.main()

Guess you like

Origin blog.csdn.net/ouihsiad/article/details/127664563