Best Python code snippet using lemoncheesecake
ashtest.py
Source:ashtest.py  
1def read_tests(filepath):2    global GLOBAL_DEBUG3    GLOBAL_DEBUG = True4    print('-------------------------------')5    type2python = {6        'Boolean' : bool,7        'Integer' : int,8        'String' : str9    }10    res2python = {11        'false' : False,12        'true' : True13    }14    f = open(filepath, mode='r')15    lines = f.readlines()16    f.close()17    nb_tests = {18        'skipped' : 0,19        'success' : 0,20        'failed'  : 0,21        'total'   : 0,22    }23    for i, line in enumerate(lines, start=1):24        if i < 3: continue # headers25        try:26            data    = line.split('\t')27            idt     = data[0]28            status  = data[1]29            py      = data[2]30            lua     = data[3]31            title   = data[4]32            content = data[5]33            content_exec = content.replace('\\n', '\n')34            resval  = data[6]35            restyp  = data[7]36            try:37                numtok  = int(data[8].rstrip())38            except ValueError:39                numtok = None40            asserts  = data[9:]41            if len(asserts) > 0:42                asserts[-1] = asserts[-1].rstrip()43        except (ValueError, IndexError) as e:44            print(f'[TEST]    {nb_tests["total"]+1:03} Skipping line {i:05d} {e}')45            nb_tests['skipped'] += 146            nb_tests['total']   += 147            continue48        if status == 'Do':49            print(f'[TEST]    {nb_tests["total"]+1:03} {title} : {content}')50            try:51                # Tokenizing52                res = Tokenizer(False).tokenize(content_exec)53                if numtok is not None and len(res) != numtok:54                    shell.write(f'[FAILED]  Wrong number of tokens, expecting {numtok} got {len(res)}\n', 'COMMENT')55                    nb_tests['failed'] += 156                    nb_tests['total']  += 157                    continue58                for assertcheck in asserts:59                    data = assertcheck.split('::')60                    if len(data) == 4:61                        what = data[0]62                        where = data[1]63                        typ = data[2]64                        val = data[3]65                        if what == 'Tokens':66                            where = int(where)67                            if res[where].typ.name != typ:68                                shell.write(f'[FAILED]  Wrong type of token, expecting {typ} got {res[where].typ}\n', 'COMMENT')69                                nb_tests['failed'] += 170                                nb_tests['total']  += 171                                continue72                            else:73                                if res[where].val != val: # all value are strings74                                    shell.write(f'[FAILED]  Wrong value of token, expecting {val} got {res[where].val}\n', 'COMMENT')75                                    nb_tests['failed'] += 176                                    nb_tests['total']  += 177                                    continue78                                else:79                                    shell.write(f'[ASSERT]  Assert ok for token {where} of type {typ} of val {val}\n', 'STRING')80                # Parsing & Interpreting81                ast = parser.parse(res)82                res = interpreter.do_ast(ast)83                ok = False84                if restyp in type2python:85                    if type(res) == type2python[restyp]:86                        if restyp == 'Boolean':87                            if res == res2python[resval]:88                                ok = True89                        elif restyp == 'Integer':90                            if res == int(resval):91                                ok = True92                        elif restyp == 'String':93                            if "'" + res + "'" == resval:94                                ok = True95                if ok:96                     shell.write(f'[SUCCESS] Expected {resval} of type {restyp} and got: {res} of type {type(res)}\n', 'STRING')97                     nb_tests['success'] += 198                     nb_tests['total']   += 199                else:100                    shell.write(f'[FAILED]  Expected {resval} of type {restyp} and got: {res} of type {type(res)}\n', 'COMMENT')101                    nb_tests['failed'] += 1102                    nb_tests['total']  += 1103            except Exception as e:104                shell.write(f'[FAILED]  Exception: {e}\n', 'COMMENT')105                traceback.print_exception(*sys.exc_info())106                nb_tests['failed'] += 1107                nb_tests['total']  += 1108    print('-------------------------------')109    if nb_tests["success"] + nb_tests["failed"] + nb_tests["skipped"] != nb_tests['total']:110        raise Exception("[ERROR] Total of tests not equal to total of tests failed/skipped/success")111    shell.write(f'Nb test success:   {nb_tests["success"]:05d} ({round(nb_tests["success"]/nb_tests["total"]*100):3d}%)\n', 'STRING')112    if nb_tests["failed"] == 0:113        shell.write(f'Nb test failed:    {nb_tests["failed"]:05d} ({round(nb_tests["failed"]/nb_tests["total"]*100):3d}%)\n', 'STRING')114    else:115        shell.write(f'Nb test failed:    {nb_tests["failed"]:05d} ({round(nb_tests["failed"]/nb_tests["total"]*100):3d}%)\n', 'COMMENT')116    shell.write(f'Nb test skipped:   {nb_tests["skipped"]:05d} ({round(nb_tests["skipped"]/nb_tests["total"]*100):3d}%)\n', 'KEYWORD')117    print('-------------------------------')118    print(f'Total test passed: {nb_tests["total"]:05d}')119    print('-------------------------------')...validation.py
Source:validation.py  
1from dynamic_prog.pattern_matching import PM_DTW2from BlockDTW.DTW_blocks import *3from timer import Timer4from progress_bar import update_progress5import random6def get_random_string(minsize, bound_homopol):7    random_string = ""8    while len(random_string) < minsize:9        # Considering only upper letters10        random_integer = random.randint(97, 100)11        nb_occurrences = random.randint(1, bound_homopol)12        for _ in range(nb_occurrences):13            random_string += chr(random_integer)14    return random_string15def main(nb_tests, size_min, bound_homopol):16    # nb_tests = 1017    # size_min = 100018    # bound_homopol = 1019    PT_strings = []20    for _ in range(nb_tests):21        PT_strings.append(22            [23                get_random_string(size_min, bound_homopol),24                get_random_string(size_min, bound_homopol),25            ]26        )27    classic_res = []28    # compare times29    with Timer() as classical_time:30        for i in range(nb_tests):31            update_progress(i / float(nb_tests))32            P = PT_strings[i][0]33            T = PT_strings[i][1]34            ldtw = PM_DTW(P, T)35            ldtw.fill()36            classic_res.append(ldtw.get_last_value())37        update_progress(1)38    classical_time.print("Durée classique = {} seconds")39    dtw_block_res = []40    nb_blocks = 041    with Timer() as block_time:42        for i in range(nb_tests):43            update_progress(i / float(nb_tests))44            P = PT_strings[i][0]45            T = PT_strings[i][1]46            dtw = DtwByBlocks(P, T)47            dtw_block_res.append(dtw.get_br_value())48            nb_blocks += dtw.get_nb_blocks()49        update_progress(1)50    block_time.print("Durée with blocks = {} seconds")51    timeb = block_time.value()52    print(f"Durée per block = {round(timeb,2)}/{nb_blocks} = {timeb/nb_blocks} seconds")53    # Validations54    for i in range(nb_tests):55        assert (56            classic_res[i] == dtw_block_res[i]57        ), f"Test failed with {PT_strings[i][0]} {PT_strings[i][1]}: {classic_res[i]} vs {dtw_block_res[i]}"58    print(f"We performed {nb_tests} tests, all passed !")59if __name__ == "__main__":60    if len(sys.argv) != 4:61        sys.stderr.write(62            f"Usage: python {sys.argv[0]} nb_tests min_size_P_T homopol_size_bound\n"63        )64    else:65        main(66            nb_tests=int(sys.argv[1]),67            size_min=int(sys.argv[2]),68            bound_homopol=int(sys.argv[3]),...AStarDriver.py
Source:AStarDriver.py  
1from AStar import *2print("-------------------------- A* Algorithm -----------------------------")3# Initializing total variables for stats4nb_tests = 205SOT_counter = 06SET_counter = 07NST_counter = 08T_cost = 09T_time = 010# Opening input text file11f = open("puzzles.txt", "r")12for line in f:13    start = eval(line)14    puzzle = Puzzle(start)15    a_solution, a_search, a_cost, a_time = astar(puzzle)16    if "no solution" not in a_solution:17        SOT_counter += len(a_solution)18        SET_counter += len(a_search)19    else:20        NST_counter += 121    T_cost += a_cost22    T_time += a_time23# Initializing averages variables for stats24SOA_counter = SOT_counter / nb_tests25SEA_counter = SET_counter / nb_tests26NSA_counter = NST_counter / nb_tests27A_cost = T_cost / nb_tests28A_time = T_time / nb_tests29# Output30print("Total length of solution path: " + str(SOT_counter))31print("Average length of solution path: " + str(SOA_counter))32print("Total length of search path: " + str(SET_counter))33print("Average length of search path: " + str(SEA_counter))34print("Total number of no solution: " + str(NST_counter))35print("Average number of no solution: " + str(NSA_counter))36print("Total cost: " + str(T_cost))37print("Average cost: " + str(A_cost))38print("Total execution time: " + str(T_time) + " seconds")...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!!
