【问题标题】:how to mock python postgres database如何模拟python postgres数据库
【发布时间】:2019-07-10 09:43:01
【问题描述】:

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

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'] != None

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

【问题讨论】:

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


    【解决方案1】:

    首先您需要返回包含来自read 函数的数据列表的rows,否则它将返回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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 2019-04-10
      相关资源
      最近更新 更多