Best Python code snippet using autotest_python
json_util.py
Source:json_util.py
1# coding=utf82import re3import json.decoder4from collections import namedtuple5from json.decoder import JSONDecoder6from json.scanner import py_make_scanner7from json.decoder import py_scanstring8class JSONDecodeError(object):9 def __init__(self, parser, message):10 self.message = message11 self.parser = parser12 def __eq__(self, err):13 return err.parser == self.parser and self.message in err.message14class errors(object):15 StringInvalidUXXXXEscape = JSONDecodeError("py_scanstring", "Invalid \\uXXXX escape")16 # 2 different case17 StringUnterminatedString = JSONDecodeError("py_scanstring", "Unterminated string starting at")18 StringInvalidControlCharacter = JSONDecodeError("py_scanstring", "Invalid control character")19 StringInvalidEscape = JSONDecodeError("py_scanstring", "Invalid \\escape")20 ObjectExceptColon = JSONDecodeError("JSONObject", "Expecting ':' delimiter")21 ObjectExceptObject = JSONDecodeError("JSONObject", "Expecting object")22 # 2 different case23 ObjectExceptKey = JSONDecodeError("JSONObject", "Expecting property name enclosed in double quotes")24 ObjectExceptComma = JSONDecodeError("JSONObject", "Expecting ',' delimiter")25 ArrayExceptObject = JSONDecodeError("JSONArray", "Expecting object")26 ArrayExceptComma = JSONDecodeError("JSONArray", "Expecting ',' delimiter")27 @classmethod28 def get_decode_error(cls, parser, message):29 err = JSONDecodeError(parser, message)30 for _, value in cls.__dict__.items():31 if isinstance(value, JSONDecodeError):32 if err == value:33 return value34 return None35 """36 01 å
ä¸ç,ä¸ç 究37 02 badcase: " --> "" success38 03 æ§å¶ç¬¦ pass39 04 unicode \\u ç pass40 05 åä¸41 06 object åé¢æ²¡æè·é " , badcase: {abc":1} --> {"abc":1}42 07 object key åé¢æ²¡æ : , badcase: {"abc"1} --> {"abc":1}43 08 object å¼å§æ£æµ Value æ¶å° StopIteration44 08.1 è¦ä¹åé¢æ²¡æäº45 08.2 è¦ä¹åé¢ä¸æ¯ "/{/[/n[ull]/t[rue]/f[alse]/number/NaN/Infinity/-Infinity å¼å¤´çä¸è¥¿46 -- 08.1 åé¢è¡¥ä¸ null}47 -- 08.2 æ èè¡¥ä¸ä¸ª "48 09 object 解æå®ä¸ä¸ª pair å,ä¸ä¸ä¸ªä¸æ¯}, æå¾
ä¸ä¸ª ','49 badcase {"k":1"s":2}50 10 å¨ 09 çåºç¡ä¸è§£æå®{"k":1, åç°ä¸ä¸ä¸ªä¸æ¯ ", è¿ä¸ªåé¢åä¼å(ææ¶å 06 ä¸è´)51 badcase {"k":1,x":2}52 11 array å¼å§æ£æµ Value æ¶å° StopIteration53 11.1 è¦ä¹åé¢æ²¡æäº,è¡¥ä¸]54 11.2 å 08.2,æ èè¡¥ä¸ä¸ª{ çç55 12 array 解æå®åä¸ä¸ª object, éè¦ä¸ä¸ª ,56 è¿é nextchar æ¢ä¸æ¯ ] ä¹ä¸æ¯, 代表è¿ä¸ª nextchar ç end ä¹å·²ç»+1 äºï¼æ以å 257 """58def errmsg_inv(e):59 assert isinstance(e, ValueError)60 message = e.message61 idx = message.rindex(':')62 errmsg, left = message[:idx], message[idx + 1:]63 numbers = re.compile(r'\d+').findall(left)64 parser = e.__dict__.get("parser", "")65 result = {66 "parsers": e.__dict__.get("parsers", []),67 "error": errors.get_decode_error(parser, errmsg),68 "lineno": int(numbers[0]),69 "colno": int(numbers[1]),70 }71 if len(numbers) == 3:72 result["pos"] = int(numbers[2])73 if len(numbers) > 3:74 result["endlineno"] = int(numbers[2])75 result["endcolno"] = int(numbers[3])76 result["pos"] = int(numbers[4])77 result["end"] = int(numbers[5])78 return result79def record_parser_name(parser):80 def new_parser(*args, **kwargs):81 try:82 return parser(*args, **kwargs)83 except Exception as e:84 if "parser" not in e.__dict__:85 e.__dict__["parser"] = parser.__name__86 if "parsers" not in e.__dict__:87 e.__dict__["parsers"] = []88 e.__dict__["parsers"].append(parser.__name__)89 raise e90 return new_parser91def make_decoder():92 json.decoder.scanstring = record_parser_name(py_scanstring)93 decoder = JSONDecoder()94 decoder.parse_object = record_parser_name(decoder.parse_object)95 decoder.parse_array = record_parser_name(decoder.parse_array)96 decoder.parse_string = record_parser_name(py_scanstring)97 decoder.parse_object = record_parser_name(decoder.parse_object)98 decoder.scan_once = py_make_scanner(decoder)99 return decoder100decoder = make_decoder()101DecodeResult = namedtuple('DecodeResult', ['success', 'exception', 'err_info'])102def decode_line(line):103 try:104 obj, end = decoder.scan_once(line, 0)105 ok = end == len(line)106 return DecodeResult(success=ok, exception=None, err_info=(obj, end))107 except StopIteration as e:108 return DecodeResult(success=False, exception=e, err_info=None)109 except ValueError as e:110 err_info = errmsg_inv(e)...
test_scanstring.py
Source:test_scanstring.py
...111 scanstring(s, 1, True)112 def test_overflow(self):113 import sys114 with self.assertRaises(OverflowError):115 self.kim_edn.decoder.py_scanstring(b"xxx", sys.maxsize + 1)116class TestPyScanstring(TestScanstring, PyTest):...
timer.py
Source:timer.py
1import time2from parser import Parser3p = Parser()4def timer(f):5 def wrapper(*args, **kwargs):6 start = time.time()7 result = f(*args, **kwargs)8 print(time.time() - start)9 return result10 return wrapper11def parse_x_times(string, x):12 for _ in range(x):13 p.parse(string)14parse_x_times = timer(parse_x_times)15string = """16 [17 {18 "precision": "zip",19 "Latitude": 37.7668,20 "Longitude": -122.3959,21 "Address": "",22 "City": "SAN FRANCISCO",23 "State": "CA",24 "Zip": "94107",25 "Country": "US"26 },27 {28 "precision": "zip",29 "Latitude": 37.371991,30 "Longitude": -122.026020,31 "Address": "",32 "City": "SUNNYVALE",33 "State": "CA",34 "Zip": "94085",35 "Country": "US"36 }37 ]38"""39import json40def load_x_times(string, x):41 for _ in range(x):42 json.loads(string)43load_x_times = timer(load_x_times)44import cProfile45cProfile.run('parse_x_times(string, 10000)')46from json.scanner import py_make_scanner47from json.decoder import py_scanstring48from json import decoder49decoder.scanstring = py_scanstring50dec = decoder.JSONDecoder()51dec.parse_string = py_scanstring52dec.scan_once = py_make_scanner(dec)53@timer54def decode_x_times(string, x):55 for _ in range(x):56 dec.decode(string)...
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!!