Python 在sqlite中创建用于单元测试的数据库

Python 在sqlite中创建用于单元测试的数据库,python,sql,python-3.x,sqlite,Python,Sql,Python 3.x,Sqlite,我有一个简单的类驱动的sqlite应用程序。基本上,我想为它运行单元测试,但到目前为止我还不能 class DB: def __init__(self, dbname='mydb.db'): try: self.connection = sqlite3.connect(dbname) except: print('Error') finally: pass 任

我有一个简单的类驱动的sqlite应用程序。基本上,我想为它运行单元测试,但到目前为止我还不能

class DB:
    def __init__(self, dbname='mydb.db'):    
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass
任何类都会使用它:

class Hello:
    def hi(self):
        db = DB() # Create db or connect to existing one
        cursor = db.connection.cursor()
现在,在测试时,我传递一个测试数据库:

db = DB('test.db')
#create datatabase here and all works fine
h = Hello()

现在,h使用mydb.db,而不是test.db。如何测试上述结构?

如果要传递DB类DB的实例,需要将该实例提供给Hello类。尝试:

class DB:
    def __init__(self, dbname='mydb.db'):    
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass

class Hello:
    def hi(self, db=DB()): # we make it have a default db of DB() (which in turn defaults to 'mydb.db')
        # db = DB() # Create db or connect to existing one
        # ^^ we remove this line because now this is the default
        cursor = db.connection.cursor()

db = DB('test.db') # this makes an instance of your DB class and calls it "db"
h = Hello(db) # now we need to feed this instance
虽然这可能不是最好的方法。您可能会从具有方法的单个类中受益更多,因为您的第二个类基本上是无用的,并且与您的第一个类密切相关:

class DB:
    def __init__(self, dbname='mydb.db'):    
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass

    def hello(self): # making a method instead
        cursor = self.connection.cursor()

db = DB('test.db') # this makes an instance of your DB class and calls it "db"
db.hello() # call our method
编辑 我错过了最初在测试代码时发现的一些东西。您的代码应该可以正常工作,但是您需要调用您创建的方法!试试这个:

import sqlite3

class DB:
    def __init__(self, dbname='mydb.db'):
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass

class Hello:
    def hi(self):
        db = DB('test.db')
        cursor = db.connection.cursor()

db = DB('test.db')
h = Hello() # make our instance
h.hi() # use the method "hi" associated with the class (our function name within the class)

使用临时数据库测试代码通常是个好主意。Sqlite在这里很有用。@ralex感谢您添加更多信息!我想我通过我的编辑找到了答案,不过OP从未调用Hello的hi方法class@Reedinationer谢谢第二种方法与我现在的行为完全一样。出于测试目的,是的,将所有内容都放在一个类中使其更容易,但我想知道是否可以保留该结构。让我试试你的第一种方法again@Reedinationer感谢您的尝试,但它无法在上拾取db_test.dball@NieSelam你怎么知道它不会把它捡起来?您是否正在使用光标进行任何操作,以将数据打印到控制台?在第二个示例中,Hello类中的db=db行默认为值mydb.db。您需要将其更改为db=db'test.db'