【问题标题】:run unit tests and coverage in certain python structure在某些 python 结构中运行单元测试和覆盖
【发布时间】:2010-12-16 13:56:53
【问题描述】:

我有一些有趣的菜鸟问题。

我尝试从命令行运行单元测试:

H:\PRO\pyEstimator>python src\test\python\test_power_estimator.py
Traceback (most recent call last):
  File "src\test\python\test_power_estimator.py", line 2, in <module>
    import src.main.python.power_estimator as power
ImportError: No module named src.main.python.power_estimator

当我尝试在所需文件夹中运行它时也会发生这种情况:

H:\PRO\pyEstimator\src\test\python>python test_power_estimator.py

我的文件夹结构如下所示。

├───src
│   │   __init__.py
│   │   __init__.pyc
│   │
│   ├───main
│   │   │   __init__.py
│   │   │   __init__.pyc
│   │   │
│   │   └───python
│   │       │   __init__.py
│   │       │   power_estimator.py
│   │       │   __init__.pyc
│   │       │   power_estimator.pyc
│   │       │
│   │       └───GUI
│   │               __init__.py
│   │
│   └───test
│       │   __init__.py
│       │
│       └───python
│               test_power_estimator.py
│               __init__.py
│               covrunner.bat
│               .coverage
│
└───doc

也许我没有看到明显的东西。 我也尝试进行报道。 这种方法好吗(文件结构)?

【问题讨论】:

    标签: python unit-testing code-coverage python-coverage


    【解决方案1】:

    您面临的直接问题是对 Python 中的“本地代码”是什么(我不确定是否有官方术语,所以我正在编造这个)以及如何导入它的误解。

    当您运行python src\test\python\test_power_estimator.py 时,sys.path 中的第一个元素设置为包含test_power_estimator.py 脚本的目录,而不是当前目录。所以语句“import src.main.python.power_estimator as power”在目录src/test/python中查找包src,结果失败。

    解决此问题的一种方法是将 PYTHONPATH 环境变量设置为“H:\PRO\pyEstimator”

    但是运行测试的推荐方法是使用测试运行器脚本。我推荐使用nosetest

    此外,nosetest 支持在运行测试时收集覆盖率数据。

    此外,拥有一个名为“src”的 python 包听起来是个坏主意。您应该将您的包重命名为您的项目。可能是“estimator”或“pyestimator”(请小写)。

    【讨论】:

    • 嗨,感谢您的回复,我为启动这个项目所做的是: import sys import os sys.path.append(os.getcwd()) from src.main.python.power_estimator import * 但我不喜欢那样。我会尝试 PYTHONPATH 代替。 “SRC”真的那么糟糕吗,而我的根包目录名称为“estimator”,并且里面有所有项目文件、文档、SConstructs 等。
    • 只要在 PyEstimator 目录下直接有一个 init.py 文件就可以了。问题是“src”是一个我不会放在模块命名空间根目录的名称。并且“src.main.python.power_estimator”是相对导入(脆弱,糟糕!)或“src”是包根名称(有点不卫生)。
    • 再次感谢。我一定会听从你的言论。你知道网络中有什么好的资源可以在这个领域采取一些务实的方法吗?我基于此:docs.python.org/tutorial/modules.html#packages,正如我们所见,这并没有耗尽良好的实践。
    • PEP8 是一个很好的基准,但是很多细节是判断和经验的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    相关资源
    最近更新 更多