Skip to content

Commit 1e770ef

Browse files
committed
Add tests for transactions and connections
1 parent ef1619e commit 1e770ef

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

tests.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,49 @@ def test_get_cursor_gets_a_cursor(self):
6565
with self.db.get_cursor("SELECT * FROM foo ORDER BY bar") as cursor:
6666
actual = cursor.fetchall()
6767
assert actual == [{"bar": "baz"}, {"bar": "buz"}]
68+
69+
70+
class TestTransaction(WithData):
71+
72+
def test_get_transaction_gets_a_transaction(self):
73+
with self.db.get_transaction() as txn:
74+
txn.execute("INSERT INTO foo VALUES ('blam')")
75+
txn.execute("SELECT * FROM foo ORDER BY bar")
76+
actual = txn.fetchall()
77+
assert actual == [{"bar": "baz"}, {"bar": "blam"}, {"bar": "buz"}]
78+
79+
def test_transaction_is_isolated(self):
80+
with self.db.get_transaction() as txn:
81+
txn.execute("INSERT INTO foo VALUES ('blam')")
82+
txn.execute("SELECT * FROM foo ORDER BY bar")
83+
actual = list(self.db.fetchall("SELECT * FROM foo ORDER BY bar"))
84+
assert actual == [{"bar": "baz"}, {"bar": "buz"}]
85+
86+
def test_transaction_commits_on_success(self):
87+
with self.db.get_transaction() as txn:
88+
txn.execute("INSERT INTO foo VALUES ('blam')")
89+
txn.execute("SELECT * FROM foo ORDER BY bar")
90+
actual = list(self.db.fetchall("SELECT * FROM foo ORDER BY bar"))
91+
assert actual == [{"bar": "baz"}, {"bar": "blam"}, {"bar": "buz"}]
92+
93+
def test_transaction_rolls_back_on_failure(self):
94+
class Heck(Exception): pass
95+
try:
96+
with self.db.get_transaction() as txn:
97+
txn.execute("INSERT INTO foo VALUES ('blam')")
98+
txn.execute("SELECT * FROM foo ORDER BY bar")
99+
raise Heck
100+
except Heck:
101+
pass
102+
actual = list(self.db.fetchall("SELECT * FROM foo ORDER BY bar"))
103+
assert actual == [{"bar": "baz"}, {"bar": "buz"}]
104+
105+
106+
class TestConnection(WithData):
107+
108+
def test_get_connection_gets_a_connection(self):
109+
with self.db.get_connection() as conn:
110+
cursor = conn.cursor()
111+
cursor.execute("SELECT * FROM foo ORDER BY bar")
112+
actual = cursor.fetchall()
113+
assert actual == [{"bar": "baz"}, {"bar": "buz"}]

0 commit comments

Comments
 (0)