|
| 1 | +import concurrent.futures |
| 2 | +import time |
| 3 | +from unittest import mock |
| 4 | +import pytest |
| 5 | + |
| 6 | +# Try to import necessary modules, but don't fail if they are missing |
| 7 | +# as the tests will skip themselves if dependencies are missing. |
| 8 | +try: |
| 9 | + import pandas |
| 10 | + import pyarrow |
| 11 | +except ImportError: |
| 12 | + pandas = None |
| 13 | + pyarrow = None |
| 14 | + |
| 15 | +from google.cloud.bigquery import _pandas_helpers |
| 16 | +from google.cloud.bigquery import schema |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture |
| 20 | +def module_under_test(): |
| 21 | + return _pandas_helpers |
| 22 | + |
| 23 | + |
| 24 | +@pytest.mark.skipif(pandas is None, reason="Requires `pandas`") |
| 25 | +@pytest.mark.skipif(pyarrow is None, reason="Requires `pyarrow`") |
| 26 | +def test_download_arrow_row_iterator_timeout(module_under_test): |
| 27 | + bq_schema = [schema.SchemaField("name", "STRING")] |
| 28 | + |
| 29 | + # Mock page with to_arrow method |
| 30 | + mock_page = mock.Mock() |
| 31 | + mock_page.to_arrow.return_value = pyarrow.RecordBatch.from_pydict({"name": ["foo"]}) |
| 32 | + |
| 33 | + def slow_pages(): |
| 34 | + # First page yields quickly |
| 35 | + yield mock_page |
| 36 | + # Sleep to exceed timeout |
| 37 | + time.sleep(0.1) |
| 38 | + yield mock_page |
| 39 | + |
| 40 | + # Timeout of 0.05s |
| 41 | + timeout = 0.05 |
| 42 | + iterator = module_under_test.download_arrow_row_iterator( |
| 43 | + slow_pages(), bq_schema, timeout=timeout |
| 44 | + ) |
| 45 | + |
| 46 | + # First item should succeed |
| 47 | + next(iterator) |
| 48 | + |
| 49 | + # Second item should fail with TimeoutError |
| 50 | + with pytest.raises(concurrent.futures.TimeoutError): |
| 51 | + next(iterator) |
| 52 | + |
| 53 | + |
| 54 | +@pytest.mark.skipif(pandas is None, reason="Requires `pandas`") |
| 55 | +@pytest.mark.skipif(pyarrow is None, reason="Requires `pyarrow`") |
| 56 | +def test_download_dataframe_row_iterator_timeout(module_under_test): |
| 57 | + bq_schema = [schema.SchemaField("name", "STRING")] |
| 58 | + dtypes = {} |
| 59 | + |
| 60 | + # Mock page |
| 61 | + mock_page = mock.Mock() |
| 62 | + # Mock iterator for _row_iterator_page_to_dataframe checking next(iter(page)) |
| 63 | + mock_page.__iter__ = lambda self: iter(["row1"]) |
| 64 | + mock_page._columns = [["foo"]] |
| 65 | + |
| 66 | + def slow_pages(): |
| 67 | + yield mock_page |
| 68 | + time.sleep(0.1) |
| 69 | + yield mock_page |
| 70 | + |
| 71 | + timeout = 0.05 |
| 72 | + iterator = module_under_test.download_dataframe_row_iterator( |
| 73 | + slow_pages(), bq_schema, dtypes, timeout=timeout |
| 74 | + ) |
| 75 | + |
| 76 | + next(iterator) |
| 77 | + |
| 78 | + with pytest.raises(concurrent.futures.TimeoutError): |
| 79 | + next(iterator) |
0 commit comments