Pytest mocking SQLalchmey

25 Views Asked by At

When I was writing the UT for the routes which I've created i've been getting below error tests/routes/test_users_routes.py - sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5439 failed: Connection refused

Below is my routes method where I'm registering the users based on some parameters

@router.post("/register")
def create_user(user: User, db: Session = Depends(get_db)):
    logger.info("Initiating the router to create user")
    request = user.dict()
    try:
        api_status, response, message, status_code = create_user_method(db, request)
        if api_status:
            return JSONResponse(
                status_code=status_code,
                content={"message": message, "status": api_status, "data": response},
            )
        else:
            return JSONResponse(
                status_code=status_code,
                content={"message": message, "status": api_status, "data": response},
            )
    except Exception as err:
        logger.error(err)
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={"message": str(err), "status": False, "data": None},
        )

And below is my test function

@patch("app.routes.users.create_user_method", new_callable=MagicMock)
def test_create_user_1(create_user_mock,get_db_mock):
    """
    Test case to create a user when API status is True
    """
    # def get_db():
    #     return mock_session_local
    
    # app.dependency_overrides[get_db] = get_db
    mock_session_local = MagicMock()
    get_db_mock.return_value = mock_session_local

    payload = {
        "data": {
            "user": {
                "first_name": "Shaheer",
                "last_name": "Muhammad",
                "email": "[email protected]",
                "mobile": "1234567890",
                "password": "Shaheer@88888",
            }
        }
    }

    create_user_mock.return_value = True, {}, "User Registered successfully.", 200

    response = client.post("/api/v1/user/register", json=payload)
    assert response.status_code == 200
    assert response.json()["status"] is True
    assert response.json()["message"] == "User Registered successfully."

I'm expecting get some other error and while mocking the actual DB session.

1

There are 1 best solutions below

0
Maxim Ivanov On

In order to make it work, you will have to override get_db dependency.

from unittest import mock

@mock.patch("app.routes.users.create_user_method", new_callable=mock.MagicMock)
def test_create_user(create_user_mock):
    """
    Test case to create a user when API status is True
    """
    def fake_get_db():
        return mock.Mock()

    app.dependency_overrides[get_db] = fake_get_db  # Here!
    create_user_mock.return_value = True, {}, "User Registered successfully.", 200

    payload = {
        "data": {
            "user": {
                "first_name": "Shaheer",
                "last_name": "Muhammad",
                "email": "[email protected]",
                "mobile": "1234567890",
                "password": "Shaheer@88888",
            }
        }
    }
    response = client.post("/api/v1/users/register", json=payload)

    assert response.status_code == 200
    assert response.json()["status"] is True
    assert response.json()["message"] == "User Registered successfully."

Note that you will have to revert the original dependency back after the test, otherwise it will affect other tests, which use the actual DB, for example.

For this refer to https://stackoverflow.com/a/68687967 and https://stackoverflow.com/a/72203335