Skip to content

Commit 4e4c73f

Browse files
committed
Revert back to other verified unnecessary mock modules
1 parent 2fd7216 commit 4e4c73f

File tree

7 files changed

+16
-77
lines changed

7 files changed

+16
-77
lines changed

src/snowflake/snowpark/mock/_connection.py

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,7 @@
1111
from copy import copy
1212
from decimal import Decimal
1313
from logging import getLogger
14-
from typing import (
15-
IO,
16-
Any,
17-
Dict,
18-
Iterable,
19-
Iterator,
20-
List,
21-
Optional,
22-
Tuple,
23-
Union,
24-
TYPE_CHECKING,
25-
)
14+
from typing import IO, Any, Dict, Iterable, Iterator, List, Optional, Tuple, Union
2615
from unittest.mock import Mock
2716

2817
import snowflake.snowpark.mock._constants
@@ -47,6 +36,7 @@
4736
)
4837
from snowflake.snowpark.async_job import AsyncJob, _AsyncResultType
4938
from snowflake.snowpark.exceptions import SnowparkSessionException
39+
from snowflake.snowpark.mock._options import pandas
5040
from snowflake.snowpark.mock._plan import MockExecutionPlan, execute_mock_plan
5141
from snowflake.snowpark.mock._snowflake_data_type import ColumnEmulator, TableEmulator
5242
from snowflake.snowpark.mock._stage_registry import StageEntityRegistry
@@ -69,9 +59,6 @@
6959
PARAM_INTERNAL_APPLICATION_NAME = "internal_application_name"
7060
PARAM_INTERNAL_APPLICATION_VERSION = "internal_application_version"
7161

72-
if TYPE_CHECKING:
73-
from snowflake.snowpark.mock._options import pandas
74-
7562

7663
class MockedSnowflakeConnection(SnowflakeConnection):
7764
def __init__(self, *args, **kwargs) -> None:
@@ -157,8 +144,6 @@ def write_table(
157144
mode: SaveMode,
158145
column_names: Optional[List[str]] = None,
159146
) -> List[Row]:
160-
from snowflake.snowpark.mock._options import pandas
161-
162147
with self._lock:
163148
for column in table.columns:
164149
if (
@@ -719,8 +704,6 @@ def execute(
719704
rows = [r for r in res]
720705

721706
if to_pandas:
722-
from snowflake.snowpark.mock._options import pandas
723-
724707
pandas_df = pandas.DataFrame()
725708
for col_name in res.columns:
726709
pandas_df[unquote_if_quoted(col_name)] = res[col_name].tolist()
@@ -826,8 +809,6 @@ def max_string_size(self) -> int:
826809

827810

828811
def _fix_pandas_df_fixed_type(table_res: TableEmulator) -> "pandas.DataFrame":
829-
from snowflake.snowpark.mock._options import pandas
830-
831812
pd_df = pandas.DataFrame()
832813
for col_name in table_res.columns:
833814
col_sf_type = table_res.sf_types[col_name]

src/snowflake/snowpark/mock/_functions.py

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import snowflake.snowpark
2525
from snowflake.snowpark._internal.analyzer.expression import FunctionExpression
2626
from snowflake.snowpark._internal.utils import unalias_datetime_part
27-
from snowflake.snowpark.mock._options import numpy
27+
from snowflake.snowpark.mock._options import numpy, pandas
2828
from snowflake.snowpark.mock._snowflake_data_type import (
2929
_TIMESTAMP_TYPE_MAPPING,
3030
_TIMESTAMP_TYPE_TIMEZONE_MAPPING,
@@ -500,8 +500,6 @@ def mock_array_agg(column: ColumnEmulator, is_distinct: bool) -> ColumnEmulator:
500500

501501
@patch("array_construct")
502502
def mock_array_construct(*columns):
503-
from snowflake.snowpark.mock._options import pandas
504-
505503
if len(columns) == 0:
506504
data = [[]]
507505
else:
@@ -1066,8 +1064,6 @@ def convert_timestamp(row):
10661064
else:
10671065
SnowparkLocalTestingException.raise_from_error(exc)
10681066

1069-
from snowflake.snowpark.mock._options import pandas
1070-
10711067
res = column.to_frame().apply(convert_timestamp, axis=1).replace({pandas.NaT: None})
10721068
return [
10731069
x.to_pydatetime() if x is not None and hasattr(x, "to_pydatetime") else x
@@ -1454,8 +1450,6 @@ def mock_to_binary(
14541450

14551451
@patch("coalesce")
14561452
def mock_coalesce(*exprs):
1457-
from snowflake.snowpark.mock._options import pandas
1458-
14591453
if len(exprs) < 2:
14601454
raise SnowparkLocalTestingException(
14611455
f"not enough arguments for function [COALESCE], got {len(exprs)}, expected at least two"
@@ -1622,8 +1616,6 @@ def construct_dict(x):
16221616
if x[i] is not None and not (drop_nulls and x[i + 1] is None)
16231617
}
16241618

1625-
from snowflake.snowpark.mock._options import pandas
1626-
16271619
combined = pandas.concat(exprs, axis=1, ignore_index=True)
16281620
return combined.apply(construct_dict, axis=1)
16291621

@@ -1653,8 +1645,6 @@ def add_years(date, duration):
16531645

16541646

16551647
def add_months(scalar, date, duration):
1656-
from snowflake.snowpark.mock._options import pandas
1657-
16581648
res = (
16591649
pandas.to_datetime(date) + pandas.DateOffset(months=scalar * duration)
16601650
).to_pydatetime()
@@ -1723,7 +1713,6 @@ def mock_date_part(part: str, datetime_expr: ColumnEmulator):
17231713
"""
17241714
unaliased = unalias_datetime_part(part)
17251715
datatype = datetime_expr.sf_type.datatype
1726-
from snowflake.snowpark.mock._options import pandas
17271716

17281717
# Year of week is another alias unique to date_part
17291718
if unaliased == "yearofweek":
@@ -1803,8 +1792,6 @@ def mock_date_trunc(part: str, datetime_expr: ColumnEmulator) -> ColumnEmulator:
18031792
"""
18041793
# Map snowflake time unit to pandas rounding alias
18051794
# Not all units have an alias so handle those with a special case
1806-
from snowflake.snowpark.mock._options import pandas
1807-
18081795
SUPPORTED_UNITS = {
18091796
"day": "D",
18101797
"hour": "h",
@@ -1903,7 +1890,6 @@ def func(x, y):
19031890
data = []
19041891
for x, y in zip(col1, col2):
19051892
data.append(None if x is None or y is None else func(x, y))
1906-
from snowflake.snowpark.mock._options import pandas
19071893

19081894
return ColumnEmulator(
19091895
pandas.Series(data, dtype=object),
@@ -2015,7 +2001,6 @@ def mock_convert_timezone(
20152001
For timezone information, refer to the `Snowflake SQL convert_timezone notes <https://docs.snowflake.com/en/sql-reference/functions/convert_timezone.html#usage-notes>`_
20162002
"""
20172003
import dateutil
2018-
from snowflake.snowpark.mock._options import pandas
20192004

20202005
# mock_convert_timezone matches the sql function call semantics.
20212006
# It has different parameters when called with 2 or 3 args.
@@ -2117,7 +2102,6 @@ def mock_concat(*columns: ColumnEmulator) -> ColumnEmulator:
21172102
SnowparkLocalTestingException.raise_from_error(
21182103
ValueError("concat expects one or more column(s) to be passed in.")
21192104
)
2120-
from snowflake.snowpark.mock._options import pandas
21212105

21222106
pdf = pandas.concat(columns, axis=1).reset_index(drop=True)
21232107
result = pdf.T.apply(
@@ -2135,7 +2119,6 @@ def mock_concat_ws(*columns: ColumnEmulator) -> ColumnEmulator:
21352119
"concat_ws expects a seperator column and one or more value column(s) to be passed in."
21362120
)
21372121
)
2138-
from snowflake.snowpark.mock._options import pandas
21392122

21402123
# Don't reset index, to preserve original indices from filtered DataFrames
21412124
pdf = pandas.concat(columns, axis=1)
@@ -2258,7 +2241,6 @@ def _rank(raw_input, dense=False):
22582241
rank = index
22592242
previous = value
22602243
final_values.append(rank)
2261-
from snowflake.snowpark.mock._options import pandas
22622244

22632245
return pandas.Series(final_values, index=raw_input.index)
22642246

src/snowflake/snowpark/mock/_nop_connection.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
Union,
1717
)
1818

19+
from snowflake.snowpark.mock._options import pandas
20+
1921
from snowflake.connector.cursor import ResultMetadata
2022
from snowflake.snowpark._internal.analyzer.analyzer_utils import unquote_if_quoted
2123
from snowflake.snowpark._internal.analyzer.expression import Attribute
@@ -57,8 +59,6 @@
5759
)
5860

5961
if TYPE_CHECKING:
60-
from snowflake.snowpark.mock._options import pandas
61-
6262
try:
6363
from snowflake.connector.cursor import ResultMetadataV2
6464
except ImportError:
@@ -123,7 +123,6 @@ def execute(
123123
List[Row], "pandas.DataFrame", Iterator[Row], Iterator["pandas.DataFrame"]
124124
]:
125125
source_plan = plan.source_plan
126-
from snowflake.snowpark.mock._options import pandas
127126

128127
if hasattr(source_plan, "execution_queries"):
129128
# If temp read-only table, explicitly create it.

src/snowflake/snowpark/mock/_pandas_util.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
quote_name_without_upper_casing,
1010
)
1111
from snowflake.snowpark._internal.type_utils import infer_type
12+
from snowflake.snowpark.mock._options import pandas as pd
1213
from snowflake.snowpark.mock._telemetry import LocalTestOOBTelemetryService
1314
from snowflake.snowpark.table import Table
1415
from snowflake.snowpark.types import (
@@ -28,7 +29,6 @@
2829
)
2930

3031
if TYPE_CHECKING:
31-
from snowflake.snowpark.mock._options import pandas as pd
3232
from snowflake.snowpark import DataFrame, Session
3333

3434

@@ -43,7 +43,6 @@ def _extract_schema_and_data_from_pandas_df(
4343
pandas type related doc: https://pandas.pydata.org/docs/user_guide/basics.html#dtypes
4444
"""
4545
import numpy
46-
from snowflake.snowpark.mock._options import pandas as pd
4746

4847
# Ensure pandas types are fully loaded before checking them
4948
def _ensure_pandas_types_available():

src/snowflake/snowpark/mock/_plan.py

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@
4242
)
4343
from snowflake.snowpark.mock._udf_utils import coerce_variant_input, remove_null_wrapper
4444
from snowflake.snowpark.mock._util import ImportContext, get_fully_qualified_name
45+
from snowflake.snowpark.mock._window_utils import (
46+
EntireWindowIndexer,
47+
RowFrameIndexer,
48+
is_rank_related_window_function,
49+
)
50+
4551
from snowflake.snowpark.mock.exceptions import SnowparkLocalTestingException
4652

4753
if TYPE_CHECKING:
@@ -142,6 +148,7 @@
142148
)
143149
from snowflake.snowpark.column import Column
144150
from snowflake.snowpark.mock._functions import MockedFunctionRegistry, cast_column_to
151+
from snowflake.snowpark.mock._options import pandas as pd
145152
from snowflake.snowpark.mock._select_statement import (
146153
MockSelectable,
147154
MockSelectableEntity,
@@ -178,9 +185,6 @@
178185
_NumericType,
179186
)
180187

181-
if TYPE_CHECKING:
182-
from snowflake.snowpark.mock._options import pandas as pd
183-
184188

185189
class MockExecutionPlan(LogicalPlan):
186190
def __init__(
@@ -427,12 +431,6 @@ def search_boundary_idx(idx, delta, _win):
427431
return idx
428432

429433
if order_spec:
430-
from snowflake.snowpark.mock._options import pandas as pd
431-
432-
# Use factory function to get proper indexer class
433-
from snowflake.snowpark.mock._window_utils import _get_entire_window_indexer
434-
435-
EntireWindowIndexer = _get_entire_window_indexer()
436434
ordered_windows = [
437435
handle_order_by_clause(order_spec, win, analyzer, expr_to_alias)
438436
for win in res.rolling(EntireWindowIndexer())
@@ -518,10 +516,6 @@ def search_boundary_idx(idx, delta, _win):
518516

519517
windows.append(win[start_idx : end_idx + 1])
520518
else: # If order by is not specified, just use the entire window
521-
# Use factory function to get proper indexer class
522-
from snowflake.snowpark.mock._window_utils import _get_entire_window_indexer
523-
524-
EntireWindowIndexer = _get_entire_window_indexer()
525519
windows = res.rolling(EntireWindowIndexer())
526520
return windows
527521

@@ -838,7 +832,6 @@ def handle_udtf_expression(
838832
):
839833

840834
# TODO: handle and support imports + other udtf attributes.
841-
from snowflake.snowpark.mock._options import pandas as pd
842835

843836
udtf_registry = analyzer.session.udtf
844837
udtf_name = exp.func_name
@@ -1031,7 +1024,6 @@ def execute_mock_plan(
10311024
expr_to_alias: Optional[Dict[str, str]] = None,
10321025
) -> Union[TableEmulator, List[Row]]:
10331026
import numpy as np
1034-
from snowflake.snowpark.mock._options import pandas as pd
10351027

10361028
if expr_to_alias is None:
10371029
expr_to_alias = plan.expr_to_alias
@@ -2212,7 +2204,6 @@ def calculate_expression(
22122204
setting keep_literal to false returns a ColumnEmulator wrapping the Python datatype of a Literal
22132205
"""
22142206
import numpy as np
2215-
from snowflake.snowpark.mock._options import pandas as pd
22162207

22172208
registry = MockedFunctionRegistry.get_or_create()
22182209

@@ -2571,13 +2562,6 @@ def _match_pattern(row) -> bool:
25712562

25722563
return output_data
25732564
if isinstance(exp, WindowExpression):
2574-
# Lazy import to avoid importing pandas at module level
2575-
from snowflake.snowpark.mock._window_utils import (
2576-
_get_entire_window_indexer,
2577-
_get_row_frame_indexer,
2578-
is_rank_related_window_function,
2579-
)
2580-
25812565
window_function = exp.window_function
25822566
window_spec = exp.window_spec
25832567

@@ -2642,8 +2626,6 @@ def _match_pattern(row) -> bool:
26422626
if not isinstance(windows, list):
26432627
pd_index = list(windows.count().index)
26442628
else:
2645-
# Create indexer class dynamically to avoid module-level pandas import
2646-
EntireWindowIndexer = _get_entire_window_indexer()
26472629
indexer = EntireWindowIndexer()
26482630
rolling = res.rolling(indexer)
26492631
windows = [ordered.loc[w.index] for w in rolling]
@@ -2652,8 +2634,6 @@ def _match_pattern(row) -> bool:
26522634
pd_index = list(rolling.count().index)
26532635

26542636
elif isinstance(window_spec.frame_spec.frame_type, RowFrame):
2655-
# Create indexer class dynamically to avoid module-level pandas import
2656-
RowFrameIndexer = _get_row_frame_indexer()
26572637
indexer = RowFrameIndexer(frame_spec=window_spec.frame_spec)
26582638
res = res.rolling(indexer)
26592639
res_index = list(res.count().index)

src/snowflake/snowpark/mock/_stage_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
unwrap_stage_location_single_quote,
2323
)
2424
from snowflake.snowpark.mock._functions import mock_to_char
25+
from snowflake.snowpark.mock._options import pandas as pd
2526
from snowflake.snowpark.mock._snowflake_data_type import (
2627
ColumnEmulator,
2728
ColumnType,
@@ -409,7 +410,6 @@ def read_file(
409410
options: Dict[str, str],
410411
) -> TableEmulator:
411412
from snowflake.snowpark.mock import CUSTOM_JSON_DECODER
412-
from snowflake.snowpark.mock._options import pandas as pd
413413

414414
stage_source_dir_path = os.path.join(self._working_directory, stage_location)
415415

src/snowflake/snowpark/mock/_util.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88
import sys
99
import tempfile
1010
from functools import cmp_to_key, partial
11-
from typing import Any, Callable, Iterable, Optional, Set, Tuple, Union, TYPE_CHECKING
11+
from typing import Any, Callable, Iterable, Optional, Set, Tuple, Union
1212

1313
from snowflake.snowpark._internal.utils import parse_table_name, quote_name
14+
from snowflake.snowpark.mock._options import pandas as pd
1415
from snowflake.snowpark.mock._snowflake_data_type import ColumnEmulator
1516
from snowflake.snowpark.types import (
1617
ArrayType,
@@ -33,9 +34,6 @@
3334
_NumericType,
3435
)
3536

36-
if TYPE_CHECKING:
37-
from snowflake.snowpark.mock._options import pandas as pd
38-
3937

4038
# placeholder map helps convert wildcard to reg. In practice, we convert wildcard to a middle string first,
4139
# and then convert middle string to regex. See the following example:

0 commit comments

Comments
 (0)