Nose不执行导入模块的doctest

4 投票
1 回答
1426 浏览
提问于 2025-04-17 17:10

我有一个项目,结构大概是这样的:

my_project_with_tests/
  project/
    __init__.py
    module.py
  test/
    test.py

module.py 文件里有两个带有 doctest 的函数:

def foo():
  """
  >>> foo()
  1
  """
  return 1

def test_foo_doctest():
    """
    >>> module.foo()
    1
    """
    pass


def bar():
  """
  >>> bar()
  """
  return 1

test.py 文件里包含了运行测试所需的内容:

import sys
import os.path
sys.path = [os.path.abspath("../project")] + sys.path


import module


def test_foo():
    assert module.foo() == 1


def test_bar():
    assert module.bar() == 1

我现在是用 nose 来运行我的测试:

nosetests                   \
    --all-modules           \
    --traverse-namespace    \
    --with-coverage         \
    --cover-tests           \
    --with-doctest          \
    --where test/

不过,它没有从我的 project 源代码目录中运行 doctests(但是测试目录中的 doctests 是可以的,因为 test_foo_doctest 通过了)。

  1. 这样调用 nose 是对的吗?
  2. 我该如何从 project 目录运行 doctests
    • 使用 nose
    • 不改变目录结构
    • 不在 project 目录中运行测试

1 个回答

2
  1. 这是调用nose的一个好方法,但有一个小问题会导致你的doctests无法运行。请看第2点。

  2. --where test/ 改成 --where .,假设你是在 project/project 目录下运行这个命令。这样nose就能找到doctests了。现在它只在test/目录里找。

撰写回答