Ive got a directory structure:
Business Logic
excel_format_error_checks.py
tests
test_excel_format_error_checks.py
When I set my import of excel_format_error_checks like below, VSCode test discovery gives an error
ModuleNotFoundError: No module named 'Business_Logic'
test_excel_format_error_checks.py
import sys
sys.path.append('..')
from Business_Logic import excel_format_error_checks
class TestExcelFormatErrorChecks(TestCase):
@patch('Business_Logic.excel_format_error_checks.openpyxl')
def test_tgl_not_missing_from_titles(self,mock_openpyxl):
...
If I change the import to from ..Business_Logic import excel_format_error_checks
, the test discovery works.
When I then try to run the tests from VSCode test discovery, I get an error because of the @patch path, ModuleNotFoundError: No module named 'Business_Logic'
.
When I try to run the tests from the terminal, I get the error
ImportError: Failed to import test module: test_excel_format_error_checks Traceback (most recent call last): File "C:\Users\brady\AppData\Local\Programs\Python\Python310\lib\unittest\loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "C:\Users\brady\Desktop\excel_formatting\excel_format_website\api\tests\test_excel_format_error_checks.py", line 6, in <module> from ..Business_Logic import excel_format_error_checks ImportError: attempted relative import with no known parent package
Questions, 1.why does test discovery only work when i add the .. to the import 2. How can I fix the issue/ fix the patch path
Thanks
CodePudding user response:
In the python language, the import usually only looks in the current directory of the file, and your file directory is obviously not in the same folder.
We can use the following code to provide relative paths. Of course, absolute paths are more commonly used.
import os
import sys
os.path.join(os.path.dirname(__file__), '../')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from BusinessLogic import excel_format_error_checks