Search code examples
python-3.6python-unittestvisual-studio-codevscode-python

how to configure unit test in vscode for python unittest


I am using Python 3.6 and latest version of vscode.

My folder structure:

/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()

here is my project settings.json:

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

Then under project root folder:

python3 -m unittest tests/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'

Solution

  • You are missing an __init__.py file under the tests folder, and the import your module needs a tweak.

    The __init__.py allows Python to go up in the folder structure and reach the src.py module (another __init__.py under src would be nice, but it is not necessary to make the vscode tests work).

    This is a working folder structure:

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

    Also, change the line in src.py:

    • (OLD) from ..src.addition import Addition
    • (NEW) from src.src import Addition