當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。