[Python] Pytest mock same object with different return values

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    I want to mock same object with different values but it's not working. I am using unittest mock and pytest

    import unittest
    from azure.cosmos.exceptions import CosmosResourceExistsError
    import pytest
    from unittest.mock import patch

    @patch('azure.cosmos.CosmosClient', autospec=True)
    @pytest.mark.run(order=1)
    def test_usage_already_exists(custom_mock_cosmo, mock_sts_session, mock_dynamodb, mock_activation_trns_map):
    print(custom_mock_cosmo)
    mock_container = mock_cosmo_container(custom_mock_cosmo)
    mock_container.read_item.return_value = {"some": "data"}
    mock_container.upsert_item.return_value = {"some": "data"}
    mock_container.create_item.side_effect = CosmosResourceExistsError(409, "Resource already exists")
    # Add debug statement to verify the mock is in place
    print(mock_container.create_item)

    with pytest.raises(CosmosResourceExistsError):
    handle(member, "INSERT", meta_data)



    @patch('azure.cosmos.CosmosClient',autospec=True)
    @pytest.mark.run(order=2)
    def test_your_function1(custom_mock_cosmo,mock_sts_session, mock_dynamodb,mock_activation_trns_map):
    print(custom_mock_cosmo)
    mock_cosmo_container(custom_mock_cosmo).read_item.return_value = {"some": "data"}
    mock_cosmo_container(custom_mock_cosmo).upsert_item.return_value = {"some": "data"}
    handle(member, "INSERT", meta_data)


    @patch('azure.cosmos.CosmosClient',autospec=True)
    @pytest.mark.run(order=3)
    def test_your_function(custom_mock_cosmo,mock_sts_session, mock_dynamodb,mock_activation_trns_map):
    print(custom_mock_cosmo)
    mock_cosmo_container(custom_mock_cosmo).read_item.return_value = {"some": "data"}
    mock_cosmo_container(custom_mock_cosmo).upsert_item.return_value = {"some": "data"}
    handle(member, "REMOVE", meta_data)


    for all the cases i am getting exception i stuck with this please provide some inputs ?

    Continue reading...

Compartilhe esta Página