Best Python code snippet using hypothesis
checker.py
Source:checker.py
...24def print_to_stderr(*objs):25 print(*objs, file=stderr)26def get_stack():27 return "stack=(" + ", ".join("{}:{}".format(frame.name, frame.lineno) for frame in traceback.extract_stack()) + ")"28def exit_with(code, message, print_traceback=False):29 print_to_stderr(message)30 print_to_stderr(get_stack())31 if print_traceback:32 traceback.print_exc()33 exit(code)34def info():35 print("vulns: 1:1")36 exit(OK)37def get_data_from_cookies(cookies):38 uid = None39 secret = None40 for cookie in cookies:41 if cookie.name == "uid":42 try:43 uid = int(cookie.value)44 except ValueError:45 exit_with(MUMBLE, "invalid uid from cookie: '{}'".format(cookie.value))46 elif cookie.name == "secret":47 secret = cookie.value48 if uid is None or secret is None:49 exit_with(MUMBLE, "uid or secret is None")50 return uid, secret51def register(hostport, password):52 url = REGISTER_URL.format(hostport=hostport)53 r = requests.post(54 url,55 json={"password": password},56 headers=generate_headers(),57 timeout=TIMEOUT,58 )59 r.raise_for_status()60 return r.cookies61def login(hostport, password, uid):62 url = LOGIN_URL.format(hostport=hostport)63 r = requests.post(64 url,65 json={"userId": uid, "password": password},66 headers=generate_headers(),67 timeout=TIMEOUT,68 )69 r.raise_for_status()70 return r.cookies71def run_task(hostport: str, cookies: CookieJar, source: str, stdin: bytes, token: str):72 url = RUN_TASK_URL.format(hostport=hostport)73 r = requests.post(74 url,75 cookies=cookies,76 json={77 "source": source,78 "stdinb64": b64encode(stdin).decode(),79 "token": token,80 },81 headers=generate_headers(),82 timeout=TIMEOUT,83 )84 r.raise_for_status()85 data = json.loads(r.content)86 if "taskId" not in data:87 exit_with(MUMBLE, "run task response has not taskId: {}".format(data))88 task_id = data["taskId"]89 if not isinstance(task_id, int):90 exit_with(MUMBLE, "task id is not int: ({}, {})".format(task_id, type(task_id)))91 return task_id92def get_task_info(hostport, cookies, task_id, token):93 url = TASK_INFO_URL.format(hostport=hostport, task_id=task_id, token=token)94 r = requests.get(95 url,96 cookies=cookies,97 headers=generate_headers(),98 timeout=TIMEOUT,99 )100 r.raise_for_status()101 data = json.loads(r.content)102 if "Stdoutb64" not in data or "Status" not in data or "Error" not in data:103 exit_with(MUMBLE, "task info response has no required field(s): {}".format(data))104 stdoutb64 = data["Stdoutb64"]105 stdout = b64decode(stdoutb64)106 status = data["Status"]107 error = data["Error"]108 if not isinstance(stdout, bytes) or not isinstance(status, int) or not isinstance(error, str):109 exit_with(MUMBLE, "at least field in task info response has wrong type: {}".format(data))110 return stdout, status, error111def check_with_task(hostname, task_func):112 hostport = get_hostport(hostname)113 password = generate_string(5)114 token = generate_string(5)115 cookies = register(hostport, password)116 uid, _ = get_data_from_cookies(cookies)117 another_cookies = login(hostport, password, uid)118 if another_cookies != cookies:119 exit_with(MUMBLE, "different cookies with same uid and password: {} != {}".format(cookies, another_cookies))120 # source, stdin, output = generate_long_output_task()121 # source, stdin, output = generate_mega_task()122 source, stdin, output = task_func()123 task_id = run_task(hostport, cookies, source, stdin, token)124 stdout = b""125 status = 1126 error = ""127 for try_index in range(CHECK_TRIES_COUNT):128 try:129 stdout, status, error = get_task_info(hostport, cookies, task_id, token)130 if status != 1:131 break132 except requests.exceptions.HTTPError as e:133 if e.response.status_code != 404:134 raise135 time.sleep(RETRY_SLEEP)136 if status == 1:137 exit_with(MUMBLE, "can not get task info, too long answer")138 elif status == 2:139 exit_with(MUMBLE, "error while task running: {}".format(error))140 if output != stdout:141 exit_with(MUMBLE, "wrong output:\n\nexpected='{}'\n\nreal='{}'\n".format(output, stdout))142 exit(OK)143def check(hostname):144 check_with_task(hostname, generate_mega_task)145 check_with_task(hostname, generate_long_output_task)146def put_first(hostname, flag_id, flag):147 hostport = get_hostport(hostname)148 password = flag149 cookie = register(hostport, password)150 uid, _ = get_data_from_cookies(cookie)151 print("{},{}".format(uid, password))152 exit(OK)153def get_first(hostname, flag_id, flag):154 hostport = get_hostport(hostname)155 raw_uid, password = flag_id.split(',')156 uid = int(raw_uid)157 try:158 login(hostport, password, uid)159 except requests.exceptions.HTTPError as e:160 if e.response.status_code == 403:161 exit_with(CORRUPT, "can not log in", print_traceback=True)162 exit(OK)163def put_second(hostname, flag_id, flag):164 hostport = get_hostport(hostname)165 password = generate_string(10)166 cookies = register(hostport, password)167 source = generate_simple_task()168 token = flag169 task_id = run_task(hostport, cookies, source, b"", token)170 uid, _ = get_data_from_cookies(cookies)171 print("{},{},{}".format(uid, password, task_id))172 exit(OK)173def get_second(hostname, flag_id, flag):174 hostport = get_hostport(hostname)175 raw_uid, password, task_id = flag_id.split(",")176 uid = int(raw_uid)177 try:178 cookies = login(hostport, password, uid)179 get_task_info(hostport, cookies, task_id, flag)180 except requests.exceptions.HTTPError as e:181 if e.response.status_code in {403, 404}:182 exit_with(CORRUPT, "can not get flag", print_traceback=True)183 exit(OK)184def get(hostname, flag_id, flag, vuln):185 {'1': get_first, '2': get_second}[vuln](hostname, flag_id, flag)186def put(hostname, flag_id, flag, vuln):187 {'1': put_first, '2': put_second}[vuln](hostname, flag_id, flag)188def not_found(*args):189 exit_with(CHECKER_ERROR, "Unsupported command: {}".format(args[1]))190COMMANDS = {'check': check, 'put': put, 'get': get, 'info': info}191def main():192 try:193 COMMANDS.get(argv[1], not_found)(*argv[2:])194 except (requests.exceptions.ConnectionError, ConnectionRefusedError, urllib3.exceptions.NewConnectionError,195 urllib3.exceptions.ReadTimeoutError, requests.exceptions.ReadTimeout):196 exit_with(DOWN, "service is down: '{}'".format(argv[1:]), print_traceback=True)197 except (requests.exceptions.HTTPError, json.decoder.JSONDecodeError, ValueError, binascii.Error):198 exit_with(MUMBLE, "known exception while doing command: '{}'".format(argv[1:]), print_traceback=True)199 except Exception:200 traceback.print_exc()201 exit(CHECKER_ERROR)202if __name__ == '__main__':...
judge.py
Source:judge.py
...121314def check_input_file(header, board):15 if len(header.split()) != 4:16 exit_with(WRONG_INPUT, 'First line must contain 4 numbers')17 for x in header.split():18 if not x.isnumeric():19 exit_with(WRONG_INPUT, 'First line must contain 4 numbers')2021 width, height, distance, population = [int(x) for x in header.split()]22 if len(board) != height:23 exit_with(WRONG_INPUT, 'Board has wrong dimensions')24 for row in board:25 if len(row) != width:26 exit_with(WRONG_INPUT, 'Board has wrong dimensions')27 for cell in row:28 if cell not in ['.', '-', '|', '+']:29 exit_with(WRONG_INPUT, 'Board must contain only . - | and + characters')30 return True313233def check_output_file(output, expected_population, board_width, board_height):34 if len(output) < expected_population:35 exit_with(WRONG_OUTPUT, 'Output file must contain %s lines (as defined in input file)' % expected_population)36 for line in output:37 if len(line) != 2 or not line[0].isnumeric() or not line[1].isnumeric:38 exit_with(WRONG_OUTPUT, 'Each line of output file must contain exactly 2 numbers')39 xx = int(line[0])40 yy = int(line[1])41 if xx < 0 or xx >= board_width:42 exit_with(WRONG_OUTPUT, 'Coordinates (%s, %s) are outside the board' % tuple(line))43 if yy < 0 or yy >= board_height:44 exit_with(WRONG_OUTPUT, 'Coordinates (%s, %s) are outside the board' % tuple(line))4546def read_board(filename):47 with open(filename) as board_file:48 raw_board = board_file.read()49 raw_board = [x for x in raw_board.split('\n') if x]50 header = raw_board[0]51 board = raw_board[2:]52 check_input_file(header, board)53 width, height, distance, population = [int(x) for x in header.split()]54 return distance, population, board, width, height555657def read_result(filename, population, width, height):58 with open(filename) as result_file:59 raw_result = [x.split() for x in result_file.read().split('\n') if x]60 check_output_file(raw_result, population, width, height)61 result = [(int(y), int(x)) for (x, y) in raw_result]62 return result636465def neighbours(board, i, j, width, height):66 neighbours = []67 if board[i][j] in ('|', '+'):68 if i > 0 and board[i-1][j] in ('|', '+'):69 neighbours.append((i-1, j))70 if i < height-1 and board[i+1][j] in ('|', '+'):71 neighbours.append((i+1, j))72 if board[i][j] in ('-', '+'):73 if j > 0 and board[i][j-1] in ('-', '+'):74 neighbours.append((i, j-1))75 if j < width-1 and board[i][j+1] in ('-', '+'):76 neighbours.append((i, j+1))77 return neighbours787980def check_distances(board, population, distance, width, height):81 distances = [[-1 for i in range(width)] for j in range(height)]8283 for i in range(len(population)):84 x, y = population[i]85 distances[x][y] = i86 queue = []87 for a, b in neighbours(board, x, y, width, height):88 queue.append((a, b, 1))8990 while queue:91 x, y, d = queue.pop(0)92 if d <= distance and distances[x][y] < i:93 if (x, y) in population:94 exit_with(PEOPLE_TOO_CLOSE, 'People are too close to each other')95 distances[x][y] = i96 for (a, b) in neighbours(board, x, y, width, height):97 queue.append((a, b, d+1))9899 return OK100101def check_placement( board, result ):102 for (y,x) in result:103 if board[y][x] == ".":104 exit_with(NOT_ON_ROAD,"Person not on a road")105106 unique = set()107 for (y,x) in result:108 if (x,y) in unique:109 exit_with(NON_UNIQUE,"Two people on the same position")110 unique.add((x,y))111112 return OK113114115116117def check_args():118 if len(sys.argv) < 3 or len(sys.argv) > 4:119 exit_with(WRONG_ARGUMENTS, 'Judge expects 2 or 3 arguments')120 if sys.argv[1] not in os.listdir():121 exit_with(WRONG_ARGUMENTS, 'Input file does not exist')122 if sys.argv[2] not in os.listdir():123 exit_with(WRONG_ARGUMENTS, 'Output file does not exist')124125126def exit_with(code, message):127 print(message)128 exit(code)129130131if __name__ == '__main__':132 try:133 check_args()134 board_file_name = sys.argv[1]135 result_file_name = sys.argv[2]136 distance, population, board, width, height = read_board(board_file_name)137 result = read_result(result_file_name, population, width, height)138 # for i in range(len(board)): print(board[i])139 # print(result)140 check_placement(board, result)141142 check_distances(board, result, distance, width, height)143 exit_with(OK, 'OK')144 except Exception as e:
...
compile_flex.py
Source:compile_flex.py
...17 subprocess.call([os.path.join(os.environ['FLEX_HOME'], 'bin', 'mxmlc'),18 '-source-path=../flex-pilot/src/',19 '-source-path+=test/resources/html/flex/',20 file_name])21def exit_with(msg):22 print msg23 sys.exit(1)24if __name__ == "__main__":25 if len(sys.argv) == 1:26 exit_with(__doc__)27 try:28 opts, _ = getopt.getopt(sys.argv[1:], "h", ["help"])29 except getopt.error, msg:30 exit_with(msg + "\nfor help use --help")31 for o, _ in opts:32 if o in ("-h", "--help"):33 exit_with(__doc__)34 if not 'FLEX_HOME' in os.environ:35 exit_with('Please set FLEX_HOME environment variable.')...
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!!