python-3.6python-unittest

Python3.6 error: ModuleNotFoundError: No module named 'src'


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 below.

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.

Solution

  • You have to run the test from the my-project folder, rather than from the test folder.

    python -m unittest test.test_file1.TestWriteDataBRToOS