2

我正在使用Python 的合同来指定前置条件/​​后置条件/不变量。我也在使用 doctests 进行单元测试。

我想让我的所有 doctest 单元测试都在启用合同的情况下运行,并且我想使用nose运行我的测试。不幸的是,如果我用鼻子运行测试,它不会执行前/后/不变断言。我在每个 .py 文件中放置了一个设置函数,以确保它contract.checkmod被调用

def setup():
    import contract
    contract.checkmod(__name__)

我可以确认这个函数在运行测试之前由鼻子执行,但合同仍然没有被执行。

另一方面,如果我通过调用运行 doctest,则会调用doctest.testmodpre/post/inv:

def _test():
    import contract
    contract.checkmod(__name__)
    import doctest
    doctest.testmod()

if __name__=='__main__':    
    _test()

下面是一个 Python 脚本的示例,如果直接调用它的测试将成功,但如果用鼻子调用则失败:

import os

def setup():
    import contract
    contract.checkmod(__name__)

def delete_file(path):
    """Delete a file. File must be present.

    >>> import minimock
    >>> minimock.mock('os.remove')
    >>> minimock.mock('os.path.exists', returns=True)

    >>> delete_file('/tmp/myfile.txt')
    Called os.path.exists('/tmp/myfile.txt')
    Called os.remove('/tmp/myfile.txt')

    >>> minimock.restore()

    pre: os.path.exists(path)
    """
    os.remove(path)

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

当我独立运行上述文件时,测试通过:

$ python contracttest.py -v
Trying:
    import minimock
Expecting nothing
ok
Trying:
    minimock.mock('os.remove')
Expecting nothing
ok
Trying:
    minimock.mock('os.path.exists', returns=True)
Expecting nothing
ok
Trying:
    delete_file('/tmp/myfile.txt')
Expecting:
    Called os.path.exists('/tmp/myfile.txt')
    Called os.remove('/tmp/myfile.txt')
ok
Trying:
    minimock.restore()
Expecting nothing
ok
2 items had no tests:
    __main__
    __main__.setup
1 items passed all tests:
   5 tests in __main__.delete_file
5 tests in 3 items.
5 passed and 0 failed.
Test passed.

这是鼻子:

$ nosetests --with-doctest contracttest.py
F
======================================================================
FAIL: Doctest: contracttest.delete_file
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/doctest.py", line 2131, in runTest
    raise self.failureException(self.format_failure(new.getvalue()))
AssertionError: Failed doctest test for contracttest.delete_file
  File "/Users/lorin/Desktop/contracttest.py", line 10, in delete_file

----------------------------------------------------------------------
File "/Users/lorin/Desktop/contracttest.py", line 17, in contracttest.delete_file
Failed example:
    delete_file('/tmp/myfile.txt')
Expected:
    Called os.path.exists('/tmp/myfile.txt')
    Called os.remove('/tmp/myfile.txt')
Got:
    Called os.remove('/tmp/myfile.txt')


----------------------------------------------------------------------
Ran 1 test in 0.055s
4

0 回答 0