· 7 years ago · Sep 27, 2018, 07:00 PM
1#!/usr/bin/env python
2
3import sqlite3, unittest
4
5class KittehDB:
6 def __init__(self,path):
7 """
8 Creates database at specified path
9 """
10 print("Creating Database")
11 self.conn = sqlite3.connect(path)
12 self.cursor = self.conn.cursor()
13 self.__execute("""
14 CREATE TABLE IF NOT EXISTS kittehs(name TEXT, weight INTEGER)
15 """)
16
17 def __del__(self):
18 """
19 Close DB Connection (for :memory: this means freeing data)
20 """
21 print("Closing database.")
22 self.conn.close()
23
24 def __execute(self,command,*args):
25 """
26 Works same as:
27 self.cursor.execute() but does an additional commit
28 """
29 self.cursor.execute(command,*args)
30 self.conn.commit()
31
32 def insert(self,name = 'myKitteh',weight = 0):
33 """
34 Insert a value to the DB
35 """
36 self.__execute('INSERT INTO kittehs VALUES (?,?)',(name,weight))
37
38 def get_contents(self):
39 """
40 Simply queries all data and writes set
41 """
42 s = {}
43 self.cursor.execute('SELECT * FROM kittehs')
44 for row in self.cursor:
45 s[row[0]] = row[1]
46
47 return s
48
49
50class KittehDBTest(unittest.TestCase):
51 def setUp(self):
52 self.db = KittehDB(':memory:')
53
54
55 def test_insert(self):
56 num = 10000
57 for i in range(num):
58 self.db.insert(str(i),i)
59
60 kDict = self.db.get_contents()
61 self.assertEqual(kDict.__len__(),num)
62
63 for i in range(num):
64 self.assertEqual(kDict[str(i)],i)
65
66
67
68
69if __name__ == '__main__':
70 unittest.main()