Python入门-程序测试

 1.功能测试

常规测试

#常规测试代码,一个模块写功能,一个模块调用功能

#=============模块1:gongneng_ceshi
def func(v1, v2):
    return v1* v2
#=============模块2
from gongneng_ceshi import func  #导入模块1

def main():
    if func(5,6) *3 ==30:
        print("乘法计算ok")
    else:
        print("数学乘法计算失败!")

def main2():
    if func("hello",3) == "hellohellohello":
        print("字符串乘法计算ok")
    else:
        print("字符串乘法计算失败!")
if __name__ == '__main__':
    main()
    main2()
"""
数学乘法计算失败!
字符串乘法计算ok
"""
常规的功能测试代码,结构简单,测试单一,测试比较分散

doctest模块,测试单个功能

import doctest  

#在程序中,对执行部分进行描述,结果部分直接编写
# 坑逼模块,>>> 后面必须留一个空格,不然会报错!!!
def fun(v1, v2):
    """
    >>> fun(5,6)
    30
    >>> fun("he",2)
    'hehe'
    """
    return v1 * v2

if __name__ == '__main__':
    doctest.testmod(verbose=True) 
    #True表示,执行时候输出详细信息,默认为False
"""
返回执行时间
Testing started at 10:32 ...
"""

unittest模块,测试单个文件

#功能模块1==============================
class Math:
    def add(self, numa, numb):
        return numa + numb
    def sub(self, numa, numb):
        return numa - numb

if __name__ == '__main__':
    m = Math()
#测试模块2==============================
from  unitest_demo import Math

import unittest

class Testmath(unittest.TestCase): #继承testcase父类
    @classmethod
    def setUpClass(self):
        print("【=======全部测试开始=====】")
    @classmethod
    def tearDownclass(self):
        print("【=======全部测试结束=====】")
    def tearDown(self) -> None:
        print("{}:测试结束".format(self.id()))
    def setUp(self) -> None:
        print("{}:测试开始".format(self.id()))
    def test_add(self):
        self.assertEqual(Math().add(1,2),3)
        
    # 不需要测试的功能,使用装饰器进行装饰
    @unittest.skip("Math.sub方法,功能暂不需要测试。")
    def test_sub(self):
        self.assertEqual(Math().sub(3,2),1)
if __name__ == '__main__':
    unittest.main()

"""
============================= test session starts =============================
collecting ... collected 2 items
test_math.py::Testmath::test_add 【=======全部测试开始=====】
PASSED                                  [ 50%]test_math.Testmath.test_add:测试开始
test_math.Testmath.test_add:测试结束
test_math.py::Testmath::test_sub SKIPPED (Math.sub方法,功能暂不需要...) [100%]
Skipped: Math.sub方法,功能暂不需要测试。
=================== 1 passed, 1 skipped, 1 warning in 0.04s ===================
Process finished with exit code 0
"""

unittest模块,测试多个文件

# 测试文件,都保存在某个目录下,可以集中测试全部文件
# 下面定义一个单独的模块脚本
import os import unittest class RunAllTest(unittest.TestCase): def test_run(self): case_path = os.getcwd() # 获取测试文件目录 discover = unittest.defaultTestLoader.discover(case_path, pattern="test_ma*.py") runner = unittest.TextTestRunner(verbosity=2) runner.run(discover) if __name__ == '__main__': unittest.main() """ Testing started at 20:25 ... Launching pytest with arguments test_file.py::RunAllTest --no-header --no-summary -q in E:\code\hunjia_16\day11_0824\unittest_demo ============================= test session starts ============================= collecting ... collected 1 item test_file.py::RunAllTest::test_run PASSED [100%]【=======全部测试开始=====】 test_math.Testmath.test_add:测试开始 test_math.Testmath.test_add:测试结束 test_add (test_math.Testmath) ... ok test_sub (test_math.Testmath) ... skipped 'Math.sub方法,功能暂不需要测试。' ---------------------------------------------------------------------- Ran 2 tests in 0.001s OK (skipped=1) ======================== 1 passed, 1 warning in 0.01s ========================= """

2.性能测试cProfile

#性能分析,profile,以及cprofile模块

import cProfile  #需要导入模块cProfile,注意P是大写
def plu(num):
    s = 0
    for i in range(num):
        s += i
    return s
if __name__ == '__main__':
    # 测试plu功能函数,后面可定义结果保存位置,文件名【不定义位置,会直接输出】
    cProfile.run("plu(9999999)", "f:\\test.result")
"""
ncalls        tottime    percall      cumtime     percall          filename:lineno(function)
函数调用总次数  总运行时间  运行平均时间   总计运行时间  运行一次的平均时间  所在文件名,代码行,函数名

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.542    0.542 <string>:1(<module>)
        1    0.542    0.542    0.542    0.542 cprofile_demo.py:4(plu)
        1    0.000    0.000    0.542    0.542 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

"""

pstats报告的保存分析

import pstats  #需要先导入模块
def main():
    stats = pstats.Stats( "f:\\test.result") #定义保存位置
    stats.sort_stats("time") #按照时间排序
    stats.print_stats()  # 打印统计报告
if __name__ == '__main__':
    main()
"""
Wed Aug 25 16:48:48 2021    f:\test.result
         4 function calls in 0.589 seconds
   Ordered by: internal time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.589    0.589    0.589    0.589 E:/code/hunjia_16/day11_0824/xing_neng_ceshi/cprofile_demo.py:4(plu)
        1    0.000    0.000    0.589    0.589 {built-in method builtins.exec}
        1    0.000    0.000    0.589    0.589 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
"""

3.代码规范性检测

python默认是pep8的规范,pycharm就是遵守这个规范,Ctrl+Alt+L可以直接调整格式

pylint模块规范检测组件

#需要先安装pylint包
#方法1==================================
"""
1.编写一段代码
2.进入Terminal窗口
3.cd到当前脚本目录
4.pylint 文件名
 pylint  .\pylint_demo.py
5.会得到类似如下返回结果
************* Module pylint_demo
pylint_demo.py:4:0: C0305: Trailing newlines (trailing-newlines)
pylint_demo.py:1:0: C0114: Missing module docstring (missing-module-docstring)
pylint_demo.py:1:0: C0115: Missing class docstring (missing-class-docstring)
pylint_demo.py:2:4: C0116: Missing function or method docstring (missing-function-docstring)
pylint_demo.py:2:4: R0201: Method could be a function (no-self-use)
pylint_demo.py:1:0: R0903: Too few public methods (1/2) (too-few-public-methods)

"""
#方法2==================================
"""
1.进入pycharm
2.打开settings---Tools---External Tools---添加执行工具----配置相关信息
3.运行程序即可
"""

flake8模块规范检测组件

# 操作同上

 

posted @ 2021-08-24 10:35  zwx901323  阅读(273)  评论(0)    收藏  举报