0

I'm writing unit tests to test my environment. I have created tests such as:

def test_database_file_present_and_readable(self):
    self.assertTrue(os.access(path_db_file, os.R_OK))

def test_connect_to_db(self):
    conn = sqlite3.connect(path_db_file)
    conn.close()

def test_create_table(self):
    conn = sqlite3.connect(path_db_file)
    cur = conn.cursor()
    cur.execute("CREATE TABLE test_table (id integer  PRIMARY KEY, name text)")
    conn.commit()
    conn.close()

def test_insert_into_table(self):
    conn = sqlite3.connect(path_db_file)
    cur = conn.cursor()
    cur.execute("insert into test_table (name) values (?)", ["Test value"])
    conn.commit()
    conn.close()

def test_update_table(self):
    conn = sqlite3.connect(path_db_file)
    cur = conn.cursor()
    cur.execute("update test_table set id = 2 where id = ?", [1])
    conn.commit()
    conn.close()

def test_delete_from_table(self):
    conn = sqlite3.connect(path_db_file)
    cur = conn.cursor()
    cur.execute("delete from test_table where id = ?", [2])
    conn.commit()
    conn.close()

def test_if_test_table_is_empty(self):
    conn = sqlite3.connect(path_db_file)
    cur = conn.cursor()
    result = cur.execute("select exists(select 1 from test_table)").fetchall()
    conn.commit()
    conn.close()
    self.assertTrue(result == 1)

def test_delete_table(self):
    conn = sqlite3.connect(path_db_file)
    cur = conn.cursor()
    cur.execute("drop table test_table")
    conn.commit()
    conn.close()

And during program execution order of tests is unknown - how to set the order or how to clean up database after creating tests with table creation?

J. Doe
  • 117
  • 1
  • 11

1 Answers1

0

You can get pointers about test method execution order here: Python unittest.TestCase execution order

One suggestion - if you are going for such testing, it's better to mock external dependencies like sqlite & test only the code you've written.

rdas
  • 20,604
  • 6
  • 33
  • 46