I know similar questions have been asked before... But I had a quick doubt... I have been following this link: https://www.python-course.eu/python3_packages.php
my code structure:
my-project -- __init__.py -- src -- __init__.py -- file1.py -- test -- __init__.py -- test_file1.py
test_file1.py:
import unittest from src.file1 import * class TestWriteDataBRToOS(unittest.TestCase): def test_getData(self): sampleData = classInFile1() sampleData.getData() self.assertNotEqual(sampleData.usrname, "") if __name__ == '__main__': unittest.main()
Here I get the error:
ModuleNotFoundError: No module named 'src'
If I change to :
import sys sys.path.insert(0, '../src') import unittest from file1 import *
then it works!
Can someone help me understand why it won't work like how it has been described in the link pasted above or any alternative way instead of writing the sys.path.insert(0, '../src')
statement.
Thanks!
Edit:
after executing from my-project dir: `python -m unittest test/test_file1/TestWriteDataBRToOS I am getting the error as updated above.
Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/lib/python2.7/unittest/__main__.py", line 12, in <module> main(module=None) File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs self.createTests() File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests self.module) File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName module = __import__('.'.join(parts_copy)) ImportError: Import by filename is not supported.
This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.
sys. path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module. When a module(a module is a python file) is imported within a Python file, the interpreter first searches for the specified module among its built-in modules.
You have to run the test from the my-project
folder, rather than from the test
folder.
python -m unittest test.test_file1.TestWriteDataBRToOS
Also you can you do:
export PYTHONPATH="${PYTHONPATH}:/path/to/your/project/"
or in Windows:
set PYTHONPATH="${PYTHONPATH}:/path/to/your/project/"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With