Python ast.Assert() Examples

The following are 21 code examples of ast.Assert(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: test_ast.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_attributes(self):
        # assert True, "bad"
        assert0 = ast.Assert()
        self.assertFalse(hasattr(assert0, 'lineno'))
        self.assertFalse(hasattr(assert0, 'col_offset'))
        assert1 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'))
        self.assertFalse(hasattr(assert1, 'lineno'))
        self.assertFalse(hasattr(assert1, 'col_offset'))
        try:
            tmp=assert1.lineno
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        try:
            tmp=assert1.col_offset
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        assert2 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'),2,3)
        self.assertEqual(assert2.lineno,2)
        self.assertEqual(assert2.col_offset,3) 
Example #2
Source File: function.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def _check_sub_node(
        self,
        node: AnyFunctionDef,
        sub_node: ast.AST,
    ) -> None:
        if isinstance(sub_node, ast.Name):
            if isinstance(sub_node.ctx, ast.Store):
                self._update_variables(node, sub_node)

        error_counters: _NodeTypeHandler = {
            ast.Return: self.returns,
            ast.Expr: self.expressions,
            ast.Await: self.awaits,
            ast.Assert: self.asserts,
        }

        for types, counter in error_counters.items():
            if isinstance(sub_node, types):
                counter[node] += 1 
Example #3
Source File: test_ast.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_attributes(self):
        # assert True, "bad"
        assert0 = ast.Assert()
        self.assertFalse(hasattr(assert0, 'lineno'))
        self.assertFalse(hasattr(assert0, 'col_offset'))
        assert1 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'))
        self.assertFalse(hasattr(assert1, 'lineno'))
        self.assertFalse(hasattr(assert1, 'col_offset'))
        try:
            tmp=assert1.lineno
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        try:
            tmp=assert1.col_offset
        except Exception as e:
            self.assertTrue(isinstance(e,AttributeError))
        assert2 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'), lineno=2, col_offset=3)
        self.assertEqual(assert2.lineno,2)
        self.assertEqual(assert2.col_offset,3) 
Example #4
Source File: gen.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __build_unconditional_arg_check(self, argname, argtype):

		presence_check = ast.Call(func = ast.Name(id='isinstance', ctx=ast.Load()),
				args         = [ast.Name(id=argname, ctx=ast.Load()), argtype],
				keywords     = [],
				lineno       = self.__get_line())

		types = [t.id for t in argtype.elts]
		check_message = ast.BinOp(
				left         = ast.Str(s='Argument \'{}\' must be of type \'{}\'. Received type: \'%s\''.format(argname, types)),
				op           = ast.Mod(),
				right        = ast.Call(func=ast.Name(id='type', ctx=ast.Load()), args=[ast.Name(id=argname, ctx=ast.Load())], keywords=[]),
				lineno       = self.__get_line())

		new_ret = ast.Assert(
			test         = presence_check,
			msg          = check_message,
			lineno       = self.__get_line())


		return new_ret 
Example #5
Source File: onelinerizer.py    From onelinerizer with MIT License 6 votes vote down vote up
def onelinerize(original):
    # original :: string
    # :: string
    t = ast.parse(original)
    table = symtable.symtable(original, '<string>', 'exec')

    original = original.strip()

    # If there's only one line anyways, be lazy
    if len(original.splitlines()) == 1 and \
       len(t.body) == 1 and \
       type(t.body[0]) in (ast.Delete, ast.Assign, ast.AugAssign, ast.Print,
                           ast.Raise, ast.Assert, ast.Import, ast.ImportFrom,
                           ast.Exec, ast.Global, ast.Expr, ast.Pass):
        return original

    return get_init_code(t, table) 
Example #6
Source File: py_converter.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def visit_match(self, match: Expr):
        """For matches, we wrap the entire expression in a thunk
        because it is easiest to implement them using if statements.
        For each clause, we generate a function that checks if the
        pattern matches. If yes, we call a function that assigns
        the variables appropriately and invokes the clause body."""
        data, defs = self.visit(match.data)
        data_var = self.generate_var_name('_match_data')

        # must ensure the data clause is executed exactly once
        thunk_body = [Assign([Name(data_var, Store())], data)]
        for clause in match.clauses:
            check_expr = self.create_match_check(clause.lhs, Name(data_var, Load()))
            body_def, body_name = self.create_match_clause_body(clause.lhs, clause.rhs)
            defs.append(body_def)

            # equiv: if check(data): return body(data)
            thunk_body.append(ast.If(
                check_expr,
                [Return(self.create_call(body_name, [Name(data_var, Load())]))],
                []
            ))

        # finally if nothing matches we have a failed assert (should never happen)
        thunk_body.append(ast.Assert(NameConstant(False), Str('Match was not exhaustive')))

        thunk_name = self.generate_function_name('_match_thunk')
        thunk_def = self.create_def(thunk_name, [], defs + thunk_body)
        return (self.create_call(thunk_name, []), [thunk_def])


    # these are both handled in the "call" case 
Example #7
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 5 votes vote down vote up
def assert_ast_to_ir2(ast_node: ast.Assert, compilation_context: CompilationContext, next_stmt_line: int):
    expr = expression_ast_to_ir2(ast_node.test,
                                 compilation_context,
                                 in_match_pattern=False,
                                 check_var_reference=lambda ast_node: None,
                                 match_lambda_argument_names=set(),
                                 current_stmt_line=ast_node.lineno)

    if not isinstance(expr.expr_type, ir2.BoolType):
        raise CompilationError(compilation_context, ast_node.test,
                               'The value passed to assert must have type bool, but got a value with type %s.' % expr.expr_type)

    if ast_node.msg:
        assert isinstance(ast_node.msg, ast.Str)
        message = ast_node.msg.s
    else:
        message = ''

    first_line_number = ast_node.lineno
    message = 'TMPPy assertion failed: {message}\n{filename}:{first_line_number}: {line}'.format(
        filename=compilation_context.filename,
        first_line_number=first_line_number,
        message=message,
        line=compilation_context.source_lines[first_line_number - 1])
    message = message.replace('\\', '\\\\').replace('"', '\"').replace('\n', '\\n')

    return ir2.Assert(expr=expr,
                      message=message,
                      source_branch=SourceBranch(compilation_context.filename,
                                                 ast_node.lineno,
                                                 next_stmt_line)) 
Example #8
Source File: keywords.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def visit_Assert(self, node: ast.Assert) -> None:
        """
        Visits ``assert`` keyword and tests that condition is correct.

        Raises:
            WrongKeywordConditionViolation

        """
        self._check_condition(node, node.test)
        self.generic_visit(node) 
Example #9
Source File: liveness.py    From kappa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_Assert(self, asr: ast.Assert) -> None:
        self.visit_simple_stmt(asr) 
Example #10
Source File: flatten.py    From kappa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_Assert(self, asr: ast.Assert) -> ActionsT:
        test, test_actions = self.visit_expr(asr.test)
        msg_actions: ActionsT
        if asr.msg is None:
            msg, msg_actions = None, []
        else:
            msg, msg_actions = self.visit_expr(asr.msg)
        result_node = ast.Assert(test=test, msg=msg)
        return test_actions + msg_actions + [result_node] 
Example #11
Source File: cps.py    From kappa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_Assert(self, asr: ast.Assert, _ctx: CPSTransformerContext) -> VisitReturnT:
        return asr, [] 
Example #12
Source File: translation.py    From mochi with MIT License 5 votes vote down vote up
def translate_assert(self, exp):
        if len(exp) != 2:
            raise MochiSyntaxError(exp, self.filename)
        assert_symbol, value_exp = exp
        pre, value = self.translate(value_exp, False)
        pre.append(ast.Assert(test=value,
                              msg=None,
                              lineno=assert_symbol.lineno,
                              col_offset=assert_symbol.col_offset))
        return pre, self.translate(NONE_SYM, False)[1] 
Example #13
Source File: gen.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __build_conditional_arg_check(self, argname, argtype):

		target_value = ast.Subscript(
							value=ast.Name(id='kwargs', ctx=ast.Load()),
							slice=ast.Index(ast.Str(s=argname)),
							ctx=ast.Load()
							)

		presence_check = ast.Call(func = ast.Name(id='isinstance', ctx=ast.Load()),
				args         = [target_value, argtype],
				keywords     = [],
				lineno       = self.__get_line())

		# Assumes that argtype is a ast.Tuple of ast.Name items
		types = [t.id for t in argtype.elts]

		check_message = ast.BinOp(
				left         = ast.Str(s='Optional argument \'{}\' must be of type \'{}\'. Received type: \'%s\''.format(argname, types)),
				op           = ast.Mod(),
				right        = ast.Call(func=ast.Name(id='type', ctx=ast.Load()), args=[target_value], keywords=[]),
				lineno       = self.__get_line())

		assert_check = ast.Assert(
			test         = presence_check,
			msg          = check_message,
			lineno       = self.__get_line())

		check_body = [assert_check]

		check = ast.Compare(left=ast.Str(s=argname, ctx=ast.Load()), ops=[ast.In()], comparators=[ast.Name(id='kwargs', ctx=ast.Load())])

		new_ret = ast.If(
			test   = check,
			body   = check_body,
			orelse = [],
			lineno = self.__get_line())

		return new_ret 
Example #14
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_assert(self):
        self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
                  "must have Load context")
        assrt = ast.Assert(ast.Name("x", ast.Load()),
                           ast.Name("y", ast.Store()))
        self.stmt(assrt, "must have Load context") 
Example #15
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_assert_stmt_2(p):
    '''assert_stmt : ASSERT test COMMA test'''
    #                     1    2     3    4
    p[0] = ast.Assert(p[2], p[4], rule=inspect.currentframe().f_code.co_name, **p[1][1])

# compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated 
Example #16
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_assert_stmt_1(p):
    '''assert_stmt : ASSERT test'''
    #                     1    2
    p[0] = ast.Assert(p[2], None, rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #17
Source File: executing.py    From executing with MIT License 5 votes vote down vote up
def assert_linenos(tree):
    for node in ast.walk(tree):
        if (
                hasattr(node, 'parent') and
                hasattr(node, 'lineno') and
                isinstance(statement_containing_node(node), ast.Assert)
        ):
            yield node.lineno 
Example #18
Source File: parser.py    From myia with MIT License 5 votes vote down vote up
def process_Assert(self, block: "Block", node: ast.Assert) -> "Block":
        """Process an assert statement."""
        cond = self.process_node(block, node.test)
        msg = (
            self.process_node(block, node.msg)
            if node.msg
            else Constant("Assertion failed")
        )
        true_block, false_block = self.make_condition_blocks(block)
        block.cond(cond, true_block, false_block)
        false_block.raises(
            false_block.apply(false_block.operation("Exception"), msg)
        )
        return true_block 
Example #19
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_assert(self):
        self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
                  "must have Load context")
        assrt = ast.Assert(ast.Name("x", ast.Load()),
                           ast.Name("y", ast.Store()))
        self.stmt(assrt, "must have Load context") 
Example #20
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_assert(self):
        self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
                  "must have Load context")
        assrt = ast.Assert(ast.Name("x", ast.Load()),
                           ast.Name("y", ast.Store()))
        self.stmt(assrt, "must have Load context") 
Example #21
Source File: test_assertrewrite.py    From pytest with MIT License 5 votes vote down vote up
def test_dont_rewrite(self) -> None:
        s = """'PYTEST_DONT_REWRITE'\nassert 14"""
        m = rewrite(s)
        assert len(m.body) == 2
        assert isinstance(m.body[1], ast.Assert)
        assert m.body[1].msg is None