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.
Related
This question has been asked before. Even though I couldn't get an answer that solves this issue.
I have the following directory and subdirectories:
I have a function hello() in test1.py that I want to import in test2.py.
test1.py:
def hello():
print("hello")
test2.py:
import demoA.test1 as test1
test1.hello()
Output:
Traceback (most recent call last):
File "c:/Users/hasli/Documents/Projects/test/demoB/test2.py", line 1, in <module>
import demoA.test1 as test1
ModuleNotFoundError: No module named 'demoA'
This is exactly as explained in https://www.freecodecamp.org/news/module-not-found-error-in-python-solved/ but I can't access hello()
I am using python 3: Python 3.8.9
You need to add demoA to the list of paths used for import.
import sys
sys.path.append('..')
import demoA.test1 as test1
test1.hello()
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
This question already has answers here:
Relative imports for the billionth time
(12 answers)
Closed 1 year ago.
Here's a file structure I'm working with:
package_example/
main.py
the_package/
__init__.py
pkg_file_1.py
pkg_file_2.py
Here are the files:
# main.py
from the_package.pkg_file_1 import foo_1
def main():
foo_1()
if __name__ == "__main__":
main()
# pkg_file_1.py
from the_package import pkg_file_2
def foo_1():
print("this is the second version, foo_1")
pkg_file_2.foo_2()
if __name__ == "__main__":
foo_1()
# pkg_file_2.py
def foo_2():
print("this is foo_2")
If I run main.py, everything works fine.
But if I run pkg_file_1.py, I get:
Traceback (most recent call last):
File "the_package/pkg_file_1.py", line 1, in <module>
from the_package import pkg_file_2
ModuleNotFoundError: No module named 'the_package'
Obviously in this simplified example, it doesn't matter, since main.py and pkg_file_1.py run the same code.
But practically, I have test scripts baked into my package structure, so I can test the code in my new environment and data. But I'm scratching my head on how I'm supposed write import statements such that I don't get a ModuleNotFoundError from both inside or outside the package.
Edit: From pavel's suggest I tried changing pkg_file_1.py to:
from ..the_package import pkg_file_2
def foo_1():
print("this is the second version, foo_1")
pkg_file_2.foo_2()
if __name__ == "__main__":
foo_1()
But running that same file gives:
Traceback (most recent call last):
File "the_package/pkg_file_1.py", line 1, in <module>
from ..the_package import pkg_file_2
ImportError: attempted relative import with no known parent package
This is why we need relative import.
# pkg_file_1.py
from . import pkg_file_2
...
How to run main.py and pkg_file1.py from package_example dir:
python3 main.py
python3 -m the_package.pkg_file1
I'm trying to run the following script:
import unittest
class RandomDataGeneratorTest(unittest.TestCase):
def setUp(self):
import numpy
def test_numpy_is_imported(self):
pi = numpy.pi
if __name__ == '__main__':
unittest.main()
However, I'm getting the following error/failure:
E
======================================================================
ERROR: test_numpy_is_imported (__main__.RandomDataGeneratorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/kurt/dev/clones/ipercron-compose/controller/random_data_tester.py", line 9, in test_numpy_is_imported
pi = numpy.pi
NameError: global name 'numpy' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.100s
FAILED (errors=1)
As I understand from https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUp, the setUp() function sould be run before any test function, so I don't see why this error arises?
You are importing within a function, so the imported name only exists there.
Try with setting something, e.g. self.test = "somestring", and assert that it is set in the test method.
I have this testing script, called test_boxplot.py:
__author__ = 'olga'
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import numpy as np
import prettyplotlib as ppl
import os
#image_comparison(baseline_images=['boxplot'], extensions=['png'])
def test_boxplot():
# Set the random seed for consistency
np.random.seed(10)
data = np.random.randn(8, 4)
labels = ['A', 'B', 'C', 'D']
fig, ax = plt.subplots()
ppl.boxplot(ax, data, xticklabels=labels)
# fig.savefig('%s/baseline_images/test_boxplot/boxplot.png' %
# os.path.dirname(__file__))
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'])
and if I run it directly, the tests all pass:
$ python test_boxplot.py
/Users/olga/workspace-git/matplotlib/lib/matplotlib/testing/decorators.py:288: UserWarning: test module run as script. guessing baseline image locations
warnings.warn('test module run as script. guessing baseline image locations')
.
----------------------------------------------------------------------
Ran 1 test in 0.224s
OK
but if I run it with nosetests it fails with this weird IndexError that centers around matplotlib's #image_comparison decorator's code:
$ nosetests test_boxplot.py
E
======================================================================
ERROR: Failure: IndexError (pop from empty list)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/loader.py", line 286, in generate
for test in g():
File "/Users/olga/workspace-git/matplotlib/lib/matplotlib/testing/decorators.py", line 145, in test
baseline_dir, result_dir = _image_directories(self._func)
File "/Users/olga/workspace-git/matplotlib/lib/matplotlib/testing/decorators.py", line 296, in _image_directories
assert mods.pop(0) == 'tests'
IndexError: pop from empty list
----------------------------------------------------------------------
Ran 1 test in 0.092s
FAILED (errors=1)
Any ideas what may be going on?
I think the problem is that the decorator expects to be used in a subdirectory names "tests" of the main project dir (usually project/tests or more correctly: the module of the test must start with something.tests.). This is the code in _image_directories():
mods = module_name.split('.')
mods.pop(0) # <- will be the name of the package being tested (in
# most cases "matplotlib")
assert mods.pop(0) == 'tests'
subdir = os.path.join(*mods)
_image_directories() has some special code in case of func.__module__ == '__main__' so you don't see the error in the first case.