• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights
2 // reserved. Use of this source code is governed by a BSD-style license that
3 // can be found in the LICENSE file.
4 
5 #include "tests/cefclient/browser/test_runner.h"
6 
7 #include <algorithm>
8 #include <map>
9 #include <set>
10 #include <sstream>
11 
12 #include "include/base/cef_callback.h"
13 #include "include/cef_parser.h"
14 #include "include/cef_task.h"
15 #include "include/cef_trace.h"
16 #include "include/cef_web_plugin.h"
17 #include "include/wrapper/cef_closure_task.h"
18 #include "include/wrapper/cef_stream_resource_handler.h"
19 #include "tests/cefclient/browser/binding_test.h"
20 #include "tests/cefclient/browser/client_handler.h"
21 #include "tests/cefclient/browser/dialog_test.h"
22 #include "tests/cefclient/browser/main_context.h"
23 #include "tests/cefclient/browser/media_router_test.h"
24 #include "tests/cefclient/browser/preferences_test.h"
25 #include "tests/cefclient/browser/resource.h"
26 #include "tests/cefclient/browser/response_filter_test.h"
27 #include "tests/cefclient/browser/root_window_manager.h"
28 #include "tests/cefclient/browser/scheme_test.h"
29 #include "tests/cefclient/browser/server_test.h"
30 #include "tests/cefclient/browser/urlrequest_test.h"
31 #include "tests/cefclient/browser/window_test.h"
32 #include "tests/shared/browser/resource_util.h"
33 
34 namespace client {
35 namespace test_runner {
36 
37 namespace {
38 
39 const char kTestHost[] = "tests";
40 const char kLocalHost[] = "localhost";
41 const char kTestOrigin[] = "http://tests/";
42 
43 // Pages handled via StringResourceProvider.
44 const char kTestGetSourcePage[] = "get_source.html";
45 const char kTestGetTextPage[] = "get_text.html";
46 const char kTestPluginInfoPage[] = "plugin_info.html";
47 
48 // Set page data and navigate the browser. Used in combination with
49 // StringResourceProvider.
LoadStringResourcePage(CefRefPtr<CefBrowser> browser,const std::string & page,const std::string & data)50 void LoadStringResourcePage(CefRefPtr<CefBrowser> browser,
51                             const std::string& page,
52                             const std::string& data) {
53   CefRefPtr<CefClient> client = browser->GetHost()->GetClient();
54   ClientHandler* client_handler = static_cast<ClientHandler*>(client.get());
55   client_handler->SetStringResource(page, data);
56   browser->GetMainFrame()->LoadURL(kTestOrigin + page);
57 }
58 
59 // Replace all instances of |from| with |to| in |str|.
StringReplace(const std::string & str,const std::string & from,const std::string & to)60 std::string StringReplace(const std::string& str,
61                           const std::string& from,
62                           const std::string& to) {
63   std::string result = str;
64   std::string::size_type pos = 0;
65   std::string::size_type from_len = from.length();
66   std::string::size_type to_len = to.length();
67   do {
68     pos = result.find(from, pos);
69     if (pos != std::string::npos) {
70       result.replace(pos, from_len, to);
71       pos += to_len;
72     }
73   } while (pos != std::string::npos);
74   return result;
75 }
76 
RunGetSourceTest(CefRefPtr<CefBrowser> browser)77 void RunGetSourceTest(CefRefPtr<CefBrowser> browser) {
78   class Visitor : public CefStringVisitor {
79    public:
80     explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) {}
81     virtual void Visit(const CefString& string) override {
82       std::string source = StringReplace(string, "<", "&lt;");
83       source = StringReplace(source, ">", "&gt;");
84       std::stringstream ss;
85       ss << "<html><body bgcolor=\"white\">Source:<pre>" << source
86          << "</pre></body></html>";
87       LoadStringResourcePage(browser_, kTestGetSourcePage, ss.str());
88     }
89 
90    private:
91     CefRefPtr<CefBrowser> browser_;
92     IMPLEMENT_REFCOUNTING(Visitor);
93   };
94 
95   browser->GetMainFrame()->GetSource(new Visitor(browser));
96 }
97 
RunGetTextTest(CefRefPtr<CefBrowser> browser)98 void RunGetTextTest(CefRefPtr<CefBrowser> browser) {
99   class Visitor : public CefStringVisitor {
100    public:
101     explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) {}
102     virtual void Visit(const CefString& string) override {
103       std::string text = StringReplace(string, "<", "&lt;");
104       text = StringReplace(text, ">", "&gt;");
105       std::stringstream ss;
106       ss << "<html><body bgcolor=\"white\">Text:<pre>" << text
107          << "</pre></body></html>";
108       LoadStringResourcePage(browser_, kTestGetTextPage, ss.str());
109     }
110 
111    private:
112     CefRefPtr<CefBrowser> browser_;
113     IMPLEMENT_REFCOUNTING(Visitor);
114   };
115 
116   browser->GetMainFrame()->GetText(new Visitor(browser));
117 }
118 
RunRequestTest(CefRefPtr<CefBrowser> browser)119 void RunRequestTest(CefRefPtr<CefBrowser> browser) {
120   // Create a new request
121   CefRefPtr<CefRequest> request(CefRequest::Create());
122 
123   if (browser->GetMainFrame()->GetURL().ToString().find("http://tests/") != 0) {
124     // The LoadRequest method will fail with "bad IPC message" reason
125     // INVALID_INITIATOR_ORIGIN (213) unless you first navigate to the
126     // request origin using some other mechanism (LoadURL, link click, etc).
127     Alert(browser,
128           "Please first navigate to a http://tests/ URL. "
129           "For example, first load Tests > Other Tests.");
130     return;
131   }
132 
133   // Set the request URL
134   request->SetURL("http://tests/request");
135 
136   // Add post data to the request.  The correct method and content-
137   // type headers will be set by CEF.
138   CefRefPtr<CefPostDataElement> postDataElement(CefPostDataElement::Create());
139   std::string data = "arg1=val1&arg2=val2";
140   postDataElement->SetToBytes(data.length(), data.c_str());
141   CefRefPtr<CefPostData> postData(CefPostData::Create());
142   postData->AddElement(postDataElement);
143   request->SetPostData(postData);
144 
145   // Add a custom header
146   CefRequest::HeaderMap headerMap;
147   headerMap.insert(std::make_pair("X-My-Header", "My Header Value"));
148   request->SetHeaderMap(headerMap);
149 
150   // Load the request
151   browser->GetMainFrame()->LoadRequest(request);
152 }
153 
RunNewWindowTest(CefRefPtr<CefBrowser> browser)154 void RunNewWindowTest(CefRefPtr<CefBrowser> browser) {
155   auto config = std::make_unique<RootWindowConfig>();
156   config->with_controls = true;
157   config->with_osr = browser->GetHost()->IsWindowRenderingDisabled();
158   MainContext::Get()->GetRootWindowManager()->CreateRootWindow(
159       std::move(config));
160 }
161 
RunPopupWindowTest(CefRefPtr<CefBrowser> browser)162 void RunPopupWindowTest(CefRefPtr<CefBrowser> browser) {
163   browser->GetMainFrame()->ExecuteJavaScript(
164       "window.open('http://www.google.com');", "about:blank", 0);
165 }
166 
RunPluginInfoTest(CefRefPtr<CefBrowser> browser)167 void RunPluginInfoTest(CefRefPtr<CefBrowser> browser) {
168   class Visitor : public CefWebPluginInfoVisitor {
169    public:
170     explicit Visitor(CefRefPtr<CefBrowser> browser) : browser_(browser) {
171       html_ =
172           "<html><head><title>Plugin Info Test</title></head>"
173           "<body bgcolor=\"white\">"
174           "\n<b>Installed plugins:</b>";
175     }
176     ~Visitor() {
177       html_ += "\n</body></html>";
178 
179       // Load the html in the browser.
180       LoadStringResourcePage(browser_, kTestPluginInfoPage, html_);
181     }
182 
183     virtual bool Visit(CefRefPtr<CefWebPluginInfo> info,
184                        int count,
185                        int total) override {
186       html_ += "\n<br/><br/>Name: " + info->GetName().ToString() +
187                "\n<br/>Description: " + info->GetDescription().ToString() +
188                "\n<br/>Version: " + info->GetVersion().ToString() +
189                "\n<br/>Path: " + info->GetPath().ToString();
190       return true;
191     }
192 
193    private:
194     std::string html_;
195     CefRefPtr<CefBrowser> browser_;
196     IMPLEMENT_REFCOUNTING(Visitor);
197   };
198 
199   CefVisitWebPluginInfo(new Visitor(browser));
200 }
201 
ModifyZoom(CefRefPtr<CefBrowser> browser,double delta)202 void ModifyZoom(CefRefPtr<CefBrowser> browser, double delta) {
203   if (!CefCurrentlyOn(TID_UI)) {
204     // Execute on the UI thread.
205     CefPostTask(TID_UI, base::BindOnce(&ModifyZoom, browser, delta));
206     return;
207   }
208 
209   browser->GetHost()->SetZoomLevel(browser->GetHost()->GetZoomLevel() + delta);
210 }
211 
212 const char kPrompt[] = "Prompt.";
213 const char kPromptFPS[] = "FPS";
214 const char kPromptDSF[] = "DSF";
215 
216 // Handles execution of prompt results.
217 class PromptHandler : public CefMessageRouterBrowserSide::Handler {
218  public:
PromptHandler()219   PromptHandler() {}
220 
221   // Called due to cefQuery execution.
OnQuery(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,int64 query_id,const CefString & request,bool persistent,CefRefPtr<Callback> callback)222   virtual bool OnQuery(CefRefPtr<CefBrowser> browser,
223                        CefRefPtr<CefFrame> frame,
224                        int64 query_id,
225                        const CefString& request,
226                        bool persistent,
227                        CefRefPtr<Callback> callback) override {
228     // Parse |request| which takes the form "Prompt.[type]:[value]".
229     const std::string& request_str = request;
230     if (request_str.find(kPrompt) != 0)
231       return false;
232 
233     std::string type = request_str.substr(sizeof(kPrompt) - 1);
234     size_t delim = type.find(':');
235     if (delim == std::string::npos)
236       return false;
237 
238     const std::string& value = type.substr(delim + 1);
239     type = type.substr(0, delim);
240 
241     // Canceling the prompt dialog returns a value of "null".
242     if (value != "null") {
243       if (type == kPromptFPS)
244         SetFPS(browser, atoi(value.c_str()));
245       else if (type == kPromptDSF)
246         SetDSF(browser, static_cast<float>(atof(value.c_str())));
247     }
248 
249     // Nothing is done with the response.
250     callback->Success(CefString());
251     return true;
252   }
253 
254  private:
SetFPS(CefRefPtr<CefBrowser> browser,int fps)255   void SetFPS(CefRefPtr<CefBrowser> browser, int fps) {
256     if (fps <= 0) {
257       // Reset to the default value.
258       CefBrowserSettings settings;
259       MainContext::Get()->PopulateBrowserSettings(&settings);
260       fps = settings.windowless_frame_rate;
261     }
262 
263     browser->GetHost()->SetWindowlessFrameRate(fps);
264   }
265 
SetDSF(CefRefPtr<CefBrowser> browser,float dsf)266   void SetDSF(CefRefPtr<CefBrowser> browser, float dsf) {
267     MainMessageLoop::Get()->PostClosure(
268         base::BindOnce(&PromptHandler::SetDSFOnMainThread, browser, dsf));
269   }
270 
SetDSFOnMainThread(CefRefPtr<CefBrowser> browser,float dsf)271   static void SetDSFOnMainThread(CefRefPtr<CefBrowser> browser, float dsf) {
272     RootWindow::GetForBrowser(browser->GetIdentifier())
273         ->SetDeviceScaleFactor(dsf);
274   }
275 };
276 
Prompt(CefRefPtr<CefBrowser> browser,const std::string & type,const std::string & label,const std::string & default_value)277 void Prompt(CefRefPtr<CefBrowser> browser,
278             const std::string& type,
279             const std::string& label,
280             const std::string& default_value) {
281   // Prompt the user for a new value. Works as follows:
282   // 1. Show a prompt() dialog via JavaScript.
283   // 2. Pass the result to window.cefQuery().
284   // 3. Handle the result in PromptHandler::OnQuery.
285   const std::string& code = "window.cefQuery({'request': '" +
286                             std::string(kPrompt) + type + ":' + prompt('" +
287                             label + "', '" + default_value + "')});";
288   browser->GetMainFrame()->ExecuteJavaScript(
289       code, browser->GetMainFrame()->GetURL(), 0);
290 }
291 
PromptFPS(CefRefPtr<CefBrowser> browser)292 void PromptFPS(CefRefPtr<CefBrowser> browser) {
293   if (!CefCurrentlyOn(TID_UI)) {
294     // Execute on the UI thread.
295     CefPostTask(TID_UI, base::BindOnce(&PromptFPS, browser));
296     return;
297   }
298 
299   // Format the default value string.
300   std::stringstream ss;
301   ss << browser->GetHost()->GetWindowlessFrameRate();
302 
303   Prompt(browser, kPromptFPS, "Enter FPS", ss.str());
304 }
305 
PromptDSF(CefRefPtr<CefBrowser> browser)306 void PromptDSF(CefRefPtr<CefBrowser> browser) {
307   if (!MainMessageLoop::Get()->RunsTasksOnCurrentThread()) {
308     // Execute on the main thread.
309     MainMessageLoop::Get()->PostClosure(base::BindOnce(&PromptDSF, browser));
310     return;
311   }
312 
313   // Format the default value string.
314   std::stringstream ss;
315   ss << RootWindow::GetForBrowser(browser->GetIdentifier())
316             ->GetDeviceScaleFactor();
317 
318   Prompt(browser, kPromptDSF, "Enter Device Scale Factor", ss.str());
319 }
320 
BeginTracing()321 void BeginTracing() {
322   if (!CefCurrentlyOn(TID_UI)) {
323     // Execute on the UI thread.
324     CefPostTask(TID_UI, base::BindOnce(&BeginTracing));
325     return;
326   }
327 
328   CefBeginTracing(CefString(), nullptr);
329 }
330 
EndTracing(CefRefPtr<CefBrowser> browser)331 void EndTracing(CefRefPtr<CefBrowser> browser) {
332   if (!CefCurrentlyOn(TID_UI)) {
333     // Execute on the UI thread.
334     CefPostTask(TID_UI, base::BindOnce(&EndTracing, browser));
335     return;
336   }
337 
338   class Client : public CefEndTracingCallback, public CefRunFileDialogCallback {
339    public:
340     explicit Client(CefRefPtr<CefBrowser> browser) : browser_(browser) {
341       RunDialog();
342     }
343 
344     void RunDialog() {
345       static const char kDefaultFileName[] = "trace.txt";
346       std::string path = MainContext::Get()->GetDownloadPath(kDefaultFileName);
347       if (path.empty())
348         path = kDefaultFileName;
349 
350       // Results in a call to OnFileDialogDismissed.
351       browser_->GetHost()->RunFileDialog(
352           static_cast<cef_file_dialog_mode_t>(FILE_DIALOG_SAVE |
353                                               FILE_DIALOG_OVERWRITEPROMPT_FLAG),
354           CefString(),  // title
355           path,
356           std::vector<CefString>(),  // accept_filters
357           0,                         // selected_accept_filter
358           this);
359     }
360 
361     void OnFileDialogDismissed(
362         int selected_accept_filter,
363         const std::vector<CefString>& file_paths) override {
364       if (!file_paths.empty()) {
365         // File selected. Results in a call to OnEndTracingComplete.
366         CefEndTracing(file_paths.front(), this);
367       } else {
368         // No file selected. Discard the trace data.
369         CefEndTracing(CefString(), nullptr);
370       }
371     }
372 
373     void OnEndTracingComplete(const CefString& tracing_file) override {
374       Alert(browser_,
375             "File \"" + tracing_file.ToString() + "\" saved successfully.");
376     }
377 
378    private:
379     CefRefPtr<CefBrowser> browser_;
380 
381     IMPLEMENT_REFCOUNTING(Client);
382   };
383 
384   new Client(browser);
385 }
386 
PrintToPDF(CefRefPtr<CefBrowser> browser)387 void PrintToPDF(CefRefPtr<CefBrowser> browser) {
388   if (!CefCurrentlyOn(TID_UI)) {
389     // Execute on the UI thread.
390     CefPostTask(TID_UI, base::BindOnce(&PrintToPDF, browser));
391     return;
392   }
393 
394   class Client : public CefPdfPrintCallback, public CefRunFileDialogCallback {
395    public:
396     explicit Client(CefRefPtr<CefBrowser> browser) : browser_(browser) {
397       RunDialog();
398     }
399 
400     void RunDialog() {
401       static const char kDefaultFileName[] = "output.pdf";
402       std::string path = MainContext::Get()->GetDownloadPath(kDefaultFileName);
403       if (path.empty())
404         path = kDefaultFileName;
405 
406       std::vector<CefString> accept_filters;
407       accept_filters.push_back(".pdf");
408 
409       // Results in a call to OnFileDialogDismissed.
410       browser_->GetHost()->RunFileDialog(
411           static_cast<cef_file_dialog_mode_t>(FILE_DIALOG_SAVE |
412                                               FILE_DIALOG_OVERWRITEPROMPT_FLAG),
413           CefString(),  // title
414           path, accept_filters,
415           0,  // selected_accept_filter
416           this);
417     }
418 
419     void OnFileDialogDismissed(
420         int selected_accept_filter,
421         const std::vector<CefString>& file_paths) override {
422       if (!file_paths.empty()) {
423         CefPdfPrintSettings settings;
424 
425         // Show the URL in the footer.
426         settings.header_footer_enabled = true;
427         CefString(&settings.header_footer_url) =
428             browser_->GetMainFrame()->GetURL();
429 
430         // Print to the selected PDF file.
431         browser_->GetHost()->PrintToPDF(file_paths[0], settings, this);
432       }
433     }
434 
435     void OnPdfPrintFinished(const CefString& path, bool ok) override {
436       Alert(browser_, "File \"" + path.ToString() + "\" " +
437                           (ok ? "saved successfully." : "failed to save."));
438     }
439 
440    private:
441     CefRefPtr<CefBrowser> browser_;
442 
443     IMPLEMENT_REFCOUNTING(Client);
444   };
445 
446   new Client(browser);
447 }
448 
MuteAudio(CefRefPtr<CefBrowser> browser,bool mute)449 void MuteAudio(CefRefPtr<CefBrowser> browser, bool mute) {
450   CefRefPtr<CefBrowserHost> host = browser->GetHost();
451   host->SetAudioMuted(mute);
452 }
453 
RunOtherTests(CefRefPtr<CefBrowser> browser)454 void RunOtherTests(CefRefPtr<CefBrowser> browser) {
455   browser->GetMainFrame()->LoadURL("http://tests/other_tests");
456 }
457 
458 // Provider that dumps the request contents.
459 class RequestDumpResourceProvider : public CefResourceManager::Provider {
460  public:
RequestDumpResourceProvider(const std::string & url)461   explicit RequestDumpResourceProvider(const std::string& url) : url_(url) {
462     DCHECK(!url.empty());
463   }
464 
OnRequest(scoped_refptr<CefResourceManager::Request> request)465   bool OnRequest(scoped_refptr<CefResourceManager::Request> request) override {
466     CEF_REQUIRE_IO_THREAD();
467 
468     const std::string& url = request->url();
469     if (url != url_) {
470       // Not handled by this provider.
471       return false;
472     }
473 
474     CefResponse::HeaderMap response_headers;
475     CefRefPtr<CefStreamReader> response =
476         GetDumpResponse(request->request(), response_headers);
477 
478     request->Continue(new CefStreamResourceHandler(200, "OK", "text/html",
479                                                    response_headers, response));
480     return true;
481   }
482 
483  private:
484   std::string url_;
485 
486   DISALLOW_COPY_AND_ASSIGN(RequestDumpResourceProvider);
487 };
488 
489 // Provider that returns string data for specific pages. Used in combination
490 // with LoadStringResourcePage().
491 class StringResourceProvider : public CefResourceManager::Provider {
492  public:
StringResourceProvider(const std::set<std::string> & pages,StringResourceMap * string_resource_map)493   StringResourceProvider(const std::set<std::string>& pages,
494                          StringResourceMap* string_resource_map)
495       : pages_(pages), string_resource_map_(string_resource_map) {
496     DCHECK(!pages.empty());
497   }
498 
OnRequest(scoped_refptr<CefResourceManager::Request> request)499   bool OnRequest(scoped_refptr<CefResourceManager::Request> request) override {
500     CEF_REQUIRE_IO_THREAD();
501 
502     const std::string& url = request->url();
503     if (url.find(kTestOrigin) != 0U) {
504       // Not handled by this provider.
505       return false;
506     }
507 
508     const std::string& page = url.substr(strlen(kTestOrigin));
509     if (pages_.find(page) == pages_.end()) {
510       // Not handled by this provider.
511       return false;
512     }
513 
514     std::string value;
515     StringResourceMap::const_iterator it = string_resource_map_->find(page);
516     if (it != string_resource_map_->end()) {
517       value = it->second;
518     } else {
519       value = "<html><body>No data available</body></html>";
520     }
521 
522     CefRefPtr<CefStreamReader> response = CefStreamReader::CreateForData(
523         static_cast<void*>(const_cast<char*>(value.c_str())), value.size());
524 
525     request->Continue(new CefStreamResourceHandler(
526         200, "OK", "text/html", CefResponse::HeaderMap(), response));
527     return true;
528   }
529 
530  private:
531   const std::set<std::string> pages_;
532 
533   // Only accessed on the IO thread.
534   StringResourceMap* string_resource_map_;
535 
536   DISALLOW_COPY_AND_ASSIGN(StringResourceProvider);
537 };
538 
539 // Add a file extension to |url| if none is currently specified.
RequestUrlFilter(const std::string & url)540 std::string RequestUrlFilter(const std::string& url) {
541   if (url.find(kTestOrigin) != 0U) {
542     // Don't filter anything outside of the test origin.
543     return url;
544   }
545 
546   // Identify where the query or fragment component, if any, begins.
547   size_t suffix_pos = url.find('?');
548   if (suffix_pos == std::string::npos)
549     suffix_pos = url.find('#');
550 
551   std::string url_base, url_suffix;
552   if (suffix_pos == std::string::npos) {
553     url_base = url;
554   } else {
555     url_base = url.substr(0, suffix_pos);
556     url_suffix = url.substr(suffix_pos);
557   }
558 
559   // Identify the last path component.
560   size_t path_pos = url_base.rfind('/');
561   if (path_pos == std::string::npos)
562     return url;
563 
564   const std::string& path_component = url_base.substr(path_pos);
565 
566   // Identify if a file extension is currently specified.
567   size_t ext_pos = path_component.rfind(".");
568   if (ext_pos != std::string::npos)
569     return url;
570 
571   // Rebuild the URL with a file extension.
572   return url_base + ".html" + url_suffix;
573 }
574 
575 }  // namespace
576 
RunTest(CefRefPtr<CefBrowser> browser,int id)577 void RunTest(CefRefPtr<CefBrowser> browser, int id) {
578   if (!browser)
579     return;
580 
581   switch (id) {
582     case ID_TESTS_GETSOURCE:
583       RunGetSourceTest(browser);
584       break;
585     case ID_TESTS_GETTEXT:
586       RunGetTextTest(browser);
587       break;
588     case ID_TESTS_WINDOW_NEW:
589       RunNewWindowTest(browser);
590       break;
591     case ID_TESTS_WINDOW_POPUP:
592       RunPopupWindowTest(browser);
593       break;
594     case ID_TESTS_REQUEST:
595       RunRequestTest(browser);
596       break;
597     case ID_TESTS_PLUGIN_INFO:
598       RunPluginInfoTest(browser);
599       break;
600     case ID_TESTS_ZOOM_IN:
601       ModifyZoom(browser, 0.5);
602       break;
603     case ID_TESTS_ZOOM_OUT:
604       ModifyZoom(browser, -0.5);
605       break;
606     case ID_TESTS_ZOOM_RESET:
607       browser->GetHost()->SetZoomLevel(0.0);
608       break;
609     case ID_TESTS_OSR_FPS:
610       PromptFPS(browser);
611       break;
612     case ID_TESTS_OSR_DSF:
613       PromptDSF(browser);
614       break;
615     case ID_TESTS_TRACING_BEGIN:
616       BeginTracing();
617       break;
618     case ID_TESTS_TRACING_END:
619       EndTracing(browser);
620       break;
621     case ID_TESTS_PRINT:
622       browser->GetHost()->Print();
623       break;
624     case ID_TESTS_PRINT_TO_PDF:
625       PrintToPDF(browser);
626       break;
627     case ID_TESTS_MUTE_AUDIO:
628       MuteAudio(browser, true);
629       break;
630     case ID_TESTS_UNMUTE_AUDIO:
631       MuteAudio(browser, false);
632       break;
633     case ID_TESTS_OTHER_TESTS:
634       RunOtherTests(browser);
635       break;
636   }
637 }
638 
DumpRequestContents(CefRefPtr<CefRequest> request)639 std::string DumpRequestContents(CefRefPtr<CefRequest> request) {
640   std::stringstream ss;
641 
642   ss << "URL: " << std::string(request->GetURL());
643   ss << "\nMethod: " << std::string(request->GetMethod());
644 
645   CefRequest::HeaderMap headerMap;
646   request->GetHeaderMap(headerMap);
647   if (headerMap.size() > 0) {
648     ss << "\nHeaders:";
649     CefRequest::HeaderMap::const_iterator it = headerMap.begin();
650     for (; it != headerMap.end(); ++it) {
651       ss << "\n\t" << std::string((*it).first) << ": "
652          << std::string((*it).second);
653     }
654   }
655 
656   CefRefPtr<CefPostData> postData = request->GetPostData();
657   if (postData.get()) {
658     CefPostData::ElementVector elements;
659     postData->GetElements(elements);
660     if (elements.size() > 0) {
661       ss << "\nPost Data:";
662       CefRefPtr<CefPostDataElement> element;
663       CefPostData::ElementVector::const_iterator it = elements.begin();
664       for (; it != elements.end(); ++it) {
665         element = (*it);
666         if (element->GetType() == PDE_TYPE_BYTES) {
667           // the element is composed of bytes
668           ss << "\n\tBytes: ";
669           if (element->GetBytesCount() == 0) {
670             ss << "(empty)";
671           } else {
672             // retrieve the data.
673             size_t size = element->GetBytesCount();
674             char* bytes = new char[size];
675             element->GetBytes(size, bytes);
676             ss << std::string(bytes, size);
677             delete[] bytes;
678           }
679         } else if (element->GetType() == PDE_TYPE_FILE) {
680           ss << "\n\tFile: " << std::string(element->GetFile());
681         }
682       }
683     }
684   }
685 
686   return ss.str();
687 }
688 
GetDumpResponse(CefRefPtr<CefRequest> request,CefResponse::HeaderMap & response_headers)689 CefRefPtr<CefStreamReader> GetDumpResponse(
690     CefRefPtr<CefRequest> request,
691     CefResponse::HeaderMap& response_headers) {
692   std::string origin;
693 
694   // Extract the origin request header, if any. It will be specified for
695   // cross-origin requests.
696   {
697     CefRequest::HeaderMap requestMap;
698     request->GetHeaderMap(requestMap);
699 
700     CefRequest::HeaderMap::const_iterator it = requestMap.begin();
701     for (; it != requestMap.end(); ++it) {
702       std::string key = it->first;
703       std::transform(key.begin(), key.end(), key.begin(), ::tolower);
704       if (key == "origin") {
705         origin = it->second;
706         break;
707       }
708     }
709   }
710 
711   if (!origin.empty() &&
712       (origin.find("http://" + std::string(kTestHost)) == 0 ||
713        origin.find("http://" + std::string(kLocalHost)) == 0)) {
714     // Allow cross-origin XMLHttpRequests from test origins.
715     response_headers.insert(
716         std::make_pair("Access-Control-Allow-Origin", origin));
717 
718     // Allow the custom header from the xmlhttprequest.html example.
719     response_headers.insert(
720         std::make_pair("Access-Control-Allow-Headers", "My-Custom-Header"));
721   }
722 
723   const std::string& dump = DumpRequestContents(request);
724   std::string str =
725       "<html><body bgcolor=\"white\"><pre>" + dump + "</pre></body></html>";
726   CefRefPtr<CefStreamReader> stream = CefStreamReader::CreateForData(
727       static_cast<void*>(const_cast<char*>(str.c_str())), str.size());
728   DCHECK(stream);
729   return stream;
730 }
731 
GetDataURI(const std::string & data,const std::string & mime_type)732 std::string GetDataURI(const std::string& data, const std::string& mime_type) {
733   return "data:" + mime_type + ";base64," +
734          CefURIEncode(CefBase64Encode(data.data(), data.size()), false)
735              .ToString();
736 }
737 
GetErrorString(cef_errorcode_t code)738 std::string GetErrorString(cef_errorcode_t code) {
739 // Case condition that returns |code| as a string.
740 #define CASE(code) \
741   case code:       \
742     return #code
743 
744   switch (code) {
745     CASE(ERR_NONE);
746     CASE(ERR_FAILED);
747     CASE(ERR_ABORTED);
748     CASE(ERR_INVALID_ARGUMENT);
749     CASE(ERR_INVALID_HANDLE);
750     CASE(ERR_FILE_NOT_FOUND);
751     CASE(ERR_TIMED_OUT);
752     CASE(ERR_FILE_TOO_BIG);
753     CASE(ERR_UNEXPECTED);
754     CASE(ERR_ACCESS_DENIED);
755     CASE(ERR_NOT_IMPLEMENTED);
756     CASE(ERR_CONNECTION_CLOSED);
757     CASE(ERR_CONNECTION_RESET);
758     CASE(ERR_CONNECTION_REFUSED);
759     CASE(ERR_CONNECTION_ABORTED);
760     CASE(ERR_CONNECTION_FAILED);
761     CASE(ERR_NAME_NOT_RESOLVED);
762     CASE(ERR_INTERNET_DISCONNECTED);
763     CASE(ERR_SSL_PROTOCOL_ERROR);
764     CASE(ERR_ADDRESS_INVALID);
765     CASE(ERR_ADDRESS_UNREACHABLE);
766     CASE(ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
767     CASE(ERR_TUNNEL_CONNECTION_FAILED);
768     CASE(ERR_NO_SSL_VERSIONS_ENABLED);
769     CASE(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
770     CASE(ERR_SSL_RENEGOTIATION_REQUESTED);
771     CASE(ERR_CERT_COMMON_NAME_INVALID);
772     CASE(ERR_CERT_DATE_INVALID);
773     CASE(ERR_CERT_AUTHORITY_INVALID);
774     CASE(ERR_CERT_CONTAINS_ERRORS);
775     CASE(ERR_CERT_NO_REVOCATION_MECHANISM);
776     CASE(ERR_CERT_UNABLE_TO_CHECK_REVOCATION);
777     CASE(ERR_CERT_REVOKED);
778     CASE(ERR_CERT_INVALID);
779     CASE(ERR_CERT_END);
780     CASE(ERR_INVALID_URL);
781     CASE(ERR_DISALLOWED_URL_SCHEME);
782     CASE(ERR_UNKNOWN_URL_SCHEME);
783     CASE(ERR_TOO_MANY_REDIRECTS);
784     CASE(ERR_UNSAFE_REDIRECT);
785     CASE(ERR_UNSAFE_PORT);
786     CASE(ERR_INVALID_RESPONSE);
787     CASE(ERR_INVALID_CHUNKED_ENCODING);
788     CASE(ERR_METHOD_NOT_SUPPORTED);
789     CASE(ERR_UNEXPECTED_PROXY_AUTH);
790     CASE(ERR_EMPTY_RESPONSE);
791     CASE(ERR_RESPONSE_HEADERS_TOO_BIG);
792     CASE(ERR_CACHE_MISS);
793     CASE(ERR_INSECURE_RESPONSE);
794     default:
795       return "UNKNOWN";
796   }
797 }
798 
SetupResourceManager(CefRefPtr<CefResourceManager> resource_manager,StringResourceMap * string_resource_map)799 void SetupResourceManager(CefRefPtr<CefResourceManager> resource_manager,
800                           StringResourceMap* string_resource_map) {
801   if (!CefCurrentlyOn(TID_IO)) {
802     // Execute on the browser IO thread.
803     CefPostTask(TID_IO, base::BindOnce(SetupResourceManager, resource_manager,
804                                        string_resource_map));
805     return;
806   }
807 
808   const std::string& test_origin = kTestOrigin;
809 
810   // Add the URL filter.
811   resource_manager->SetUrlFilter(base::BindRepeating(RequestUrlFilter));
812 
813   // Add provider for resource dumps.
814   resource_manager->AddProvider(
815       new RequestDumpResourceProvider(test_origin + "request.html"), 0,
816       std::string());
817 
818   // Set of supported string pages.
819   std::set<std::string> string_pages;
820   string_pages.insert(kTestGetSourcePage);
821   string_pages.insert(kTestGetTextPage);
822   string_pages.insert(kTestPluginInfoPage);
823 
824   // Add provider for string resources.
825   resource_manager->AddProvider(
826       new StringResourceProvider(string_pages, string_resource_map), 0,
827       std::string());
828 
829 // Add provider for bundled resource files.
830 #if defined(OS_WIN)
831   // Read resources from the binary.
832   resource_manager->AddProvider(
833       CreateBinaryResourceProvider(test_origin, std::string()), 100,
834       std::string());
835 #elif defined(OS_POSIX)
836   // Read resources from a directory on disk.
837   std::string resource_dir;
838   if (GetResourceDir(resource_dir)) {
839     resource_manager->AddDirectoryProvider(test_origin, resource_dir, 100,
840                                            std::string());
841   }
842 #endif
843 }
844 
Alert(CefRefPtr<CefBrowser> browser,const std::string & message)845 void Alert(CefRefPtr<CefBrowser> browser, const std::string& message) {
846   if (browser->GetHost()->GetExtension()) {
847     // Alerts originating from extension hosts should instead be displayed in
848     // the active browser.
849     browser = MainContext::Get()->GetRootWindowManager()->GetActiveBrowser();
850     if (!browser)
851       return;
852   }
853 
854   // Escape special characters in the message.
855   std::string msg = StringReplace(message, "\\", "\\\\");
856   msg = StringReplace(msg, "'", "\\'");
857 
858   // Execute a JavaScript alert().
859   CefRefPtr<CefFrame> frame = browser->GetMainFrame();
860   frame->ExecuteJavaScript("alert('" + msg + "');", frame->GetURL(), 0);
861 }
862 
IsTestURL(const std::string & url,const std::string & path)863 bool IsTestURL(const std::string& url, const std::string& path) {
864   CefURLParts parts;
865   CefParseURL(url, parts);
866 
867   const std::string& url_host = CefString(&parts.host);
868   if (url_host != kTestHost && url_host != kLocalHost)
869     return false;
870 
871   const std::string& url_path = CefString(&parts.path);
872   return url_path.find(path) == 0;
873 }
874 
CreateMessageHandlers(MessageHandlerSet & handlers)875 void CreateMessageHandlers(MessageHandlerSet& handlers) {
876   handlers.insert(new PromptHandler);
877 
878   // Create the binding test handlers.
879   binding_test::CreateMessageHandlers(handlers);
880 
881   // Create the dialog test handlers.
882   dialog_test::CreateMessageHandlers(handlers);
883 
884   // Create the media router test handlers.
885   media_router_test::CreateMessageHandlers(handlers);
886 
887   // Create the preferences test handlers.
888   preferences_test::CreateMessageHandlers(handlers);
889 
890   // Create the server test handlers.
891   server_test::CreateMessageHandlers(handlers);
892 
893   // Create the urlrequest test handlers.
894   urlrequest_test::CreateMessageHandlers(handlers);
895 
896   // Create the window test handlers.
897   window_test::CreateMessageHandlers(handlers);
898 }
899 
RegisterSchemeHandlers()900 void RegisterSchemeHandlers() {
901   // Register the scheme handler.
902   scheme_test::RegisterSchemeHandlers();
903 }
904 
GetResourceResponseFilter(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefRequest> request,CefRefPtr<CefResponse> response)905 CefRefPtr<CefResponseFilter> GetResourceResponseFilter(
906     CefRefPtr<CefBrowser> browser,
907     CefRefPtr<CefFrame> frame,
908     CefRefPtr<CefRequest> request,
909     CefRefPtr<CefResponse> response) {
910   // Create the response filter.
911   return response_filter_test::GetResourceResponseFilter(browser, frame,
912                                                          request, response);
913 }
914 
915 }  // namespace test_runner
916 }  // namespace client
917