Nie Selam
Nie Selam

Reputation: 1451

Create database for unit testing in sqlite

I have a simple class driven sqlite app. Basically, I want to run unit tests for it, but I haven't been able to so far.

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

Any class would use it then:

class Hello:
    def hi(self):
        db = DB() # Create db or connect to existing one
        cursor = db.connection.cursor()

Now, when testing, I pass on a test database:

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

Now, h makes use of mydb.db, instead of test.db. How does one go out about testing the above structure?

Upvotes: 0

Views: 7151

Answers (1)

Reedinationer
Reedinationer

Reputation: 5774

If you want to pass the instance of your DB class (db) you would need to feed the instance to your Hello class. Try:

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

Although this probably isn't the best way to go about it. You would likely benefit more from having a single class with methods because your second class is basically useless and is very closely related to your first class anyways:

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

EDIT

I missed something originally that I found from testing my code. Your code should work fine, but you need to call the method you've made! Try this:

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)

Upvotes: 1

Related Questions