`
410063005
  • 浏览: 178127 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

unittest和doctest的使用

 
阅读更多

使用python unittest做测试

http://www.cnblogs.com/imouren/archive/2011/08/04/2127997.html

 

python unittest单元测试

http://catmic27.blog.51cto.com/2517040/946852

 

# coding: utf-8
class Area:
    def __init__(self, width=100, height=100):
        self._width = width
        self._height = height
        
    def get_width(self):
        return self._width
     
    def get_height(self):
        return self._height
        
    def get_area(self):
        return self._width * self._height
        
    def set_width(self, width):
        if width <= 0:
            raise ValueError, "Illegal width value"
        self._width = width    
        
    def set_height(self, height):
        if height <= 0:
            raise ValueError, "Illegal height value"
        self._height = height
        
import unittest        
class AreaTest(unittest.TestCase):
    def setUp(self):
        self.area = Area()
        
    def tearDown(self):
        self.area = None
    
    def test_area(self):
        self.assertEqual(self.area.get_area(), 100 * 100)
        
    def test_width(self):
        self.area.set_width(1)
        self.assertEqual(self.area.get_area(), 1 * 100)
        
if __name__ == '__main__':
    unittest.main()

  unittest.TestCase有如下用于测试的方法

 

assertAlmostEqual
assertAlmostEquals
assertEqual
assertEquals
assertFalse
assertNotAlmostEqual
assertNotAlmostEquals
assertNotEqual
assertNotEquals
assertRaises
assertTrue
assert_
countTestCases
debug
defaultTestResult
fail
failIf
failIfAlmostEqual
failIfEqual
failUnless
failUnlessAlmostEqual
failUnlessEqual
failUnlessRaises
failureException
id
run
setUp
shortDescription
tearDown
 

 

# coding: utf-8

class SampleClass:
    """
    >>> print 1
    1

    >>> # comments get ignored.  so are empty PS1 and PS2 prompts:
    >>>
    ...

    Multiline example:
    >>> sc = SampleClass(3)
    >>> for i in range(10):
    ...     sc = sc.double()
    ...     print sc.get(),
    6 12 24 48 96 192 384 768 1536 3072
    """
    def __init__(self, val):
        """
        >>> print SampleClass(12).get()
        12
        """
        self.val = val

    def get(self):
        """
        >>> print SampleClass(3).get()
        3
        """
        return self.val

    def double(self):
        """
        >>> print SampleClass(10).double().get()
        20
        """
        return SampleClass(self.val + self.val)

    def a_staticmethod(val):
        """
        这个静态方法将传入的值加1并返回
        >>> print SampleClass.a_staticmethod(10)
        11
        """
        return val + 1

    a_staticmethod = staticmethod(a_staticmethod)

    def a_classmethod(cls, val):
        """
        这个类方法将传入的值加12并返回

        >>> print SampleClass.a_classmethod(100)
        112
        >>> print SampleClass(0).a_classmethod(0)
        12
        """
        return val + 12
    a_classmethod = classmethod(a_classmethod)

    a_property = property(get, doc="""
        >>> print SampleClass(22).a_property
        22
        """)

    class NestedClass:
        """
        这个嵌套类对val进行平方求值

        >>> x = SampleClass.NestedClass(5)
        >>> y = x.square()
        >>> print y.get()        
        25
        """
        def __init__(self, val=0):
            """
            """
            self.val = val

        def square(self):
            return SampleClass.NestedClass(self.val * self.val)

        def get(self):
            return self.val
            
        
def sample_func(v):
    """
    Blah blah

    >>> print sample_func(22)
    44
    >>> print sample_func(0)
    0
    >>> print sample_func(-22)
    -44

    Yee ha!
    """
    return v+v


"""
这是一个使用doctest进行测试的小例子. 主要测试factorial
是否返回阶乘

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> [factorial(long(n)) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000L
    >>> factorial(30L)
    265252859812191058636308480000000L
    """
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result


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

 

 

# -*- coding: utf-8 -*-

import doctest

class SampleNewStyleClass(object):
    r"""
    打印1, 2, 3, 中间有换行
    >>> print '1\n2\n3'
    1
    2
    3
    """

    def __init__(self, val):
        """
        """
        self.val = val

    def double(self):
        """
        这个方法返回一个新的SampleNewStyleClass对象,
        其值为原来的2倍

        >>> print SampleNewStyleClass(23).double().get()
        46
        """
        return SampleNewStyleClass(self.val + self.val)

    def get(self):
        """
        这个方法返回val值

        >>> print SampleNewStyleClass(25).get()
        25
        """
        return self.val

if __name__ == '__main__':
    doctest.testmod()
    

 

 

def test_DocTestSuite():
    """DocTestSuite creates a unittest test suite from a doctest.

       We create a Suite by providing a module.  A module can be provided
       by passing a module object:

         >>> import unittest
         >>> import test.sample_doctest
         >>> suite = doctest.DocTestSuite(test.sample_doctest)
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=4>

       We can also supply the module by name:

         >>> suite = doctest.DocTestSuite('test.sample_doctest')
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=4>

       We can use the current module:

         >>> suite = test.sample_doctest.test_suite()
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=4>

       We can supply global variables.  If we pass globs, they will be
       used instead of the module globals.  Here we'll pass an empty
       globals, triggering an extra error:

         >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=5>

       Alternatively, we can provide extra globals.  Here we'll make an
       error go away by providing an extra global variable:

         >>> suite = doctest.DocTestSuite('test.sample_doctest',
         ...                              extraglobs={'y': 1})
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=3>

       You can pass option flags.  Here we'll cause an extra error
       by disabling the blank-line feature:

         >>> suite = doctest.DocTestSuite('test.sample_doctest',
         ...                      optionflags=doctest.DONT_ACCEPT_BLANKLINE)
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=5>

       You can supply setUp and tearDown functions:

         >>> def setUp(t):
         ...     import test.test_doctest
         ...     test.test_doctest.sillySetup = True

         >>> def tearDown(t):
         ...     import test.test_doctest
         ...     del test.test_doctest.sillySetup

       Here, we installed a silly variable that the test expects:

         >>> suite = doctest.DocTestSuite('test.sample_doctest',
         ...      setUp=setUp, tearDown=tearDown)
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=3>

       But the tearDown restores sanity:

         >>> import test.test_doctest
         >>> test.test_doctest.sillySetup
         Traceback (most recent call last):
         ...
         AttributeError: 'module' object has no attribute 'sillySetup'

       The setUp and tearDown funtions are passed test objects. Here
       we'll use the setUp function to supply the missing variable y:

         >>> def setUp(test):
         ...     test.globs['y'] = 1

         >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=9 errors=0 failures=3>

       Here, we didn't need to use a tearDown function because we
       modified the test globals, which are a copy of the
       sample_doctest module dictionary.  The test globals are
       automatically cleared for us after a test.
       """

def test_DocFileSuite():
    """We can test tests found in text files using a DocFileSuite.

       We create a suite by providing the names of one or more text
       files that include examples:

         >>> import unittest
         >>> suite = doctest.DocFileSuite('test_doctest.txt',
         ...                              'test_doctest2.txt',
         ...                              'test_doctest4.txt')
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=3 errors=0 failures=3>

       The test files are looked for in the directory containing the
       calling module.  A package keyword argument can be provided to
       specify a different relative location.

         >>> import unittest
         >>> suite = doctest.DocFileSuite('test_doctest.txt',
         ...                              'test_doctest2.txt',
         ...                              'test_doctest4.txt',
         ...                              package='test')
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=3 errors=0 failures=3>

       Support for using a package's __loader__.get_data() is also
       provided.

         >>> import unittest, pkgutil, test
         >>> added_loader = False
         >>> if not hasattr(test, '__loader__'):
         ...     test.__loader__ = pkgutil.get_loader(test)
         ...     added_loader = True
         >>> try:
         ...     suite = doctest.DocFileSuite('test_doctest.txt',
         ...                                  'test_doctest2.txt',
         ...                                  'test_doctest4.txt',
         ...                                  package='test')
         ...     suite.run(unittest.TestResult())
         ... finally:
         ...     if added_loader:
         ...         del test.__loader__
         <unittest.result.TestResult run=3 errors=0 failures=3>

       '/' should be used as a path separator.  It will be converted
       to a native separator at run time:

         >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=1 errors=0 failures=1>

       If DocFileSuite is used from an interactive session, then files
       are resolved relative to the directory of sys.argv[0]:

         >>> import types, os.path, test.test_doctest
         >>> save_argv = sys.argv
         >>> sys.argv = [test.test_doctest.__file__]
         >>> suite = doctest.DocFileSuite('test_doctest.txt',
         ...                              package=types.ModuleType('__main__'))
         >>> sys.argv = save_argv

       By setting `module_relative=False`, os-specific paths may be
       used (including absolute paths and paths relative to the
       working directory):

         >>> # Get the absolute path of the test package.
         >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
         >>> test_pkg_path = os.path.split(test_doctest_path)[0]

         >>> # Use it to find the absolute path of test_doctest.txt.
         >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')

         >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=1 errors=0 failures=1>

       It is an error to specify `package` when `module_relative=False`:

         >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
         ...                              package='test')
         Traceback (most recent call last):
         ValueError: Package may only be specified for module-relative paths.

       You can specify initial global variables:

         >>> suite = doctest.DocFileSuite('test_doctest.txt',
         ...                              'test_doctest2.txt',
         ...                              'test_doctest4.txt',
         ...                              globs={'favorite_color': 'blue'})
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=3 errors=0 failures=2>

       In this case, we supplied a missing favorite color. You can
       provide doctest options:

         >>> suite = doctest.DocFileSuite('test_doctest.txt',
         ...                              'test_doctest2.txt',
         ...                              'test_doctest4.txt',
         ...                         optionflags=doctest.DONT_ACCEPT_BLANKLINE,
         ...                              globs={'favorite_color': 'blue'})
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=3 errors=0 failures=3>

       And, you can provide setUp and tearDown functions:

         >>> def setUp(t):
         ...     import test.test_doctest
         ...     test.test_doctest.sillySetup = True

         >>> def tearDown(t):
         ...     import test.test_doctest
         ...     del test.test_doctest.sillySetup

       Here, we installed a silly variable that the test expects:

         >>> suite = doctest.DocFileSuite('test_doctest.txt',
         ...                              'test_doctest2.txt',
         ...                              'test_doctest4.txt',
         ...                              setUp=setUp, tearDown=tearDown)
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=3 errors=0 failures=2>

       But the tearDown restores sanity:

         >>> import test.test_doctest
         >>> test.test_doctest.sillySetup
         Traceback (most recent call last):
         ...
         AttributeError: 'module' object has no attribute 'sillySetup'

       The setUp and tearDown funtions are passed test objects.
       Here, we'll use a setUp function to set the favorite color in
       test_doctest.txt:

         >>> def setUp(test):
         ...     test.globs['favorite_color'] = 'blue'

         >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=1 errors=0 failures=0>

       Here, we didn't need to use a tearDown function because we
       modified the test globals.  The test globals are
       automatically cleared for us after a test.

       Tests in a file run using `DocFileSuite` can also access the
       `__file__` global, which is set to the name of the file
       containing the tests:

         >>> suite = doctest.DocFileSuite('test_doctest3.txt')
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=1 errors=0 failures=0>

       If the tests contain non-ASCII characters, we have to specify which
       encoding the file is encoded with. We do so by using the `encoding`
       parameter:

         >>> suite = doctest.DocFileSuite('test_doctest.txt',
         ...                              'test_doctest2.txt',
         ...                              'test_doctest4.txt',
         ...                              encoding='utf-8')
         >>> suite.run(unittest.TestResult())
         <unittest.result.TestResult run=3 errors=0 failures=2>

    
 

 

分享到:
评论

相关推荐

    Python中的测试模块unittest和doctest的使用教程

    主要介绍了Python中的测试模块unittest和doctest的使用教程,本文来自于IBM官方网站技术文档,需要的朋友可以参考下

    Python单元测试工具doctest和unittest使用解析

    主要介绍了Python单元测试工具doctest和unittest使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    elm-doctest:针对Elm-lang源文件的doctest运行程序

    榆木doctest 针对Elm-lang源文件的安装npm install elm-doctest 它取决于elm并假定可以通过系统范围内的安装或npm模块安装来使用elm-make和elm-repl 。 确保elm-make成功处理您的elm源文件。它是如何工作的? 它利用...

    python 测试实现方法

    1)doctest 使用doctest是一种类似于命令行尝试的方式,用法很简单,如下 复制代码 代码如下:def f(n): “”” &gt;&gt;&gt; f(1) 1 &gt;&gt;&gt; f(2) 2 “”” print(n) if __name__ == ‘__main__’: import doctest doctest.testmod...

    Python.Unit.Test.Automation.pdf

    Quickly learn how to automate unit testing of Python 3 code with Python 3 automation libraries, such as doctest, unittest, nose, nose2, and pytest. This book explores the important concepts in ...

    CS362_Inclass_Assignments:课堂分配

    CS362_Inclass_Assignments...使用以下python3 -m doctest -v unitTest.py运行doc测试: python3 -m doctest -v unitTest.py 使用以下python3 -m unittest unitTest.py运行单元测试: python3 -m unittest unitTest.py

    详解Python中的测试工具

    本文介绍了两个Python中的测试工具: doctest和unittest,并配以简单的例子来说明这两个测试模块的使用方法,需要的朋友可以参考下

    Python Testing - Beginner's Guide (2010).pdf

    Chapter 5: When Doctest isn't Enough: Unittest to the Rescue introduces the unittest framework and discusses when it is preferred over doctest. Chapter 6: Running Your Tests: Follow Your Nose ...

    Python Testing_ Beginner’s Guide.pdf

    Chapter 5: When Doctest isn't Enough: Unittest to the Rescue introduces the unittest framework and discusses when it is preferred over doctest. Chapter 6: Running Your Tests: Follow Your Nose ...

    Learning Python Testing(PACKT,2014)

    From there, the discussion proceeds to unittest.mock and mock objects, and to unittest. Next, Nose is introduced and discussed. Later on, focus turns from the tools themselves toward best practices ...

    Python单元和文档测试实例详解

    主要介绍了Python单元和文档测试,结合实例形式分析了Python单元测试模块unittest及文档测试模块doctest相关使用技巧,需要的朋友可以参考下

    python testing cookbook

    Python开发和使用Python和Python测试基本的了解程序员会发现这个食谱有利。这将建立在基本的知识装备要充分利用Python测试工具的中级和高级技巧。分解成许多小的代码的食谱,你可以按照自己的速度阅读这本书,无论...

    Python Cookbook

    8.10 在Python 2.4中使用doctest和unittest 331 8.11 在单元测试中检查区间 334 第9章 进程、线程和同步 336 引言 336 9.1 同步对象中的所有方法 339 9.2 终止线程 342 9.3 将Queue.Queue用作优先级队列 344 ...

    Python Unit Test Automation:for Python Developers and Testers

    Quickly learn how to automate unit testing of Python 3 code with Python 3 automation libraries, such as doctest, unittest, nose, nose2, and pytest. This book explores the important concepts in ...

    Mastering Python [2016]

    You will also get familiar with different testing systems such as py.test, doctest, and unittest, and debugging tools such as Python debugger and faulthandler. You will learn to optimize application ...

    sinon:独立于测试框架且与Python无关的测试间谍,存根和模拟(发音为“叹气”)

    诗乃 ... python,unittest,间谍,存根,模拟,沙盒,unittest2,pytest,sinon,doctest 文献资料 请单击此处阅读文档 先前的讨论 Reddit(r / Python): Sinon.PY,另一个受Sinn.JS启发的模拟库

    Python Testing Cookbook.pdf

    The Python unit testing framework, originally referred to as “PyUnit” and now known as unittest, is a framework that makes it easier for you to write automated test suites efficiently in Python....

Global site tag (gtag.js) - Google Analytics