简体   繁体   中英

Visual Studio 2019 - Cannot run Python unittests - Failed to import test module:

Was successfully developing on Python with VS2019 for last several days now. So my environment seems to be properly installed and appropriate configured.


So I want to use unittest for Python with Visual Studio 2019 and came along here: https://docs.microsoft.com/en-us/visualstudio/python/unit-testing-python-in-visual-studio

Then started with a freshly created empty project. The test module 'test_A.py' is located in a subfolder called "tests":

解决方案资源管理器

It is exactly the same code from the MS Docs example (Link above):

    import unittest

    class Test_test1(unittest.TestCase):
        def test_A(self):
            self.fail("Not implemented")

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

In the project settings I turned on 'unittest' and set the root folder like this:

项目设置

The Test Explorer is directly showing the test class:

测试资源管理器

But running the tests, always this ImportError comes up, that the module cannot be found and therefore is not existing:

Test Name:  test_A
Test FullName:  test_A::tests\test_A.py::Test_test1::test_A
Test Source:    D:\pyproject\pyproject\tests\test_A.py : line 4
Test Outcome:   Failed
Test Duration:  0:00:00

Test Name:  test_A
Test Outcome:   Failed
Result StackTrace:  3.7
Result Message: Failed to import test module: test_A
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'test_A'
Result StandardError:   
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\case.py", line 59, in testPartExecutor
    yield
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\case.py", line 628, in run
    testMethod()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\loader.py", line 34, in testFailure
    raise self._exception
ImportError: Failed to import test module: test_A
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'test_A'

Why is Visual Studio in trouble, when previously detecting the test module??? Somewhat strange to me... Thanks for any hint.

I had similar issues with pytest in different IDEs and the solution was to add __init__.py in the tests folder. You can try that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM