lundi 29 juillet 2019

Python Mocking the postgres database

MagicMock name='con.cursor.fetchall' id='a121213312' I want to have value when I call read function

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)



The error when I test it

AssertionError: MagicMock name='con.cursor.fetchall' id='a121213312' != (9, 'jibreel')

Aucun commentaire:

Enregistrer un commentaire