webpagereplay_wrapper.py revision b058a8f201af2d99f3d02aa956ab118df2d9c67d
1# Copyright 2015 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5from autotest_lib.client.bin import utils
6from telemetry.internal.util import webpagereplay
7
8
9class WebPageReplayWrapper(object):
10    """
11    Wraps around WPR Server to be conveniently used in autotest.
12
13    """
14
15    _REPLAY_HOST = "127.0.0.1"
16
17
18    def __init__(self, archive_path):
19        """
20        Creates a WPR server using archive_path and pre-set arguments.
21
22        @param archive_path: path to the .wpr archive to be used.
23
24        """
25
26        port = utils.get_unused_port()
27        self._http_port = port if port else 8080
28
29        port = utils.get_unused_port()
30        self._https_port = port if port else 8713
31
32        self._server = webpagereplay.ReplayServer(
33                archive_path=archive_path,
34                replay_host=WebPageReplayWrapper._REPLAY_HOST,
35                http_port=self._http_port,
36                https_port=self._https_port,
37                dns_port=None,
38                replay_options=[])
39
40
41    @property
42    def chrome_flags_for_wpr(self):
43        """
44        @return: list of Chrome flags needed to direct traffic to WPR server.
45
46        """
47        return ['--host-resolver-rules=MAP * %s, EXCLUDE localhost' %
48                WebPageReplayWrapper._REPLAY_HOST,
49                '--testing-fixed-http-port=%s' % self._http_port,
50                '--testing-fixed-https-port=%s' % self._https_port,
51                '--ignore-certificate-errors']
52
53
54    def __enter__(self):
55        return self._server.__enter__()
56
57
58    def __exit__(self, exc_type, exc_val, exc_tb):
59        return self._server.__exit__(exc_type, exc_val, exc_tb)
60
61
62class NullWebPageReplayWrapper(object):
63    """
64    Empty class. Created to simply clients code, no other purpose.
65
66    Client will do:
67    with chrome.Chrome() as cr, wpr_server:
68       ....
69
70    When we are not using WPR we will return this empty class, leaving client's
71    code uniform and unchanged.
72
73    """
74
75    @property
76    def chrome_flags_for_wpr(self):
77        """
78        @return: an empty list. This is an empty class.
79
80        """
81        return []
82
83
84    def __enter__(self):
85        return self
86
87
88    def __exit__(self, exc_type, exc_val, exc_tb):
89        pass
90