如何模拟python postgres数据库

时间:2019-07-10 09:43:01

标签: python python-3.x postgresql unit-testing mocking

我尝试模拟我的数据库,但是当我测试它的结果是无。

try:
    con = psycopg2.connect(
                    host="yhvh",
                    database="python_db",
                    user="postgres",
                    password="pass",
                    )
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")

    # 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]}")

这是我测试的代码

    def test_read(self):

        expected = [9, 'aaa']

        with patch('psycopg2.connect') as mock_connect:
            mock_con_cm = mock_connect.return_value
            mock_con = mock_con_cm.__enter__.return_value
            mock_cur = mock_con.cursor.return_value
            mock_cur.fetchall.return_value = expected

            result = db.read(mock_connect)
            self.assertEqual(expected, result)

我收到一个assertionError:[9,'aaa']!=无

结果如何具有等于预期的值?

1 个答案:

答案 0 :(得分:0)

首先,您需要返回rows,其中包含来自read函数的数据列表,否则返回None。 然后使用assertListEqual(expected, result)检查列表中的元素。

您的最终代码将如下所示。

def read(con):
    """
    Read data in Database
    """
    print("Read")

    # 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

断言应该是

self.assertListEqual(expected, result)