|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import unittest.mock as mock |
| 16 | + |
| 17 | +import pandas as pd |
| 18 | + |
| 19 | +# Importing bigframes registers the accessor. |
| 20 | +import bigframes # noqa: F401 |
| 21 | + |
| 22 | + |
| 23 | +def test_dataframe_accessor_sql_scalar(): |
| 24 | + df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) |
| 25 | + |
| 26 | + with mock.patch("bigframes.pandas.io.api.read_pandas") as mock_read_pandas: |
| 27 | + with mock.patch("bigframes.bigquery.sql_scalar") as mock_sql_scalar: |
| 28 | + mock_bf_df = mock.MagicMock() |
| 29 | + mock_bf_df.columns = ["a", "b"] |
| 30 | + mock_bf_df.__getitem__.side_effect = lambda x: f"series_{x}" |
| 31 | + mock_read_pandas.return_value = mock_bf_df |
| 32 | + |
| 33 | + mock_result_series = mock.MagicMock() |
| 34 | + mock_sql_scalar.return_value = mock_result_series |
| 35 | + mock_result_series.to_pandas.return_value = pd.Series([4, 6]) |
| 36 | + |
| 37 | + # This should trigger the accessor |
| 38 | + result = df.bigquery.sql_scalar("ROUND({0} + {1})") |
| 39 | + |
| 40 | + mock_read_pandas.assert_called_once() |
| 41 | + # check it was called with df |
| 42 | + assert mock_read_pandas.call_args[0][0] is df |
| 43 | + |
| 44 | + mock_sql_scalar.assert_called_once_with( |
| 45 | + "ROUND({0} + {1})", ["series_a", "series_b"] |
| 46 | + ) |
| 47 | + |
| 48 | + pd.testing.assert_series_equal(result, pd.Series([4, 6])) |
| 49 | + |
| 50 | + |
| 51 | +def test_dataframe_accessor_sql_scalar_with_session(): |
| 52 | + df = pd.DataFrame({"a": [1]}) |
| 53 | + mock_session = mock.MagicMock() |
| 54 | + |
| 55 | + with mock.patch("bigframes.pandas.io.api.read_pandas") as mock_read_pandas: |
| 56 | + with mock.patch("bigframes.bigquery.sql_scalar") as mock_sql_scalar: |
| 57 | + mock_bf_df = mock.MagicMock() |
| 58 | + mock_bf_df.columns = ["a"] |
| 59 | + mock_bf_df.__getitem__.side_effect = lambda x: f"series_{x}" |
| 60 | + mock_read_pandas.return_value = mock_bf_df |
| 61 | + |
| 62 | + mock_result_series = mock.MagicMock() |
| 63 | + mock_sql_scalar.return_value = mock_result_series |
| 64 | + |
| 65 | + df.bigquery.sql_scalar("template", session=mock_session) |
| 66 | + |
| 67 | + mock_read_pandas.assert_called_once_with(df, session=mock_session) |
0 commit comments