python下常见的测试框架之二--doctest

来源:互联网 发布:淘宝店店铺介绍范文 编辑:程序博客网 时间:2024/06/01 10:03
doctest是python内建的测试模块,使用也相对比较简单。主要有两种方式:
一,放在类定义后方法定义前。


class ShoppingCart(object):
    """
    This is documentation for the this entire recipe.
    With it, we can demonstrate usage of the code.


    >>> cart = ShoppingCart().add("tuna sandwich", 15.0)
    >>> len(cart)
    1
    >>> cart.item(1)
    'tuna sandwich'
    >>> cart.price(1)
    15.0
    >>> print round(cart.total(9.25), 2)
    16.39
    """




    def __init__(self):
        self.items = []


    def add(self, item, price):
        self.items.append(Item(item, price))
        return self


    def item(self, index):
        return self.items[index-1].item


    def price(self, index):
        return self.items[index-1].price


    def total(self, sales_tax):
        sum_price = sum([item.price for item in self.items])
        return sum_price*(1.0 + sales_tax/100.0)


    def __len__(self):
        return len(self.items)


class Item(object):
    def __init__(self, item, price):
        self.item = item
        self.price = price




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






二:放在类定义前面:
"""
This is documentation for the this entire recipe.
With it, we can demonstrate usage of the code.


>>> cart = ShoppingCart().add("tuna sandwich", 15.0)
>>> len(cart)
1
>>> cart.item(1)
'tuna sandwich'
>>> cart.price(1)
15.0
>>> print round(cart.total(9.25), 2)
16.39
"""


class ShoppingCart(object):
    def __init__(self):
        self.items = []


    def add(self, item, price):
        self.items.append(Item(item, price))
        return self


    def item(self, index):
        return self.items[index-1].item


    def price(self, index):
        return self.items[index-1].price


    def total(self, sales_tax):
        sum_price = sum([item.price for item in self.items])
        return sum_price*(1.0 + sales_tax/100.0)


    def __len__(self):
        return len(self.items)


class Item(object):
    def __init__(self, item, price):
        self.item = item
        self.price = price




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




>>>是交互式python提示符,doctest通过比对>>>后的函数和下一行的结果来判断测试用例是否通过。
对空格等敏感,如果结果里面有不相关的空格,tab等符号会导致测试用例失败。
字典等结构很难测试,因为python并不保证顺序。
在期望的结果里面最好不要有对象引用,因为他们的值也不一定每次相同。




doctest的作用范围是每一个docstring。翻译不太清楚这个含义,那就把原文和示范用例搬上来。the doctest module looks for every docstring.for each docstring it finds,it creates a shallow copy of the module's global variables and then runs the code and checks results. apeart from that,every variable created is locally scoped and then cleaned up when the test is complete.


"""
This is documentation for the this entire recipe.
With it, we can demonstrate usage of the code.


>>> cart = ShoppingCart().add("tuna sandwich", 15.0)
>>> len(cart)
1
>>> cart.item(1)
'tuna sandwich'
>>> cart.price(1)
15.0
>>> print (round(cart.total(9.25), 2))
16.39
"""


class ShoppingCart(object):
    def __init__(self):
        self.items = []


    def add(self, item, price):
        self.items.append(Item(item, price))
        return self


    def item(self, index):
        return self.items[index-1].item


    def price(self, index):
        return self.items[index-1].price


    def total(self, sales_tax):
        sum_price = sum([item.price for item in self.items])
        return sum_price*(1.0 + sales_tax/100.0)


    def __len__(self):
        return len(self.items)


class Item(object):
    def __init__(self, item, price):
        self.item = item
        self.price = price




if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)
运行结果如下:
>>> ================================ RESTART ================================
>>> 
Trying:
    cart = ShoppingCart().add("tuna sandwich", 15.0)
Expecting nothing
ok
Trying:
    len(cart)
Expecting:
    1
ok
Trying:
    cart.item(1)
Expecting:
    'tuna sandwich'
ok
Trying:
    cart.price(1)
Expecting:
    15.0
ok
Trying:
    print (round(cart.total(9.25), 2))
Expecting:
    16.39
ok
9 items had no tests:
    __main__.Item
    __main__.Item.__init__
    __main__.ShoppingCart
    __main__.ShoppingCart.__init__
    __main__.ShoppingCart.__len__
    __main__.ShoppingCart.add
    __main__.ShoppingCart.item
    __main__.ShoppingCart.price
    __main__.ShoppingCart.total
1 items passed all tests:




我们在item方法下加一个docstring。则整个代码为
"""
This is documentation for the this entire recipe.
With it, we can demonstrate usage of the code.


>>> cart = ShoppingCart().add("tuna sandwich", 15.0)
>>> len(cart)
1
>>> cart.item(1)
'tuna sandwich'
>>> cart.price(1)
15.0
>>> print (round(cart.total(9.25), 2))
16.39
"""


class ShoppingCart(object):
    def __init__(self):
        self.items = []


    def add(self, item, price):
        self.items.append(Item(item, price))
        return self


    def item(self, index):
        """
        >>> cart.item(1)
        'tuna sandwich'
        """
        return self.items[index-1].item


    def price(self, index):
        return self.items[index-1].price


    def total(self, sales_tax):
        sum_price = sum([item.price for item in self.items])
        return sum_price*(1.0 + sales_tax/100.0)


    def __len__(self):
        return len(self.items)


class Item(object):
    def __init__(self, item, price):
        self.item = item
        self.price = price




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


运行结果为:
>>> ================================ RESTART ================================
>>> 
Trying:
    cart = ShoppingCart().add("tuna sandwich", 15.0)
Expecting nothing
ok
Trying:
    len(cart)
Expecting:
    1
ok
Trying:
    cart.item(1)
Expecting:
    'tuna sandwich'
ok
Trying:
    cart.price(1)
Expecting:
    15.0
ok
Trying:
    print (round(cart.total(9.25), 2))
Expecting:
    16.39
ok
Trying:
    cart.item(1)
Expecting:
    'tuna sandwich'
**********************************************************************
File "E:\python\book\python testing cookbook\[Python.Testing.Cookbook(第1版)].源代码\4668_Code\Chapter 3\03\recipe19b.py", line 26, in __main__.ShoppingCart.item
Failed example:
    cart.item(1)
Exception raised:
    Traceback (most recent call last):
      File "C:\Python33\lib\doctest.py", line 1287, in __run
        compileflags, 1), test.globs)
      File "<doctest __main__.ShoppingCart.item[0]>", line 1, in <module>
        cart.item(1)
    NameError: name 'cart' is not defined
8 items had no tests:
    __main__.Item
    __main__.Item.__init__
    __main__.ShoppingCart
    __main__.ShoppingCart.__init__
    __main__.ShoppingCart.__len__
    __main__.ShoppingCart.add
    __main__.ShoppingCart.price
    __main__.ShoppingCart.total
1 items passed all tests:
   5 tests in __main__
**********************************************************************
1 items had failures:
   1 of   1 in __main__.ShoppingCart.item
6 tests in 10 items.
5 passed and 1 failed.
***Test Failed*** 1 failures.


从运行结果可以看到cart没有定义,也就是说doctest在运行完第一个docstring之后,就把全部的变量清除了,所以导致cart没有定义。如果在item下的docstring下加入>>>cart = ShoppingCart().add("tuna sandwich", 15.0)后再运行,则这个错误会清除。




如果想忽略掉某个测试用例,可以写成如下形式。
>>> len(cart)  #doctest:  +SKIP
1
如果想忽略掉空格,可以在测试用例后加上 #doctest:  +NORMALIZE_WHITESPACE
0 0
原创粉丝点击