Best Python code snippet using autotest_python
ffMozREPL.py
Source:ffMozREPL.py
...115 self.tn.write(command.encode() + b"\n")116 (index, match, data) = self.tn.expect(Mozrepl.bprompt, timeout=self.timeout)117 return data.decode("utf8")118 119 def get_text_result(self, command, sep=''):120 """121 Execute the command and fetch its result as text.122 """123 lines = self.run(command).split("\n")124 if re.search(Mozrepl.sprompt[0].strip(), lines[-1]):125 lines = lines[:-1]126 return sep.join(lines)127 128 def set_tab_url(self, url, tabID=-1):129 """130 Open a URL in any tab, use -1 for the *current* tab.131 """132 with self:133 if not (tabID == 0 or tabID == -1):134 #There should always be a tab zero, same for a current tab.135 #Skip check.136 if not (-1 <= tabID < self.get_number_of_tabs()):137 raise ValueError("TabID should be -1 for current tab or the tab ID.")138 if tabID == -1:139 self.run("content.location.href = '{u}'".format(u=url))140 else:141 self.run("gBrowser.tabContainer.childNodes[{i}].linkedBrowser.contentDocument.location.href = '{u}'".format(i=tabID, u=url))142 143 def get_tab_url(self, tabID=-1):144 """145 URL of the tab, use -1 for the *current* tab.146 """147 #Access Window Element.148 #gBrowser.tabContainer.childNodes[{i}].linkedBrowser.contentDocument.defaultView149 #gBrowser.tabContainer.childNodes[{i}].linkedBrowser.contentWindow150 with self:151 if not (tabID == 0 or tabID == -1):152 #There should always be a tab zero, same for a current tab.153 #Skip check.154 if not (-1 <= tabID < self.get_number_of_tabs()):155 raise ValueError("TabID should be -1 for current tab or the tab ID.")156 #Ignore first and last char to remove quotes around the Url.157 if tabID == -1:158 return self.get_text_result("content.location.href")[1:-1]159 #linkedBrowser == browser, contentDocument == content160 return self.get_text_result('gBrowser.tabContainer.childNodes[{i}].linkedBrowser.contentDocument.location.href'.format(i=tabID))[1:-1]161 def open_new_tab(self, url=None):162 """163 Open a new empty tab and put the focus on it.164 """165 if url is None:166 url = "about:blank"167 with self:168 self.run('gBrowser.selectedTab = gBrowser.addTab("{}");'.format(url))169 170 def get_number_of_tabs(self):171 """172 Number of tabs in the browser.173 """174 with self:175 result = self.get_text_result('gBrowser.tabContainer.childNodes.length')176 return int(result)177 178 def set_selected_tab(self, n):179 """180 Put the focus on the selected tab.181 """182 with self:183 if n != 0:184 #There should always be a tab zero185 #Skip check.186 if not (0 <= n < self.get_number_of_tabs()):187 raise ValueError("Incorrect tab number!")188 self.run('gBrowser.selectedTab = gBrowser.tabContainer.childNodes[{n}]'.format(n=n))189 190 def get_selected_tab_index(self):191 """192 Return the currently selected tab id.193 """194 with self:195 result = self.get_text_result('gBrowser.tabContainer.selectedIndex')196 return int(result)197 198 def is_tab_selected(self, n):199 """200 Put the focus on the selected tab.201 """202 with self:203 if n != 0:204 #There should always be a tab zero.205 #Skip check.206 if not (0 <= n < self.get_number_of_tabs()):207 raise ValueError("Incorrect tab number!")208 result = self.get_text_result('gBrowser.tabContainer.childNodes[{n}].selected'.format(n=n))209 return bool(strtobool(result))210 211 def get_tab_elementByClassName_html(self, classNames, index=0, tabID=-1):212 """213 Return the HTML source of an element.214 """215 with self:216 tmpVarName = "MozReplTempValue"217 self.run('{v} = gBrowser.tabContainer.childNodes[{i}].linkedBrowser.contentDocument.getElementsByClassName("{n}")'.format(v=tmpVarName, i=tabID, n=classNames))218 result = self.get_text_result('{v}.length <= {c} ? "None" : {v}[{c}].innerHTML'.format(v=tmpVarName, c=index))219 self.run('delete {v}'.format(v=tmpVarName))220 if result == '"None"':221 return None222 return result.strip(string.whitespace+'"')223 224 def get_tab_elementByClassName_href(self, classNames, index=0, tabID=-1):225 """226 Get the url an element points to.227 """228 with self:229 tmpVarName = "MozReplTempValue"230 self.run('{v} = gBrowser.tabContainer.childNodes[{i}].linkedBrowser.contentDocument.getElementsByClassName("{n}")'.format(v=tmpVarName, i=tabID, n=classNames))231 result = self.get_text_result('{v}.length <= {c} ? "None" : {v}[{c}].href'.format(v=tmpVarName, c=index))232 self.run('delete {v}'.format(v=tmpVarName))233 if result == '"None"':234 return None235 return result.strip(string.whitespace+'"')236 237 def get_tab_elementById_html(self, elementId, tabID=-1):238 """239 HTML source of the current tab.240 If the current page is big, don't use241 this method on it, it'll take much time.242 """243 with self:244 tmpVarName = "MozReplTempValue"245 self.run('{v} = gBrowser.tabContainer.childNodes[{i}].linkedBrowser.contentDocument.getElementById("{e}")'.format(v=tmpVarName, i=tabID, e=elementId))246 result = self.get_text_result('{v} == null ? "None" : {v}.innerHTML'.format(v=tmpVarName))247 self.run('delete {v}'.format(v=tmpVarName))248 if result == '"None"':249 return None250 return result.strip(string.whitespace+'"')251 252 def tab_movie_player_available(self, playerId='movie_player', tabID=-1):253 """254 """255 with self:256 tmpVarName = "MozReplTempValue"257 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})258 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s') == null ? false : true\", %s)" % (playerId, tmpVarName))259 self.run('delete {v}'.format(v=tmpVarName))260 return bool(strtobool(result))261 262 def get_tab_movie_player_state(self, playerId='movie_player', tabID=-1):263 """264 Returns the state of the player.265 266 -1 -- unstarted267 0 -- ended268 1 -- playing269 2 -- paused270 3 -- buffering271 5 -- video cued272 """273 with self:274 tmpVarName = "MozReplTempValue"275 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})276 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').getPlayerState()\", %s)" % (playerId, tmpVarName))277 self.run('delete {v}'.format(v=tmpVarName))278 if result == '"None"':279 return -1280 intRes = int(result)281 if -1 > intRes or intRes > 3:282 #Dont use 5 Video Cued, return -1 Unstarted.283 #Same for any other status.284 return -1285 return intRes286 287 def get_tab_movie_player_current_time(self, playerId='movie_player', tabID=-1):288 """289 Returns the elapsed time in seconds since the video started playing.290 """291 with self:292 tmpVarName = "MozReplTempValue"293 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})294 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').getCurrentTime()\", %s)" % (playerId, tmpVarName))295 self.run('delete {v}'.format(v=tmpVarName))296 if result == '"None"':297 return None298 return float(result)299 300 def get_tab_movie_player_duration(self, playerId='movie_player', tabID=-1):301 """302 Returns the duration in seconds of the currently playing video.303 """304 with self:305 tmpVarName = "MozReplTempValue"306 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})307 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').getDuration()\", %s)" % (playerId, tmpVarName))308 self.run('delete {v}'.format(v=tmpVarName))309 if result == '"None"':310 return None311 return float(result)312 313 def tab_movie_player_seek(self, time, playerId='movie_player', tabID=-1):314 """315 HTML source of the current tab.316 If the current page is big, don't use317 this method on it, it'll take much time.318 """319 with self:320 tmpVarName = "MozReplTempValue"321 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})322 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').seekTo(%s, true)\", %s)" % (playerId, time, tmpVarName))323 self.run('delete {v}'.format(v=tmpVarName))324 if result == '"None"':325 return None326 return result.strip(string.whitespace+'"')327 def tab_movie_player_getVolume(self, playerId='movie_player', tabID=-1):328 """329 HTML source of the current tab.330 If the current page is big, don't use331 this method on it, it'll take much time.332 """333 with self:334 tmpVarName = "MozReplTempValue"335 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})336 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').getVolume()\", %s)" % (playerId, tmpVarName))337 self.run('delete {v}'.format(v=tmpVarName))338 return float(result)339 340 def tab_movie_player_setVolume(self, vol, playerId='movie_player', tabID=-1):341 """342 HTML source of the current tab.343 If the current page is big, don't use344 this method on it, it'll take much time.345 """346 with self:347 tmpVarName = "MozReplTempValue"348 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})349 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').setVolume(%s)\", %s)" % (playerId, vol, tmpVarName))350 self.run('delete {v}'.format(v=tmpVarName))351 if result == '"None"':352 return None353 return result.strip(string.whitespace+'"')354 def tab_movie_player_play(self, play=True, playerId='movie_player', tabID=-1):355 """356 HTML source of the current tab.357 If the current page is big, don't use358 this method on it, it'll take much time.359 """360 with self:361 tmpVarName = "MozReplTempValue"362 self.run("%(var)s = Components.utils.Sandbox(gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow,{sandboxPrototype:gBrowser.tabContainer.childNodes[%(id)s].linkedBrowser.contentWindow, wantXrays:false})" % {'var':tmpVarName, 'id':tabID})363 if play:364 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').playVideo()\", %s)" % (playerId, tmpVarName))365 else:366 result = self.get_text_result("Components.utils.evalInSandbox(\"document.getElementById('%s').pauseVideo()\", %s)" % (playerId, tmpVarName))367 self.run('delete {v}'.format(v=tmpVarName))368 if result == '"None"':369 return None370 return result.strip(string.whitespace+'"')371 372 def close_tab(self, tabID=-1):373 """374 Close the current tab.375 """376 with self:377 if not (-1 <= tabID < self.get_number_of_tabs()):378 raise ValueError("TabID should be -1 for current tab or the tab ID.")379 if tabID == -1:380 self.run('gBrowser.removeCurrentTab()')381 else:382 self.run('gBrowser.removeTab(gBrowser.tabContainer.childNodes[{}])'.format(tabID))383 384 def get_curr_tab_title(self):385 """386 Title of the page in the current tab.387 """388 with self:389 result = self.get_text_result('document.title')390 return result391 392 def get_tab_list(self):393 cmd = \394"""395String.prototype.format = function() {396 var formatted = this;397 for(arg in arguments) {398 formatted = formatted.replace("{" + arg + "}", arguments[arg]);399 }400 return formatted;401};402var all_tabs = gBrowser.mTabContainer.childNodes;403var tab_list = [];404for (var i = 0; i < all_tabs.length; ++i ) {405 var tab = gBrowser.getBrowserForTab(all_tabs[i]).contentDocument;406 if(tab.location != "about:blank")407 tab_list.push({"url":tab.location, "title":tab.title});408}409for (var i=0; i<tab_list.length; ++i) {410 var title = tab_list[i].title;411 title = title.replace(/"/g, "'");412 var item = '{"index": {0}, "title": "{1}", "url": "{2}"}'.format(i, title, tab_list[i].url);413 repl.print(item);414}415"""416 with self:417 result = self.get_text_result(cmd, sep='\n')418 li = []419 for e in result.split('\n'):420 li.append(json.loads(e))421 return li422 def restoreRepl(self):423 with self:424 self.run('repl.home()')425 426 def isLoadingDocument(self):427 with self:428 result = self.get_text_result("window.getBrowser().webProgress.isLoadingDocument")429 return bool(strtobool(result))430 431 def back(self):432 with self:433 return self.run("gBrowser.goBack()")434 435 @staticmethod436 def sanitizeText(txt):437 txt = txt.strip(string.whitespace + '"')438 if txt.startswith("[URL]") == True:439 txt = txt[len("[URL]"):0-(len("[/URL]"))]440 #<span>The Young Turks LIVE! 6.01.17</span>441 442 ...
annotation_utils.py
Source:annotation_utils.py
1# Copyright 2013 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4"""Generates annotated output.5TODO(stip): Move the gtest_utils gtest parser selection code from runtest.py6to here.7TODO(stip): Move the perf dashboard code from runtest.py to here.8"""9import re10from slave import slave_utils11# Status codes that can be returned by the evaluateCommand method.12# From buildbot.status.builder.13# See: http://docs.buildbot.net/current/developer/results.html14SUCCESS, WARNINGS, FAILURE, SKIPPED, EXCEPTION, RETRY = range(6)15def getText(result, observer, name):16 """Generate a text summary for the waterfall.17 Updates the waterfall with any unusual test output, with a link to logs of18 failed test steps.19 """20 GTEST_DASHBOARD_BASE = ('http://test-results.appspot.com'21 '/dashboards/flakiness_dashboard.html')22 # TODO(xusydoc): unify this with gtest reporting below so getText() is23 # less confusing24 if hasattr(observer, 'PerformanceSummary'):25 basic_info = [name]26 summary_text = ['<div class="BuildResultInfo">']27 summary_text.extend(observer.PerformanceSummary())28 summary_text.append('</div>')29 return basic_info + summary_text30 # basic_info is an array of lines to display on the waterfall.31 basic_info = [name]32 disabled = observer.DisabledTests()33 if disabled:34 basic_info.append('%s disabled' % str(disabled))35 flaky = observer.FlakyTests()36 if flaky:37 basic_info.append('%s flaky' % str(flaky))38 failed_test_count = len(observer.FailedTests())39 if failed_test_count == 0:40 if result == SUCCESS:41 return basic_info42 elif result == WARNINGS:43 return basic_info + ['warnings']44 if observer.RunningTests():45 basic_info += ['did not complete']46 # TODO(xusydoc): see if 'crashed or hung' should be tracked by RunningTests().47 if failed_test_count:48 failure_text = ['failed %d' % failed_test_count]49 if observer.master_name:50 # Include the link to the flakiness dashboard.51 failure_text.append('<div class="BuildResultInfo">')52 failure_text.append('<a href="%s#testType=%s'53 '&tests=%s">' % (GTEST_DASHBOARD_BASE,54 name,55 ','.join(observer.FailedTests())))56 failure_text.append('Flakiness dashboard')57 failure_text.append('</a>')58 failure_text.append('</div>')59 else:60 failure_text = ['crashed or hung']61 return basic_info + failure_text62def annotate(test_name, result, log_processor, perf_dashboard_id=None):63 """Given a test result and tracker, update the waterfall with test results."""64 # Always print raw exit code of the subprocess. This is very helpful65 # for debugging, especially when one gets the "crashed or hung" message66 # with no output (exit code can have some clues, especially on Windows).67 print 'exit code (as seen by runtest.py): %d' % result68 get_text_result = SUCCESS69 for failure in sorted(log_processor.FailedTests()):70 clean_test_name = re.sub(r'[^\w\.\-]', '_', failure)71 slave_utils.WriteLogLines(clean_test_name,72 log_processor.FailureDescription(failure))73 for report_hash in sorted(log_processor.MemoryToolReportHashes()):74 slave_utils.WriteLogLines(report_hash,75 log_processor.MemoryToolReport(report_hash))76 if log_processor.ParsingErrors():77 # Generate a log file containing the list of errors.78 slave_utils.WriteLogLines('log parsing error(s)',79 log_processor.ParsingErrors())80 log_processor.ClearParsingErrors()81 if hasattr(log_processor, 'evaluateCommand'):82 parser_result = log_processor.evaluateCommand('command')83 if parser_result > result:84 result = parser_result85 if result == SUCCESS:86 if (len(log_processor.ParsingErrors()) or87 len(log_processor.FailedTests()) or88 len(log_processor.MemoryToolReportHashes())):89 print '@@@STEP_WARNINGS@@@'90 get_text_result = WARNINGS91 elif result == slave_utils.WARNING_EXIT_CODE:92 print '@@@STEP_WARNINGS@@@'93 get_text_result = WARNINGS94 else:95 print '@@@STEP_FAILURE@@@'96 get_text_result = FAILURE97 for desc in getText(get_text_result, log_processor, test_name):98 print '@@@STEP_TEXT@%s@@@' % desc99 if hasattr(log_processor, 'PerformanceLogs'):100 if not perf_dashboard_id:101 raise Exception('runtest.py error: perf step specified but'102 'no test_id in factory_properties!')103 for logname, log in log_processor.PerformanceLogs().iteritems():104 lines = [str(l).rstrip() for l in log]...
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!!