Nose的简单用法

安装

使用pip进行安装
pip install nose

基本用法&举例

nose会自动识别源文件,目录或包中的测试用例。任何符合正则表达式(?:^|[b_.-])[Tt]est的类、函数、文件或目录,以及TestCase的子类都会被识别并执行。

测试文件及目录格式

  1. 目录格式如下

    1
    2
    3
    4
    5
    $ tree
    .
    ├── main.py
    └── test
    └──test.py
  2. main.py内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/usr/bin/env python
    # encoding: utf-8


    def Testfun():
    """docstring for Testfun"""
    a = 1
    b = 2
    assert a == b
  3. main.py内容如下:

    1
    2
    3
    4
    5
    6
    #!/usr/bin/env python
    # encoding: utf-8


    import nose
    nose.main()

nose用法

  1. 在test目录下执行nosetests
  2. 在根目录下执行python main.py

得到的输出结果均为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
F
======================================================================
FAIL: docstring for Testfun
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/home/yarving/workspace/nose_demo/test/test.py", line 9, in Testfun
assert a == b
AssertionError

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

0%