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.
Related
I am learning monogoDB, I am beginner but I am facing some errors. What is my coding error and tell me the solution for that?
this is post.py file
import uuid
from database import Database
import datetime
class Post (object):
def __init__(self,blog_id,title,content,author,date=datetime.datetime.utcnow(),id=None):
self.blog_id=blog_id
self.title=title
self.content=content
self.author=author
self.created_date=date
self.id=uuid.uuid4().hex if id is None else id
def save_to_mongo(self):
Database.insert(collection='students',data=self.json())
def json(self):
return {
'id':self.id,
'blog_id':self.blog_id,
'author':self.author,
'content':self.content,
'title':self.title,
'created_date':self.created_date
}
#staticmethod
def from_mongo(id):
return Database.find_one(collection='students',query={'id':id})
#staticmethod
def from_blog(id):
return [post for post in Database.find(collection='students',query={'blog_id':id})]
database.py file
import pymongo
class Database(object):
URI="mongodb//127.0.0.1:27017"
DATABASE=None
#staticmethod
def initialize():
client=pymongo.MongoClient(Database.URI)
Database.DATABASE=client['local']
#staticmethod
def insert(collection,data):
Database.DATABASE[collection].insert(data)
#staticmethod
def insert(collection,query):
return Database.DATABASE[collection].find(data)
#staticmethod
def insert(collection,query):
return Database.DATABASE[collection].find_one(data)
this is test.py file
from database import Database
from post import Post
Database.initialize()
post=Post(blog_id="123",title="Anoother great post",content="This is some
sample content",author="rahul")
post.save_to_mongo()
i got the following error during running test.py
[Running] python "d:\myprograms\python\test.py"
Traceback (most recent call last):
File "d:\myprograms\python\test.py", line 9, in <module>
post.save_to_mongo()
File "d:\myprograms\python\post.py", line 15, in save_to_mongo
Database.insert(collection='students',data=self.json())
TypeError: insert() got an unexpected keyword argument 'data'
So I am trying to setup a unittest for a threaded class in python
The class looks like this:
#Singleton
class EventManager(threading.Thread):
def __init__(self):
self.__eventDict = {}
self.__eventDictLock = threading.Lock()
self.__eventQueue = Queue()
self.__subscriberList = []
threading.Thread.__init__(self)
def run(self):
while(True):
if self.__eventQueue.qsize() > 0:
self.__runEvent()
else:
time.sleep(1)
My unittest looks like this:
eventManager = EventManager.Instance()
eventManager.start()
class EventManagerTest(unittest.TestCase):
#pre-test initialization
def setUp(self):
pass
#post-test destruction
def tearDown(self):
pass
def testRegisterEvent(self):
global eventManager
logger.debug("Entering testRegisterEvent()")
eventManager.registerEvent("MyEvent")
logger.debug("testRegisterEvent() appears to have successfully registered")
self.assertIn("MyEvent", eventManager.__subscriberList)
self.assertFalse( eventManager.__eventDict["MyEvent"])
And I'm getting an error like this:
ERROR: testRegisterEvent (__main__.EventManagerTest)
Traceback (most recent call last):
File "EventManager_Test.py", line 59, in testRegisterEvent
self.assertIn("MyEvent", eventManager.__eventDict)
AttributeError: 'EventManager' object has no attribute '\_EventManagerTest\__eventDict'
Where is the _EventManagerTest__eventDict attribute coming from? That is not the attribute I'm calling and it's preventing me from running a unit test.
As __eventDict starts with two underscore, it is a private attribute, therefore its name is “mangled”, that's why the name changed.
The problem is not related to unittest, it is just that you are trying to access a private attribute.
To solve your problem, remove one (or two) underscore(s) at the beginning of the name of __eventDict to make it protected (or public).
I'm having a python problem with a simple program. The program is supposed to allow the user to make a make a Cow() instance and give the cow a name in the parameter.
class Cow():
def __init__(self, name):
self.name = name
if self.name == None:
raise NoNameCowError("Your cow must have a name")
def speak(self):
print self.name, "says moo"
Now when I do
cow.Cow("Toby")
I get the error
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
cow.Cow("Toby")
File "C:\Users\Samga_000\Documents\MyPrograms\cow.py", line 8, in __init__
self.name = name
AttributeError: Cow instance has no attribute 'name'
Help? I originally thought I did something wrong with the exception but it doesn't seem to be that. Thanks in advance.
I think you modified your source code and didn't reloaded the module:
Buggy version:
class Cow():
def __init__(self, name):
if self.name == None:
raise NoNameCowError("Your cow must have a name")
def speak(self):
print self.name, "says moo"
>>> import so
Error raised as expected:
>>> so.Cow('abc1')
Traceback (most recent call last):
File "<ipython-input-4-80383f90b571>", line 1, in <module>
so.Cow('abc1')
File "so.py", line 3, in __init__
if self.name == None:
AttributeError: Cow instance has no attribute 'name'
Now let's modify the source code and add this line self.name = name:
>>> import so
>>> so.Cow('abc1')
Traceback (most recent call last):
File "<ipython-input-6-80383f90b571>", line 1, in <module>
so.Cow('abc1')
File "so.py", line 3, in __init__
self.name = name
AttributeError: Cow instance has no attribute 'name'
eh! still same error? That's because python is still using the old .pyc file or the cached module object. Just reload the module and updated code works fine:
>>> reload(so)
<module 'so' from 'so.py'>
>>> so.Cow('dsfds')
<so.Cow instance at 0x8b78e8c>
From docs:
Note For efficiency reasons, each module is only imported once per
interpreter session. Therefore, if you change your modules, you must
restart the interpreter – or, if it’s just one module you want to test
interactively, use reload(), e.g. reload(modulename).
A better version of your code:
class Cow():
def __init__(self, name=None): #Use a default value
self.name = name
if self.name is None: #use `is` for testing against `None`
raise NoNameCowError("Your cow must have a name")
I'm staring at the name check; this object requires the name argument does it not?
if self.name == None:
raise NoNameCowError("Your cow must have a name")
I'm a little Python thick, but that looks like a required arg.
When your declaring Cow, you need to pass object in the parentheses:
class Cow(object):
rest of code.
This way Python knows the class your declaring is an object with attributes and methods.
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...
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.