小编Ale*_*sha的帖子

运行鼻子测试时输入错误,我无法在鼻子外面重现

当我使用nosetests来运行一个我无法在鼻子外面重现的测试套件时,我遇到了一个神秘的导入错误.此外,当我跳过测试的子集时,导入错误消失.

执行摘要: 我在Nose中收到导入错误a)仅在排除带有某个属性的测试时出现,并且b)无法在交互式python会话中重现,即使我确保sys.path对两者都相同.

细节:

包结构如下所示:

project/
    module1/__init__.py
    module1/foo.py
    module1/test/__init__.py
    module1/test/foo_test.py
    module1/test/test_data/foo_test_data.txt
    module2/__init__.py
    module2/bar.py
    module2/test/__init__.py
    module2/test/bar_test.py
    module2/test/test_data/bar_test_data.txt
Run Code Online (Sandbox Code Playgroud)

一些foo_test.py测试的速度很慢,所以我创建了一个@slow装饰,让我有nosetests选择跳过它们:

def slow(func):
    """Decorator sets slow attribute on a test method, so 
       nosetests can skip it in quick test mode."""
    func.slow = True
    return func

class TestFoo(unittest.TestCase):

    @slow
    def test_slow_test(self):
        load_test_data_from("test_data/")
        slow_test_operations_here


    def test_fast_test(self):
        load_test_data_from("test_data/")
Run Code Online (Sandbox Code Playgroud)

当我想只运行快速单元测试时,我会使用

nosetests -vv -a'!slow'
Run Code Online (Sandbox Code Playgroud)

从项目的根目录.当我想要运行它们时,我删除了最后的参数.

我怀疑是这个烂摊子应该归咎于细节.单元测试需要从文件加载测试数据(不是最佳实践,我知道.)文件放在每个测试包中名为"test_data"的目录中,单元测试代码通过相对路径引用它们,假设正在从test /目录运行unit test,如上面的示例代码所示.

为了从项目的根目录中运行nose,我在每个测试包中将以下代码添加到init .py:

import os
import sys

orig_wd = os.getcwd()

def setUp():
    """
    test package setup:  change working directory to the …
Run Code Online (Sandbox Code Playgroud)

python unit-testing nose importerror

14
推荐指数
2
解决办法
8145
查看次数

标签 统计

importerror ×1

nose ×1

python ×1

unit-testing ×1