How to use _datetime_strategy method in pandera

Best Python code snippet using pandera_python

strategies.py

Source:strategies.py Github

copy

Full Screen

...180MAX_DT_VALUE = 2**63 - 1181def _is_datetime_tz(pandera_dtype: DataType) -> bool:182 native_type = getattr(pandera_dtype, "type", None)183 return isinstance(native_type, pd.DatetimeTZDtype)184def _datetime_strategy(185 dtype: Union[np.dtype, pd.DatetimeTZDtype], strategy186) -> SearchStrategy:187 if isinstance(dtype, pd.DatetimeTZDtype):188 def _to_datetime(value) -> pd.DatetimeTZDtype:189 if isinstance(value, pd.Timestamp):190 return value.tz_convert(tz=dtype.tz) # type: ignore[union-attr]191 return pd.Timestamp(value, unit=dtype.unit, tz=dtype.tz) # type: ignore[union-attr]192 return st.builds(_to_datetime, strategy)193 else:194 res = (195 st.just(dtype.str.split("[")[-1][:-1])196 if "[" in dtype.str197 else st.sampled_from(npst.TIME_RESOLUTIONS)198 )199 return st.builds(dtype.type, strategy, res)200def numpy_time_dtypes(201 dtype: Union[np.dtype, pd.DatetimeTZDtype], min_value=None, max_value=None202):203 """Create numpy strategy for datetime and timedelta data types.204 :param dtype: numpy datetime or timedelta datatype205 :param min_value: minimum value of the datatype to create206 :param max_value: maximum value of the datatype to create207 :returns: ``hypothesis`` strategy208 """209 def _to_unix(value: Any) -> int:210 if dtype.type is np.timedelta64:211 return pd.Timedelta(value).value212 return pd.Timestamp(value).value213 min_value = MIN_DT_VALUE if min_value is None else _to_unix(min_value)214 max_value = MAX_DT_VALUE if max_value is None else _to_unix(max_value)215 return _datetime_strategy(dtype, st.integers(min_value, max_value))216def numpy_complex_dtypes(217 dtype,218 min_value: complex = complex(0, 0),219 max_value: Optional[complex] = None,220 allow_infinity: bool = None,221 allow_nan: bool = None,222):223 """Create numpy strategy for complex numbers.224 :param dtype: numpy complex number datatype225 :param min_value: minimum value, must be complex number226 :param max_value: maximum value, must be complex number227 :returns: ``hypothesis`` strategy228 """229 max_real: Optional[float]230 max_imag: Optional[float]231 if max_value:232 max_real = max_value.real233 max_imag = max_value.imag234 else:235 max_real = max_imag = None236 if dtype.itemsize == 8:237 width = 32238 else:239 width = 64240 # switch min and max values for imaginary if min value > max value241 if max_imag is not None and min_value.imag > max_imag:242 min_imag = max_imag243 max_imag = min_value.imag244 else:245 min_imag = min_value.imag246 strategy = st.builds(247 complex,248 st.floats(249 min_value=min_value.real,250 max_value=max_real,251 width=width,252 allow_infinity=allow_infinity,253 allow_nan=allow_nan,254 ),255 st.floats(256 min_value=min_imag,257 max_value=max_imag,258 width=width,259 allow_infinity=allow_infinity,260 allow_nan=allow_nan,261 ),262 ).map(dtype.type)263 @st.composite264 def build_complex(draw):265 value = draw(strategy)266 hypothesis.assume(min_value <= value)267 if max_value is not None:268 hypothesis.assume(max_value >= value)269 return value270 return build_complex()271def to_numpy_dtype(pandera_dtype: DataType):272 """Convert a :class:`~pandera.dtypes.DataType` to numpy dtype compatible273 with hypothesis."""274 try:275 np_dtype = pandas_engine.Engine.numpy_dtype(pandera_dtype)276 except TypeError as err:277 if is_datetime(pandera_dtype):278 return np.dtype("datetime64[ns]")279 raise TypeError(280 f"Data generation for the '{pandera_dtype}' data type is "281 "currently unsupported."282 ) from err283 if np_dtype == np.dtype("object") or str(pandera_dtype) == "str":284 np_dtype = np.dtype(str)285 return np_dtype286def pandas_dtype_strategy(287 pandera_dtype: DataType,288 strategy: Optional[SearchStrategy] = None,289 **kwargs,290) -> SearchStrategy:291 # pylint: disable=line-too-long,no-else-raise292 """Strategy to generate data from a :class:`pandera.dtypes.DataType`.293 :param pandera_dtype: :class:`pandera.dtypes.DataType` instance.294 :param strategy: an optional hypothesis strategy. If specified, the295 pandas dtype strategy will be chained onto this strategy.296 :kwargs: key-word arguments passed into297 `hypothesis.extra.numpy.from_dtype <https://hypothesis.readthedocs.io/en/latest/numpy.html#hypothesis.extra.numpy.from_dtype>`_ .298 For datetime, timedelta, and complex number datatypes, these arguments299 are passed into :func:`~pandera.strategies.numpy_time_dtypes` and300 :func:`~pandera.strategies.numpy_complex_dtypes`.301 :returns: ``hypothesis`` strategy302 """303 def compat_kwargs(*args):304 return {k: v for k, v in kwargs.items() if k in args}305 # hypothesis doesn't support categoricals or objects, so we'll will need to306 # build a pandera-specific solution.307 if is_category(pandera_dtype):308 raise TypeError(309 "data generation for the Category dtype is currently "310 "unsupported. Consider using a string or int dtype and "311 "Check.isin(values) to ensure a finite set of values."312 )313 np_dtype = to_numpy_dtype(pandera_dtype)314 if strategy:315 if _is_datetime_tz(pandera_dtype):316 return _datetime_strategy(pandera_dtype.type, strategy) # type: ignore317 return strategy.map(np_dtype.type)318 elif is_datetime(pandera_dtype) or is_timedelta(pandera_dtype):319 return numpy_time_dtypes(320 pandera_dtype.type if _is_datetime_tz(pandera_dtype) else np_dtype, # type: ignore321 **compat_kwargs("min_value", "max_value"),322 )323 elif is_complex(pandera_dtype):324 return numpy_complex_dtypes(325 np_dtype,326 **compat_kwargs(327 "min_value", "max_value", "allow_infinity", "allow_nan"328 ),329 )330 return npst.from_dtype(...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pandera automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful