在单元测试中测试删除表sqlite的正确方法

时间:2019-04-02 14:47:47

标签: python sqlite unit-testing

我正在编写单元测试来测试我的环境。 我创建了以下测试:

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()

在程序执行期间,测试的顺序是未知的-使用表创建创建测试后如何设置顺序或如何清理数据库?

1 个答案:

答案 0 :(得分:0)

您可以在此处获得有关测试方法执行顺序的指针:Python unittest.TestCase execution order

一个建议-如果要进行这样的测试,最好模拟sqlite之类的外部依赖项并仅测试您编写的代码。