Best Python code snippet using autotest_python
ebakup_application_tests.py
Source:ebakup_application_tests.py
...20 tests for the EbakupInvocation helper class.21 '''22 def test_run_ebakup_without_args_exits_with_failure(self):23 runner = EbakupInvocation()24 runner.set_testcase(self)25 runner.allowDefaultConfig()26 runner.run()27 runner.assertFailed()28 def test_run_ebakup_without_args_shows_usage_message(self):29 runner = EbakupInvocation()30 runner.set_testcase(self)31 runner.allowDefaultConfig()32 runner.run()33 runner.assertOutputMatchesRegex(b'^usage: ebakup')34 def test_run_ebakup_with_help_shows_help_message(self):35 runner = EbakupInvocation('--help')36 runner.set_testcase(self)37 runner.allowDefaultConfig()38 runner.run()39 runner.assertSuccess()40 runner.assertOutputMatchesRegex(b'^usage: ebakup')41 runner.assertOutputMatchesRegex(b'\n -h, --help +show this help')42class BackupChecker(object):43 def __init__(self, testcase, dbpath, bkname):44 self.tc = testcase45 self.dbpath = dbpath46 self.bk = BackupReader(dbpath, bkname)47 self.content = ContentReader(dbpath)48 def set_reference_tree(self, tree):49 self.tree = tree50 def assertSameFilesPresent(self):51 treepaths = set(x for x in self.tree.iterate_files())52 bkpaths = set(x.decode('utf-8', errors='surrogateescape')53 for x in self.bk.iterate_files())54 self.tc.assertEqual(treepaths, bkpaths)55 def assertFilesHaveCorrectContentAndChecksums(self):56 for path in self.bk.iterate_files():57 self.assertFileHaveCorrectContent(path)58 self.assertFileHaveCorrectChecksum(path)59 def assertFileHaveCorrectContent(self, path):60 data = self.tree.get_file_content(path)61 bkdata = self._get_bk_data_for_path(path)62 self.tc.assertEqual(data, bkdata)63 def _get_bk_data_for_path(self, path):64 finfo = self.bk.get_file_info(path)65 cpath = makepath('backup', self.content.get_path(finfo.cid))66 with open(cpath, 'rb') as f:67 data = f.read()68 return data69 def assertFileHaveCorrectChecksum(self, path):70 data = self.tree.get_file_content(path)71 checksum = hashlib.sha256(data).digest()72 bkchecksum = self._get_bk_checksum_for_path(path)73 self.tc.assertEqual(checksum, bkchecksum)74 def _get_bk_checksum_for_path(self, path):75 finfo = self.bk.get_file_info(path)76 cinfo = self.content.get_content_info(finfo.cid)77 return cinfo.checksum78time_1 = '2014-03-29T20:20:40.369238'79time_2 = '2014-04-17T01:01:43.623171'80time_3 = '2014-04-30T08:24:40.640211'81@unittest.skipUnless(tests.settings.run_live_tests, 'Live tests are disabled')82class TestEbakupLive(unittest.TestCase):83 class SharedContext(object):84 def __init__(self):85 if not tests.settings.run_live_tests:86 return87 tree = self._create_tree_after_second_backup()88 self.tree_after_second_backup = tree89 def _create_tree_after_second_backup(self):90 testcase = TestEbakupLive()91 os.makedirs(root_path)92 testcase._setup_second_backup_completed()93 tree = FileTree()94 tree.load_from_path(makepath(''))95 shutil.rmtree(root_path)96 return tree97 shared_context = None98 def setUp(self):99 if self.shared_context is None:100 TestEbakupLive.shared_context = TestEbakupLive.SharedContext()101 os.makedirs(root_path)102 def tearDown(self):103 if True:104 shutil.rmtree(root_path)105 def test_making_first_backup(self):106 self._given_basic_config()107 self._given_source_tree(_data.source_tree_1)108 self._given_current_time_is(time_1)109 result = self._run_ebakup('backup', '--create', 'main')110 result.assertSuccessAndNoOutput()111 self.assertBackupMatchesTree(time_1, _data.backup_tree_1)112 def test_making_second_backup(self):113 self._given_first_backup_completed()114 self._given_source_tree(_data.source_tree_2)115 self._given_current_time_is(time_2)116 result = self._run_ebakup('backup', 'main')117 result.assertSuccessAndNoOutput()118 self.assertBackupMatchesTree(time_2, _data.backup_tree_2)119 def test_cached_state_after_second_backup(self):120 self._given_second_backup_completed()121 self._given_current_time_is(time_3)122 self.assertBackupMatchesTree(time_2, _data.backup_tree_2)123 def test_shadowcopy_matches_tree(self):124 self._given_second_backup_completed()125 self._given_current_time_is(time_3)126 result = self._run_ebakup(127 'shadowcopy',128 '--target', makepath('shadowtest'),129 '2014-04-17T01:01')130 result.assertSuccessAndNoOutput()131 self.assertDirMatchesTree(makepath('shadowtest'), _data.backup_tree_2)132 self.assertFileIsHardLinkToContent(133 makepath('shadowtest', 'other/plain'))134 def test_verify_finds_some_problems(self):135 self._given_second_backup_completed()136 self._given_current_time_is(time_3)137 content1 = _data.backup_tree_2.get_file_content('photos/DSC_2474.JPG')138 cid1 = self._get_cid_for_data(content1)139 cpath1 = makepath('backup', self._get_content_path_for_data(content1))140 content2 = _data.backup_tree_2.get_file_content('other/plain')141 cid2 = self._get_cid_for_data(content2)142 cpath2 = makepath('backup', self._get_content_path_for_data(content2))143 os.unlink(cpath1)144 with open(cpath2, "r+") as f:145 f.write('changed')146 result = self._run_ebakup('verify')147 self.assertVerifyResult(148 result,149 content_missing=(hexstr(cid1),),150 content_changed=(hexstr(cid2),))151 def assertBackupMatchesTree(self, bkname, tree, dbpath=None):152 if dbpath is None:153 dbpath = makepath('backup')154 checker = BackupChecker(self, dbpath, bkname[:16])155 checker.set_reference_tree(tree)156 checker.assertSameFilesPresent()157 checker.assertFilesHaveCorrectContentAndChecksums()158 def assertFileIsHardLinkToContent(self, path):159 data = self._get_file_content_for_full_path(path)160 content_path = self._get_content_path_for_data(data)161 self.assertTrue(162 os.path.samefile(path, makepath('backup', content_path)))163 def assertDirMatchesTree(self, path, tree):164 for name in tree.iterate_files():165 fdata = self._get_file_content(os.path.join(path, name))166 self.assertEqual(tree.get_file_content(name), fdata)167 for base, dirs, files in os.walk(path):168 for name in files:169 fpath = os.path.relpath(os.path.join(base, name), path)170 self.assertTrue(tree.has_file(fpath), msg=fpath)171 def assertVerifyResult(172 self, result, content_missing=(), content_changed=()):173 out, err = result._get_interesting_output()174 self.assertEqual(b'', err)175 out_cmissing = []176 out_cchanged = []177 re_line = re.compile(rb'^\s*([^:]+):\s*(.*)$')178 for line in out.split(b'\n'):179 if (line == b'' or180 line.startswith(b'Results of verifying') or181 line.startswith(b'ERRORS: ') or182 line.startswith(b'Warnings: ')):183 continue184 match = re_line.match(line)185 self.assertNotEqual(None, match, msg=line)186 what = match.group(1)187 which = match.group(2)188 if what == b'Content missing':189 out_cmissing.append(which.decode('utf-8'))190 elif what == b'Content not matching checksum':191 out_cchanged.append(which.decode('utf-8'))192 else:193 self.fail('Unknown output: ' + str(line))194 self.assertCountEqual(195 [str(x) for x in content_missing], out_cmissing)196 self.assertCountEqual(197 [str(x) for x in content_changed], out_cchanged)198 def _given_basic_config(self):199 self._write_file('config', _data.config_1)200 def _given_source_tree(self, tree):201 if os.path.exists(makepath('source')):202 shutil.rmtree(makepath('source'))203 tree.write_to_disk(makepath('source'))204 def _given_current_time_is(self, time):205 self.fake_start_time = time206 def _given_first_backup_completed(self):207 self._given_basic_config()208 self._given_source_tree(_data.source_tree_1)209 self._given_current_time_is(time_1)210 self._run_ebakup('backup', '--create', 'main')211 def _setup_second_backup_completed(self):212 self._given_first_backup_completed()213 self._given_source_tree(_data.source_tree_2)214 self._given_current_time_is(time_2)215 self._run_ebakup('backup', 'main')216 def _given_second_backup_completed(self):217 self.shared_context.tree_after_second_backup.write_to_disk(218 makepath(''))219 def _run_ebakup(self, *args):220 runner = EbakupInvocation(221 '--config', makepath('config'),222 '--fake-start-time', self.fake_start_time,223 *args)224 runner.set_testcase(self)225 runner.run()226 return runner227 def _get_content_path_for_data(self, data):228 digest = hashlib.sha256(data).digest()229 return ContentReader.get_path(digest)230 def _get_cid_for_data(self, data):231 return hashlib.sha256(data).digest()232 def _write_file(self, innerpath, content):233 if isinstance(content, str):234 content = content.encode('utf-8')235 path = makepath(innerpath)236 os.makedirs(os.path.dirname(path), exist_ok=True)237 with open(path, 'xb') as f:238 wrote = f.write(content)...
1005.py
Source:1005.py
...8# ëë¹íìì ì¬ì©í í9queue = deque()10# ì í 건물ë¤ì ì
ë ¥íê³ ì§ì
ì°¨ì를 ë±ë¡í´ì¤ í¨ì11# í
ì¤í¸ì¼ì´ì¤ë§í¼ ë°ë³µí´ì¼í´ì í¨ìë¡ ë§ë¤ìë¤.12def set_testcase(time):13 for i in range(time):14 front, back = map(int, si().split())15 # frontë²ì§¸ 건물ì ì§ì´ì¼ back 건물ì ì§ì ì ìë¤.16 graph[front].append(back)17 # back 건물ì ì§ì
ì°¨ì +118 entry[back] += 119 target = int(si().rstrip())20 return target21def bfs(q: deque, target):22 # ê° ê±´ë¬¼ê¹ì§ ììëë ìê°ì ì ì¥íë¤.23 result = [0] * (n + 1)24 # ì§ì
ì°¨ìê° 0ì¸ ê±´ë¬¼ë¤ì íì ë´ëë¤.25 for i in range(1, n + 1):26 if entry[i] == 0:27 q.append(i)28 result[i] += build_time[i]29 while q:30 # íì¬ ê±´ì¤íë 건물31 now = q.popleft()32 # íì¬ ê±´ë¬¼ì ì íì¼ë¡ ê°ì§ë 건물ë¤33 for b in graph[now]:34 # ê° ê±´ë¬¼ë¤ì ì§ì
ì°¨ì를 íëì© ì¤ì¬ì¤ë¤.35 entry[b] -= 136 # ë¤ì 건물ë¤ì ì§ëë° ê±¸ë¦¬ë ìê°(ì´ì ì ì
ë ¥ë ìì¹) vs íì¬ ê±´ë¬¼ì ì§ê³ ë¤ì 건물ê¹ì§ ì§ë ìê°37 # ë ê°ë¥¼ ë¹êµí´ì ë³ëª©ììì ëí ìê°ë§ ì
ë ¥í´ì¤ì¼íë¤.38 result[b] = max(result[b], result[now] + build_time[b])39 if entry[b] == 0:40 q.append(b)41 return result[target]42# rootìì ì í건물ë¤ì ìê°ì ëí´ê°ë©´ì ê³ì°íë¤.43# í íìì¼ë¡ íì¬ ê±´ë¬¼ì ê±´ì¤íëë° ê±¸ë¦¬ë ìê°ì ì ì¥í´ëê³ 44# ê·¸ ë¤ì 건물ì ì§ëë° ê±¸ë¦¬ë ìê°ì ê·¸ ê°ì ëí ê°ì ì ì¥íë¤.45# ë¤ì ê±´ë¬¼ì´ ì í ê±´ë¬¼ì´ ì¬ë¬ ê°ì¸ ê²½ì° ë³ëª©ììì ëí ìê°ì ì ì¥í´ì¤ì¼íë¤.46# íì¬ ê°ê³¼ ë¤ì´ì¨ ê°ì¤ í° ê°ì ì ì¥íë ë°©ìì¼ë¡ ê°±ì ìí¨ë¤.47# ì§ì
ì°¨ìê° ìì´ì§ ë
¸ë를 íì ë£ë ìì¼ë¡ ê³ìí´ì ì§í.48for j in range(T):49 # 건물 ê°ìì ë¹êµ íì50 n, k = map(int, si().split())51 # indexë²ì§¸ 건물 ë¤ì ìì¼í 건물ë¤ì´ ë´ê¸¸ 리ì¤í¸52 graph = [[] for _ in range(n + 1)]53 # ì§ì
ì°¨ìê° ë´ê¸¸ 리ì¤í¸54 entry = [0] * (n + 1)55 # 건물 ê±´ì¤ìê° ë¦¬ì¤í¸56 build_time = [0] + list(map(int, si().split()))57 w = set_testcase(k)58 t = bfs(queue, w)59 answer.append(t)60 queue.clear()61for ans in answer:...
generate_test.py
Source:generate_test.py
2import subprocess3from commands import getstatusoutput as getout4max_line=10**2 +15max_value=506def set_testcase():7 try:8 fil = open("inp_fib",'w')9 for i in xrange(1,max_line):10 testcase = random.randrange(1,max_value)11 fil.write(str(testcase)+"\n")12 13 except IOError:14 print 'No such file'15 finally:16 fil.close()17def check_student_case():18 try:19 student_file = open("out",'r')20 correct_file = open("sout" ,'r')21 command_diff = str("diff -y --suppress-common-lines "+ \22 str(student_file.name) + " " +str(correct_file.name) + \23 " | grep ^ | wc -l")24 status,ans = getout(command_diff)25 ans = int(ans)26 if ans>100:ans = 10027 print 'Fibonacci Score for ',student_file.name + ' is : ', 100 - int(ans)28 except IOError,OSError:29 print 'Error Occured'30 31 finally:32 student_file.close()33 correct_file.close()34def create_student_output():35 try :36 student_code_file = open("student_code.sh")37 exec_string = "./" + student_code_file.name38 getout(exec_string)39 #Generates the student's out file to be compared 40 except :41 print 'Couldn\'t load student code'42 finally:43 student_code_file.close()44 45if __name__ == '__main__':46 # set_testcase()47 create_student_output()...
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!!