2017-07-30 14 views
0

質問は簡単ですが、答えはわかりません...Python doctest:データベースの挿入や削除のテスト方法は?

私はテストで初心者ですが、私はsql3データベースをドライブするクラスをテストする際に問題があります。このようなクラスをテストするための最良の方法は何ですか?クラスをテストするか、の機能が問題ではありませんが、他のものをテストしますか?テストはテスト行を挿入しますか?

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で拡張コードを実行することは可能ですか? – 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

関連する問題