【问题标题】:how to configure unit test in vscode for python unittest如何在vscode中为python unittest配置单元测试
【发布时间】:2019-12-24 00:06:39
【问题描述】:

我正在使用 Python 3.6 和最新版本的 vscode。

我的文件夹结构:

/folder
    /src
        src.py
    /tests
        src_test.py

src.py:

class Addition:
  def __init__(self, a, b):
    self.a = a
    self.b = b
  def run(self):
    return self.a + self.b

src_test.py:

import unittest

from ..src.addition import Addition

class TestAddition(unittest.TestCase):
  def test_addition(self):
    inst = Addition(5, 10)
    res = inst.run()
    self.assertEqual(res, 16)

if( __name__ == "main"):
  unittest.main()

这是我的项目 settings.json:

{
  "python.testing.unittestArgs": [
    "-v",
    "-s",
    ".",
    "-p",
    "*_test.py"
  ],
  "python.testing.pytestEnabled": false,
  "python.testing.nosetestsEnabled": false,
  "python.testing.unittestEnabled": true
}

然后在项目根目录下:

python3 -m unittest 测试/src_test.py

 File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'tests.src_test'

【问题讨论】:

    标签: python-3.6 python-unittest vscode-settings vscode-python


    【解决方案1】:

    您在测试文件夹下缺少__init__.py 文件,并且您的模块的导入需要调整。

    __init__.py 允许 Python 在文件夹结构中向上并到达 src.py 模块(src 下的另一个 __init__.py 会很好,但没有必要让 vscode 测试工作)。

    这是一个工作文件夹结构:

    .
    ├── src
    │   └── src.py
    └── tests
        ├── __init__.py
        └── src_test.py
    

    另外,更改 src.py 中的行:

    • (旧)from ..src.addition import Addition
    • (新)from src.src import Addition

    【讨论】:

    • 我就是这么做的。但是,我有错误: ModuleNotFoundError: No module named 'model' 。 . .我像这样执行导入: from src.package.myclass import MyClass
    • 你知道它是什么吗?我在 vscode 中使用 pipenv 来管理我的项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2014-06-16
    • 1970-01-01
    • 2018-06-06
    • 2019-12-29
    • 2018-09-12
    相关资源
    最近更新 更多