Python automated test summary [4]

1 Overview

The methodology of testing is based on the views mentioned in the previous article:

  • Functional testing is not recommended to be automated
  • The most cost-effective interface test
  • Interface testing can be automated
  • To automate the interface, you must have the ability to see the nature of the data through the interface

The test automation discussed later will   also be introduced around  interface automation  .

2 Testable architecture

Currently popular Internet industry, "a service, multi-client" architecture is a kind of  can be a good test of  the architecture, the architecture is as follows:

  1. The server and the client communicate using Http (or WebSocket)
  2. The format of data exchange is generally Json (or XML)
  3. Because there are many downstream devices, the server interface has strong stability requirements

3 Realization of automation technology

Based on the above characteristics, the simplified description of the interface automation test of this system is to do the following things:

  1. Use scripts to make HTTP requests to the interface
  2. Parse the return value
  3. Determine according to the design document
  4. Organize test scripts in a project to form automated test projects

Of course, the above is purely a technical point of view to explain the problem. If it is to be combined with a specific project, it is necessary to design different steps and data to meet different business logic requirements.

For the above 4 purposes, there are several frameworks or tools that can be achieved:

  1. requests

    An Http request library claims to make Http requests more human-friendly, and this framework does achieve this goal.

  2. json

    Conversion library for json and python data types provided by python

  3. pyunit

    The pyunit automation framework provides a large number of assert assertion methods to automate data logic judgments

  4. pycharm

    As a powerful IDE, its performance in project organization is also extremely good

About  pyunit  and  pycharm  have been introduced in the previous section of this series of articles, and will not be repeated here. The focus of this article is on two python libraries related to http communication and data analysis: requests library  and  json library  .

4   json

4.1 Basic introduction

Chinese official homepage:

http://www.json.org/json-zh.html

The introduction to the use of JSON is already self-evident. Although many years ago, there was a  saying that XML and JSON were  equally divided in the field of data encoding and decoding , but after so many years, the momentum of JSON is getting better and better, and the voice of XML is getting smaller and smaller.

Regarding the definition of JSON, quote the original text on the official website  [1] :

JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy to read and write. At the same time, it is easy to parse and generate by machine. It is based on JavaScript Programming Language, Standard ECMA-262 3rd Edition-a subset of December 1999. JSON uses a text format that is completely language-independent, but also uses habits similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

At present, JSON has obviously become the backbone of the standard encoding and decoding of character data exchange on the Internet. As an Internet developer, it is necessary to understand it and use it.

JSON, as a string encoding and decoding plan, is language-independent  . There are various languages ​​on the JSON official website  [1] . Various languages ​​(Java/Php/C#/C/C++/Python/R/Ruby, etc.) have their own implementation methods, which can also be referred to

4.2 python library

The main language of this article is the Python language, and the expanded content is also related to the  Python language. The following Python language JSON libraries are provided on the JSON official website  [1] :

  • The Python Standard Library.
  • simplejson.
  • I stay.
  • Yajl-Py.
  • ultrasound.
  • metamagic.json.

In general, use the first one: The Python Standard Library (Python Standard Library)

Official document address:

https://docs.python.org/2/library/json.html

The main function is: JSON encoding and decoding.

Main functions:

  • Decoding function (loading): convert character stream into json object

    • loads: load string variables
    • load: load file stream
  • Encoding function (unloading): convert the json object into a character stream

    • dumps: output to string variables
    • dump: output to file stream

The above several interfaces are easy to confuse memory. The introduction provides an identification technique: the end with s (loads, dumps) is used to process the string variable  str  .

In general, loads and dumps are used the most, because most of the program operations are memory operations, that is, they mainly process string variables. The following is an example of the official website.

String decoding:

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> json.loads('"\\"foo\\bar"')
u'"foo\x08ar'

String encoding:

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"

For the correspondence between the Python standard data types and the Json data types, please see the official website  [2]

[1] ( 123 )  JSON official website
[2] Python's Json encoding and decoding data correspondence table

Official homepage: 5 requests

5.1 Basic introduction

http://docs.python-requests.org/en/master/

The requests library is a specially encapsulated and extremely user-friendly Http request library. Its purpose is to make Http requests under python easier, and it does achieve its purpose.

installation method:

pip install requests

5.2 Use example

The current general web applications are based on get or post requests. For these two Http requests, the requests library provides very elegant solutions.

The most basic get request

# coding:utf-8
import requests

__author__ = 'harmo'


def get_demo():
    """
    requests 的get方法演示,不带参数
    by:Harmo
    :return:
    """
    url = 'http://www.baidu.com'
    res = requests.get(url)
    print res.url
    print res.status_code


if __name__ == '__main__':
    get_demo()

operation result:

http://www.baidu.com/
200

Get request with parameters:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('http://httpbin.org/get', params=payload)

Post request with parameters:

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

6 Comprehensive example

Combined with the judgment library of pyunit, you can make a simplest interface automation test script according to the following process:

  1. Prepare request parameters according to the document
  2. Requests for the specified http interface
  3. Json parse the returned string
  4. Use pyunit's assert function for judgment
  5. Generate corresponding test report, export or connect with information system

The following is a test of a user login interface. According to the design document, if the interface is successfully logged in, the returned character format is:

{
    "code":200,
    "msg":"",
    "data":{
        "token": "382998dafa5143fd8a38c535be0d1502"
    }
}

If the login fails, the following values ​​are returned:

{"code":403,"msg":"forbidden","data":""}

Then the corresponding test script code is

def test_admin_user_login(self):
    """
    测试用户登录
    by:Harmo
    :return:
    """

    url = "%s%s" % (self.base_url, '/task/admin-user-login/')

    params = dict(
        user='admin',
        password='222222',

    )

    res = requests.post(url, data=params)
    print res.text

    res_dict = json.loads(res.text)
    self.assertEqual(res_dict['code'], 200)

operation result:

Through the prompts of the running results above, we can see that the specified data input does not return the value we expect after passing through the server interface. At this time, we can troubleshoot whether there is a problem with the server interface, or who modified the test data, causing the result to fail to meet expectations.

7 Summary

The content of this small part mainly talks about how to use  requests library  and  json library  to easily build Http interface automated test projects. Basically, if you have mastered the above skills, test developers will have the ability to automate script development. The main task behind is to combine specific project requirements for logical design and data preparation.

With just this step, you have entered the door of automated testing, congratulations.

Gathering sand into a tower, countless interface automation test scripts mentioned above can be integrated into an automated test project, and this automated test project is a prerequisite for continuous integration and rapid iteration, and finally, as a tester, it can become the whole project. It’s a very important part.

During this time, organizing information has become my habit! The following are the resources I collected and sorted out. Insert picture description here
For friends who are learning software testing, it should be the most comprehensive preparation warehouse. Many friends review these contents and get offers from major manufacturers such as BATJ. This warehouse has also helped A lot of software testing learners, I hope to help you too!

The universe is uncertain, you and I are both dark horses

Follow WeChat public account: [Programmer Erhei] You can get this warehouse resource for free!

Guess you like

Origin blog.csdn.net/m0_52650621/article/details/112908435