Example: Testing an SQLite database

  1. To test whether the database library.db was created with create_db.py, we import ../save-data/create_db.py and os in addition to sqlite3 and unittest:

    1import os
    2import sqlite3
    3import unittest
    4
    5import create_db
    
  2. Then we first define a test class TestCreateDB:

    8class TestCreateDB(unittest.TestCase):
    
  3. In it we then define the test method test_db_exists, in which we use assert to assume that the file exists in os.path:

     9    def test_db_exists(self):
    10        assert os.path.exists("library.db")
    
  4. Now we also check whether the books table was created. For this we try to create the table again and expect with assertRaises that sqlite is terminated with an OperationalError:

    12    def test_table_exists(self):
    13        with self.assertRaises(sqlite3.OperationalError):
    14            create_db.cursor.execute("CREATE TABLE books(title text)")
    
  5. 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.