Python 的 Unitest 目录结构,导入包问题

104 阅读1分钟

总览

例如使用 PDM 的 pdm init 新建 Python 项目,获得的目录结构将长成这样:

my-project/
├── src
│   └── myproject
│       ├── __init__.py
│       └── script.py
└── tests
    ├── __init__.py
    └── test_script.py

src 下放各个包,test 下放测试代码。

问题来了。该怎样从 test_script.py 中导入 script.py 的成员内容,从而编写测试代码?

实践

例如,script.py 中的内容:

def double(x: int):
    return x*2

那么 test_script.py 可以这样写:

import unittest
from src.myproject.script import double


class TestScript(unittest.TestCase):
    def test_double(self):
        res = double(2)
        self.assertEqual(res, 4)


if __name__ == '__main__':
    unittest.main()

然后在 my-project 目录下执行 python -m unittest,就能自动找到测试用例并执行。

参考来源