Repository navigation
SystemError: Parent module '' not loaded, cannot perform relative import #67
Copy link
Copy link
Closed
Description
I had imported another test file, in one (main) test file like this:
from .text_extraction_unit_tests import PrefixStrippingViewUnitTests
wrap_plus_module = sys.modules["Wrap Plus.wrap_plus"]
def run_unit_tests(unit_tests_to_run=[]):
runner = unittest.TextTestRunner()
classes = \
[
PrefixStrippingViewUnitTests,
SemanticLineWrapUnitTests,
LineBalancingUnitTests,
]
if len( unit_tests_to_run ) < 1:
# Comment all the tests names on this list, to run all Unit Tests
unit_tests_to_run = \
[
# "test_semantic_line_wrap_line_starting_with_comment",
# "test_split_lines_with_trailing_new_line",
# "test_split_lines_without_trailing_new_line",
# "test_balance_characters_between_line_wraps_with_trailing_new_line",
# "test_balance_characters_between_line_wraps_without_trailing_new_line",
# "test_balance_characters_between_line_wraps_ending_with_long_word",
]
runner.run( suite( classes, unit_tests_to_run ) )
def suite(classes, unit_tests_to_run):
"""
Problem with sys.argv[1] when unittest module is in a script
https://stackoverflow.com/questions/2812218/problem-with-sys-argv1-when-unittest-module
Is there a way to loop through and execute all of the functions in a Python class?
https://stackoverflow.com/questions/2597827/is-there-a-way-to-loop-through-and-execute
looping over all member variables of a class in python
https://stackoverflow.com/questions/1398022/looping-over-all-member-variables-of-a-class
"""
suite = unittest.TestSuite()
unit_tests_to_run_count = len( unit_tests_to_run )
for _class in classes:
_object = _class()
for function_name in dir( _object ):
if function_name.lower().startswith( "test" ):
if unit_tests_to_run_count > 0 \
and function_name not in unit_tests_to_run:
continue
suite.addTest( _class( function_name ) )
return suiteUsing this I can run the unit tests by my loader file inside the file Wrap Plus.wrap_plus:
def run_tests():
"""
How do I unload (reload) a Python module?
https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module
"""
print( "\n\n" )
sublime_plugin.reload_plugin( "Wrap Plus.tests.text_extraction_unit_tests" )
sublime_plugin.reload_plugin( "Wrap Plus.tests.semantic_linefeed_unit_tests" )
sublime_plugin.reload_plugin( "Wrap Plus.tests.semantic_linefeed_manual_tests" )
from .tests import semantic_linefeed_unit_tests
# Comment all the tests names on this list, to run all Unit Tests
unit_tests_to_run = \
[
# "test_semantic_line_wrap_ending_with_comma_list",
# "test_is_command_separated_list_5_items",
# "test_is_command_separated_list_4_items",
# "test_is_command_separated_list_3_items",
# "test_is_command_separated_list_2_items",
]
semantic_linefeed_unit_tests.run_unit_tests( unit_tests_to_run )
def plugin_loaded():
"""
Running single test from unittest.TestCase via command line
https://stackoverflow.com/questions/15971735/running-single-test-from-unittest-testcase
"""
run_tests()And it successfully run I reload the Wrap Plus.wrap_plus file:
reloading plugin Wrap Plus.tests.text_extraction_unit_tests
reloading plugin Wrap Plus.tests.semantic_linefeed_unit_tests
reloading plugin Wrap Plus.tests.semantic_linefeed_manual_tests
...................................................
----------------------------------------------------------------------
Ran 51 tests in 0.601s
OK
reloading plugin Wrap Plus.wrap_plus
But when I use the UnitTesting command UnitTesting: Test Current Package, I got this error:
semantic_linefeed_unit_tests (unittest.loader.ModuleImportFailure) ... ERROR
test_double_quotes_wrappting (text_extraction_unit_tests.PrefixStrippingViewUnitTests) ... ok
test_double_quotes_wrappting_without_leading_whitespace (text_extraction_unit_tests.PrefixStrippingViewUnitTests) ... ok
test_triple_quotes_comment (text_extraction_unit_tests.PrefixStrippingViewUnitTests) ... ok
test_triple_quotes_wrappting (text_extraction_unit_tests.PrefixStrippingViewUnitTests) ... ok
test_triple_quotes_wrappting_without_leading_whitespace (text_extraction_unit_tests.PrefixStrippingViewUnitTests) ... ok
======================================================================
ERROR: semantic_linefeed_unit_tests (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./python3.3/unittest/case.py", line 384, in _executeTestPart
File "./python3.3/unittest/loader.py", line 32, in testFailure
ImportError: Failed to import test module: semantic_linefeed_unit_tests
Traceback (most recent call last):
File "./python3.3/unittest/loader.py", line 261, in _find_tests
File "./python3.3/unittest/loader.py", line 239, in _get_module_from_name
File "D:\SublimeText\Data\Packages\Wrap Plus\tests\semantic_linefeed_unit_tests.py", line 11, in <module>
from .text_extraction_unit_tests import PrefixStrippingViewUnitTests
SystemError: Parent module '' not loaded, cannot perform relative import
----------------------------------------------------------------------
Ran 6 tests in 0.544s
FAILED (errors=1)
UnitTesting: Done.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels
Activity
evandrocoan commentedon Dec 4, 2017
Changing the initial import structure from:
to:
Seems to solved the problem. Now all the Unit Tests ran with success:
Fixed the UnitTesting package not running the Unit Tests, issue:
Fixed KeyError while importing by UnitTesting packages,
evandrocoan commentedon Dec 6, 2017
I am not sure why, but I tried this fix on another package, and it did not worked. Then I searched and found this other solution by changing this:
To this:
randy3k commentedon Dec 6, 2017
I am not sure what you want to achieve. You need to make sure that the tests are organized such as they could be discovered by
discover.evandrocoan commentedon Dec 6, 2017
They are being discovered, the error was the importing of helper functions/classes from helper files.
I had created an
utilities.pyto put common functions/classes through all my tests files on my package, but when was calling theUnitTestingpackage to run the tests, it could not import the functions from the utilities files. For example, given the following file structure:On the file
utitiles.py, I had the following classBasicSublimeTextViewTestCaseextendingunittest.TestCase:Details
Then on my test files
clear_cursors_carets_last_selection_unit_tests.pyandclear_cursors_carets_first_selection_unit_tests.py, I would import theutilitiesmodule, so I can use it:Details
This was how I made it work. On the my first attempt, I was just trying to import
utilities.pyfile on my test filesclear_cursors_carets_first_selection_unit_tests.pyandclear_cursors_carets_last_selection_unit_tests.pywith:But this was failing with:
When I called the
UnitTestingcommandUnitTesting: Test Current Packageon a project file likeclear_cursors_carets_last_selection_unit_tests.py.But it was not falling when I used my own runner I already have setup. In addition to the
UnitTestingpackage to run tests, I also had make my own runner on the fileunit_tests_runner.py, so I can run individual Unit Tests and to be independent of theUnitTestingpackage to run tests.Details
Then I can call this runner from my main application using this:
On the beginning I was only using my runner to run Unit Tests, but @ehuss asked to use the UnitTesting package to run the tests on a pull request to his repository, then since then I started adding it as compatible with the runners I was already using.
randy3k commentedon Dec 7, 2017
Are you sure that the test cases are discoverable? AKAIK, unittest discover only search files named as
test*.py.EDIT: I saw that you have changed the pattern for discovery.
randy3k commentedon Dec 7, 2017
I checked out your master branch: https://github.com/evandrocoan/Sublime-Wrap-Plus/tree/master and UnitTesting was working properly.
Details
EDIT: I just realized that you were talking about a different package.
randy3k commentedon Dec 7, 2017
I checked out https://github.com/evandrocoan/ClearCursorsCarets
and UnitTesting was also working.
Details
randy3k commentedon Dec 7, 2017
I see what's going on now. You were trying to use relative import
from .utilities import BasicSublimeTextViewTestCase. However, the tests was not imported as module so relative import is not possible. (You gave too much information so I missed it).You could move the files into a folder with
__init__.py. In this way, the tests will be imported as a module. Check https://github.com/divmain/GitSavvy/tree/master/tests/test_git as an example.evandrocoan commentedon Dec 7, 2017
But I am doing this already have then in a folder with
__init__.pyand if I usefrom . import utilitiesI got this error:However, If I do:
It does work:
This is my
unittesting.jsonfile:The differences I see from that example is the
unittesting.jsonwhich is almost empty:And that the tests which does relative import are inside a folder called
tests_gitwith a__init__.pyand everything starts with the nametest_. On my project I set the"pattern" : "*unit_tests.py",so I expect the test files to end withunit_tests.py.Am I required to move everything to another folder inside the tests folder with a
__init__.py, then the relative import will start working? But I wonder why I need to create another folder inside the tests folder for thefrom . import BasicSublimeTextViewTestCaseto work.randy3k commentedon Dec 7, 2017
Unittesting only imports directories under tests as modules, so you have to put it under
/tests/testsomrthingelse/. In fact, the top level__init__.pyis never used.randy3k commentedon Dec 7, 2017
I may look into the possibility to import
testsas a module.Edit: it seems that it requires quite some work based on the
unittest’sdiscoverfunction. I don’t expect to see it soon.Fixed KeyError while importing by UnitTesting packages,
Fixed KeyError while importing by UnitTesting packages,
Moved manual_tests.py to tests/testing/ due SystemError
Moved manual_tests.py to tests/testing/ due SystemError
Thom1729 commentedon Jan 16, 2019
Hopefully this can be fixed as part of #155.
randy3k commentedon Jan 16, 2019
I am not sure how easy or how hard it would be done. It seems that
unittest.discoverdoesn't try to import the starting directory as a module.Thom1729 commentedon Jan 16, 2019
Yeah, the default implementation of
discoveris a bit screwy. It patchessys.pathand does other weird stuff. For UnitTesting, we can guarantee that tests will always be inside a package that is already loaded or loadable (with some caveats around dependencies). This should let us use a simpler approach that behaves more predictably.randy3k commentedon Jan 16, 2019
If we specify
start_dir = 'PATH TO PACKAGE'rather thanstart_dir = 'PATH TO PACKAGE/tests', it should theoretically importtestsmodule as a package if a__init__.pyis found. But then it will run into a danger that for example a filetestsomething.pyunderPACKAGE/src/may be wrongly classified as a test file.Thom1729 commentedon Jan 16, 2019
Could we just pass
start_dir='PATH TO PACKAGE/tests', top_level_dir='PATH TO PACKAGE'? I haven't tried it out, and my understanding of the overcomplicated default loader logic is incomplete, but it seems like this may be what it's for.randy3k commentedon Jan 16, 2019
It would work only if there is a
__init__.pyundertestsso it will break a lot of current users of UnitTesting.randy3k commentedon Dec 5, 2019
Hopefully the next update will handle it.
deathaxe commentedon Nov 10, 2025
Fixed by PR #277.