ts_lib_pytest.df_snapshot module#
Testing utilities for Polars DataFrame snapshots.
This module provides a custom snapshot testing implementation that stores Polars DataFrame snapshots as Parquet files and uses polars.testing.assert_frame_equal for comparison with clear diff output.
- class DataframeSnapshot(path: Path | str, is_snapshot_update: bool = False)[source]#
Bases:
objectClass to manage Polars DataFrame snapshots stored as Parquet files.
This class provides snapshot testing functionality for Polars DataFrames by storing them as Parquet files and comparing them using polars.testing.assert_frame_equal. The parent directory for the snapshot file is automatically created if it doesn’t exist.
- Parameters:
path (Path | str) – Complete file path to the snapshot file
is_snapshot_update (bool, optional) – If True, snapshots will be updated instead of compared. Defaults to False.
- Usage:
Typically used with the df_snapshot pytest fixture:
def test_my_dataframe(df_snapshot: DataframeSnapshot): df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) df_snapshot.assert_frame_equal(df)
Or create directly:
snapshot = DataframeSnapshot("example-output/unit/test_df_snapshot.parquet") df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) snapshot.assert_frame_equal(df)
To update snapshots, run the test with –df-snapshot-update
- Raises:
ImportError – If polars is not installed when trying to use the class
- assert_frame_equal(df_right: polars.DataFrame, *, check_row_order: bool = True, check_column_order: bool = True, check_dtypes: bool = True, check_exact: bool = False, rel_tol: float = 1e-05, abs_tol: float = 1e-08, categorical_as_str: bool = False) None[source]#
Compare DataFrame to snapshot or update the snapshot.
If this is the first run and no snapshot exists, the snapshot will be created and the test will fail to alert the developer. If is_snapshot_update is True, the snapshot will be updated instead of compared.
- Parameters:
df_right – The DataFrame to compare against the snapshot
check_row_order – Whether to check that rows are in the same order
check_column_order – Whether to check that columns are in the same order
check_dtypes – Whether to check that data types match
check_exact – Whether to check exact equality for floating point values
rel_tol – Relative tolerance for floating point comparisons
abs_tol – Absolute tolerance for floating point comparisons
categorical_as_str – Whether to compare categorical columns as strings
- Raises:
FileNotFoundError – If snapshot doesn’t exist and is created for the first time
AssertionError – If the DataFrame doesn’t match the snapshot