pycharm中测试的三种模式(unittest框架、pytest框架、普通模式)

1、python运行脚本的三种模式

经过查阅资料才发现,原来python的运行脚本的方式有多种:html

  • 例如普通模式运行,不会自动去加载测试用例执行
  • unittest 测试框架运行模式,能够自动去发现testcase并执行 pytest
  • 测试框架运行模式,就是咱们上面2个步骤都是使用pytest测试框架运行的

重要原则:第一次按照何种模式执行测试用例,后续都会按照这种方式去执行python

2、pycharm中 no tests were found

首次使用测试用例时,按照网上教程会首次出现 no tests were found 的状况。
在这里插入图片描述web

上图中会出现no test were found的状况。框架

根本缘由是在定义的类中的函数没有以test开头。svg

3、理解unittest框架中的setUpClass、setUp、tearDown、tearDownClass

python unitest单元测试框架中,有几个特殊的状况以下:函数

setUp():每一个测试方法运行前运行,测试前的初始化工做。一条用例执行一次,若N次用例就执行N次,根据用例的数量来定。单元测试

setUpClass():全部的测试方法运行前运行,为单元测试作前期准备,但必须使用@classmethod装饰器进行修饰,整个测试过程当中只执行一次。测试

tearDown():每一个测试方法运行结束后运行,测试后的清理工做。一条用例执行一次,若N次用例就执行N次。ui

tearDownClass():全部的测试方法运行结束后运行,为单元测试作后期清理工做,但必须使用@classmethod装饰器进行修饰,整个测试过程当中只执行一次。code

4、默认使用pytest框架去执行unittest框架中的测试用例

在这里插入图片描述
此时程序中运行默认使用pytest框架,如图中所示:
在这里插入图片描述

5、取消默认而且在unittest框架下运行

pycharm执行某些程序时会默认在unittest框架下执行,从而致使程序报错,怎样解决这个问题呢?

File->setting->Tools->Python Intergrated Tools->Default test runner->py.test

选择后若是显示未安装,请先安装py.test
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

6、普通运行模式,导出测试报告

import unittest
import time,HTMLTestRunner


class AlienTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print("TestCase  start running ")

    def test_1_run(self):
        print("hello world_1")

    def test_2_run(self):
        print("hello world_2")

    def test_3_run(self):
        print("hello world_3")


if __name__ == '__main__':
    print('hello world')
    suite = unittest.makeSuite(AlienTest)
    now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())
    filename = "/Users/test/The_Order_Of_TestCase/Report/" + now + "_result.html"
    fp = open(filename, 'wb')
    runner = HTMLTestRunner.HTMLTestRunner(
        stream=fp,
        title=u'ALIEN测试报告',
        description=u'ALIEN用例执行状况:')

    runner.run(suite)
    # 关闭文件流,不关的话生成的报告是空的
    fp.close()

默认是使用unittest模式运行的,结果以下,其实这样不会执行main()函数,更不会导出报告
在这里插入图片描述
最终经过建立普通模式的运行模式,而后按照以下方式能够运行
在这里插入图片描述
最终的测试报告以下:
在这里插入图片描述

7、总结

  • (1)使用pytest测试框架时候,不须要main()函数,系统能够自动识别测试用例并执行。
  • (2)即便包含main()函数,点击它去执行,也不会去执行main()函数。
  • (3)具体是使用哪一个测试框架执行,不是经过main()函数设置的,在别的地方。