gpt4 book ai didi

python-2.7 - 如何使用pytest测试使用数据库连接的python函数?

转载 作者:行者123 更新时间:2023-12-04 16:45:33 28 4
gpt4 key购买 nike

我是单元测试和使用 Pytest 来测试我的代码的新手。使用 pytest 为基本函数编写测试很容易,但我无法围绕“猴子补丁”和“模拟”的概念来测试查询数据库的函数。

这是我的代码,没有使用猴子补丁和模拟,我实际上是在查询数据库,我不想这样做 -

def test_execute_sql():
conn = data_platform.DataPlatformConnection()
sql_out = conn.execute_sql("SELECT sid, name, code FROM prod.school WHERE sid = 1158;")
# sql_out = [(1158, 'Lakeview Elementary School', '4141034')]
assert sql_out[0] == (1158, 'Lakeview Elementary School', '4141034')

def test_execute_sql_return_single_value():
conn = data_platform.DataPlatformConnection()
sql_out = conn.execute_sql("SELECT code FROM prod.school WHERE sid = 1158;")
# sql_out = [('4141034',)]
assert sql_out[0][0] == '4141034'

# testing exception
with pytest.raises(Exception) as excinfo:
conn.execute_sql("")
assert 'The sql clause parameter is blank' in str(excinfo.value)

有人可以向我解释pytest中 mock 的概念吗?这样我就可以开始使用它了。

最佳答案

这会起作用

@pytest.mark.django_db
def test_execute_sql():
conn = data_platform.DataPlatformConnection()
sql_out = conn.execute_sql("SELECT sid, name, code FROM prod.school WHERE sid = 1158;")
# sql_out = [(1158, 'Lakeview Elementary School', '4141034')]
assert sql_out[0] == (1158, 'Lakeview Elementary School', '4141034')

@pytest.mark.django_db
def test_execute_sql_return_single_value():
conn = data_platform.DataPlatformConnection()
sql_out = conn.execute_sql("SELECT code FROM prod.school WHERE sid = 1158;")
# sql_out = [('4141034',)]
assert sql_out[0][0] == '4141034'

# testing exception
with pytest.raises(Exception) as excinfo:
conn.execute_sql("")
assert 'The sql clause parameter is blank' in str(excinfo.value)

关于python-2.7 - 如何使用pytest测试使用数据库连接的python函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47600164/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com