Search code examples
pythonunit-testingvisual-studio-codepipenv

unit testing a pipenv project in VSCODE


I was doing a simple unit test with unittest, and my *_test.py goes like:

import unittest
import pdf_text_extract
import re

class TestPdf2TxtMethod(unittest.TestCase):
    def test_txtextract(self):
        test_pdf_file = "test.pdf"

        extraction_result = pdf_text_extract.txt_extract(test_pdf_file)

        #remove page number infos
        extraction_result = re.sub(r'--\d+/\d+--\n\n', '', extraction_result)

        with open("expected.txt", 'r') as f:
            expected_content = f.read()

        self.assertEqual(expected_content, extraction_result)

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

in which txt_extract is a function using different modules, and I manage those modules with pipenv.

I know it seems to be a kind of virtual environment, like when you try to run the test locally, you are not able to import those modules and ModuleNotFound error is gonna occur.

like when I run the test, I have such an error:

Failed to import test module: pdf_text_extract_test
Traceback (most recent call last):
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "pdf_text_extract_test.py", line 2, in <module>
    import pdf_text_extract
  File "pdf_text_extract.py", line 2, in <module>
    import fitz
ModuleNotFoundError: No module named 'fitz'

I want to know, how to do the unit test when you are testing the code importing a lot of libraries and highly rely on pipenv on vscode.

I'm not sure about wether there are mistakes in the test file, so your kindly answer is gonna be really important for me.

Thanks.

I try to run the testing python file in terminal using pipenv run python test.py , and it's okay with right result. but when I'm using vscode test, such error also occurs together with the detailed information I show you above:
vscode testing error

so I wonder how can I make this work correctly, showing the structure of testing file like what I can see in the official doc.


Solution

  • ModuleNotFoundError: No module named 'fitz'

    Usually, this was caused by the incorrect python interpreter.

    You can use shortcuts Ctrl+Shift+P and type Python: Select Interpreter to choose your python interpreter which you installed the package in.