telemetry
index
telemetry/__init__.py

A library for cross-platform browser tests.

 
Package Contents
       
core (package)
decorators
exception_formatter
page (package)
test
test_runner
unittest (package)
util (package)
value (package)
web_components (package)

 
Classes
       
__builtin__.object
telemetry.core.browser.Browser
optparse.Values
telemetry.core.browser_options.BrowserFinderOptions
telemetry.core.web_contents.WebContents(__builtin__.object)
telemetry.core.tab.Tab
telemetry.page.page_test.PageTest(telemetry.core.command_line.ArgumentHandlerMixIn)
telemetry.page.page_measurement.PageMeasurement

 
class Browser(__builtin__.object)
    A running browser instance that can be controlled in a limited way.
 
To create a browser instance, use browser_finder.FindBrowser.
 
Be sure to clean up after yourself by calling Close() when you are done with
the browser. Or better yet:
  browser_to_create = FindBrowser(options)
  with browser_to_create.Create() as browser:
    ... do all your operations on browser here
 
  Methods defined here:
Close(self)
Closes this browser.
GetStackTrace(self)
GetStandardOutput(self)
GetSystemInfo(self)
Returns low-level information about the system, if available.
 
See the documentation of the SystemInfo class for more details.
SetHTTPServerDirectories(self, paths)
Returns True if the HTTP server was started, False otherwise.
SetReplayArchivePath(self, archive_path, append_to_existing_wpr=False, make_javascript_deterministic=True)
Start(self)
StartLocalServer(self, server)
Starts a LocalServer and associates it with this browser.
 
It will be closed when the browser closes.
StartProfiling(self, profiler_name, base_output_file)
Starts profiling using |profiler_name|. Results are saved to
|base_output_file|.<process_name>.
StartTracing(self, custom_categories=None, timeout=10)
StopProfiling(self)
Stops all active profilers and saves their results.
 
Returns:
  A list of filenames produced by the profiler.
StopTracing(self)
Stops tracing and returns the result as TimelineData object.
__enter__(self)
__exit__(self, *args)
__init__(self, backend, platform_backend)
is_profiler_active(self, profiler_name)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
browser_type
cpu_stats
Returns a dict of cpu statistics for the system.
{ 'Browser': {
    'CpuProcessTime': S,
    'TotalTime': T
  },
  'Gpu': {
    'CpuProcessTime': S,
    'TotalTime': T
  },
  'Renderer': {
    'CpuProcessTime': S,
    'TotalTime': T
  }
}
Any of the above keys may be missing on a per-platform basis.
extensions
foreground_tab
http_server
io_stats
Returns a dict of IO statistics for the browser:
{ 'Browser': {
    'ReadOperationCount': W,
    'WriteOperationCount': X,
    'ReadTransferCount': Y,
    'WriteTransferCount': Z
  },
  'Gpu': {
    'ReadOperationCount': W,
    'WriteOperationCount': X,
    'ReadTransferCount': Y,
    'WriteTransferCount': Z
  },
  'Renderer': {
    'ReadOperationCount': W,
    'WriteOperationCount': X,
    'ReadTransferCount': Y,
    'WriteTransferCount': Z
  }
}
is_content_shell
Returns whether this browser is a content shell, only.
is_tracing_running
local_servers
Returns the currently running local servers.
memory_stats
Returns a dict of memory statistics for the browser:
{ 'Browser': {
    'VM': R,
    'VMPeak': S,
    'WorkingSetSize': T,
    'WorkingSetSizePeak': U,
    'ProportionalSetSize': V,
    'PrivateDirty': W
  },
  'Gpu': {
    'VM': R,
    'VMPeak': S,
    'WorkingSetSize': T,
    'WorkingSetSizePeak': U,
    'ProportionalSetSize': V,
    'PrivateDirty': W
  },
  'Renderer': {
    'VM': R,
    'VMPeak': S,
    'WorkingSetSize': T,
    'WorkingSetSizePeak': U,
    'ProportionalSetSize': V,
    'PrivateDirty': W
  },
  'SystemCommitCharge': X,
  'SystemTotalPhysicalMemory': Y,
  'ProcessCount': Z,
}
Any of the above keys may be missing on a per-platform basis.
platform
supports_extensions
supports_system_info
supports_tab_control
supports_tracing
synthetic_gesture_source_type
tabs

 
class BrowserFinderOptions(optparse.Values)
    Options to be used for discovering a browser.
 
  Methods defined here:
AppendExtraBrowserArgs(self, args)
Copy(self)
CreateParser(self, *args, **kwargs)
MergeDefaultValues(self, defaults)
__init__(self, browser_type=None)

Methods inherited from optparse.Values:
__cmp__(self, other)
__repr__ = _repr(self)
__str__(self)
ensure_value(self, attr, value)
read_file(self, filename, mode='careful')
read_module(self, modname, mode='careful')

 
class PageMeasurement(telemetry.page.page_test.PageTest)
    Glue code for running a measurement across a set of pages.
 
To use this, subclass from the measurement and override MeasurePage. For
example:
 
   class BodyChildElementMeasurement(PageMeasurement):
      def MeasurePage(self, page, tab, results):
         body_child_count = tab.EvaluateJavaScript(
             'document.body.children.length')
         results.Add('body_children', 'count', body_child_count)
 
   if __name__ == '__main__':
       page_measurement.Main(BodyChildElementMeasurement())
 
To add test-specific options:
 
   class BodyChildElementMeasurement(PageMeasurement):
      def AddCommandLineArgs(parser):
         parser.add_option('--element', action='store', default='body')
 
      def MeasurePage(self, page, tab, results):
         body_child_count = tab.EvaluateJavaScript(
            'document.querySelector('%s').children.length')
         results.Add('children', 'count', child_count)
 
 
Method resolution order:
PageMeasurement
telemetry.page.page_test.PageTest
telemetry.core.command_line.ArgumentHandlerMixIn
__builtin__.object

Methods defined here:
MeasurePage(self, page, tab, results)
Override to actually measure the page's performance.
 
page is a page_set.Page
tab is an instance of telemetry.core.Tab
 
Should call results.Add(name, units, value) for each result, or raise an
exception on failure. The name and units of each Add() call must be
the same across all iterations. The name 'url' must not be used.
 
Prefer field names that are in accordance with python variable style. E.g.
field_name.
 
Put together:
 
   def MeasurePage(self, page, tab, results):
     res = tab.EvaluateJavaScript('2+2')
     if res != 4:
       raise Exception('Oh, wow.')
     results.Add('two_plus_two', 'count', res)
__init__(self, action_name_to_run='', needs_browser_restart_after_each_page=False, discard_first_result=False, clear_cache_before_each_run=False)

Data descriptors defined here:
results_are_the_same_on_every_page
By default, measurements are assumed to output the same values for every
page. This allows incremental output, for example in CSV. If, however, the
measurement discovers what values it can report as it goes, and those values
may vary from page to page, you need to override this function and return
False. Output will not appear in this mode until the entire pageset has
run.

Methods inherited from telemetry.page.page_test.PageTest:
CanRunForPage(self, page)
Override to customize if the test can be ran for the given page.
CleanUpAfterPage(self, page, tab)
Called after the test run method was run, even if it failed.
CreateExpectations(self, page_set)
Override to make this test generate its own expectations instead of
any that may have been defined in the page set.
CreatePageSet(self, args, options)
Override to make this test generate its own page set instead of
allowing arbitrary page sets entered from the command-line.
CustomizeBrowserOptions(self, options)
Override to add test-specific options to the BrowserOptions object
CustomizeBrowserOptionsForPageSet(self, page_set, options)
Set options required for this page set.
 
These options will be used every time the browser is started while running
this page set. They may, however, be further modified by
CustomizeBrowserOptionsForSinglePage or by the profiler.
CustomizeBrowserOptionsForSinglePage(self, page, options)
Set options specific to the test and the given page.
 
This will be called with the current page when the browser is (re)started.
Changing options at this point only makes sense if the browser is being
restarted for each page. Note that if page has a startup_url, the browser
will always be restarted for each run.
DidNavigateToPage(self, page, tab)
Override to do operations right after the page is navigated and after
all waiting for completion has occurred.
DidRunAction(self, page, tab, action)
Override to do operations after running the action on the page.
DidRunActions(self, page, tab)
Override to do operations after running the actions on the page.
DidRunPageRepeats(self, page)
Override to do operations after each page is iterated over.
DidRunTest(self, browser, results)
Override to do operations after all page set(s) are completed.
 
This will occur before the browser is torn down.
DidStartBrowser(self, browser)
Override to customize the browser right after it has launched.
DidStartHTTPServer(self, tab)
Override to do operations after the HTTP server is started.
IsExiting(self)
RequestExit(self)
RestartBrowserBeforeEachPage(self)
Should the browser be restarted for the page?
 
This returns true if the test needs to unconditionally restart the
browser for each page. It may be called before the browser is started.
Run(self, page, tab, results)
RunNavigateSteps(self, page, tab)
Navigates the tab to the page URL attribute.
 
Runs the 'navigate_steps' page attribute as a compound action.
StopBrowserAfterPage(self, browser, page)
Should the browser be stopped after the page is run?
 
This is called after a page is run to decide whether the browser needs to
be stopped to clean up its state. If it is stopped, then it will be
restarted to run the next page.
 
A test that overrides this can look at both the page and the browser to
decide whether it needs to stop the browser.
TabForPage(self, page, browser)
Override to select a different tab for the page.  For instance, to
create a new tab for every page, return browser.tabs.New().
ValidatePageSet(self, page_set)
Override to examine the page set before the test run.  Useful for
example to validate that the pageset can be used with the test.
WillNavigateToPage(self, page, tab)
Override to do operations before the page is navigated, notably Telemetry
will already have performed the following operations on the browser before
calling this function:
* Ensure only one tab is open.
* Call WaitForDocumentReadyStateToComplete on the tab.
WillRunAction(self, page, tab, action)
Override to do operations before running the action on the page.
WillRunActions(self, page, tab)
Override to do operations before running the actions on the page.
WillRunPageRepeats(self, page)
Override to do operations before each page is iterated over.
WillRunTest(self, options)
Override to do operations before the page set(s) are navigated.
WillStartBrowser(self, browser)
Override to manipulate the browser environment before it launches.

Data descriptors inherited from telemetry.page.page_test.PageTest:
action_name_to_run
attempts
Maximum number of times test will be attempted.
clear_cache_before_each_run
When set to True, the browser's disk and memory cache will be cleared
before each run.
close_tabs_before_run
When set to True, all tabs are closed before running the test for the
first time.
discard_first_result
When set to True, the first run of the test is discarded.  This is
useful for cases where it's desirable to have some test resource cached so
the first run of the test can warm things up.
max_errors
Maximum number of errors allowed for the page set.
max_failures
Maximum number of failures allowed for the page set.

Class methods inherited from telemetry.core.command_line.ArgumentHandlerMixIn:
AddCommandLineArgs(cls, parser) from __builtin__.type
Override to accept custom command-line arguments.
ProcessCommandLineArgs(cls, parser, args) from __builtin__.type
Override to process command-line arguments.
 
We pass in parser so we can call parser.error().

Data descriptors inherited from telemetry.core.command_line.ArgumentHandlerMixIn:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class Tab(telemetry.core.web_contents.WebContents)
    Represents a tab in the browser
 
The important parts of the Tab object are in the runtime and page objects.
E.g.:
    # Navigates the tab to a given url.
    tab.Navigate('http://www.google.com/')
 
    # Evaluates 1+1 in the tab's JavaScript context.
    tab.Evaluate('1+1')
 
 
Method resolution order:
Tab
telemetry.core.web_contents.WebContents
__builtin__.object

Methods defined here:
Activate(self)
Brings this tab to the foreground asynchronously.
 
Not all browsers or browser versions support this method.
Be sure to check browser.supports_tab_control.
 
Please note: this is asynchronous. There is a delay between this call
and the page's documentVisibilityState becoming 'visible', and yet more
delay until the actual tab is visible to the user. None of these delays
are included in this call.
ClearCache(self, force)
Clears the browser's networking related disk, memory and other caches.
 
Args:
  force: Iff true, navigates to about:blank which destroys the previous
      renderer, ensuring that even "live" resources in the memory cache are
      cleared.
ClearHighlight(self, color)
Clears a highlight of the given bitmap.RgbaColor.
CollectGarbage(self)
GetCookieByName(self, name, timeout=60)
Returns the value of the cookie by the given |name|.
Highlight(self, color)
Synchronously highlights entire tab contents with the given RgbaColor.
 
TODO(tonyg): It is possible that the z-index hack here might not work for
all pages. If this happens, DevTools also provides a method for this.
Navigate(self, url, script_to_evaluate_on_commit=None, timeout=60)
Navigates to url.
 
If |script_to_evaluate_on_commit| is given, the script source string will be
evaluated when the navigation is committed. This is after the context of
the page exists, but before any script on the page itself has executed.
PerformActionAndWaitForNavigate(self, action_function, timeout=60)
Executes action_function, and waits for the navigation to complete.
 
action_function must be a Python function that results in a navigation.
This function returns when the navigation is complete or when
the timeout has been exceeded.
Screenshot(self, timeout=60)
Capture a screenshot of the tab's contents.
 
Returns:
  A telemetry.core.Bitmap.
StartVideoCapture(self, min_bitrate_mbps)
Starts capturing video of the tab's contents.
 
This works by flashing the entire tab contents to a arbitrary color and then
starting video recording. When the frames are processed, we can look for
that flash as the content bounds.
 
Args:
  min_bitrate_mbps: The minimum caputre bitrate in MegaBits Per Second.
      The platform is free to deliver a higher bitrate if it can do so
      without increasing overhead.
StopVideoCapture(self)
Stops recording video of the tab's contents.
 
This looks for the initial color flash in the first frame to establish the
tab content boundaries and then omits all frames displaying the flash.
 
Yields:
  (time_ms, bitmap) tuples representing each video keyframe. Only the first
  frame in a run of sequential duplicate bitmaps is typically included.
    time_ms is milliseconds since navigationStart.
    bitmap is a telemetry.core.Bitmap.
__init__(self, inspector_backend)

Data descriptors defined here:
browser
The browser in which this tab resides.
dom_stats
A dictionary populated with measured DOM statistics.
 
Currently this dictionary contains:
{
  'document_count': integer,
  'node_count': integer,
  'event_listener_count': integer
}
is_video_capture_running
screenshot_supported
True if the browser instance is capable of capturing screenshots.
url
video_capture_supported
True if the browser instance is capable of capturing video.

Methods inherited from telemetry.core.web_contents.WebContents:
Close(self)
Closes this page.
 
Not all browsers or browser versions support this method.
Be sure to check browser.supports_tab_control.
EvaluateJavaScript(self, expr, timeout=90)
Evalutes expr in JavaScript and returns the JSONized result.
 
Consider using ExecuteJavaScript for cases where the result of the
expression is not needed.
 
If evaluation throws in JavaScript, a Python EvaluateException will
be raised.
 
If the result of the evaluation cannot be JSONized, then an
EvaluationException will be raised.
EvaluateJavaScriptInContext(self, expr, context_id, timeout=90)
Similar to ExecuteJavaScript, except context_id can refer to an iframe.
The main page has context_id=1, the first iframe context_id=2, etc.
ExecuteJavaScript(self, expr, timeout=90)
Executes expr in JavaScript. Does not return the result.
 
If the expression failed to evaluate, EvaluateException will be raised.
ExecuteJavaScriptInContext(self, expr, context_id, timeout=90)
Similar to ExecuteJavaScript, except context_id can refer to an iframe.
The main page has context_id=1, the first iframe context_id=2, etc.
HasReachedQuiescence(self)
Determine whether the page has reached quiescence after loading.
 
Returns:
  True if 2 seconds have passed since last resource received, false
  otherwise.
StartTimelineRecording(self, options=None)
StopTimelineRecording(self)
TakeJSHeapSnapshot(self, timeout=120)
WaitForDocumentReadyStateToBeComplete(self, timeout=90)
WaitForDocumentReadyStateToBeInteractiveOrBetter(self, timeout=90)
WaitForJavaScriptExpression(self, expr, timeout)
Waits for the given JavaScript expression to be True.
 
This method is robust against any given Evaluation timing out.

Data descriptors inherited from telemetry.core.web_contents.WebContents:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
is_timeline_recording_running
message_output_stream
timeline_model

 
Functions
       
RunPage = Run(test, page_set, expectations, finder_options)
Runs a given test against a given page_set with the given options.

 
Data
        __all__ = ['Browser', 'BrowserFinderOptions', 'PageMeasurement', 'RunPage', 'Tab']