I am trying to catch a sqlite3.IntegrityError
error with pytest.raises()
.
Here's some toy code to illustrate the behavior.
import sqlite3
import pytest
def func(cursor):
try:
cursor.execute("INSERT INTO Test (Name) VALUES ('Entry1')")
except sqlite3.IntegrityError as e:
print(e)
def test_func():
connection = sqlite3.connect(":memory:")
c = connection.cursor()
c.execute(
"""
CREATE TABLE IF NOT EXISTS Test (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT UNIQUE NOT NULL)
"""
)
c.execute("INSERT INTO Test (Name) VALUES ('Entry1')")
with pytest.raises(sqlite3.IntegrityError) as e:
func(cursor=c)
assert str(e.value) == "UNIQUE constraint failed: Test.Name"
The code of my func
actually throws the anticipated error and prints to stdout, because Entry1
is already in the table and violates the UNIQUE
restriction. However, the test fails. I don't understand why pytest
didn't raise a sqlite3.IntegrityError
. Here's the test's output:
FAILED [100%]UNIQUE constraint failed: Test.Name
err.py:12 (test_func)
def test_func():
connection = sqlite3.connect(":memory:")
c = connection.cursor()
c.execute(
"""
CREATE TABLE IF NOT EXISTS Test (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT UNIQUE NOT NULL)
"""
)
c.execute("INSERT INTO Test (Name) VALUES ('Entry1')")
with pytest.raises(sqlite3.IntegrityError) as e:
> func(cursor=c)
E Failed: DID NOT RAISE <class 'sqlite3.IntegrityError'>
err.py:28: Failed
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…