Best Python code snippet using lemoncheesecake
compiler.py
Source:compiler.py  
...22_is_test_function = lambda u: _is_function(u) and not isinstance(u.space.kind, UndefinedSpaceType)23_is_field         = lambda u: _is_function(u) and     isinstance(u.space.kind, UndefinedSpaceType)24_is_proxy         = lambda u: _is_field(u) or isinstance(u, Tuple)25_is_op_test_function = lambda op: (isinstance(op, (Grad, Curl, Div)) and26                                   _is_test_function(op.args[0]))27#==============================================================================28def _decompose_lie_derivative(*args):29    #---------------------------------------30    # Try to extract Grad and Cross terms31    #---------------------------------------32    # ... 1 form33    grad_term  = [i for i in args if (isinstance(i, Grad) and34                                      isinstance(i._args[0], Dot))]35    # TODO improve36    cross_term = [i for i in args if (isinstance(i, Cross) and37                                      (isinstance(i._args[0], Curl) or38                                       isinstance(i._args[1], Curl)))]39    if grad_term and cross_term:40        others = [i for i in args if i not in (grad_term + cross_term)]41        return grad_term, cross_term, others42    #---------------------------------------43    # Try to extract Curl and Mul terms44    #---------------------------------------45    curl_term = []46    mul_term  = []47    others    = []48    for i in args:49        # ... 1 form50        if isinstance(i, Curl) and isinstance(i.args[0], Cross):51            curl_term.append(i)52        # Special case to handle anti-commutativity of Curl operator:53        # Mul(-1, Curl(Cross(a, b))) --> Curl(Cross(b, a))54        # TODO avoid this hack55        elif (isinstance(i, Mul) and len(i.args) == 2 and i.args[0] == -1 and56              isinstance(i.args[1], Curl) and57              isinstance(i.args[1].args[0], Cross)58              ):59            a, b = i.args[1].args[0].args60            new_cross = Cross(b, a, evaluate=False)61            new_curl  = Curl(new_cross)62            curl_term.append(new_curl)63        # TODO improve64        elif (isinstance(i, Mul) and (isinstance(i.args[0], Div) or65                                      isinstance(i.args[1], Div)) ):66            mul_term.append(i)67        else:68            others.append(i)69    if curl_term and mul_term:70        return curl_term, mul_term, others71    #---------------------------------------72    # Unsuccessful: return input arguments73    #---------------------------------------74    return [], [], args75#==============================================================================76class ExteriorCalculusExpr(CalculusFunction):77    def __new__(cls, *args, **options):78        # (Try to) sympify args first79        if options.pop('evaluate', True):80            r = cls.eval(*args, **options)81        else:82            r = None83        if r is None:84            return Basic.__new__(cls, *args, **options)85        else:86            return r87    def __getitem__(self, indices, **kw_args):88        if is_sequence(indices):89            # Special case needed because M[*my_tuple] is a syntax error.90            return Indexed(self, *indices, **kw_args)91        else:92            return Indexed(self, indices, **kw_args)93    @classmethod94    def eval(cls, *_args, **kwargs):95        """."""96        if not _args:97            return98        if not len(_args) == 1:99            raise ValueError('Expecting one argument')100        expr = _args[0]101        tests = kwargs.pop('tests', [])102        atoms = kwargs.pop('atoms', {})103        assert isinstance(atoms, dict)104        if _is_field(expr):105            return expr106        if isinstance(expr, (tuple, list, Tuple)):107            return expr108        if isinstance(expr, _coeffs_registery):109            return expr110        if _is_test_function(expr):111            name = expr.name112            dim  = expr.space.ldim113            kind = expr.space.kind114            if expr in atoms.keys():115                return atoms[expr]116            elif isinstance(kind, H1SpaceType):117                if not(expr in tests):118                    return DifferentialForm(name, index=0, dim=dim)119                else:120                    return DifferentialForm(name, index=3, dim=dim)121            elif isinstance(kind, HcurlSpaceType):122                if not(expr in tests):123                    return DifferentialForm(name, index=1, dim=dim)124                else:125                    return DifferentialForm(name, index=2, dim=dim)126            elif isinstance(kind, HdivSpaceType):127                if not(expr in tests):128                    return DifferentialForm(name, index=2, dim=dim)129                else:130                    return DifferentialForm(name, index=1, dim=dim)131            elif isinstance(kind, L2SpaceType):132                if not(expr in tests):133                    return DifferentialForm(name, index=3, dim=dim)134                else:135                    return DifferentialForm(name, index=0, dim=dim)136            else:137                msg = 'Cannot convert {} to differential form'.format(expr)138                raise TypeError(msg)139        if isinstance(expr, Grad):140            arg = expr._args[0]141            newarg = cls.eval(arg, tests=tests, atoms=atoms)142            if not(arg in tests):143                return d(newarg)144            else:145                return -delta(newarg)146        if isinstance(expr, Curl):147            arg = expr._args[0]148            newarg = cls.eval(arg, tests=tests, atoms=atoms)149            if not(arg in tests):150                return d(newarg)151            else:152                return delta(newarg)153        if isinstance(expr, Div):154            arg = expr._args[0]155            if isinstance(arg, Mul):156                if len(arg.args) == 2:157                    left, right = arg.args[:]158                    newleft = cls.eval(left, tests=tests, atoms=atoms)159                    newright = cls.eval(right, tests=tests, atoms=atoms)160                    if  _is_test_function(right) and _is_proxy(left):161                        return ld(newleft, newright)162                    elif  _is_test_function(left) and _is_proxy(right):163                        return ld(newright, newleft)164                else:165                    raise NotImplementedError('')166            newarg = cls.eval(arg, tests=tests, atoms=atoms)167            if not(arg in tests):168                return d(newarg)169            else:170                return -delta(newarg)171        if isinstance(expr, Dot):172            left, right = expr._args[:]173            newleft = cls.eval(left, tests=tests, atoms=atoms)174            newright = cls.eval(right, tests=tests, atoms=atoms)175            if _is_test_function(left) and _is_test_function(right):176                if left in tests:177                    return wedge(newright, hodge(newleft))178                elif right in tests:179                    return wedge(newleft, hodge(newright))180                else:181                    raise ValueError('argument not appears as a test function')182            elif _is_op_test_function(left) and _is_test_function(right):183                if left._args[0] in tests:184                    return wedge(newright, hodge(newleft))185                elif right in tests:186                    return wedge(newleft, hodge(newright))187                else:188                    raise ValueError('argument not appears as a test function')189            elif _is_test_function(left) and _is_op_test_function(right):190                return wedge(newleft, hodge(newright))191            elif _is_test_function(right):192                if not(right in tests):193                    return ip(newleft, newright)194                else:195                    return jp(newleft, newright)196            elif _is_test_function(left):197                raise NotImplementedError('')198            elif  _is_op_test_function(right) and _is_proxy(left):199                raise NotImplementedError('')200            elif  _is_op_test_function(left) and _is_proxy(right):201                if isinstance(left, Grad):202                    if left._args[0] in tests:203                        raise NotImplementedError('')204                    else:205                        return ld(newright, newleft._args[0])206                else:207                    raise NotImplementedError('')208            else:209                print(type(left))210                print(type(right))211                raise NotImplementedError('')212        if isinstance(expr, Cross):213            # TODO ORDER OF LEFT AND RIGHT DEPEND ON THE STR!!214            #      TO BE IMPROVED215            left, right = expr._args[:]216            if _is_test_function(right):217                dim = right.space.ldim218                if not(right in tests):219                    right = DifferentialForm(right.name, index=2, dim=dim)220                    return ip(left, right)221                else:222                    right = DifferentialForm(right.name, index=1, dim=dim)223                    return -jp(left, right)224            else:225                raise NotImplementedError('')226        if isinstance(expr, Inner):227            left, right = expr._args[:]228            if isinstance(left, Grad) and isinstance(right, Grad):229                if (_is_function(left._args[0]) and230                    _is_function(right._args[0])):231                    left  = left._args[0]232                    right = right._args[0]233                    newleft = cls.eval(left, tests=tests, atoms=atoms)234                    newright = cls.eval(right, tests=tests, atoms=atoms)235                    if left in tests:236                        expr  = wedge(d(newright), hodge(d(newleft)))237                        expr += wedge(d(delta(newright)), hodge(newleft))238                    elif right in tests:239                        expr  = wedge(d(newleft), hodge(d(newright)))240                        expr += wedge(d(delta(newleft)), hodge(newright))241                    else:242                        raise ValueError('either left/right must be a test function')243                    return expr244                else:245                    raise NotImplementedError('')246            else:247                raise NotImplementedError('')248        if isinstance(expr, Add):249            # looking for Lie derivative terms250            a, b, c = _decompose_lie_derivative(*expr.args)251            newargs = []252            for ai in a:253                for bi in b:254                    ai_tests = [i for i in ai.atoms() if _is_test_function(i)]255                    bi_tests = [i for i in bi.atoms() if _is_test_function(i)]256                    test = set(ai_tests) & set(bi_tests)257                    test = list(test)258                    if len(test) == 1:259                        test = test[0]260                        # to distinguish between lie deriv of 1 and 2 forms261                        if isinstance(ai, Grad) and isinstance(bi, Cross):262                            if isinstance(ai._args[0], Dot):263                                # TODO implement anti commutativity for264                                #      Cross265                                if (isinstance(bi._args[0], Curl) and266                                    (_is_field(bi._args[1]) or267                                     isinstance(bi._args[1], Tuple))):268                                    bi_test  = bi._args[0]._args[0]269                                    bi_proxy = bi._args[1]270                                    # grad(dot(,)) args271                                    ai_left,ai_right = ai._args[0]._args[:]272                                    if _is_test_function(ai_left):273                                        ai_proxy = ai_right274                                        ai_test  = ai_left275                                    elif _is_test_function(ai_right):276                                        ai_proxy = ai_left277                                        ai_test  = ai_right278                                    if ((ai_test == bi_test) and279                                        (ai_proxy == bi_proxy)):280                                        if not ai_test == test:281                                            raise NotImplementedError('')282                                        ai_proxy = cls.eval(ai_proxy, tests=tests, atoms=atoms)283                                        ai_test  = cls.eval(ai_test, tests=tests, atoms=atoms)284                                        newargs = [ld(ai_proxy, ai_test)]285                                else:286                                    raise NotImplementedError('')287                        # to distinguish between lie deriv of 1 and 2 forms288                        elif isinstance(ai, Curl) and isinstance(bi, Mul):289                            if isinstance(ai._args[0], Cross) and len(bi.args) == 2:290                                # TODO implement anti commutativity for291                                #      Cross292                                if (_is_test_function(bi._args[0]._args[0]) and293                                    (_is_field(bi._args[1]) or294                                     isinstance(bi._args[1], Tuple))):295                                    bi_test  = bi._args[0]._args[0]296                                    bi_proxy = bi._args[1]297                                    # grad(dot(,)) args298                                    ai_left,ai_right = ai._args[0]._args[:]299                                    if _is_test_function(ai_left):300                                        ai_proxy = ai_right301                                        ai_test  = ai_left302                                    elif _is_test_function(ai_right):303                                        ai_proxy = ai_left304                                        ai_test  = ai_right305                                    if ((ai_test == bi_test) and306                                        (ai_proxy == bi_proxy)):307                                        if not ai_test == test:308                                            raise NotImplementedError('')309                                        ai_proxy = cls.eval(ai_proxy, tests=tests, atoms=atoms)310                                        ai_test  = cls.eval(ai_test, tests=tests, atoms=atoms)311                                        newargs = [ld(ai_proxy, ai_test)]312                                else:313                                    raise NotImplementedError('')314                    elif len(test) > 1:315                        raise ValueError('wrong expression')316            args = [cls.eval(i, tests=tests, atoms=atoms) for i in c] + newargs317            return Add(*args)318        if isinstance(expr, Mul):319            coeffs  = [a for a in expr.args if isinstance(a, _coeffs_registery)]320            vectors = [a for a in expr.args if not(a in coeffs)]321            alpha = S.One322            if coeffs:323                alpha = Mul(*coeffs)324            if len(vectors) == 2:325                left, right = vectors326                newleft = cls.eval(left, tests=tests, atoms=atoms)327                newright = cls.eval(right, tests=tests, atoms=atoms)328                if _is_test_function(left) and _is_test_function(right):329                    if left in tests:330                        return alpha*wedge(newright, hodge(newleft))331                    elif right in tests:332                        return alpha*wedge(newleft, hodge(newright))333                    else:334                        raise ValueError('argument not appears as a test function')335                elif _is_op_test_function(left) and _is_test_function(right):336                    if left._args[0] in tests:337                        return alpha*wedge(newright, hodge(newleft))338                    elif right in tests:339                        return alpha*wedge(newleft, hodge(newright))340                    else:341                        raise ValueError('argument not appears as a test function')342                elif _is_test_function(left) and _is_op_test_function(right):343                    if right._args[0] in tests:344                        return alpha*wedge(newleft, hodge(newright))345                    elif left in tests:346                        return alpha*wedge(newright, hodge(newleft))347                    else:348                        raise ValueError('argument not appears as a test function')349                else:350                    convert = False351                    if isinstance(vectors[0], ScalarFunction):352                        left  = vectors[1]353                        right = vectors[0]354                        convert = True355                    elif isinstance(vectors[1], ScalarFunction):356                        left  = vectors[0]...discovery.py
Source:discovery.py  
...24    ]25    test_defined_in_module = filter(_defined_in_module(module_name), tests)26    return sorted(test_defined_in_module, key=_definition_line)27def _is_test_function_or_test_class(obj: Any) -> bool:28    return _is_test_function(obj) or _is_test_class(obj)29def _is_test_function(obj: Any) -> bool:30    if not inspect.isfunction(obj):31        return False32    if not obj.__name__.startswith("test_"):33        return False34    sig = inspect.signature(obj)35    if len(sig.parameters) != 1:36        return False37    test_context_param = list(sig.parameters.values())[0]38    return test_context_param.annotation == TestContext39def _is_test_class(obj: Any) -> bool:40    return inspect.isclass(obj) and obj.__name__.startswith("Test") and _has_test_method(obj)41def _has_test_method(obj: type) -> bool:42    # Use isfunction instead of ismethod because the functions defined on the class only become43    # "methods" when you access them on an instance of the class and they get bound to that...base.py
Source:base.py  
...21        )22    def _is_test_file(self, filename: str) -> bool:23        stem = get_stem(self.filename)24        return stem.startswith('test_')25    def _is_test_function(self, node: ast.AST) -> bool:26        return isinstance(node, ast.FunctionDef) and node.name.startswith('test_')27    def _should_check_node(self, node: ast.AST) -> bool:...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!!
