skip to Main Content

I’ve got a project with a suite of Python unit tests (using the unittest framework) that import Pytorch and cv2.
I am able to run them all from the command line with

python -m unittest discover -s tests/

But get import errors in the VSCode UI when I try to load them:

Failed to import test module: test_overlays
Traceback (most recent call last):
  File "XXXAppDataLocalContinuumanaconda3libunittestloader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "XXXAppDataLocalContinuumanaconda3libunittestloader.py", line 377, in _get_module_from_name
    __import__(name)
  File "XXXteststest_overlays.py", line 13, in <module>
...
    import torch
ModuleNotFoundError: No module named 'torch'

My project is structured as a "wrapper application" importing utilities from a core library:

main_proj/
   library/
      packages and modules importing torch
   tests/
      unit tests for the application

The tests generally test only the wrapper application (there are separate tests for the library), but I occasionally import modules from library/.

Because the tests are outside main_proj/library, I need to add the library explicitly to the path at the top of each unit test:

import unittest
import sys
import os, os.path

sys.path.append(os.path.join(os.getcwd(), 'library'))

Why does this arrangement work just fine from the command line, but not from VSCode?

2

Answers


  1. Chosen as BEST ANSWER

    What resolved this issue was to:

    1. Update VSCode to the latest version

    2. Switch to an older Python 3.6 Anaconda environment (Ctrl+Shift+P, then Choose Interpreter...) -- I'm not sure this step is necessary

    3. Close VSCode

    4. Delete the Python extensions and reinstall them:

      • From git bash:

        cd ~/.vscode/extensions
        rm -fr *python*
        
      • Re-open VSCode and navigate to the extensions panel (Cog wheel->Extensions) and search for Python)

    Afterward, I was able to use my Python 3.8+Torch 1.12 environment without any hitches.

    It seems that something between VSCode and the Python extensions can occasionally get corrupted and requires a clean start in order to recover.


  2. I had this myself today in a similar way. Test discovery could not find numpy, yet according to pip from the command line it was installed in the pyenv-venv.

    Turns out I had the directory using an older pyenv-venv (3.8.12) on the command line, that had the pip packages installed. Yet VSCode was using a newer pyenv-venv (3.10.6) which I had forgotten to install numpy into.

    So, to match what VSCode was set to, and the one I thought I was using…

    pyenv local venv_3.10.6
    pip install matplotlib
    

    fixed it. Now Test Explorer was able to discover the unittests correctly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search