2017-07-30 50 views
0

這個問題很簡單,我不知道的答案...Python doctest:如何測試數據庫插入或刪除功能?

我是新手測試和我有問題測試類驅動sql3數據庫。測試這種類的最佳方式是什麼?測試類或測試init功能不是問題,但其他?測試插入一個測試行?

import sqlite3 


class DataBase: 
    def __init__(self): 
     self._database_path = 'data.sql' 
     self._conn = sqlite3.connect(self._database_path) 
     self._cursor = self._conn.cursor() 

    def get(self, sql): 
     # select 
     self._cursor.execute(sql) 
     dataset = [] 
     for row in self._cursor: 
      dataset.append(row) 

     return dataset 

    def post(self, sql): 
     # insert 
     self._cursor.execute(sql) 
     self._conn.commit() 

謝謝大家,謝謝你的回答!

回答

0

您可以使用數據庫的回滾功能。 只需將self._conn.commit()替換爲self._conn.rollback(),即可測試sql的有效性,但不會影響數據。

如果您需要測試一系列操作(即:獲取數據 - >修改數據 - >插入新數據 - >刪除一些數據 - >再次獲取數據),您可以刪除代碼中的所有_conn.commit(),運行測試並最終致電_conn.rollback()

例子:

import sqlite3 


class DataBase: 
    def __init__(self): 
     self._database_path = 'data.sql' 
     self._conn = sqlite3.connect(self._database_path) 
     self._cursor = self._conn.cursor() 

    def get(self, sql): 
     # select 
     self._cursor.execute(sql) 
     dataset = [] 
     for row in self._cursor: 
      dataset.append(row) 

     return dataset 

    def post(self, sql): 
     # insert 
     self._cursor.execute(sql) 

    def delete(self, sql): 
     # delete 
     self._cursor.execute(sql) 

    def rollback(self): 
     self._conn.rollback() 

# You do your tests: 
db = DataBase() 
data = db.get('select name from table') 
new_data = ['new' + name for name in data] 
db.post('insert into table values {}'.format(','.join('({})'.format(d) for d in new_data))) 
db.delete('delete from table where name = \'newMario\'') 
check = bool(db.get('select name from table where name = \'newMario\'')) 
if check: 
    print('delete ok') 

# You make everything as before the test: 
db.rollback() 
+0

非常感謝您的回答,但是:如果我必須使用DocTest進行操作,該怎麼辦?有可能在DocTest中運行extense代碼? – user1936566

0

我想在正式sqlite3的測試CursorTests就是一個很好的例子。

https://github.com/python/cpython/blob/master/Lib/sqlite3/test/dbapi.py#L187

你可以寫setUptearDown方法來設置和回滾數據庫。

from unittest import TestCase 


class TestDataBase(TestCase): 
    def setUp(self): 
     self.db = DataBase() 

    def test_get(self): 
     pass # your code here 

    def test_post(self): 
     pass # your code here 
+0

非常感謝您的回答,但是:如果我必須使用DocTest進行操作,該怎麼辦?這是可能的?? – user1936566

相關問題