Relative import error using python unittest - python

I'm using the built-in python unittest module. My directory structure is as follows:
game.py
test/test_game.py
The content of test_game.py:
import unittest
from ..game import *
class TestGame(unittest.TestCase):
def test_pawn(self):
game = Game()
game.make_move("e2e3")
self.assertEqual(game.board[6][5].piece_type, "P")
if __name__ == '__main__':
unittest.main()
Here's the problem. When I run python -m unittest test/test_game.py I get the error:
ImportError: Failed to import test module: test_game
Traceback (most recent call last):
File "/usr/local/Cellar/python#3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
ModuleNotFoundError: No module named 'test.test_game'

I was missing the test/__init__.py file. With this change, I didn't even need the relative ..game import.. But I'm wondering why python requires this just to import

Related

Importing modules in embedded python

I'm trying to get module imports to work in embeddable python, but it doesn't want to work
C:\Users\test\Desktop\winpy\python-3.10.10-embed-win32>type run_scripts\script.py
from module_test import test
print("Hello world!")
print(test())
C:\Users\test\Desktop\winpy\python-3.10.10-embed-win32>type run_scripts\module_test.py
def test():
return "Test!"
C:\Users\test\Desktop\winpy\python-3.10.10-embed-win32>#python.exe run_scripts\script.py
Traceback (most recent call last):
File "C:\Users\test\Desktop\winpy\python-3.10.10-embed-win32\run_scripts\script.py", line 1, in <module>
from module_test import test
ModuleNotFoundError: No module named 'module_test'
Why is the module not being imported? I tried changing PYTHONPATH but it didn't help

Unittest library keeps having problems importing module upon running tests

I have the following folder structure:
The content of my files are as follows:
library.py:
def hello():
return "Hello World"
main.py:
from library import hello
def main_func():
return hello()
test_main.py:
import unittest
from src.main import main_func
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual(main_func(), "Hello World!")
if __name__ == "__main__":
unittest.main()
Now, when I run my unittests using the following command:
python3 -m unittest discover test
I get the following error:
ImportError: Failed to import test module: test_main
Traceback (most recent call last):
File "/Users/user/.pyenv/versions/3.8.11/lib/python3.8/unittest/loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "/Users/user/.pyenv/versions/3.8.11/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name
__import__(name)
File "/Users/user/Desktop/example/test/test_main.py", line 3, in <module>
from src.main import main_func
File "/Users/user/Desktop/example/src/main.py", line 1, in <module>
from library import hello
ModuleNotFoundError: No module named 'library'
Can someone please explain how I can get this to work? I am deploying functions to AWS lambda so need the import structure as it is otherwise it won't work. Is there a way to configure unittests to work with this import structure?

coverage cannot find modules in my project

I am trying to use coverage from the terminal (as I am using the community version of pycharm, which doesn't have support for coverage). However, I always get the same error:
ModuleNotFoundError: No module named 'src' The package structure of my project is very simple: it has 2 packages, src and test, and inside the test package is another package called unit, wherer I keep my unit tests.
This is the code that I have trying to run with coverage.
import unittest
from src.interpolacion import interpolacion
class DummyTest(unittest.TestCase):
def test_nothing(self):
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
Please notice how src.interpolacion.interpolacion is not even used and, regardless, it fails with this error:
======================================================================
ERROR: DummyTest (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: DummyTest
Traceback (most recent call last):
File "C:\Users\jose.m.ramirez.leon\AppData\Local\Programs\Python\Python38\lib\unittest\loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "C:\Users\jose.m.ramirez.leon\PycharmProjects\dummyPythonProject\test\unit\DummyTest.py", line 2, in <module>
from src.interpolacion import interpolacion
ModuleNotFoundError: No module named 'src'
I am going mad with this. Could anyone please help me regain my sanity?

no module named "3rd party library" in subfolder

My folder structure is as follows.
main
main.py
library
utils.py
utils.py has the following code
from aws_requests_auth.aws_auth import AWSRequestsAuth
def testAuth():
print('some code code')
main.py has the following code
from library.utils import testAuth
def start():
print ('some code')
I have run pip install aws_requests_auth in both my main and library folder.
When i tried to run python3 main.py I got this error
Traceback (most recent call last):
File "main.py", line 1, in <module>
from library.utils import testAuth
File "/Users/Docs/library/utils.py", line 1, in <module>
from aws_requests_auth.aws_auth import AWSRequestsAuth
ModuleNotFoundError: No module named 'aws_requests_auth'
How do i ensure 3rd party libraries are installed properly for sub folders? Thanks!

ImportError: No module named util.dtree_util

I get this error when loading a file using cPickle.
Directory tree:
/qanta/preprocess/dparse_to_dtree.py
/qanta/qanta.py
/qanta/util/dtree_util.py
main.py
extract_data.py
main.py imports extract_data.py
extract_data.py imports dparse_to_dtree.py
A function in dparse_to_dtree.py cPickle dumps a dtree object which is defined in dtree_util.py
then from Main.py a subprocess calls qanta.py to execute but there I get the error:
Traceback (most recent call last):
File "qanta/qanta.py", line 142, in <module>
cPickle.load(open(args['data'], 'rb'))
ImportError: No module named util.dtree_util
What is going wrong here?
You also need to add a __init__.py file. See this question.
Not very nice but adding
import sys
sys.path.append('./qanta/util')
and importing with from ... import * solved the problem

Categories