When I run my selenium python tests via right click run in PyCharm, all is good. However, when I try to run with command line (pytest), I get error. Here is my folder structure:
[projectname]/
├── Driver
├── Driver.py
├── Tests
├── TestFolder
├── TestName.py
Driver.py file looks like this:
from selenium import webdriver
Instance = None
def Initialize():
global Instance
Instance = webdriver.Chrome()
Instance.implicitly_wait(2)
return Instance
def QuitDriver():
global Instance
Instance.quit()
TestName.py looks like this:
import unittest
from Driver import Driver
from Tests.Transactions.HelperFunctions import *
class StreamsTest(unittest.TestCase):
#classmethod
def setUp(cls):
Driver.Initialize()
def testSameDayEverySecond(self):
ConnectSenderWallet()
AppPage.HandleDevAmountsTitleAndAddress()
HandleCreateAndAssert()
#classmethod
def tearDown(cls):
Driver.QuitDriver()
And when I run pytest -v -s Tests/TestFolder/TestName.py, I get following errors in my console:
ImportError while importing test module '/Users/dusandev/Desktop/w-test/Tests/TestFolder/TestName.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../../miniconda3/lib/python3.9/importlib/__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
Tests/TestFolder/TestName.py:2: in <module>
from Driver import Driver
E ModuleNotFoundError: No module named 'Driver'
Thank you for your help!
Python is trying to load the Driver class from Driver.py, however, you don't have one. You may want to do one of the following:
Create a Driver class in Driver.py
Replace from Driver import Driver with from Driver import *
Replace from Driver import Driver with import Driver
Related
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
I have a simple directory structure:
proj/
src/
__init__.py
foo.py
bar.py
test/
__init__.py
test_foo.py
test_foo.py
import unittest
import sys
sys.path.append('../src')
from src import foo
class TestFoo(unittest.TestCase):
def test_foo(self):
foo.start()
if __name__ == '__main__':
unittest.main()
foo.py
import bar
def start():
bar.do_stuff()
When running my test (I'm using vscode), I get the following error:
Failed to import test module: test_foo
Traceback (most recent call last):
File "~/.pyenv/versions/3.8.6/lib/python3.8/unittest/loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "~/.pyenv/versions/3.8.6/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name
__import__(name)
File "~/proj/test/test_foo.py", line 6, in <module>
from src import foo
File "~/proj/src/foo.py", line 1, in <module>
import bar
ModuleNotFoundError: No module named 'bar'
I'm not sure why the test can't discover the src/bar when importing src/foo
Instead of import bar try from src import bar.
from src import bar
def start():
bar.do_stuff()
Notice
Keep in mind, that you only adjusted the path in the test. You do not want the tests to work, but the application to fail because you forgot to adjust the path in the application at some point.
What is in your bar.py file? Just the do_stuff() function? Or is the do_stuff() function a method of object bar?
Depending on the answer to the question above, try doing something like this in your foo.py file:
from proj.src.bar import [name of function you're testing here]
In your specific case, it would be like this if do_stuff() is a standalone function:
from proj.src.bar import do_stuff
and then your foo.py file would be:
from proj.src.bar import do_stuff
def stuff():
do_stuff()
However, if do_stuff() is a method of the bar object, it would probably be something like this, although it's hard to tell without knowing the contents of the bar.py file:
from proj.src.bar import bar
and then your foo.py file would be similar to the way you have it now:
from proj.src.bar import bar
def stuff():
bar.do_stuff()
I recently ran into a similar problem when trying to import one neighboring file into another. This link helped me out, too.
Two changes:
from src import bar in foo.py,
before import modules in test_foo.py, add
import sys
sys.path.append("./")
Then you should be able to run code successfully.
In my case, I had imports of modules which are not actually installed, in my bar.py file, such as:
import requests
After installing those modules, VSCode showed tests properly.
Simply speaking, I have this directory structure:
src/
my_file1.py
tests/
__init__.py
my_file1_test.py
In my_file1.py:
def my_func1(a):
return a + 99
How do I then access my_func1 from the tests? In my_file1_test.py I can't access the method:
# from ??? import ?? # is this needed at all?
def my_test1():
res = my_func1(123) # unaccessible
assert res = 222
Will I have to create __init__.py in scr directory first?
update1
from src.myfile import my_func1
===>
ModuleNotFoundError: No module named 'scr'
And if I add __init__.py then it'll become:
ImportError: cannot import name 'my_func1' from 'src'
If you run pytest from your project root with
python -m pytest
you then have to import the function, as you guessed, with:
from src.myfile import my_func1
I have my .py module which is in C:\Python_Projects\MyModules\ with the name button_generator.py.
My code goes something like this:
module_path='C:\\Python_Projects\\MyModules'
module_name='button_generator.py'
sys.path.append(module_path)
try:
limp=importlib.import_module(module_name.split('.')[0])
except:
print 'module import error'
I have tried other versions aswell:
importlib.import_module(module_name) without the split
importlib.import_module('C:\Python_Projects\MyModules\button_generator.py')
importlib.import_module('C:\Python_Projects\MyModules\button_generator')
The folder C:\Python_Projects\MyModules is in my sys.path as I checked during debug.
Why wouldn't the module import?
I suggest you to reorder your project directories and avoid calling other modules which are not in your current directory project. You'll avoid those kind of errors.
For example, let's organize our project directories and folders to look something like this:
MyProjectFolder/
├── main.py
└── modules
├── __init__.py
└── MyLib.py
NB: Don't forget to add an empty file called __init__.py
MyLib.py :
#!/usr/bin/python3
class MyLib:
def __init__(self):
self.say_hello = "Hello i'm in modules/MyLib"
def print_say_hello(self):
print(self.say_hello)
main.py:
#!/usr/bin/python3
# from folder.file import class
from modules.MyLib import MyLib
class MainClass:
def __init__(self):
my_lib = MyLib() # load MyLib class
my_lib.print_say_hello() # access to MyLib methods
### Test
if __name__ == '__main__':
app = MainClass()
In terminal when i run:
$ python3 main.py
output:
Hello i'm in modules/MyLib
So here we have successfully imported the class in modules/MyLib.py into our main.py file.
I found the error:
After treating the ImportError exception by printing it's args, I noticed that button_generator.py had an Import that was not resolving. Basically, button_generator.py could not be imported because it had a wrong import.
I'm running the following command from the console
$ py.test -m selenium
But then I keep getting this error:
___________________________________________________ ERROR collecting setup_distribution/verify_distribution_list.py ____________________________________________________
setup_distribution/verify_distribution_list.py:1: in <module>
> from foodnet.tests.selenium.base import SeleniumFoodnetTestCase
/home/frank/.virtualenvs/foodnet27/local/lib/python2.7/site-packages/_pytest/assertion/rewrite.py:159: in load_module
> py.builtin.exec_(co, mod.__dict__)
base.py:8: in <module>
> class SeleniumFoodnetTestCase(TestCase):
E TypeError: 'module' object is not callable
Below is the code I'm using:
base.py
from unittest import TestCase
from foodnet.tests import selenium
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException
#selenium
class SeleniumFoodnetTestCase(TestCase):
superuser_username = 'admin'
superuser_password = 'some_pwd'
server_base_url = "http://localhost:8000"
def setUp(self): # The rest of the code hidden
verify_distribution_list.py
from foodnet.tests.selenium.base import SeleniumFoodnetTestCase
class CreateDistributionList(SeleniumFoodnetTestCase):
def test_create_distribution_list(self):
driver = self.driver
# The rest of the code hidden for brevity
Any ideas why I'm getting the above error?
UPDATE: Below is my directory structure
foodnet
|
|- tests
|
|- selenium
|
|- base.py
|
|- setup_distribution
|
|- verify_distribution_list.py