在特定Python结构中运行单元测试和覆盖率

1 投票
1 回答
1394 浏览
提问于 2025-04-15 16:00

我遇到了一些搞笑的新手问题。

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

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

也许我没有看到什么明显的东西。 我还尝试运行覆盖率测试。 这样的做法(文件结构)好吗?

1 个回答

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还支持在运行测试时收集覆盖率数据。

此外,给你的Python包起名为“src”听起来不是个好主意。你应该把你的包重命名为你的项目名。可以考虑用“estimator”或者“pyestimator”(请用小写)。

撰写回答