IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> Selenium3自动化测试【37】单元测试Unittest(2) -> 正文阅读

[开发测试]Selenium3自动化测试【37】单元测试Unittest(2)

引言

unittest是Python标准库中自带的单元测试框架。unittest可以组织执行测试用例,并且提供了丰富的断言方法,可以判断测试用例是否通过,最终生成测试结果。

【2021】UI自动化测试:Selenium3自动化测试
(https://edu.csdn.net/course/detail/29953)
【测试全栈列视频课程】请点击我哦…
(https://edu.csdn.net/agency/59)

1. 测试结果

TextTestRunner测试执行器负责测试执行调度并且生成测试结果给用户。可以将测试结果直接在控制台中输出,也可以将测试结果输出到外部文件。
有时候想要很清楚的看到每条用例执行的详细信息,可以通过设置verbosity参数实现,verbosity默认为1,可以设置为0和2。

  • 0(静默模式): 只能获得总的测试用例数和总的结果; ? 1(默认模式): 非常类似静默模式, 只是在每个成功的用例前面有个“.”
  • 每个失败的用例前面有个 “E”; ? 2(详细模式):
  • 测试结果会显示每个测试用例的所有相关的信息,且你在命令行里加入不同的参数可以起到一样的效果。

1.1 输出到IDE结果中

Verbosity=0,修改test_suite.py文件,代码如下:

import unittest
from UnitTestDemo.test_mathfunc import TestMathFunc

if __name__ == "__main__":
    suite = unittest.TestSuite()
    # 执行加法、减法、除法
    tests = [TestMathFunc("test_add"),TestMathFunc("test_divide"),TestMathFunc("test_minus")]
    suite.addTests(tests)
    # addTest()添加单个TestCase
    #suite.addTest(TestMathFunc("test_multi"))

    # #####################################
    # verbosity默认为1,可以设置为0和2。
    #
    # 0(静默模式): 你只能获得总的测试用例数和总的结果。
    # 1(默认模式): 非常类似静默模式, 只是在每个成功的用例前面有个“.” 每个失败的用例前面有个 “E”
    # 2(详细模式): 测试结果会显示每个测试用例的所有相关的信息,且你在命令行里加入不同的参数可以起到一样的效果
    # #####################################
    runner = unittest.TextTestRunner(verbosity=0)
    runner.run(suite)

运行test_suite.py,结果如下:

Ran 3 tests in 0.000s
OK
修改test_suite.py文件,设置Verbosity=1,运行代码结果如下:
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

修改test_suite.py文件,设置Verbosity=2,运行代码结果如下。

test_add (UnitTestDemo.test_mathfunc.TestMathFunc)
测试加法add() ... ok
test_divide (UnitTestDemo.test_mathfunc.TestMathFunc)
测试除法divide ... ok
test_minus (UnitTestDemo.test_mathfunc.TestMathFunc)
测试减法minus ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK

1.2 将结果输出到外部文件中

优化test_suite.py文件,通过stream参数将结果输出到外部文件中,优化test_suite.py后的代码如下:

import unittest
from UnitTestDemo.test_mathfunc import TestMathFunc

if __name__ == "__main__":
    suite = unittest.TestSuite()
    # 执行加法、减法、除法
    tests = [TestMathFunc("test_add"),TestMathFunc("test_divide"),TestMathFunc("test_minus")]
    suite.addTests(tests)
    # addTest()添加单个TestCase
    #suite.addTest(TestMathFunc("test_multi"))
    # #####################################
    # verbosity默认为1,可以设置为0和2。
    # 0(静默模式): 你只能获得总的测试用例数和总的结果。
    # 1(默认模式): 非常类似静默模式, 只是在每个成功的用例前面有个“.” 每个失败的用例前面有个 “E”
    # 2(详细模式): 测试结果会显示每个测试用例的所有相关的信息,且你在命令行里加入不同的参数可以起到一样的效果
    # #####################################
    # # ========================
    # # 结果输出位置1:将结果输出到控制台中
    # # ========================
    # runner = unittest.TextTestRunner()
    # runner.run(suite)
    # ========================
    # 结果输出位置2:将结果输出到外部文件中
    # ========================
    with open("d:\\result.txt", "a") as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2)
        runner.run(suite)

运行test_suite.py,可以观察到在D盘下多了result.txt文件,result.txt文件内容如图所示。 在这里插入图片描述

图 result.txt结果内容

2. 测试初始化与还原

通过使用Fixture,可以定义测试执行之前的准备工作和测试执行之后的清理工作。

  • setUp():是执行用例的前置条件。如建立数据库连接;
  • tearDown():执行完用例后,为了不影响下一次用例的执行,一般有个数据还原的过程,tearDown是执行用例的后置条件。如关闭数据库连接。

2.1 setUp()与tearDown()

  • setUp():每个测试case运行之前运行;
  • tearDown():每个测试case运行完之后执行。

修改UnitTestDemo创建的test_mathfunc.py,增加setUp()与tearDown(),代码如下:

import unittest
from UnitTestDemo.mathfunc import *

class TestMathFunc(unittest.TestCase):
    """测试mathfunc.py"""
    # 在每条测试用例执行之前准备好测试环境
    def setUp(self):
        print("do something before test!")

    def test_add(self):
        """测试加法add()"""
        self.assertEqual(3,add(1,2))
        self.assertNotEqual(3,add(2,2))

    def test_minus(self):
        """测试减法minus"""
        self.assertEqual(1,minus(3,2))

    def test_multi(self):
        """测试乘法multi"""
        self.assertEqual(6,multi(2,3))

    def test_divide(self):
        """测试除法divide"""
        self.assertEqual(2,divide(6,3))
        self.assertEqual(2,divide(5,2))

    # 在每条测试用例执行结束之后清理测试环境,还原到初始状态
    def tearDown(self):
        print("do something after test!")

运行test_suite.py,test_suite.py代码如下:

import unittest
from UnitTestDemo.test_mathfunc import TestMathFunc

if __name__ == "__main__":
    suite = unittest.TestSuite()
    # 执行加法、减法、除法
    tests = [TestMathFunc("test_add"),TestMathFunc("test_divide"),TestMathFunc("test_minus")]
    suite.addTests(tests)

    # #####################################
    # verbosity默认为1,可以设置为0和2。
    # 0(静默模式): 你只能获得总的测试用例数和总的结果。
    # 1(默认模式): 非常类似静默模式, 只是在每个成功的用例前面有个“.” 每个失败的用例前面有个 “E”
    # 2(详细模式): 测试结果会显示每个测试用例的所有相关的信息,且你在命令行里加入不同的参数可以起到一样的效果
    # #####################################

    # # ========================
    # # 结果输出位置1:将结果输出到控制台中
    # # ========================
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)

运行test_suite.py,结果如下。

do something before test!
test_add (UnitTestDemo.test_mathfunc.TestMathFunc)
do something after test!
do something before test!
测试加法add() ... ok
do something after test!
test_divide (UnitTestDemo.test_mathfunc.TestMathFunc)
do something before test!
测试除法divide ... FAIL
do something after test!
test_minus (UnitTestDemo.test_mathfunc.TestMathFunc)
测试减法minus ... ok
====================================================================
FAIL: test_divide (UnitTestDemo.test_mathfunc.TestMathFunc)
测试除法divide
----------------------------------------------------------------------
Traceback (most recent call last):
File "*****\UnitTestDemo\test_mathfunc.py", line 60, in test_divide
self.assertEqual(2,divide(5,2))
AssertionError: 2 != 2.5
----------------------------------------------------------------------
Ran 3 tests in 0.001s
FAILED (failures=1)

2.2 setUpClass ()与tearDownClass ()

  • setUpClass():必须使用@classmethod 装饰器,所有case运行前只运行一次;
  • tearDownClass():必须使用@classmethod装饰器,所有case运行完后只运行一次。

修改UnitTestDemo创建的test_mathfunc.py,增加setUpClass ()与tearDownClass (),代码如下:

import unittest
from UnitTestDemo.mathfunc import *

class TestMathFunc(unittest.TestCase):
    """测试mathfunc.py"""
    @classmethod
    def setUpClass(cls):
        print("do something before testClass,only run once!")

    def test_add(self):
        """测试加法add()"""
        self.assertEqual(3,add(1,2))
        self.assertNotEqual(3,add(2,2))

    def test_minus(self):
        """测试减法minus"""
        self.assertEqual(1,minus(3,2))

    def test_multi(self):
        """测试乘法multi"""
        self.assertEqual(6,multi(2,3))

    def test_divide(self):
        """测试除法divide"""
        self.assertEqual(2,divide(6,3))
        self.assertEqual(2,divide(5,2))

    @classmethod
    def tearDownClass(cls):
        print("do something after testClass,only run once!")

test_suite.py内容不变,运行test_suite.py,结果如下:

do something before testClass,only run once!
test_add (UnitTestDemo.test_mathfunc.TestMathFunc)
do something after testClass,only run once!
测试加法add() ... ok
test_divide (UnitTestDemo.test_mathfunc.TestMathFunc)
测试除法divide ... FAIL
test_minus (UnitTestDemo.test_mathfunc.TestMathFunc)
测试减法minus ... ok
====================================================================
FAIL: test_divide (UnitTestDemo.test_mathfunc.TestMathFunc)
测试除法divide
----------------------------------------------------------------------
Traceback (most recent call last):
 File "***\Book\UnitTestDemo\test_mathfunc.py", line 97, in test_divide
   self.assertEqual(2,divide(5,2))
AssertionError: 2 != 2.5
----------------------------------------------------------------------
Ran 3 tests in 0.001s
FAILED (failures=1)

3. 测试用例跳过(skip)

在执行测试用例时,有时候有些用例是不需要执行的,unittest提供了跳过用例的方法。

  • @unittest.skip(reason):强制跳过,不需要判断条件。reason是跳过原因的描述必须填写;
  • @unittest.skipIf(condition, reason):condition为True时跳过用例;
  • @unittest.skipUnless(condition, reason):当condition为False时跳过用例;
  • @unittest.expectedFailure:如果test失败了,这个test不计入失败的case数目。

以@unitest.skipUnless为例。通过@unitest.skipUnless来跳过是否执行某条测试用例,修改test_mathfunc.py,修改后的代码如下:

import unittest
from UnitTestDemo.mathfunc import *

class TestMathFunc(unittest.TestCase):
    """测试mathfunc.py"""
     # @unittest.skip("don't run this case!")
     # @unittest.skipIf(3<2,"don't run this case!")
    @unittest.skipUnless(1>2,"don't run this case!")
    def test_add(self):
        """测试加法add()"""
        self.assertEqual(3,add(1,2))
        self.assertNotEqual(3,add(2,2))

    def test_minus(self):
        """测试减法minus"""
        self.assertEqual(1,minus(3,2))

    def test_multi(self):
        """测试乘法multi"""
        self.assertEqual(6,multi(2,3))

    def test_divide(self):
        """测试除法divide"""
        self.assertEqual(2,divide(6,3))
        self.assertEqual(2.5,divide(5,2))

未给test_mathfunc.py添加 @unitest.skipUnless前,运行test_suite.py的结果如下。

test_add (UnitTestDemo.test_mathfunc.TestMathFunc)
测试加法add() ... ok
test_divide (UnitTestDemo.test_mathfunc.TestMathFunc)
测试除法divide ... ok
test_minus (UnitTestDemo.test_mathfunc.TestMathFunc)


测试减法minus ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK

修改test_mathfunc.py代码,添加 @unitest.skipUnless后,运行test_suite.py的结果如下。

test_add (UnitTestDemo.test_mathfunc.TestMathFunc)
测试加法add() ... skipped "don't run this case!"
test_divide (UnitTestDemo.test_mathfunc.TestMathFunc)
测试除法divide ... ok
test_minus (UnitTestDemo.test_mathfunc.TestMathFunc)
测试减法minus ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK (skipped=1)

可观察到test_add()用例未被执行,被跳过了。这是由于@unittest.skipUnless(condition, reason):当condition为False(@unittest.skipUnless(1>2,“don’t run this case!”))时跳过用例。

测试精讲视频

如果你觉的文章读的不过瘾,可以查看详细的视频教程。
【2021】UI自动化测试:Selenium3自动化测试
(https://edu.csdn.net/course/detail/29953)
【测试全系列视频课程】请点击我哦…
(https://edu.csdn.net/agency/59)

学习路线如下

微信图片_20210816100905.png微信图片_202108161009051.png微信图片_202108161009052.png
在这里插入图片描述

热销图书

图书京东、当当有售
京东: https://item.jd.com/12784287.html
当当: http://product.dangdang.com/29177828.html
0.9733767060093851.png

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2022-05-08 08:25:31  更:2022-05-08 08:25:56 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 16:02:20-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码