How to use collected_errors method in pandera

Best Python code snippet using pandera_python

restricted.py

Source:restricted.py Github

copy

Full Screen

1from .restricted_builtins import safe_builtins2from collections import namedtuple3from .transformer import RestrictingNodeTransformer4from .exceptions import CompileError5import ast6import warnings7CompileResult = namedtuple(8 'CompileResult', 'code, errors, warnings, used_names')9syntax_error_template = (10 'Line {lineno}: {type}: {msg} at statement: {statement!r}')11def _compile_restricted_mode(12 source,13 filename='<string>',14 mode="exec",15 flags=0,16 dont_inherit=False,17 policy=RestrictingNodeTransformer):18 byte_code = None19 collected_errors = []20 collected_warnings = []21 used_names = {}22 if policy is None:23 # Unrestricted Source Checks24 byte_code = compile(source, filename, mode=mode, flags=flags,25 dont_inherit=dont_inherit)26 elif issubclass(policy, RestrictingNodeTransformer):27 c_ast = None28 allowed_source_types = [str, ast.Module]29 if not issubclass(type(source), tuple(allowed_source_types)):30 raise TypeError('Not allowed source type: '31 '"{0.__class__.__name__}".'.format(source))32 c_ast = None33 # workaround for pypy issue https://bitbucket.org/pypy/pypy/issues/255234 if isinstance(source, ast.Module):35 c_ast = source36 else:37 try:38 c_ast = ast.parse(source, filename, mode)39 except (TypeError, ValueError) as e:40 collected_errors.append(str(e))41 except SyntaxError as v:42 collected_errors.append(syntax_error_template.format(43 lineno=v.lineno,44 type=v.__class__.__name__,45 msg=v.msg,46 statement=v.text.strip() if v.text else None47 ))48 if c_ast:49 policy_instance = policy(50 collected_errors, collected_warnings, used_names)51 policy_instance.visit(c_ast)52 if not collected_errors:53 byte_code = compile(c_ast, filename, mode=mode # ,54 # flags=flags,55 # dont_inherit=dont_inherit56 )57 else:58 raise TypeError('Unallowed policy provided for RestrictedPython')59 return CompileResult(60 byte_code,61 tuple(collected_errors),62 collected_warnings,63 used_names)64def compile_restricted_exec(65 source,66 filename='<string>',67 flags=0,68 dont_inherit=False,69 policy=RestrictingNodeTransformer):70 """Compile restricted for the mode `exec`."""71 return _compile_restricted_mode(72 source,73 filename=filename,74 mode='exec',75 flags=flags,76 dont_inherit=dont_inherit,77 policy=policy)78def compile_restricted_eval(79 source,80 filename='<string>',81 flags=0,82 dont_inherit=False,83 policy=RestrictingNodeTransformer):84 """Compile restricted for the mode `eval`."""85 return _compile_restricted_mode(86 source,87 filename=filename,88 mode='eval',89 flags=flags,90 dont_inherit=dont_inherit,91 policy=policy)92class RestrictedPython:93 def eval(self, source, restricted_globals=None):94 if restricted_globals is None:95 restricted_globals = {}96 if '__builtins__' not in restricted_globals:97 restricted_globals['__builtins__'] = safe_builtins.copy()98 result = compile_restricted_eval(source)99 if result.errors:100 raise CompileError(result.errors[0])101 assert result.code is not None102 return eval(result.code, restricted_globals)103 def exec(self, source, restricted_globals=None):104 if restricted_globals is None:105 restricted_globals = {}106 if '__builtins__' not in restricted_globals:107 restricted_globals['__builtins__'] = safe_builtins.copy()108 result = compile_restricted_exec(source)109 assert result.errors == (), result.errors110 assert result.code is not None111 return exec(result.code, restricted_globals)112restrictedpy = RestrictedPython()113class RestrictedExpression(object):114 """A base class for restricted code."""115 nltosp = str.maketrans('\r\n', ' ')116 expr_globals = {'__builtins__': None}117 # No restrictions.118 default_guarded_getattr = getattr119 @staticmethod120 def default_guarded_getitem(ob, index):121 # No restrictions.122 return ob[index]123 @staticmethod124 def default_guarded_getiter(ob):125 # No restrictions.126 return ob127 def init_expr(self, expr):128 """Create a restricted expression129 where:130 expr -- a string containing the expression to be evaluated.131 """132 expr = expr.strip()133 self.__name__ = expr134 expr = expr.translate(self.nltosp)135 return expr136 def compile_expr(self, expr):137 result = compile_restricted_eval(expr, '<string>')138 if result.errors:139 raise SyntaxError(result.errors[0])140 used = tuple(result.used_names)141 return result.code, used142 def eval(self, expr, mapping={}):143 # This default implementation is probably not very useful. :-(144 # This is meant to be overridden.145 expr = self.init_expr(expr)146 rcode, used = self.compile_expr(expr)147 global_scope = {148 '_getattr_': RestrictedExpression.default_guarded_getattr,149 '_getitem_': RestrictedExpression.default_guarded_getitem,150 '_getiter_': RestrictedExpression.default_guarded_getiter,151 }152 global_scope.update(self.expr_globals)153 for name in used:154 if (name not in global_scope) and (name in mapping):155 global_scope[name] = mapping[name]156 return eval(rcode, global_scope)...

Full Screen

Full Screen

check-aws-credentials.py

Source:check-aws-credentials.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3# Import Python libs4import json5import argparse6def check_for_credentials(data, disallowed_keys_with_values):7 errors = set()8 for key, value in data.items():9 if key in disallowed_keys_with_values and value:10 errors.add(key)11 if isinstance(value, dict):12 for error in check_for_credentials(value, disallowed_keys_with_values):13 errors.add(error)14 return errors15def main():16 parser = argparse.ArgumentParser()17 parser.add_argument(18 '-k', '--key',19 dest='keys',20 metavar='KEY',21 action='append',22 default=[23 'aws_access_key',24 'aws_secret_key'25 ]26 )27 parser.add_argument('files', nargs='+')28 args = parser.parse_args()29 if not args.files:30 parser.exit('No files were passed in')31 collected_errors = {}32 for fname in args.files:33 try:34 with open(fname) as rfh:35 data = json.loads(rfh.read())36 except ValueError:37 parser.exit('Failed to JSON load {}'.format(fname))38 errors = check_for_credentials(data, args.keys)39 if errors:40 collected_errors[fname] = errors41 if collected_errors:42 for fname, errors in collected_errors.items():43 print('Found a populated secret key value in {}:'.format(fname))44 for error in errors:45 print(' - {}'.format(error))46 parser.exit(1)47if __name__ == "__main__":...

Full Screen

Full Screen

ex_02.py

Source:ex_02.py Github

copy

Full Screen

1# Utwórz dowolną krotkę zawierającą kilka wartości np. 10.2# Pozwól użytkownikowi podać dowolny index oraz wartość.3# Spróbuj w krotce podmienić wartość na zadanym indeksie. Obsłuż błąd.4items = (1, 0, 'a', 'b', 'test', 4, 6, 7, ['x', 'y'])5collected_errors = []6try:7 index = int(input('Give index number: '))8except ValueError as e:9 result = 010 collected_errors.append(e)11try:12 value = input('Give index value: ')13except ValueError as e:14 result = 015 collected_errors.append(e)16try:17 items[index] = value18except (TypeError, NameError) as e:19 result = 120 collected_errors.append(e)21print(result)22for err in collected_errors:...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pandera automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful