Problem
I am trying to make unit tests for my project, but I am having issues figuring out where my error is in regards to absolute importing the module to test. I am using Visual Studio Code as my IDE.
My directories look like this:
project_folder
+ code_files
- reader.py
- __init__.py
+ tests
- test_reader.py
- data.txt
- __init__.py
My "test_reader.py" file looks like this:
import unittest
from code_files.reader import Reader
class Test_LineCounter(unittest.TestCase):
def test_empty_file_long(self):
self.assertEqual(Reader.line_counter(self, "data.txt"), 4)
if __name__ == "__main__":
unittest.main()
However, I keep getting the error:
ModuleNotFoundError: No module named 'code_files'
Attempted Solutions
To be completely honest, when I was going into this project I was not very strong working with directories, packages, or modules. I have read many articles online and have read many forum posts on Stack Overflow and other websites trying to figure out what may be causing this error and how I can resolve it. Through this, I feel like I have gained a pretty good understanding of how Python handles packages and modules. Yet I still can't seem to get this problem figured out.
I have tried putting the "code_files" package into a different directory to see if that would work:
project_folder
+ app
+ code_files
- reader.py
- __init__.py
And then imported by:
from app.code_files.reader import Reader
But then I got the error:
ModuleNotFoundError: No module named 'app'
The only time I managed to get "test_reader" to work was when I had my directory structed as follows:
project_folder
+ code_files
- reader.py
- __init__.py
+ test_reader.py
+ data.txt
+ __init__.py
Final Comments
Any help would be greatly appreciated! I feel like there is a very simple solution to this that I just keep overlooking. I know very similar questions have been asked on here before, but all of the determined solutions I have seen are what I have already tried or am currently doing. So I apologize if this is a repetitive question. Thanks!
