How to use py_scanstring method in autotest

Best Python code snippet using autotest_python

json_util.py

Source:json_util.py Github

copy

Full Screen

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)...

Full Screen

Full Screen

test_scanstring.py

Source:test_scanstring.py Github

copy

Full Screen

...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):...

Full Screen

Full Screen

timer.py

Source:timer.py Github

copy

Full Screen

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)...

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 autotest 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