当前位置: 首页>>代码示例>>Python>>正文


Python ast.Assert方法代码示例

本文整理汇总了Python中ast.Assert方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Assert方法的具体用法?Python ast.Assert怎么用?Python ast.Assert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.Assert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_attributes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,代码来源:test_ast.py

示例2: test_attributes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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) 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:21,代码来源:test_ast.py

示例3: onelinerize

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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) 
开发者ID:csvoss,项目名称:onelinerizer,代码行数:19,代码来源:onelinerizer.py

示例4: __build_unconditional_arg_check

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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 
开发者ID:fake-name,项目名称:ChromeController,代码行数:23,代码来源:gen.py

示例5: _check_sub_node

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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 
开发者ID:wemake-services,项目名称:wemake-python-styleguide,代码行数:21,代码来源:function.py

示例6: assert_ast_to_ir2

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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)) 
开发者ID:google,项目名称:tmppy,代码行数:33,代码来源:_ast_to_ir2.py

示例7: test_dont_rewrite

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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 
开发者ID:pytest-dev,项目名称:pytest,代码行数:8,代码来源:test_assertrewrite.py

示例8: test_assert

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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") 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:8,代码来源:test_ast.py

示例9: process_Assert

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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 
开发者ID:mila-iqia,项目名称:myia,代码行数:16,代码来源:parser.py

示例10: assert_linenos

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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 
开发者ID:alexmojaki,项目名称:executing,代码行数:10,代码来源:executing.py

示例11: p_assert_stmt_1

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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]) 
开发者ID:histogrammar,项目名称:histogrammar-python,代码行数:6,代码来源:hgawk_grammar.py

示例12: p_assert_stmt_2

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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 
开发者ID:histogrammar,项目名称:histogrammar-python,代码行数:8,代码来源:hgawk_grammar.py

示例13: __build_conditional_arg_check

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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 
开发者ID:fake-name,项目名称:ChromeController,代码行数:40,代码来源:gen.py

示例14: translate_assert

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
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] 
开发者ID:i2y,项目名称:mochi,代码行数:12,代码来源:translation.py

示例15: visit_Assert

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Assert [as 别名]
def visit_Assert(self, asr: ast.Assert, _ctx: CPSTransformerContext) -> VisitReturnT:
        return asr, [] 
开发者ID:NetSys,项目名称:kappa,代码行数:4,代码来源:cps.py


注:本文中的ast.Assert方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。