Example: Testing an SQLite database¶
To test whether the database
library.dbwas created withcreate_db.py, we import../save-data/create_db.pyand os in addition to sqlite3 and unittest:1import os 2import sqlite3 3import unittest 4 5import create_db
Then we first define a test class
TestCreateDB:8class TestCreateDB(unittest.TestCase):
In it we then define the test method
test_db_exists, in which we useassertto assume that the file exists in os.path:9 def test_db_exists(self): 10 assert os.path.exists("library.db")
Now we also check whether the
bookstable was created. For this we try to create the table again and expect withassertRaisesthatsqliteis terminated with anOperationalError:12 def test_table_exists(self): 13 with self.assertRaises(sqlite3.OperationalError): 14 create_db.cursor.execute("CREATE TABLE books(title text)")
We do not want to carry out further tests on a database in the file system but in an SQLite database in the working memory:
17class TestCommands(unittest.TestCase): 18 def setUp(self): 19 self.conn = sqlite3.connect(":memory:") 20 cursor = self.conn.cursor()
See also
You can find more examples for testing your SQLite database functions in the SQLite test suite test_sqlite3.