Best Python code snippet using ddt_python
test_functional.py
Source:test_functional.py  
...179        :param: None180        :return: None181        """182        pass183    def func_wo_doc():184        pass185    class Myint(int):186        pass187    class Mytest(object):188        pass189    d1 = Myint(1)190    d1.__name__ = 'case1'191    d1.__doc__ = """docstring1"""192    d2 = Myint(2)193    d2.__name__ = 'case2'194    data_hello = data(d1, d2, {'test': True})(func_w_doc)195    data_hello2 = data(d1, d2, {'test': True})(func_wo_doc)196    setattr(Mytest, 'first_test', data_hello)197    setattr(Mytest, 'second_test', data_hello2)...utils.py
Source:utils.py  
1import numpy as np2from . import ffi, lib3from .dtypes import _INDEX, lookup_dtype4def libget(name):5    """Helper to get items from GraphBLAS which might be GrB or GxB"""6    try:7        return getattr(lib, name)8    except AttributeError:9        ext_name = f"GxB_{name[4:]}"10        try:11            return getattr(lib, ext_name)12        except AttributeError:13            pass14        raise15def wrapdoc(func_with_doc):16    """Decorator to copy `__doc__` from a function onto the wrapped function"""17    def inner(func_wo_doc):18        func_wo_doc.__doc__ = func_with_doc.__doc__19        return func_wo_doc20    return inner21# Include most common types (even mistakes)22_output_types = {23    int: int,24    float: float,25    list: list,26    slice: slice,27    tuple: tuple,28    np.ndarray: np.ndarray,29    # Mistakes30    object: object,31    type: type,32}33_output_types.update((k, k) for k in np.cast)34def output_type(val):35    try:36        return _output_types[type(val)]37    except KeyError:38        return type(val)39def ints_to_numpy_buffer(array, dtype, *, name="array", copy=False, ownable=False, order="C"):40    if (41        isinstance(array, np.ndarray)42        and not np.issubdtype(array.dtype, np.integer)43        and not np.issubdtype(array.dtype, np.bool8)44    ):45        raise ValueError(f"{name} must be integers, not {array.dtype.name}")46    array = np.array(array, dtype, copy=copy, order=order)47    if ownable and (not array.flags.owndata or not array.flags.writeable):48        array = array.copy(order)49    return array50def _get_subdtype(dtype):51    while dtype.subdtype is not None:52        dtype = dtype.subdtype[0]53    return dtype54def values_to_numpy_buffer(array, dtype=None, *, copy=False, ownable=False, order="C"):55    if dtype is not None:56        dtype = lookup_dtype(dtype)57        array = np.array(array, _get_subdtype(dtype.np_type), copy=copy, order=order)58    else:59        is_input_np = isinstance(array, np.ndarray)60        array = np.array(array, copy=copy, order=order)61        if array.dtype.hasobject:62            raise ValueError("object dtype for values is not allowed")63        if not is_input_np and array.dtype == np.int32:  # pragma: no cover64            # fix for win64 numpy handling of ints65            array = array.astype(np.int64)66        dtype = lookup_dtype(array.dtype)67    if ownable and (not array.flags.owndata or not array.flags.writeable):68        array = array.copy(order)69    return array, dtype70def get_shape(nrows, ncols, dtype=None, **arrays):71    if nrows is None or ncols is None:72        # Get nrows and ncols from the first 2d array73        is_subarray = dtype.np_type.subdtype is not None74        for name, arr in arrays.items():75            if name == "values" and is_subarray:76                # We could be smarter and determine the shape of the dtype sub-arrays77                if arr.ndim >= 3:78                    break79            elif arr.ndim == 2:80                break81        else:82            raise ValueError(83                "Either nrows and ncols must be provided, or one of the following arrays"84                f'must be 2d (from which to get nrows and ncols): {", ".join(arrays)}'85            )86        if nrows is None:87            nrows = arr.shape[0]88        if ncols is None:89            ncols = arr.shape[1]90    return nrows, ncols91class class_property:92    __slots__ = "classval", "member_property"93    def __init__(self, member_property, classval):94        self.classval = classval95        self.member_property = member_property96    def __get__(self, obj, type=None):97        if obj is None:98            return self.classval99        return self.member_property.__get__(obj, type)100    @property101    def __set__(self):102        return self.member_property.__set__103# A similar object may eventually make it to the GraphBLAS spec.104# Hide this from the user for now.105class _CArray:106    __slots__ = "array", "_carg", "dtype", "_name"107    def __init__(self, array=None, dtype=_INDEX, *, size=None, name=None):108        if size is not None:109            self.array = np.empty(size, dtype=dtype.np_type)110        else:111            self.array = np.array(array, dtype=_get_subdtype(dtype.np_type), copy=False, order="C")112        c_type = dtype.c_type if dtype._is_udt else f"{dtype.c_type}*"113        self._carg = ffi.cast(c_type, ffi.from_buffer(self.array))114        self.dtype = dtype115        self._name = name116    @property117    def name(self):118        if self._name is not None:119            return self._name120        if len(self.array) < 20:121            values = ", ".join(map(str, self.array))122        else:123            values = (124                f"{', '.join(map(str, self.array[:5]))}, "125                "..., "126                f"{', '.join(map(str, self.array[-5:]))}"127            )128        return f"({self.dtype.c_type}[]){{{values}}}"129class _Pointer:130    __slots__ = "val"131    def __init__(self, val):132        self.val = val133    @property134    def _carg(self):135        return self.val.gb_obj136    @property137    def name(self):138        name = self.val.name139        if not name:140            c = type(self.val).__name__[0]141            name = f"{'M' if c == 'M' else c.lower()}_temp"142        return f"&{name}"143def _autogenerate_code(144    filename,145    text,146    specializer=None,147    begin="# Begin auto-generated code",148    end="# End auto-generated code",149):150    """Super low-tech auto-code generation used by _automethods.py and _infixmethods.py"""151    with open(filename) as f:152        orig_text = f.read()153    if specializer:154        begin = f"{begin}: {specializer}"155        end = f"{end}: {specializer}"156    begin += "\n"157    end += "\n"158    boundaries = []159    stop = 0160    while True:161        try:162            start = orig_text.index(begin, stop)163            stop = orig_text.index(end, start)164        except ValueError:165            break166        boundaries.append((start, stop))167    new_text = orig_text168    for start, stop in reversed(boundaries):169        new_text = f"{new_text[:start]}{begin}{text}{new_text[stop:]}"170    with open(filename, "w") as f:171        f.write(new_text)172    import subprocess...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
