魔法模拟器名称为“con.cursor.fetchall”,ID为“a121213312”。
当我调用read函数时,我希望能够获得值。
db.py
try:
con = psycopg2.connect(
host="yhvh",
database="python_db",
user="postgres",
password="ichoose",
)
except:
print("Unable to connect database")
# Open a cursor to perform database operation
cur = con.cursor()
def read(con):
"""
Read data in Database
"""
print("Read")
cur = con.cursor()
# execute the query
data ="SELECT id, name FROM employees"
cur.execute(
data
)
# fetchall - returns all entries
rows = cur.fetchall()
for r in rows:
print(f"id {r[0]} name {r[1]}")
return rows
test_db.py
class TestDb(unittest.TestCase):
"""
Study
- Mock and Unittes
"""
def test_read(self):
expected = (9, 'jibreel')
with patch("db.con") as mock_connect:
mock_con = mock_connect.return_value
mock_cur = mock_con.cursor.return_value
mock_cur.fetchall.return_value = expected
result = db.read(mock_connect)
print(result)
self.assertEqual(result, expected)
我在测试时遇到了错误。
AssertionError: MagicMock的名称为'con.cursor.fetchall',ID为'a121213312',但实际结果是(9, 'jibreel')。