Best Python code snippet using avocado_python
caterpillar_test.py
Source:caterpillar_test.py
...51 """Makes a temporary output directory and stores it in self.output_path.52 """53 super(TestCaseWithOutputDir, self).setUp()54 self.output_path = os.path.join(self.temp_path, MINIMAL_APP_NAME)55 caterpillar.setup_output_dir(MINIMAL_PATH, self.output_path,56 BOILERPLATE_DIR, REPORT_DIR)57# Test cases.58class TestSetupOutputDir(TestCaseWithTempDir):59 """Tests setup_output_dir."""60 def setUp(self):61 """Makes a path to an output web app and stores it in self.output_path."""62 super(TestSetupOutputDir, self).setUp()63 self.output_path = os.path.join(self.temp_path, MINIMAL_APP_NAME)64 def test_setup_output_dir_makes_dir(self):65 """Tests that setup_output_dir makes the expected output directory."""66 caterpillar.setup_output_dir(MINIMAL_PATH, self.output_path,67 BOILERPLATE_DIR, REPORT_DIR)68 self.assertTrue(os.path.isdir(self.output_path))69 def test_setup_output_dir_makes_boilerplate_dir(self):70 """Tests that setup_output_dir makes a boilerplate directory."""71 caterpillar.setup_output_dir(MINIMAL_PATH, self.output_path,72 BOILERPLATE_DIR, REPORT_DIR)73 self.assertTrue(74 os.path.isdir(os.path.join(self.output_path, BOILERPLATE_DIR)))75 def test_setup_output_dir_makes_report_dir(self):76 """Tests that setup_output_dir makes a report directory."""77 caterpillar.setup_output_dir(MINIMAL_PATH, self.output_path,78 BOILERPLATE_DIR, REPORT_DIR)79 self.assertTrue(80 os.path.isdir(os.path.join(self.output_path, REPORT_DIR)))81 def test_setup_output_dir_makes_polyfill_dir(self):82 """Tests that setup_output_dir makes a polyfill directory."""83 caterpillar.setup_output_dir(84 MINIMAL_PATH, self.output_path, BOILERPLATE_DIR, REPORT_DIR)85 self.assertTrue(os.path.isdir(86 os.path.join(self.output_path, BOILERPLATE_DIR, 'polyfills')))87 def test_setup_output_dir_copies_all_files(self):88 """Tests that setup_output_dir copies all input files to the output app."""89 caterpillar.setup_output_dir(90 MINIMAL_PATH, self.output_path, BOILERPLATE_DIR, REPORT_DIR)91 for root, _, files in os.walk(MINIMAL_PATH):92 for name in files:93 relpath = os.path.relpath(os.path.join(root, name), MINIMAL_PATH)94 path = os.path.join(self.output_path, relpath)95 self.assertTrue(os.path.exists(path))96 def test_setup_output_dir_no_unexpected_files(self):97 """Tests that setup_output_dir doesn't add any unexpected files."""98 caterpillar.setup_output_dir(99 MINIMAL_PATH, self.output_path, BOILERPLATE_DIR, REPORT_DIR)100 for root, _, files in os.walk(self.output_path):101 for name in files:102 relpath = os.path.relpath(os.path.join(root, name), self.output_path)103 path = os.path.join(MINIMAL_PATH, relpath)104 self.assertTrue(os.path.exists(path))105 def test_setup_output_dir_force_false(self):106 """Tests that force=False disallows overwriting of an existing directory."""107 os.mkdir(self.output_path)108 with self.assertRaises(caterpillar.CaterpillarError) as e:109 caterpillar.setup_output_dir(110 MINIMAL_PATH, self.output_path, BOILERPLATE_DIR, REPORT_DIR)111 self.assertEqual(e.exception.message, 'Output directory already exists.')112 def test_input_dir_does_not_exist(self):113 """Tests that an error is raised if the input directory does not exist."""114 input_dir = os.path.join(self.temp_path, 'not a directory')115 with self.assertRaises(caterpillar.CaterpillarError) as e:116 caterpillar.setup_output_dir(117 input_dir, self.output_path, BOILERPLATE_DIR, REPORT_DIR)118 self.assertEqual(e.exception.message,119 'Input directory `{}` does not exist.'.format(input_dir))120 def test_input_not_a_directory(self):121 """Tests that an error is raised if the input is not a directory."""122 input_path = os.path.join(self.temp_path, 'a file')123 with open(input_path, 'w') as _:124 pass125 with self.assertRaises(caterpillar.CaterpillarError) as e:126 caterpillar.setup_output_dir(127 input_path, self.output_path, BOILERPLATE_DIR, REPORT_DIR)128 self.assertEqual(e.exception.message,129 'Input `{}` is not a directory.'.format(input_path))130 def test_setup_output_dir_force_true_copies_all_files(self):131 """Tests that force=True allows overwriting of an existing directory."""132 os.mkdir(self.output_path)133 caterpillar.setup_output_dir(134 MINIMAL_PATH, self.output_path, BOILERPLATE_DIR, REPORT_DIR, force=True)135 for root, _, files in os.walk(MINIMAL_PATH):136 for name in files:137 relpath = os.path.relpath(os.path.join(root, name), MINIMAL_PATH)138 path = os.path.join(self.output_path, relpath)139 self.assertTrue(os.path.exists(path))140 def test_setup_output_dir_force_true_deletes_existing_files(self):141 """Tests that force=True deletes files in existing directory."""142 os.mkdir(self.output_path)143 test_filename = 'existing file'144 with open(os.path.join(self.output_path, test_filename), 'w') as f:145 pass146 caterpillar.setup_output_dir(147 MINIMAL_PATH, self.output_path, BOILERPLATE_DIR, REPORT_DIR, force=True)148 self.assertFalse(149 os.path.exists(os.path.join(self.output_path, test_filename)))150class TestCleanupOutputDir(TestCaseWithOutputDir):151 """Tests cleanup_output_dir."""152 def test_no_manifest(self):153 """Tests that the manifest is removed."""154 caterpillar.cleanup_output_dir(self.output_path)155 self.assertFalse(156 os.path.exists(os.path.join(self.output_path, 'manifest.json')))157class TestCopyStaticCode(TestCaseWithOutputDir):158 """Tests copy_static_code."""159 def test_no_copy(self):160 """Tests copying no files."""...
utils_io.py
Source:utils_io.py
1import sys, os, datetime, cv2, warnings, parse, tempfile2import numpy as np3from utils_funcs import random4# ---5COLUMNS = os.getenv ('COLUMNS', default = '80')6P1F = '{:<' + COLUMNS + '}'7N1F = '\n{:<' + COLUMNS + '}'8def tp1(x):9 print (P1F.format(x), end = '\r', flush = True)10def ctp1(x):11 print (N1F.format(x), end = '\r', flush = True)12def np1(x):13 print (x, end = '', flush = True)14def cnp1(x):15 print ('\n', x, sep = '', end = '', flush = True)16def p1(x, **k):17 print (P1F.format(x), **k)18def c1(x):19 print (x)20def cp1(x, **k):21 print (N1F.format(x), **k)22# ---23def hr(c = '-', **k):24 print (''.join ([c * int (COLUMNS)]), **k)25def h1(title, c = '=', title_head = 3):26 hr (c, end = f'\r{c * title_head} {title} \n')27def h2(title, c = '-', title_head = 3):28 hr (c, end = f'\r{c * title_head} {title} \n')29# ---30def s_(i):31 return i, 's' if i > 1 else ''32def is_are_(i):33 return i, 'are' if i > 1 else 'is'34# ---35tempdir = tempfile.gettempdir ()36def setup_output_dir (outs, log = True):37 if not os.path.exists (outs):38 if log: print (f'Creating output directory: {outs}')39 os.makedirs (outs)40 return outs41def dir_or_file_in_dir (default_filename, suff):42 def aux (f, filename = default_filename):43 dirname = os.path.dirname (f) if f.endswith (suff) else f44 if dirname is not None:45 setup_output_dir (dirname)46 if f.endswith (suff):47 return f48 return os.path.join (f, f'{filename}')49 return aux50class OutputDir:51 '''52 Class to help ensure output directory is created before starting any53 lengthy computations.54 '''55 def __init__(self, outs = tempdir, log = None,56 enable_stamp = True, stamp = None, prefix_stamp = False):57 self.dirpath = setup_output_dir (outs, log = log)58 self.enable_stamp = enable_stamp59 self.prefix_stamp = prefix_stamp60 self.reset_stamp (stamp = stamp)61 def reset_stamp (self, stamp = None):62 self.stamp = datetime.datetime.now ().strftime("%Y%m%d-%H%M%S") \63 if stamp is None and self.enable_stamp else \64 stamp if self.enable_stamp else ''65 @property66 def path(self) -> str:67 return self.dirpath68 def filepath(self, base, suff = '') -> str:69 return os.path.join (self.dirpath, base + suff)70 def stamped_filename(self, base, sep = '-', suff = '') -> str:71 return ((self.stamp + sep + base) if self.enable_stamp and self.prefix_stamp else \72 (base + sep + self.stamp) if self.enable_stamp else \73 (base)) + suff74 def stamped_filepath(self, *args, **kwds) -> str:75 return os.path.join (self.dirpath, self.stamped_filename (*args, **kwds))76 def subdir(self, name) -> str:77 dirname = self.filepath (name)78 if not os.path.exists (dirname):79 os.makedirs (dirname)80 return dirname81 def fresh_dir(self, basename, suff_fmt = '-{:x}', **kwds):82 outdir = self.filepath (basename + suff_fmt.format (random.getrandbits (16)))83 try:84 os.makedirs (outdir)85 return OutputDir (outdir, **kwds)86 except FileExistsError:87 return self.fresh_dir (basename, suff_fmt = suff_fmt, **kwds)88# ---89def _write_in_file (f, mode, *fmts):90 f = open (f, mode)91 for fmt in fmts: f.write (fmt)92 f.close ()93def write_in_file (f, *fmts):94 _write_in_file (f, "w", *fmts)95def append_in_file (f, *fmts):96 _write_in_file (f, "a", *fmts)97def save_in_csv (filename):98 def save_an_array (arr, name, directory = '.', log = True):99 f = os.path.join (directory, filename + '.csv')100 if log: p1 (f'Appending array into `{f}\'')101 with open (f, 'a') as file:102 file.write (name + ' ')103 np.savetxt (file, arr, newline = ' ')104 file.write ('\n')105 return save_an_array106def save_an_image(im, name, directory = '.', log = True, channel_upscale = 255):107 f = os.path.join (directory, name + '.png')108 if log: p1 (f'Outputing image into `{f}\'')109 cv2.imwrite (f, im * channel_upscale)110def save_an_image_(channel_upscale = 255):111 return lambda *args, **kwds: \112 save_an_image (*args, channel_upscale = channel_upscale, **kwds)113def save_adversarial_examples(adv, origin, diff, di):114 save_an_image(adv[0], adv[1], di)115 save_an_image(origin[0], origin[1], di)116 if diff is not None:...
system_test.py
Source:system_test.py
...3import importlib4import subprocess5import filecmp6import argparse7def setup_output_dir(output_dir):8 if not os.path.exists(output_dir):9 os.mkdir(output_dir)10def execute_testsuite(exe, suite_path, suite_out_path, suite_ans_path):11 correct_count = 012 suite_name = os.path.basename(suite_path)13 suite_mod_path = os.path.join(suite_path, "suite.py")14 suite = None15 if os.path.exists(suite_mod_path):16 module_path = ".".join(["testcases", suite_name, "suite"])17 mod = importlib.import_module(module_path)18 suite = getattr(mod, "Suite")19 case_files = list()20 for name in os.listdir(suite_path):21 if name.startswith("t") and name.endswith(".txt"):22 case_files.append(name)23 print("Starting test suite ``{suite}``".format(suite=suite_name))24 for case in sorted(case_files):25 if suite:26 suite.setUp()27 case_path = os.path.join(suite_path, case)28 out_path = os.path.join(suite_out_path, case)29 ans_path = os.path.join(suite_ans_path, case)30 with open(case_path) as fp:31 content = fp.readlines()32 content.insert(0, ".output {out_path}\n".format(out_path=out_path))33 p = subprocess.Popen([exe], stdin=subprocess.PIPE) 34 for line in content:35 p.stdin.write(line.encode())36 p.stdin.close()37 p.wait()38 if suite:39 suite.tearDown()40 is_result_match = filecmp.cmp(out_path, ans_path)41 if is_result_match:42 print("The test file {case} passed".format(case=case))43 correct_count += 144 else:45 print("The test file {case} failed".format(case=case))46 print("The test suite ``{}`` total passed {}/{}".format(suite_name,47 correct_count, len(case_files)))48 print()49 return correct_count, len(case_files)50def main():51 parser = argparse.ArgumentParser()52 parser.add_argument("shell", help="The path of the compiled shell")53 parser.add_argument("test_case", help="The test case to be run, default: all", nargs="*", default="all")54 args = parser.parse_args()55 if not isinstance(args.test_case, list):56 args.test_case = "all"57 58 file_path = os.path.dirname(__file__)59 testcase_path = os.path.join(file_path, "testcases")60 output_path = os.path.join(file_path, "output")61 answer_path = os.path.join(file_path, "answer")62 if args.test_case == "all":63 args.test_case = os.listdir(testcase_path)64 65 for test_suite in args.test_case:66 if test_suite == "__pycache__":67 continue68 suite_path = os.path.join(testcase_path, test_suite)69 suite_out_path = os.path.join(output_path, test_suite)70 suite_ans_path = os.path.join(answer_path, test_suite)71 if os.path.isdir(suite_path):72 setup_output_dir(suite_out_path)73 ret = execute_testsuite(sys.argv[1], suite_path, suite_out_path, suite_ans_path)74 correct_count, total_count = ret75if __name__ == "__main__":...
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!!