How to use set_testcase method in autotest

Best Python code snippet using autotest_python

ebakup_application_tests.py

Source:ebakup_application_tests.py Github

copy

Full Screen

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

Full Screen

Full Screen

1005.py

Source:1005.py Github

copy

Full Screen

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

Full Screen

Full Screen

generate_test.py

Source:generate_test.py Github

copy

Full Screen

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

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