|
| 1 | +from unittest import mock |
| 2 | + |
| 3 | +from google.cloud import retail_v2 |
| 4 | +import pytest |
| 5 | + |
| 6 | +from search_pagination import search_pagination |
| 7 | + |
| 8 | + |
| 9 | +@pytest.fixture |
| 10 | +def test_config(project_id): |
| 11 | + return { |
| 12 | + "project_id": project_id, |
| 13 | + "placement_id": "default_placement", |
| 14 | + "visitor_id": "test_visitor", |
| 15 | + } |
| 16 | + |
| 17 | + |
| 18 | +@mock.patch.object(retail_v2.SearchServiceClient, "search") |
| 19 | +def test_search_pagination(mock_search, test_config, capsys): |
| 20 | + # Mock first response |
| 21 | + mock_product_1 = mock.Mock() |
| 22 | + mock_product_1.id = "product_1" |
| 23 | + |
| 24 | + mock_result_1 = mock.Mock() |
| 25 | + mock_result_1.product = mock_product_1 |
| 26 | + |
| 27 | + mock_first_response = mock.MagicMock() |
| 28 | + mock_first_response.next_page_token = "token_for_page_2" |
| 29 | + mock_first_response.__iter__.return_value = [mock_result_1] |
| 30 | + |
| 31 | + # Mock second response |
| 32 | + mock_product_2 = mock.Mock() |
| 33 | + mock_product_2.id = "product_2" |
| 34 | + |
| 35 | + mock_result_2 = mock.Mock() |
| 36 | + mock_result_2.product = mock_product_2 |
| 37 | + |
| 38 | + mock_second_response = mock.MagicMock() |
| 39 | + mock_second_response.next_page_token = "" |
| 40 | + mock_second_response.__iter__.return_value = [mock_result_2] |
| 41 | + |
| 42 | + mock_search.side_effect = [mock_first_response, mock_second_response] |
| 43 | + |
| 44 | + search_pagination( |
| 45 | + project_id=test_config["project_id"], |
| 46 | + placement_id=test_config["placement_id"], |
| 47 | + visitor_id=test_config["visitor_id"], |
| 48 | + query="test query", |
| 49 | + ) |
| 50 | + |
| 51 | + out, _ = capsys.readouterr() |
| 52 | + assert "--- First Page ---" in out |
| 53 | + assert "Product ID: product_1" in out |
| 54 | + assert "--- Second Page ---" in out |
| 55 | + assert "Product ID: product_2" in out |
| 56 | + |
| 57 | + # Verify calls |
| 58 | + assert mock_search.call_count == 2 |
| 59 | + |
| 60 | + # Check first call request |
| 61 | + first_call_request = mock_search.call_args_list[0].kwargs["request"] |
| 62 | + assert first_call_request.page_size == 5 |
| 63 | + assert not first_call_request.page_token |
| 64 | + |
| 65 | + # Check second call request |
| 66 | + second_call_request = mock_search.call_args_list[1].kwargs["request"] |
| 67 | + assert second_call_request.page_size == 5 |
| 68 | + assert second_call_request.page_token == "token_for_page_2" |
0 commit comments