zoukankan      html  css  js  c++  java
  • doctest模块

    doctest

    doctest为python自带一个测试模块,他会搜索模块中看起来像是交互式会话的代码片段,然后执行并验证结果;

    使用方式1:

    1、测试用例的位置必须放在整个模块文件的开头,或者紧接着对象声明语句的下一行。也就是可以被 __doc__ 这个属性引用到的地方。并非像普通注释一样写在哪里都可以。

    2、verbose 参数用于控制是否输出详细信息,默认为 False,如果不写,那么运行时不会输出任何东西,除非测试 fail。

    3、启动测试的方式是在 __main__ 函数里调用了 doctest.testmod() 函数。

    举例:

    定义一个模块test_doctest.py

    def multiply(a, b):
    """
    >>> multiply(2,3)
    6
    >>> multiply('asd',2)
    'asdasd'
    """
    return a*b

    if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)

    执行结果:
    D:Python27python.exe D:/PythonGit/PythonGit/my_code/learn_test/unnecessary_math.py
    Trying:
    multiply(2,3)
    Expecting:
    6
    ok
    Trying:
    multiply('asd',2)
    Expecting:
    'asdasd'
    ok
    1 items had no tests:
    __main__
    1 items passed all tests:
    2 tests in __main__.multiply
    2 tests in 2 items.
    2 passed and 0 failed.
    Test passed.

    Process finished with exit code 0

    使用方式二:
    在没有main函数的情况下,可以使用命令行来启动测试;
    python -m doctest test_doctest.py
    python -m doctest -v test_doctest.py(-v等价于上面的verbose=True)

    使用方式三:
    把测试用例写到一个独立文件中,如下:
    testfile.txt
    >>> from test import multiply
    >>> multiply(2,3)
    6
    >>> multiply('aaa',2)
    'aaaaaa'

    运行方式如下:
    import doctest

    doctest.testfile('testfile.txt')


     
  • 相关阅读:
    TypeError: Buffer.alloc is not a function
    node.js服务端程序在Linux上持久运行
    C#中的反射
    群要事日记
    vs2017 自定义生成规则 错误 MSB3721 命令 ”已退出,返回代码为 1。
    VP9 Video Codec
    用户手册是Yasm汇编
    更改Mysql数据库存储位置
    注册表项
    C#开发可以可视化操作的windows服务
  • 原文地址:https://www.cnblogs.com/quyong/p/8532352.html
Copyright © 2011-2022 走看看