Selenium3自动化测试【37】单元测试Unittest(2)

Selenium3自动化测试【37】单元测试Unittest(2),第1张

引言

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)

学习路线如下


热销图书

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/878004.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存