Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: global name 'client' is not defined

Tags:

python

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
like image 705
kayu Avatar asked May 08 '26 09:05

kayu


1 Answers

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.

like image 108
Sylhare Avatar answered May 11 '26 01:05

Sylhare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!