Home | History | Annotate | Download | only in automation
      1 // Copyright (c) 2012 The Chromium 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 
      5 #ifndef CHROME_TEST_AUTOMATION_AUTOMATION_PROXY_H_
      6 #define CHROME_TEST_AUTOMATION_AUTOMATION_PROXY_H_
      7 
      8 #include <string>
      9 #include <vector>
     10 
     11 #include "base/basictypes.h"
     12 #include "base/compiler_specific.h"
     13 #include "base/memory/scoped_ptr.h"
     14 #include "base/synchronization/waitable_event.h"
     15 #include "base/threading/platform_thread.h"
     16 #include "base/threading/thread.h"
     17 #include "base/time/time.h"
     18 #include "chrome/browser/ui/browser.h"
     19 #include "chrome/common/automation_constants.h"
     20 #include "chrome/test/automation/automation_handle_tracker.h"
     21 #include "chrome/test/automation/browser_proxy.h"
     22 #include "ipc/ipc_channel_proxy.h"
     23 #include "ipc/ipc_sender.h"
     24 #include "ipc/ipc_sync_channel.h"
     25 #include "ui/base/ui_base_types.h"
     26 #include "ui/gfx/native_widget_types.h"
     27 #include "url/gurl.h"
     28 
     29 class BrowserProxy;
     30 class TabProxy;
     31 class WindowProxy;
     32 struct ExternalTabSettings;
     33 
     34 // This is an interface that AutomationProxy-related objects can use to
     35 // access the message-sending abilities of the Proxy.
     36 class AutomationMessageSender : public IPC::Sender {
     37  public:
     38   // Sends a message synchronously; it doesn't return until a response has been
     39   // received or a timeout has expired.
     40   //
     41   // The function returns true if a response is received, and returns false if
     42   // there is a failure or timeout (in milliseconds).
     43   //
     44   // NOTE: When timeout occurs, the connection between proxy provider may be
     45   //       in transit state. Specifically, there might be pending IPC messages,
     46   //       and the proxy provider might be still working on the previous
     47   //       request.
     48   virtual bool Send(IPC::Message* message) = 0;
     49   virtual bool Send(IPC::Message* message, int timeout_ms) = 0;
     50 };
     51 
     52 // This is the interface that external processes can use to interact with
     53 // a running instance of the app.
     54 class AutomationProxy : public IPC::Listener, public AutomationMessageSender {
     55  public:
     56   AutomationProxy(base::TimeDelta action_timeout, bool disconnect_on_failure);
     57   virtual ~AutomationProxy();
     58 
     59   // Creates a previously unused channel id.
     60   static std::string GenerateChannelID();
     61 
     62   // Initializes a channel for a connection to an AutomationProvider.
     63   // If use_named_interface is false, it will act as a client
     64   // and connect to the named IPC socket with channel_id as its path.
     65   // If use_named_interface is true, it will act as a server and
     66   // use an anonymous socketpair instead.
     67   void InitializeChannel(const std::string& channel_id,
     68                          bool use_named_interface);
     69 
     70   // IPC callback
     71   virtual bool OnMessageReceived(const IPC::Message& msg);
     72   virtual void OnChannelError();
     73 
     74   // Close the automation IPC channel.
     75   void Disconnect();
     76 
     77   // Waits for the app to launch and the automation provider to say hello
     78   // (the app isn't fully done loading by this point).
     79   // Returns SUCCESS if the launch is successful.
     80   // Returns TIMEOUT if there was no response by action_timeout_
     81   // Returns VERSION_MISMATCH if the automation protocol version of the
     82   // automation provider does not match and if perform_version_check_ is set
     83   // to true. Note that perform_version_check_ defaults to false, call
     84   // set_perform_version_check() to set it.
     85   AutomationLaunchResult WaitForAppLaunch();
     86 
     87   // See description in AutomationMsg_WaitForProcessLauncherThreadToGoIdle.
     88   bool WaitForProcessLauncherThreadToGoIdle() WARN_UNUSED_RESULT;
     89 
     90   // Waits for any initial page loads to complete.
     91   // NOTE: this only fires once for a run of the application.
     92   // Returns true if the load is successful
     93   bool WaitForInitialLoads() WARN_UNUSED_RESULT;
     94 
     95   // Waits for the initial destinations tab to report that it has finished
     96   // querying.  |load_time| is filled in with how long it took, in milliseconds.
     97   // NOTE: this only fires once for a run of the application.
     98   // Returns true if the load is successful.
     99   bool WaitForInitialNewTabUILoad(int* load_time) WARN_UNUSED_RESULT;
    100 
    101   // Open a new browser window of type |type|, returning true on success. |show|
    102   // identifies whether the window should be shown. Returns true on success.
    103   bool OpenNewBrowserWindow(Browser::Type type, bool show) WARN_UNUSED_RESULT;
    104 
    105   // Fills the number of open browser windows into the given variable, returning
    106   // true on success. False likely indicates an IPC error.
    107   bool GetBrowserWindowCount(int* num_windows) WARN_UNUSED_RESULT;
    108 
    109   // Block the thread until the window count becomes the provided value.
    110   // Returns true on success.
    111   bool WaitForWindowCountToBecome(int target_count) WARN_UNUSED_RESULT;
    112 
    113   // Fills the number of open normal browser windows (normal type and
    114   // non-incognito mode) into the given variable, returning true on success.
    115   // False likely indicates an IPC error.
    116   bool GetNormalBrowserWindowCount(int* num_windows) WARN_UNUSED_RESULT;
    117 
    118   // Returns true if one of the tabs in any window displays given url.
    119   bool IsURLDisplayed(GURL url) WARN_UNUSED_RESULT;
    120 
    121   // Get the duration of the last |event_name| in the browser.  Returns
    122   // false if the IPC failed to send.
    123   bool GetMetricEventDuration(const std::string& event_name,
    124                               int* duration_ms) WARN_UNUSED_RESULT;
    125 
    126   // Returns the BrowserProxy for the browser window at the given index,
    127   // transferring ownership of the pointer to the caller.
    128   // On failure, returns NULL.
    129   //
    130   // Use GetBrowserWindowCount to see how many browser windows you can ask for.
    131   // Window numbers are 0-based.
    132   scoped_refptr<BrowserProxy> GetBrowserWindow(int window_index);
    133 
    134   // Sends the browser a new proxy configuration to start using. Returns true
    135   // if the proxy config was successfully sent, false otherwise.
    136   bool SendProxyConfig(const std::string& new_proxy_config) WARN_UNUSED_RESULT;
    137 
    138   // These methods are intended to be called by the background thread
    139   // to signal that the given event has occurred, and that any corresponding
    140   // Wait... function can return.
    141   void SignalAppLaunch(const std::string& version_string);
    142   void SignalInitialLoads();
    143   // load_time is how long, in ms, the tab contents took to load.
    144   void SignalNewTabUITab(int load_time);
    145 
    146   // Gets the next extension test result in |result|. Returns false if there
    147   // was a problem sending the result querying RPC.
    148   bool GetExtensionTestResult(bool* result, std::string* message);
    149 
    150   // Generic pattern for sending automation requests.
    151   bool SendJSONRequest(const std::string& request,
    152                        int timeout_ms,
    153                        std::string* response) WARN_UNUSED_RESULT;
    154 
    155   // Begin tracing specified category_patterns on the browser instance. Blocks
    156   // until browser acknowledges that tracing has begun (or failed if false is
    157   // returned). |category_patterns| is a comma-delimited list of category
    158   // wildcards.
    159   // A category pattern can have an optional '-' prefix to exclude category
    160   // groups that contain matching category.
    161   // Either all category_patterns must be included or all must be excluded.
    162   //
    163   // Example: BeginTracing("test_MyTest*");
    164   // Example: BeginTracing("test_MyTest*,test_OtherStuff");
    165   // Example: BeginTracing("-excluded_category1,-excluded_category2");
    166   //
    167   // See base/event_trace.h for documentation of included and excluded
    168   // category_patterns.
    169   bool BeginTracing(const std::string& category_patterns) WARN_UNUSED_RESULT;
    170 
    171   // End trace and collect the trace output as a json string.
    172   bool EndTracing(std::string* json_trace_output) WARN_UNUSED_RESULT;
    173 
    174   IPC::SyncChannel* channel();
    175 
    176   // AutomationMessageSender implementation.
    177   virtual bool Send(IPC::Message* message) WARN_UNUSED_RESULT;
    178   virtual bool Send(IPC::Message* message, int timeout_ms) WARN_UNUSED_RESULT;
    179 
    180   // Wrapper over AutomationHandleTracker::InvalidateHandle. Receives the
    181   // message from AutomationProxy, unpacks the messages and routes that call to
    182   // the tracker.
    183   virtual void InvalidateHandle(const IPC::Message& message);
    184 
    185   base::TimeDelta action_timeout() const {
    186     return action_timeout_;
    187   }
    188 
    189   // Sets the timeout for subsequent automation calls.
    190   void set_action_timeout(base::TimeDelta timeout) {
    191     DCHECK(timeout <= base::TimeDelta::FromMinutes(10))
    192         << "10+ min of automation timeout "
    193            "can make the test hang and be killed by buildbot";
    194     action_timeout_ = timeout;
    195   }
    196 
    197   // Returns the server version of the server connected. You may only call this
    198   // method after WaitForAppLaunch() has returned SUCCESS or VERSION_MISMATCH.
    199   // If you call it before this, the return value is undefined.
    200   std::string server_version() const {
    201     return server_version_;
    202   }
    203 
    204   // Call this while passing true to tell the automation proxy to perform
    205   // a version check when WaitForAppLaunch() is called. Note that
    206   // platform_version_check_ defaults to false.
    207   void set_perform_version_check(bool perform_version_check) {
    208     perform_version_check_ = perform_version_check;
    209   }
    210 
    211   // These functions set and reset the IPC::Channel pointer on the tracker.
    212   void SetChannel(IPC::Channel* channel);
    213   void ResetChannel();
    214 
    215   // See description above |channel_disconnected_on_failure_|.
    216   bool channel_disconnected_on_failure() const {
    217     return channel_disconnected_on_failure_;
    218   }
    219 
    220  protected:
    221   template <class T> scoped_refptr<T> ProxyObjectFromHandle(int handle);
    222   void InitializeThread();
    223   void InitializeHandleTracker();
    224 
    225   scoped_ptr<base::Thread> thread_;
    226   scoped_ptr<IPC::SyncChannel> channel_;
    227   scoped_ptr<AutomationHandleTracker> tracker_;
    228 
    229   base::WaitableEvent app_launched_;
    230   base::WaitableEvent initial_loads_complete_;
    231   base::WaitableEvent new_tab_ui_load_complete_;
    232   int new_tab_ui_load_time_;
    233 
    234   // An event that notifies when we are shutting-down.
    235   scoped_ptr<base::WaitableEvent> shutdown_event_;
    236 
    237   // The version of the automation provider we are communicating with.
    238   std::string server_version_;
    239 
    240   // Whether to perform a version check between the automation proxy and
    241   // the automation provider at connection time. Defaults to false, you can
    242   // set this to true if building the automation proxy into a module with
    243   // a version resource.
    244   bool perform_version_check_;
    245 
    246   // If true, the proxy will disconnect the IPC channel on first failure
    247   // to send an IPC message. This helps avoid long timeouts in tests.
    248   bool disconnect_on_failure_;
    249 
    250   // Set if disconnect_on_failure_ caused the connection to be dropped.
    251   bool channel_disconnected_on_failure_;
    252 
    253   // Delay to let the browser execute the command.
    254   base::TimeDelta action_timeout_;
    255 
    256   base::PlatformThreadId listener_thread_id_;
    257 
    258   DISALLOW_COPY_AND_ASSIGN(AutomationProxy);
    259 };
    260 
    261 #endif  // CHROME_TEST_AUTOMATION_AUTOMATION_PROXY_H_
    262