2013-09-23 65 views
0

我想对使用MySQL数据库的代码运行一些测试。现在,代码由多个模块组成,这些模块全部导入公共模块mainlib。这个模块没有MySQLdb Python - 测试数据库

db = MySQLdb.connect(host='localhost', user='admin', password='admin', db='MyDatabase'). 

我想用测试数据库而不是真正的数据库做测试。

我想我可以关闭连接(mainlib.db.close()),并创建的测试脚本一个新的连接:

db = MySQLdb.connect(host='localhost', user='admin', password='admin', db='TestDatabase') 

,并命名用相同的全局变量新的光标。但我不确定其他模块中的进口是如何工作的。在任何情况下,这种方法似乎并没有工作,因为我得到了InterfaceError: (0, '')以及从我的测试数据库cursor没有数据返回。

有谁知道如何切换到一个测试数据库,而无需修改源代码?

+0

@Steve,谢谢;那工作。如果你把它作为答案,我会选择它。另外,如果您对如何将mainlib重新配置为更漂亮的解决方案有任何想法,请告诉我! – newt

回答

1

Python的 “全局” 变量不具有全局范围。它们是模块范围变量。因此,不同模块中同名的全局变量不是同一个变量。

我想你可能会关闭mainlib.db,然后将mytestcode.db设置为一个新的数据库。所有其他代码当然会继续使用mainlib.db,现在已关闭。

尝试mainlib.db = MySQLdb.connect(...),与同为光标。直接修改另一个模块的变量是很丑陋的,但它可以像你期望的那样工作。

另一种方法是引入配置如何mainlib打开数据库的方式。例如,你可以有这样的功能在mainlib:现在

db = None 
dbname = None 
cursor = None 

def connectdb(name = None): 
    """ 
    Set up the global database connection and cursor, if it isn't already. 

    Omit 'name' when the caller doesn't care what database is used, 
    and is happy to accept whatever database is already connected or 
    connect to a default database. 

    Since there cannot be multiple global databases, an exception is thrown 
    if 'name' is specified, the global connection already exists, and the 
    names don't match. 
    """ 
    global db, dbname, cursor 
    if db is None: 
     if name is None: 
      name = 'MyDatabase' 
     db = MySQLdb.connect(host='localhost', user='admin', password='admin', db=name) 
     dbname = name 
     cursor = db.cursor() 
    elif name not in (None, dbname): 
     raise Exception('cannot connect to the specified db: the global connection already exists and connects to a different db') 

,在正常的程序(不是每一个模块,只是顶层的),你导入mainlib后立即打电话mainlib.connectdb()。在您的测试代码中,您可以拨打mainlib.connectdb('TestDatabase')

或者,你可以有connectdb返回光标和/或连接对象,这样一来,一切使用全局数据库可以通过这个功能。

就个人而言,我不喜欢使用这个在所有的全局 - 我想有一个函数来创建一个数据库连接,我会通过该数据库作为参数到任何需要它。但是,我知道这方面的口味各不相同。

0

速战速决是使用相同的光标,而是选择表时要明确与数据库。例如,如果你在两个数据库中都有一个表T,

你可以做

select * from myDatabase.T #if you want to use the real table 

select * from TestDatabase.T #if you want to use the test table 
+0

我可以在我的测试脚本中做到这一点,但其余的模块(我在测试脚本中调用的)将继续使用真实的数据库。 – newt