【问题标题】:No tests discovered when using VSCode, python and absolute imports使用 VSCode、python 和绝对导入时未发现任何测试
【发布时间】:2020-01-23 12:41:05
【问题描述】:

我正在尝试将单元测试添加到我的 python 项目中,但我无法让 VS Code 发现我的测试。问题是当我尝试导入我正在测试的class 时。

  • 如果我尝试run 测试文件,它会通过。
  • 如果我省略了from A.myfile import MyFile,就会发现测试。

问题:我在这里做错了什么?


文件结构

root
├── A
│   ├── __init__.py
│   └── myfile.py
└── tests
    ├── __init__.py
    └── A
        ├── __init__.py
        └── test_myfile.py

myfile.py

class MyFile(object):
    def __init__(self):
        self.value = 1

test_myfile.py

import unittest
from A.myfile import MyFile

class Test_MyFile(unittest.TestCase):
    def test_my_file(self):
        self.assertTrue(True)

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

.env

PYTHONPATH=PATH_TO_ROOT

settings.json

{
    "python.pythonPath": "PATH_TO_PYTHON\python.exe",
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        "./tests",
        "-p",
        "test_*.py",
        "-t",
        "."
    ],
    "python.envFile": "${workspaceFolder}/.env",
    "python.testing.pytestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.unittestEnabled": true
}

Python 测试日志

start

VSCode 版本:1.38.1
Python 版本:2.7.14 (x64)

【问题讨论】:

  • 你的根文件夹添加到路径了吗? cd /path/to/root && export PATH=$PATH:$(pwd)
  • 仅限PYTHONPATH - 这就是我拥有.env 文件的原因。我在 Windows 10 上。

标签: python unit-testing visual-studio-code windows-10 python-unittest


【解决方案1】:

这可能是因为为-t 设置的值。如果unittest- 解释为使用默认设置,那么它使用的是-s,即tests 目录,因此您的import A 行正在导入tests/A/__init__.py 而不是A/__init__.py,这会导致找不到A.myfile 时的ImportError(检查测试输出以查看故障)。

- 更改为.,它有望解决问题以锚定项目的顶级目录。

【讨论】:

  • 你在 dash 上绝对是正确的,但遗憾的是它并不能解决问题。我已经修复了问题中的错误。我晚上一直在考虑这个问题,这是我的问题,当python已经找到更接近测试文件的root/test/A文件夹时,它没有查看root/A/文件夹?
  • @Chau 我刚刚注意到您使用的是 Python 2 而不是 Python 3。添加 from __future__ import absolute_imports 看看是否可以解决问题。
  • 我已经尝试过了,即使在 python 3 环境下,仍然没有发现测试:|
  • @Chau 您是否在终端中尝试过此操作并且可以正常工作?基本上,扩展并没有做任何神奇的事情,因此您可以从配置中获取这些参数并在终端中使用它们,直到它适合您(docs on unittest discovery)。否则,我会将您的 tests/A 目录重命名为 tests/test_A 以避免包名称冲突或尝试使用 pytest 进行发现(它仍然允许您使用 unittest 编写测试)。
猜你喜欢
  • 2018-06-06
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多