No tests discovered when using VSCode, python and absolute imports

假如想象 提交于 2020-06-16 20:10:08

问题


I am trying to add unit tests to my python project and I can't get VS Code to discover my test. The problem is when I try to import the class that I am testing.

  • If I try to run the test file, it passes.
  • If I omit the from A.myfile import MyFile the test is discovered.

Question: What am I doing wrong here?


File structure:

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 test log:

start

VSCode version: 1.38.1
Python version: 2.7.14 (x64)


回答1:


It's probably because of the value set for -t. If unittest is interpreting that - to use the default setting then it's using -s which is the tests directory, and so your import A line is importing tests/A/__init__.py instead of A/__init__.py which is leading to an ImportError when A.myfile can't be found (check the test output to see the failure).

Change that - to . and it should hopefully fix things to anchor the top directory for your project.



来源:https://stackoverflow.com/questions/58062521/no-tests-discovered-when-using-vscode-python-and-absolute-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!