How to use the setUp() method in Python's unittest - python

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.

Related

How can I run a script after importing it?

Problem
I would like to import a script containing many functions and then run them, so that I can use the function. I may have misunderstood the purpose of import. I am working in Jupyter.
Reprex
#Create the script in a local folder
%%writefile test.py
c = 500
def addup(a,b,c):
return a*b + (c)
#import the file and use it
import test
addup(1,5,c)
#Error message
---------------------------------------------------------------------------
# NameError Traceback (most recent call last)
# <ipython-input-1-71cb0c70c39d> in <module>
# 1 import test
# ----> 2 addup(1,5,c)
# NameError: name 'addup' is not defined
Any help appreciated.
You have not called the function! You need a dot . to call a function from a module.
This is the correct syntax:
import test
result = test.addup(1,5,c)
Import a specific function:
from test import addup
addup(1,5,c)
Importing all of the module's functions:
from test import *
addup(1,5,c) # this way you can use any function from test.py without the need to put a dot

How can I write the python import statements, such that the file works from both inside and outside its package? [duplicate]

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

Test not being executed from command line

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.

Python nosetest doesn't work, but directly running it does using matplotlib's #image_comparison

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.

Getting TypeError(): test_if_module_exists() when running nosetests

UPDATE: If i change
from scitools.std import *
to e.g.
from scitools.std import sqrt, zeros
everything works fine..
I'm trying to run nosestests -s myfile.py, but I'm getting this error all the time:
======================================================================
ERROR: Test if modulename can be imported, and if not, write
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/usr/local/lib/python2.7/dist-packages/nose/util.py", line 613, in newfunc
return func(*arg, **kw)
TypeError: test_if_module_exists() takes at least 1 argument (0 given)
PROGRAM:
from scitools.std import *
import nose.tools as nt
def test_test():
diff = 1E-6
nt.assert_almost_equal(diff, 0, delta=1E-5)
def main():
print __name__
if __name__ == "__main__":
main()
I'm running Nose 1.3.0. Have searched all over the internet for solutions, can't find a thing!
Thanks guys!
Because you're using a wildcard import... Dont use wildcards!
Basically when you say
from scitools.stf import *
You are also importing everything from:
scitools.easyviz
scitools.basics
The way that nose works is that it looks for all the functions named test_ in your module. That includes every function you wrote and every function that you imported. This is called Duck typing. So if there is a function you do not want nose to try to run, Dont import it. When you were using a a wildcard import, you are importing everything, which is most of why wildcards are not a good idea to use. Just import the functions you need, eg
from scitools.std import sqrt, zeros

Categories

Resources