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

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)

Related

AttributeError: 'LoginPage' object has no attribute 'driver'

I have a base class. Inheriting base class, login.py runs without any problem. But when I run Company_Management.py its giving me:
Traceback (most recent call last):
File "/home/sohel/eclipse-workspace/Copell/copell/Company_Management.py", line 22, in test_company
em.test_logn()
File "/home/sohel/eclipse-workspace/Copell/copell/login.py", line 15, in test_logn
driver =self.driver
AttributeError: 'LoginPage' object has no attribute 'driver'
What I am trying to do is that, when I will run Company_Management.py it will excute test_logn(self) method first then will click on 2 urls from xpath.
base.py
import unittest
import time
from selenium import webdriver
class Login(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome('/home/sohel/eclipse-workspace/chromedriver')
cls.driver.maximize_window()
cls.driver.get("https:www.car.com/login?back_url=%2F")
time.sleep(3)
#classmethod
def tearDownClass(cls):
cls.driver.close()
if __name__ == '__main__':
unittest.main()
login.py
import base
import unittest
import time
class LoginPage(base.Login):
def test_logn(self):
driver =self.driver
driver.find_element_by_id("email").clear()
driver.find_element_by_id("email").send_keys("keya#gmail.com")
driver.find_element_by_id("password").clear()
driver.find_element_by_id("password").send_keys("Abcd1234")
driver.find_element_by_xpath("//button[#type='submit']").click()
def test_logout(self):
self.driver.find_element_by_xpath("//li[9]/a/span").click()
if __name__ == '__main__':
unittest.main()
Company_Management.py
import base
import unittest
import login
import logging
import time
class CompanyManagement(base.Login):
def test_company(self):
driver = self.driver
em = login.LoginPage()
em.test_logn()
driver.find_element_by_xpath("//ec-ui-side-bar/div/div/ul/li[3]/a/span").click()
driver.find_element_by_xpath("//ec-ui-side-bar/div/div/ul/li[3]/ul/li/a/span").click()
time.sleep(3)
if __name__ == '__main__':
unittest.main()
ERROR: test_company (copell.Company_Management.CompanyManagement) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/sohel/eclipse-workspace/Copell/copell/Company_Management.py", line 22, in test_company em.test_logn() File "/home/sohel/eclipse-workspace/Copell/copell/login.py", line 15, in test_logn driver =self.driver AttributeError: 'LoginPage' object has no attribute 'driver' --------------------------------------------------------------------- Ran 1 test in 7.227s FAILED (errors=1)
Both your classes extend [Python 2]: class unittest.TestCase(methodName='runTest').
According to [Python 2]: Skipping tests and expected failures
Skipped tests will not have setUp() or tearDown() run around them. Skipped classes will not have setUpClass() or tearDownClass() run.
Also, according to [Python 2]: setUpClass and tearDownClass:
If you want the setUpClass and tearDownClass on base classes called then you must call up to them yourself.
What happens:
login.py: LoginPage is instantiated (and run) automatically by the unittest framework (unittest.main()) and setUpClass method is called -
which adds the driver attribute to the LoginPage class - and (automatically, to) all its instances
Company_Management.py: LoginPage is instantiated manually by you (em = login.LoginPage()), but the setUpClass method isn't called - and thus LoginPage (or any of its instances) doesn't have the driver attribute - hence your error. To fix it, manually call the method yourself, either:
After instantiating the class (on the instance):
em = login.LoginPage()
em.setUpClass()
On the class itself (better, before instantiating it)
login.LoginPage.setUpClass()
em = login.LoginPage()

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.

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...

'SentinelObject' object has no attribute 'reset_mock'

I am not sure why the following code is not working. I am using the Mock framework. Anyone could explain it to me?
The error I get is this:
$ python test_mock.py
Calls the mock object method. not a real one. ... ERROR
======================================================================
ERROR: Calls the mock object method. not a real one.
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_mock.py", line 37, in test_is_method_called
self.sut.do_something()
File "test_mock.py", line 21, in do_something
self.__obj.method()
File "build/bdist.linux-i686/egg/mock.py", line 365, in __getattr__
self._children[name] = self._get_child_mock(parent=self, name=name, wraps=wraps)
File "build/bdist.linux-i686/egg/mock.py", line 458, in _get_child_mock
return klass(**kw)
File "build/bdist.linux-i686/egg/mock.py", line 282, in __init__
self.reset_mock()
File "build/bdist.linux-i686/egg/mock.py", line 303, in reset_mock
self._return_value.reset_mock()
AttributeError: 'SentinelObject' object has no attribute 'reset_mock'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
The code is:
import unittest
import mock
class Fubar ():
def __init__(self):
pass
def method (self):
print "I am a Stup!d Monkey!"
class Monkey ():
def __init__(self, obj):
self.__obj = obj
def do_something (self):
if not isinstance(self.__obj, Fubar):
raise RuntimeError
self.__obj.method()
class TestMoneky (unittest.TestCase):
def setUp(self):
self.mock_obj = mock.Mock(name="Mock object", spec=["method"])
self.sut = Monkey(self.mock_obj)
def tearDown(self):
pass
def test_is_method_called (self):
"""Calls the mock object method. not a real one."""
with mock.patch("__builtin__.isinstance") as mock_inst:
mock_inst.return_value = True
self.sut.do_something()
self.assertTrue(self.mock_obj.method.called)
def main ():
"""Simple runner."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestMoneky))
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
main()
The problems (sadly) is trivial. I am patching isinstance() to always return True. So, somewhere in the bowels of the module, something is asking whether my mock object is a Sentinel and (since I am overriding the return value), True is returned. Thus the wrong internal behaviour is exhibited.
The solution is therefore to not patch isinstance() but instead provide the mock with a spec that matches the class it is supposed to match:
def setUp(self):
self.mock_obj = mock.Mock(name="Mock object", spec=Fubar)
self.sut = Monkey(self.mock_obj)
def test_is_method_called (self):
"""Calls the mock object method. not a real one."""
self.sut.do_something()
self.assertTrue(self.mock_obj.method.called)
Can anyone see a way to do this without coupling the mock to Fubar???...

Python Unit Tests - Am I using SetUp wrong?

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.

Categories