Skip to main content
 首页 » 编程设计

python之名称错误 : global name 'client' is not defined

2025年05月04日8freeliver54

在这里我做了用于连接 mongo 的 python 类并从 mongo 数据库获取数据并处理它我为此做了单元测试用例我得到了以下错误

NameError: 全局名称 'client' 未定义

python 类:

 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()) 

我的单元测试用例

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() 

我在运行测试用例时遇到以下错误,但运行 python 脚本可以正常工作

错误:

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 

请您参考如下方法:

对我来说,在使用 Python 3.6.x 和 Python 2.x 运行我的测试时会发生这种情况。 某些异常名称在 Python 2.x 中不可用。

例如ConnectionError:

在 Python 2.x 中,使用 python 解释器时,我得到一个 NameError,因为它无法识别它。

>>> raise ConnectionError 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
NameError: name 'ConnectionError' is not defined 

在 Python 3.6.x 中,使用 python3 解释器,我得到了正确的 ConnectionError

>>> raise ConnectionError 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
ConnectionError 

在使用多个版本的 Python 或不同的 venv 时可能会很棘手。希望对调试有帮助。