I have a test automation project where so far everything was working great.
I was able to run all the test by setting the Python path by typing the below command:
set PYTHONPATH="projectpath"
then
python .\"testscriptpath"
Now this week I started seeing this error:
ModuleNotFoundError : No Module named 'tests'
I tried the solution of adding a blank __init__.py file, but it didn't help.
I am looking for a solution to generate XML report files.
Below is the code:
import unittest
import allure
import xmlrunner
from selenium.webdriver.common.by import By
from tests.common import WICSUtils
from tests.common.GenericUtils import wics_select_by_visible_text, wics_utils_click, wics_select_by_index, \
wics_utils_get_text
from tests.icc.ICC_Common_Methods import search_by_offender_id_icc, make_initial_decision, \
go_to_inmate_classification_report, go_to_job_submitter_screen_and_submit_report, \
refresh_job_queue_until_job_finished
class ICCInmateInitialClassification(unittest.TestCase):
#classmethod
def setUpClass(cls):
# Get new driver instance
global myDriver
global emailAddress
global userFolder
myDriver = GenericUtils.get_new_driver_instance()
#allure.step("Logging into WICS")
def test_01_logging_into_WICS(self):
global emailfolderforreports
emailfolderforreports = "Reports"
WICSUtils.loginToWICS(myDriver, WICSUtils.Environment.UAT1, test)
expectedTitle = "ODSP590 - My Landing Page"
actualTitle = WICSUtils.get_page_main_title(myDriver)
GenericUtils.wics_assertion_is_substring(expectedTitle, actualTitle, myDriver)
#classmethod
def tearDownClass(cls):
WICSUtils.logOutWICS(myDriver)
myDriver.quit()
if __name__ == '__main__':
# main method to run xmlrunner to produce xml report in test-reports folder
with open('../../../test-results/ICC_R001_Inmate_Initial_Classification.xml', 'wb') as output:
unittest.main(
testRunner=xmlrunner.XMLTestRunner(output=output),
failfast=False, buffer=False, catchbreak=False)
Below is the error stack trace:
PS C:\Users\VellaSR\PycharmProjects\wics-selenium-scripts> python .\tests\icc\High\ICC_R001_Inmate_Initial_Classification.py
Traceback (most recent call last):
File ".\tests\icc\High\ICC_R001_Inmate_Initial_Classification.py", line 8, in <module>
from tests.common import WICSUtils
ModuleNotFoundError: No module named 'tests'
In order to make Python resolves all your relative imports, you must execute your script from the root working directory.
In your case, for example, the root is wics-selenium-scripts. You need to go there with your terminal, and then execute python path/to/your/script.py, e.g. python tests\icc\High\scriptName.py
Related
I have a Python project in which I have the following folder structure:
> root
> download_module
> __init__.py
> downloadProcess.py
> sharedFunctions.py
> someHelper.py
> useSharedFunction.py
The download_module/__init__.py has the following code:
from .sharedFunctions import stringArgumentToDate
from .downloadProcess import downloadProcessMethod
The sharedFunctions.py file contains the following function:
def stringArgumentToDate(arg):
dateformat = "%m/%d/%Y"
date = None
if arg.isnumeric():
date = datetime.fromtimestamp(int(arg))
if date == None:
date = datetime.strptime(arg, dateformat)
return date
Then on the useSharedFunction.py I try to import the shared function and use it like this.
from download_module import stringArgumentToDate
from download_module import downloadProcessMethod
def main():
arg = '03/14/2022'
dateArg = stringArgumentToDate(arg)
if __name__ == '__main__':
main()
When I try to run this by using python3 useSharedFunction.py I got the following error:
Traceback (most recent call last):
File "useSharedFunction.py", line 4, in <module>
from download_module import stringArgumentToDate
File "/Users/jacobo/Documents/project/download_module/__init__.py", line 2, in <module>
from .download_module import downloadAndProcessMethod
File "/Users/jacobo/Documents/project/download_module/downloadProcess.py", line 10, in <module>
from sharedFunctions import stringArgumentToDate, otherFunction
ModuleNotFoundError: No module named 'sharedFunctions'
I do believe the error is in downloadProcess since at the beggining of the file we got this import:
from sharedFunctions import stringArgumentToDate, otherFunction
from someHelper import Helper
Which refers to sibling files.
However I'm unsure what will be a proper fix to allow to run the downloadProcess.py main independently but also, being able to call it one of its method from a root or any other file out of the module.
Consider this structure:
┬ module
| ├ __init__.py
| ├ importing_submodule.py
| └ some_submodule.py
├ __main__.py
├ some_submodule.py
└ module_in_parent_dir.py
with content:
__main__.py
import module
/module/__init__.py
from . import importing_submodule
/module/importing_submodule.py
from some_submodule import SomeClass
/module/some_submodule.py
print("you imported from module")
class SomeClass:
pass
/some_submodule.py
print("you imported from root")
class SomeClass:
pass
/module_in_parent_dir.py
class SomeOtherClass:
pass
How sibling import works
(skip this section if you know already)
Now lets run __main__.py and it will say "you imported from root".
But if we change code a bit..
/module/importing_submodule.py
from module.some_submodule import SomeClass
It now says "You imported from module" as we wanted, probably with scary red line in IDE saying "Unresolved reference" if you didn't config working directory in IDE.
How this happen is simple: script root(Current working directory) is decided by main script(first script that's running), and python uses namespaces.
Python's import system uses 2 import method, and for convenience let's call it absolute import and relative import.
Absolute import: Import from dir listed in sys.path and current working directory
Relative import: Import relative to the very script that called import
And what decide the behavior is whether we use . at start of module name or not.
Since we imported by from some_submodule without preceeding dot, python take it as 'Absolute import'(the term we decided earlier).
And then when we also specified module name like from module.some_submodule python looks for module in path list or in current working directory.
Of course, this is never a good idea; script root can change via calls like os.chdir() then submodules inside module folder may get lost.
Therefore, the best practices for sibling import is using relative import inside module folder.
/module/importing_submodule.py
from .some_submodule import SomeClass
Making script that work in both way
To make submodule import it's siblings when running as main script, yet still work as submodule when imported by other script, then use try - except and look for ImportError.
For importing_submodule.py as an example:
/module/importing_submodule.py
try:
from .some_submodule import SomeClass
except ImportError:
# attempted relative import with no known parent package
# because this is running as main script, there's no parent package.
from some_submodule import SomeClass
Importing modules from parent directory is a bit more tricky.
Since submodule is now main script, relative import to parent level directory doesn't work.
So we need to add the parent directory to sys.path, when the script is running as main script.
/module/importing_submodule.py
try:
from .some_submodule import SomeClass
except ImportError:
# attempted relative import with no known parent package
# because this is running as main script, there's no parent package.
from some_submodule import SomeClass
# now since we don't have parent package, we just append the path.
from sys import path
import pathlib
path.append(pathlib.Path(__file__).parent.parent.as_posix())
print("Importing module_in_parent_dir from sys.path")
else:
print("Importing module_in_parent_dir from working directory")
# Now either case we have parent directory of `module_in_parent_dir`
# in working dir or path, we can import it
# might need to suppress false IDE warning this case.
# noinspection PyUnresolvedReferences
from module_in_parent_dir import SomeOtherClass
Output:
"C:\Program Files\Python310\python.exe" .../module/importing_module.py
you imported from module
Importing module_in_parent_dir from sys.path
Process finished with exit code 0
"C:\Program Files\Python310\python.exe" .../__main__.py
you imported from module
Importing module_in_parent_dir from working directory
Process finished with exit code 0
I'm trying to create a project with the following structure:
my_file.ipynb
my_package_directory > __init__.py test.py
Within test.py lets say I have a very simple class:
class Test:
def __init__(self, name):
self.name = name
from with in a code cell I try to insatiate the class and print out the defined variable:
from my_package_directory.test import Test
test = Test('bob')
print(test.name)
If I try to run the cell I get an error:
ImportError: cannot import name 'Test' from 'my_package_directory.test'
Is there a certain way to do this in a Jupyter notebook?
Thank you.
Probably the root of your files is not in the python module search path.
You can check your module search path with:
import sys
print(sys.path)
If you append the location of your notebook and your package to that path, it should be importable:
sys.path.append('/path/to/where/jupyter/notebook/resides')
from my_package_directory.test import Test # should work
Note that you have to restart the kernel whenever you change the implementation of your module - This can be circumvented with some jupyter notebook magic.
I am attempting to import a class named MainMenus from this file
B:\Programming\Python\RaceDash\src\UIModules\Menus.py
here is the code for the class
class MainMenus:
def StartUp():
#do stuff
def MainMenu():
#doing other stuff
I also have the _init_.py file in this path
B:\Programming\Python\RaceDash\src\UIModules\__init__.py
my main python file is here
B:\Programming\Python\RaceDash\src\Main.Py
and looks like this
from .UIModules.Menus import MainMenus
def Main():
MainMenus.StartUp()
while True:
MainMenus.MainMenu()
userSelect = input(": ")
Main()
pylance gives no errors when but when I attempt to run the program I get this error:
ile "b:\Programming\Python\RaceDash\src\Main.Py", line 1, in <module>
from .UIModules.Menus import MainMenus
ImportError: attempted relative import with no known parent package
When I remove the leading period pylance shows this error
Import "UIModules.Menus" could not be resolved
The application runs fine but I lose intellisense for any function from the other class.
What could be causing this issue?
You should move the package folder to a directory that is already in PATH
export PYTHONPATH="${PYTHONPATH}:B:\Programming\Python\RaceDash\src\
python3 Main.py
My issue is solved by going to the folder of my program and changing the extension. My file were not register as py file because I have created them in my VScode folder.
Below test works as expected when I execute from PyCharm but when I attempt to run python TestData.py from command line I receive :
Traceback (most recent call last):
File "TestData.py", line 3, in <module>
from service.DataAccessor import Data
ModuleNotFoundError: No module named 'service'
When I try python -m unittest
I receive:
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Both commands are run from project directory.
Project structure is:
project/service
- DataAccessor.py
project/test
- TestData.py
Code:
TestData.py :
import unittest
from service.DataAccessor import Data
class TestData(unittest.TestCase):
def test_get_data(self):
print(Data.getDf(self))
self.assertEqual(3, 3)
if __name__ == '__main__':
unittest.main()
DataAccessor.py:
import pandas as pd
class Data():
def getDf(self):
df = pd.read_csv("./data.csv")
return df
Coming from Java background I'm not 100% sure why this works but adding an empty __init__.py to the dirs: test & service and executed python -m unittest test.TestData executes the test.
My error is like
(base) C:\Users\lenovo\projects\gothonweb2>python bin/app.py
Traceback (most recent call last):
File "bin/app.py", line 2, in <module>
from gothonweb2 import map
ModuleNotFoundError: No module named 'gothonweb2'
The project directory is
C:\Users\lenovo\projects\gothonweb2
bin
__init__.py
app.py
gothonweb2
__init__.py
web.py
templates
layout.html
show_room.html
you_died.html
tests
__init__.py
app_tests.py
map_tests.py
tools.py
The code in bin/app.py is :
import web
from gothonweb2 import map
import urllib.request
urls=(
'/game','GameEngine',
'/','Index',
)
app=web.application(urls,globals())
#Title hack so that debug mode works with sessions
if web.config.get('_session') is None:
store=web.session.DiskStore('sessions')
session=web.session.Session(app,store,initializer={'room':None})
web.config._session=session
else:
session=web.config._session
render=web.template.render('templates/',base="layout")
class Index(object):
def GET(self):
#this is use to"setup"the session with starting values
session.room=map.START
web.seeother("/game")
class GameEngine(object):
def GET(self):
if session.room:
return render.show_room(room=session.room)
else:
return render.you_died()
def POST(self):
form=web.input(action=None)
#there is a bug here,can you fix it?
if session.room and form.action:
session.room=session.room.go(form.action)
web.seeother("/game")
if __name__=="__main__":
app.run()
I got the error just as above. Also the project's path and the import gothonweb2 part are also above. I don't know why it returns 'No module named 'gothonweb2''. Can someone help me?