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

时间:2017-12-01 19:23:05

标签: python-2.7 pytest

我不熟悉单元测试并使用Pytest测试我的代码。使用pytest很容易编写基本函数的测试,但是我无法理解" monkey-patching"和"嘲笑"用于测试查询数据库的函数。

这是我的代码,没有使用monkeypatching和mocking,我实际上是在查询数据库,我不想这样做 -

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中嘲笑的概念吗?这样我才能开始使用它。

1 个答案:

答案 0 :(得分:0)

这将起作用

@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)