Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python's unittest give "ImportError: Import by filename is not supported." in WSL bash?

On Windows, I have a Python code base with some unit tests (based on unittest) in sub-folders.

I use the Windows Command Prompt to change to the folder and run all tests using python -m unittest subfolder/tests.py. The tests in the file are then detected and run.

When I try to do the same in the Windows Subsystem for Linux bash shell, I get the following error with stack trace:

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.

Why does this error occur in WSL bash but not in cmd? How can I fix this to work in both?

PS - Here is an example of a tests.py as referred to above:

import unittest
from target import target

class tests(unittest.TestCase):

  def test_pi(self):
      expected = 3.1415926
      actual = truncate(target.pi(), 7)
      self.assertEqual(actual, expected)

  def truncate(num, digits):
      return int(num * 10**digits) / 10**digits

if __name__ == '__main__':
    unittest.main()
like image 688
urig Avatar asked Feb 04 '18 07:02

urig


1 Answers

Try to first change directory to <test_cases_dir> and then run the command without the .py suffix

from python docs

python -m unittest test_module.TestClass

in your example:

cd subfolder
python -m unittest tests.tests

(for the enthusiasts only) from unittest implementation, a relative path cannot be imported:

def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.

The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.

The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
    parts_copy = parts[:]
    while parts_copy:
        try:
            module = __import__('.'.join(parts_copy))
            break
        except ImportError:
 . . . 
like image 195
xstsp Avatar answered Oct 18 '22 15:10

xstsp