Python 3 interface testing actual (lower) - unittest testing framework

This Section

  • unittest Profile
  • Written Cases
  • Organizational and operational use cases
  • Generate test reports

unitttest Profile

Reference: unittest official documents

Why use unittest?
When writing an interface automation use cases, we generally build a .py file for an interface, a test case package is a function (method), but in the process a batch execution, if one error, use cases can not be executed back. EXAMPLE performed using a test frame may not affect each other and more flexible control is performed

unittest Features

  • python carrying unit testing framework, without having to install
  • Example interfering with execution
  • Provide a range of different setUp (test preparation) and tearDown (test cleanup) method
  • It provides a wealth of assertions
  • EXAMPLES All modules may be performed in batch by discover
  • May be illustrated by the TestSuite (test set) flexible organization

unittest major part

  • TestCase: cases with object class to inherit the preparation of test cases so as to have properties and methods TestCase
  • TestSuite: test set or test suite, a set of test cases, cases for tissues, supports nested
  • TestLoader: Example loader used for adding to the use of the embodiment TestSuite
  • TextTestRunner: Use Case actuator (result output text), performed in units generally use case TestSuite
  • TestResult: Test Results

Written Cases

  1. Test_ a new beginning (must) .py files, such astest_user_login.py
  2. Import unittest
  3. Write a Test at the beginning of class (must), and the inheritance unittest.TestCase, as a test class
  4. Test_ beginning of a write (to be) a method in the class, as with cases

test_user_login.py The file must begin with # test_

import unittest  # 导入unittest
import requests

class TestUserLogin(unittest.TestCase): # 类必须Test开头,继承TestCase才能识别为用例类 url = 'http://115.28.108.130:5000/api/user/login/' def test_user_login_normal(self): # 一条测试用例,必须test_开头 data = {"name": "张三", "password": "123456"} res = requests.post(url=self.url, data=data) self.assertIn('登录成功', res.text) # 断言 def test_user_login_password_wrong(self): data = {"name": "张三", "password": "1234567"} res = requests.post(url=self.url, data=data) self.assertIn('登录失败', res.text) # 断言 if __name__ == '__main__': # 如果是直接从当前模块执行(非别的模块调用本模块) unittest.main(verbosity=2) # 运行本测试类所有用例,verbosity为结果显示级别 

By writing order is not executed, but by a case name ascii code sequence to execute: a procedure example executed

Use Case assertion
unittest provides a wealth of assertion methods commonly used for the following:

  • For equality
    • assertEqual (a, b) / assertNotEqual (a, b): assert values ​​are equal
    • assertIs (a, b) / assertIsNot (a, b): to say whether the same object (the same memory address)
    • assertListEqual (list1, list2) / assertItemNotEqual (list1, list2): assert this list for equality
    • assertDictEqual (dict1, dict2) / assertDictNotEqual (dict1, dict2): assert dictionary for equality
  • Is empty
    • assertIsNone(a)/assertIsNotNone(a)
  • Judge true and false
    • assertTrue(a)/assertFalse(a)
  • Contains
    • assertIn (a, b) / assertNotIn (a, b) is contained in a # b
  • The size of the judgment
    • assertGreater(a,b)/assertLess(a,b) : 断言a>b / 断言a<b
    • assertGreaterEqual(a,b)/assertLessEqual: 断言a>=b / 断言a<=b
  • Type judgment
    • assertIsInstance (a, dict) / assertNotIsInstance (a, list) # assertion is a dictionary / non-assertion a list

Example:

import unittest

case = unittest.TestCase()
case.assertEqual(1,2.0/2) # 通过1=2.0/2 case.assertEqual(1, True) # 通过 case.assertIs(1.0, 2.0/2) # 失败,不是同一对象 case.assertListEqual([1,2],[1,2]) # 通过(顺序要一致) case.assertDictEqual({"a":1,"b":2},{"b":2,"a":1}) # 通过,字典本无序 case.assertIsNone({}) # 失败 case.assertFalse({}) # 通过,空字典为False case.assertIn("h","hello") # 通过 case.assertGreater(3,2) # 通过,3>2 case.assertIsInstance({"a":1}, dict) # 通过 

A method of unittest.TestCase is asserted, the assertion by determining whether through use cases (Pass / Fail)

Test Fixtures (Example wrapped with)
the Test Fixtures i.e. setUp (prepared by Example) and tearDown (cleanup Test) method for testing were performed before and after the test

Range divided according to different functions:

  • setUp () / tearDown (): before each use case / post-execution time
  • setUpClass () / tearDownClass (): When executed once for each test class loader / end
  • setUpMoudle () / tearDownMoudle (): each test module (py a file as a module) to load / execute once at the end of
import unittest

def setUpModule(): # 当前模块执行前只执行一次 print('=== setUpModule ===') def tearDownModule(): # 当前模块执行后只执行一次 print('=== tearDownModule ===') class TestClass1(unittest.TestCase):  @classmethod # 声明为类方法(必须) def setUpClass(cls): # 类方法,注意后面是cls,整个类只执行一次 print('--- setUpClass ---')  @classmethod def tearDownClass(cls): print('--- tearDownClass ---') def setUp(self): # 该类中每个测试用例执行一次 print('... setUp ...') def tearDown(self): print('... tearDown ...') def test_a(self): # 测试用例 print("a") def test_B(self): # 大写B的ascii比小写a靠前,会比test_a先执行 print("B") class TestClass2(unittest.TestCase): # 该模块另一个测试类 def test_A(self): print("A") if __name__ == '__main__': unittest.main() 

Results of the:

=== setUpModule ===
--- setUpClass ---
... setUp ...
B
... tearDown ...
... setUp ...
a
... tearDown ...
--- tearDownClass ---
A
=== tearDownModule ===
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s OK 

Complete interface test
a complete use cases require test interface comprising:

  1. Data Preparation: Prepare the test data, may be prepared manually, you may also be used to prepare codes (generally relates to database operations)
  2. Environmental tests: If the manual data preparation, checking the connection database environment using a more robust embodiment
  3. Transmission request: a request transmission interface
  4. Assertion Response / database asserted: after the assertion in response, the database need to be asserted, the interface to ensure the correctness of operation of the database
  5. Data cleansing: if the interface has more database operations, changes need to be restored after the assertion

test_user_reg.py

import unittest
import requests
from db import *   # 导入db.py文件,源码见上篇

# 数据准备
NOT_EXIST_USER = '范冰冰'
EXIST_USER = '张三'


class TestUserReg(unittest.TestCase): url = 'http://115.28.108.130:5000/api/user/reg/' def test_user_reg_normal(self): # 环境检查 if check_user(NOT_EXIST_USER): del_user(NOT_EXIST_USER) # 发送请求 data = {'name': NOT_EXIST_USER, 'password': '123456'} res = requests.post(url=self.url, json=data) # 期望响应结果,注意字典格式和json格式的区别(如果有true/false/null要转化为字典格式) except_res = { "code": "100000", "msg": "成功", "data": { "name": NOT_EXIST_USER, "password": "e10adc3949ba59abbe56e057f20f883e" } } # 响应断言(整体断言) self.assertDictEqual(res.json(), except_res) # 数据库断言 self.assertTrue(check_user(NOT_EXIST_USER)) # 环境清理(由于注册接口向数据库写入了用户信息) del_user(NOT_EXIST_USER) def test_user_reg_exist(self): # 环境检查 if not check_user(EXIST_USER): add_user(EXIST_USER) # 发送请求 data = {'name': EXIST_USER, 'password': '123456'} res = requests.post(url=self.url, json=data) # 期望响应结果,注意字典格式和json格式的区别(如果有true/false/null要转化为字典格式) except_res = { "code": "100001", "msg": "失败,用户已存在", "data": { "name": EXIST_USER, "password": "e10adc3949ba59abbe56e057f20f883e" } } # 响应断言(整体断言) self.assertDictEqual(res.json(), except_res) # 数据库断言(没有注册成功,数据库没有添加新用户) # 环境清理(无需清理) if __name__ == '__main__': unittest.main(verbosity=2) # 运行所有用例 

Organizational and operational use cases

In addition to using unittest.main () to run the entire test class, we can also test set flexible organization to be run by TestSuite

  1. New TestSuite and add test cases
import unittest
from test_user_login import TestUserLogin  
from test_user_reg import TestUserReg # 从上面两个例子里导入测试类 suite = unittest.TestSuite() suite.addTest(TestUserLogin('test_user_login_normal')) # 添加单个用例 suite.addTests([TestUserReg('test_user_reg_normal'),TestUserReg('test_user_reg_exist')]) # 添加多个用例 # 运行测试集 unittest.TextTestRunner(verbosity=2).run(suite) # verbosity显示级别,运行顺序为添加到suite中的顺序 
  1. Use makeSuite come production examples Collection
import unittest
from test_user_login import TestUserLogin

suite1 = unittest.makeSuite(TestUserLogin, 'test_user_login_normal') # 使用测试类的单条用例制作测试集 suite2 = unittest.makeSuite(TestUserLogin) # 使用整个测试类制作测试集合(包含该测试类所有用例) unittest.TextTestRunner(verbosity=2).run(suite1) 
  1. Use TestLoader generate test sets (a loader Example)
improt unittest
from test_user_login import TestUserLogin

suite = unittest.TestLoader().loadTestsFromTestCase(TestUserLogin) # 加载该测试类所有用例并生成测试集

unittest.TextTestRunner(verbosity=2).run(suite)
  1. Using Discover (use cases found) through all use cases
import unittest

suite = unittest.defaultTestLoader.discover("./")  # 遍历当前目录及子包中所有test_*.py中所有unittest用例
unittest.TextTestRunner(verbosity=2).run(suite)

note:

  • Subdirectory contains the required __init__.pydocuments, and should be a Python package
  • All use cases as test _ *. Py, contains the test classes should begin with Test, and inherit unittest.TestCase, patients should begin with a test_
  1. Nesting test set
import unittest
from test_user_login import TestUserLogin

suite1 = unittest.TestSuite()
suite1.addTest(TestUserLogin('test_user_login_normal'))

suite2 = makeSuite(TestUserLogin, 'test_user_login_password_wrong') suite = unittest.TestSuite([suite1, suite2]) # 将两个测试集组合为一个 unittest.TextTestRunner(verbosity=2).run(suite) 

Generate test reports

Generated text report

import unittest

suite = unittest.defaultTestLoader.discover("./")

# 输出测试结果到文本文件
with open("result.txt","w") as f: unittest.TextTestRunner(stream=f,verbosity=2).run(suite) # 将输出流stream输出到文件 

Generate HTML reports

  1. Download HTMLTestRunnerCN
  2. Unzip and extract the package python3x folder HTMLTestRunnerCN.py copied to the project directory
  3. New Script in the directoryrun_all.py
import unittest
from HTMLTestReportCN import HTMLTestRunner

suite = unittest.defaultTestLoader.discover("./")

f = open("report.html", 'wb') # 二进制写格式打开要生成的报告文件 HTMLTestRunner(stream=f,title="Api Test",description="测试描述",runner="卡卡").run(suite) f.close() 
  1. Run the script will be generated report.html in the current folder, you can open a browser
Project preview
testing report

Source Download Link: https://pan.baidu.com/s/1gXwYOCL6BfRW4XVgxkCpIA Password: jdgo




Guess you like

Origin www.cnblogs.com/gdg87813/p/11225543.html