Python Unit Tests - Am I using SetUp wrong? - python

What am I doing wrong here?
import unittest
class Test_1(unittest.TestCase):
def SetUp(self):
self.data = []
def test_data(self):
self.assertEqual(len(self.data),0)
if __name__=='__main__':
unittest.main()
When I run it, it says:
Traceback (most recent call last):
File "C:...\break_unit_test.py", line
9 , in test_data
self.assertEqual(len(self.data),0) AttributeError: 'Test_1' object has no
attribute 'data'
I'm trying to follow this example.

It must be named setUp, starting with a lowercase s.

Related

AttributeError: 'module' object has no attribute 'add'

I am learning how to write unit-test.
app.py:
class MyClass:
def add(self):
return 2+2
app_test.py:
import app
import unittest
class TestMyClass(unittest.TestCase):
def test_add(self):
self.assertEqual(app.add(), 4)
if __name__ == '__main__':
unittest.main()
Command for run: python -m unittest app_test.TestMyClass.
Error:
Traceback (most recent call last):
File "app_test.py", line 6, in test_add
self.assertEqual(app.add(), 4)
AttributeError: 'module' object has no attribute 'add'
Your test is calling add() directly, when it's an object method. Create an object first. This should work.
from app import MyClass
import unittest
class TestMyClass(unittest.TestCase):
def test_add(self):
o = MyClass()
self.assertEqual(o.add(), 4)

AttributeError: None does not have the attribute 'print'

So I am practicing some unit test and I am trying to check for an output that is within a For Loop. Here is my run code
def main():
for i in range(100):
print("Argh!")
Pretty basic, now here is my test code.
import unittest
from unittest import mock # possibly "from unittest import mock" depending on version.
from RunFile import main
class TestMain(unittest.TestCase):
def test_main(self):
with mock.patch.object(main(), 'print') as mock_print:
main()
expected_calls = [mock.call('Argh!') for _ in range(100)]
mock_print.assert_has_calls(expected_calls)
if __name__ == '__main__':
unittest.main()
Here is the error message I get back. I'm not to sure how to resolve this.
UPDATED: Here is the full trace back
======================================================================
ERROR: test_main (__main__.TestMain)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:/Users/jsalce/Documents/Testsuites/IfStatements/Testsuite.py", line 9, in test_main
with mock.patch.object(RunFile, 'print') as mock_print:
File "C:\Python33\lib\unittest\mock.py", line 1148, in __enter__
original, local = self.get_original()
File "C:\Python33\lib\unittest\mock.py", line 1122, in get_original
"%s does not have the attribute %r" % (target, name)
AttributeError: <module 'RunFile' from 'C:\\Users\\jsalce\\Documents\\Testsuites\\IfStatements\\RunFile.py'> does not have the attribute 'print'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Thank you all in advance!
Generally speaking, for mock.patch.object, you want to patch something that you have an easy handle on -- e.g. a module or a class. Usually, you need to patch something that is one level above what you want to replace. For example if you want to patch the foo function in module bar, then you need mock.patch.object(bar, 'foo').
In your case, technically, print is a builtin, but you can patch it on the module where you're using it. This will add a RunFile.print "method" (which is actually a mock) that you can test assertions against. Apparently, since print doesn't actually exist on the module, we need to add create=True to tell mock to create RunFile.print since it doesn't already exist. With that in mind, I'd re-write the unittest as:
import RunFile
class TestMain(unittest.TestCase):
def test_main(self):
with mock.patch.object(RunFile, 'print', create=True) as mock_print:
RunFile.main()
expected_calls = [mock.call('Argh!') for _ in range(100)]
mock_print.assert_has_calls(expected_calls)
if __name__ == '__main__':
unittest.main()

NameError: global name 'client' is not defined

Here i did the python class for connecting mongo and get the data from mongo database and process it i did the unit test cases for this i got following error
NameError: global name 'client' is not defined
python class :
from pymongo.errors import ConnectionFailure, AutoReconnect
import pymongo
from pymongo import MongoClient
class ConnectionError(Exception):
pass
class ChkMongo:
item_list=[]
dict1={}
def makeMongocon(self):
global client
try :
client = MongoClient("localhost", 27017)
except AutoReconnect, e:
raise ConnectionFailure(str(e))
def findRecords(self):
self.db = client.serv
for item in self.db.serv.find():
self.item_list.insert(0,item)
return self.item_list
if __name__ == '__main__':
c=ChkMongo()
c.makeMongocon()
print(c.findRecords())
my unit test case
from pymongo.errors import ConnectionFailure
import unittest;
from app.ChkMongo import *
class TestChkMongo(unittest.TestCase):
def setUp(self):
self.c=ChkMongo()
def test_makeMongocon(self):
self.assertRaises(ConnectionFailure,self.c.makeMongocon)
def test_findRecords(self):
print(self.c.findRecords())
self.assertDictContainsSubset({'name':'matthew'},self.c.findRecords())
def test_calculate_charge_with_tax(self):
self.assertAlmostEqual(290,self.c.calculate_charge_with_tax('matthew'))
if __name__ == '__main__':
unittest.main()
i got following error when run the test cases but run the python script that will work fine
Error:
Traceback (most recent call last):
File "/test/test_chkMongo.py", line 16, in test_findRecords
print(self.c.findRecords())
File "n/app/ChkMongo.py", line 29, in findRecords
self.db = client.serventer code here
NameError: global name 'client' is not defined
For me it happens when running my test with Python 3.6.x and Python 2.x.
Some exception names are not available in Python 2.x.
For example with ConnectionError:
in Python 2.x, using python interpreter, I get a NameError because it does not recognize it.
>>> raise ConnectionError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ConnectionError' is not defined
in Python 3.6.x, using python3 interpreter, I get the right ConnectionError
>>> raise ConnectionError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ConnectionError
It can be tricky when working with multiple versions of Python or different venv. Hope it helps with the debugging.
I have no idea why you are using a global variable here for client. That should be an instance variable of the ChkMongo class.
class ChkMongo:
def __init__(self):
self.item_list = []
self.dict1 = {}
def makeMongocon(self):
try:
self.client = MongoClient("localhost", 27017)
except AutoReconnect, e:
raise ConnectionFailure(str(e))
def findRecords(self):
self.db = self.client.serv
for item in self.db.serv.find():
self.item_list.insert(0,item)
return self.item_list
Note that item_list and dict1 also need to be instance properties, not class ones.

static method in Python not working

I'm learning by my self Python and I have a mind blowing issue, because I don't understand why is not working. I'm using PyDev and I've download version 2 of Python. I have this code:
class Utils:
#staticmethod
def hello():
print "Hi! I'm the Utils class"
Utils.hello() #Hi! I'm the Utils class
and everything is working fine at this point. But if I import the Utils class and call the static method from another module...
import Utils
Utils.hello()
I get this error:
Traceback (most recent call last):
File "C:\Users\migugonz\Desktop\Docs\Per Folder\WorkSpacePy\Rosalind\src\bioinformatics\stronghold\Pruebas.py", line 40, in <module>
Utils.hello()
AttributeError: 'module' object has no attribute 'hello'
I thing it can't be a big deal, but I've been searching a solution and as long I know this shlould be work.
I believe you need to do Utils.Utils.hello()
or import like from Utils import Utils

AttributeError: 'Widget17_Sorter' object has no attribute 'get_data_from_database'

Actually I don't see what I am doing wrong here but I guess it is a very simple and basic problem:
Module 1 called Widget17_Sorter.py:
class Widget17_Sorter(object):
def get_data_from_database(self, database_name, user, password, host ):
...do stuff here...
Module 2 called Test_Widget17_Sorter.py (actually a unit test)
import Widget17_Sorter
class Test(unittest.TestCase):
...do some other stuff here...
def test_get_data_from_database(self):
sorter = Widget17_Sorter.Widget17_Sorter()
raw_data = sorter.get_data_from_database( self.database_name,
self.user, self.password, self.host )
When executing the test I get the following error message:
ERROR: test_get_data_from_database (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "TestWidget17_Sorter.py", line 50, in test_get_data_from_database
raw_data = sorter.get_data_from_database( self.database_name,
AttributeError: 'Widget17_Sorter' object has no attribute 'get_data_from_database'
Why?
Try importing this way:
from Widget17_Sorter import Widget17_Sorter
...
my_widget = Widget17_Sorter(...)
my_widget.get_data_from_database(...)
...and put both scripts in the same folder...

Categories