Remove unused files

This commit is contained in:
Corey Johnson
2012-08-13 09:46:11 -07:00
parent 23cec49892
commit b8cbcdc4b5
53 changed files with 0 additions and 13747 deletions

View File

@@ -57,7 +57,6 @@
'tests/cefclient/client_renderer.h',
'tests/cefclient/client_switches.cpp',
'tests/cefclient/client_switches.h',
'tests/cefclient/resource_util.h',
'tests/cefclient/util.h',
],
'mac_bundle_resources': [
@@ -193,7 +192,6 @@
'include/internal/cef_types_mac.h',
'tests/cefclient/cefclient_mac.mm',
'tests/cefclient/client_handler_mac.mm',
'tests/cefclient/resource_util_mac.mm',
],
}],
[ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', {
@@ -282,8 +280,6 @@
'tests/cefclient/client_switches.cpp',
'tests/cefclient/client_switches.h',
'tests/cefclient/process_helper_mac.cpp',
'tests/cefclient/resource_util.h',
'tests/cefclient/resource_util_mac.mm',
'tests/cefclient/util.h',
],
# TODO(mark): Come up with a fancier way to do this. It should only

View File

@@ -1,104 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cefclient/binding_test.h"
#include <algorithm>
#include <string>
#include "include/wrapper/cef_stream_resource_handler.h"
#include "cefclient/resource_util.h"
namespace binding_test {
namespace {
const char* kTestUrl = "http://tests/binding";
const char* kMessageName = "binding_test";
// Handle messages in the browser process.
class ProcessMessageDelegate : public ClientHandler::ProcessMessageDelegate {
public:
ProcessMessageDelegate() {
}
// From ClientHandler::ProcessMessageDelegate.
virtual bool OnProcessMessageReceived(
CefRefPtr<ClientHandler> handler,
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE {
std::string message_name = message->GetName();
if (message_name == kMessageName) {
// Handle the message.
std::string result;
CefRefPtr<CefListValue> args = message->GetArgumentList();
if (args->GetSize() > 0 && args->GetType(0) == VTYPE_STRING) {
// Our result is a reverse of the original message.
result = args->GetString(0);
std::reverse(result.begin(), result.end());
} else {
result = "Invalid request";
}
// Send the result back to the render process.
CefRefPtr<CefProcessMessage> response =
CefProcessMessage::Create(kMessageName);
response->GetArgumentList()->SetString(0, result);
browser->SendProcessMessage(PID_RENDERER, response);
return true;
}
return false;
}
IMPLEMENT_REFCOUNTING(ProcessMessageDelegate);
};
// Handle resource loading in the browser process.
class RequestDelegate: public ClientHandler::RequestDelegate {
public:
RequestDelegate() {
}
// From ClientHandler::RequestDelegate.
virtual CefRefPtr<CefResourceHandler> GetResourceHandler(
CefRefPtr<ClientHandler> handler,
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
std::string url = request->GetURL();
if (url == kTestUrl) {
// Show the binding contents
CefRefPtr<CefStreamReader> stream =
GetBinaryResourceReader("binding.html");
ASSERT(stream.get());
return new CefStreamResourceHandler("text/html", stream);
}
return NULL;
}
IMPLEMENT_REFCOUNTING(RequestDelegate);
};
} // namespace
void CreateProcessMessageDelegates(
ClientHandler::ProcessMessageDelegateSet& delegates) {
delegates.insert(new ProcessMessageDelegate);
}
void CreateRequestDelegates(ClientHandler::RequestDelegateSet& delegates) {
delegates.insert(new RequestDelegate);
}
void RunTest(CefRefPtr<CefBrowser> browser) {
// Load the test URL.
browser->GetMainFrame()->LoadURL(kTestUrl);
}
} // namespace binding_test

View File

@@ -1,24 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_BINDING_TEST_H_
#define CEF_TESTS_CEFCLIENT_BINDING_TEST_H_
#pragma once
#include "cefclient/client_app.h"
#include "cefclient/client_handler.h"
namespace binding_test {
// Delegate creation. Called from ClientApp and ClientHandler.
void CreateProcessMessageDelegates(
ClientHandler::ProcessMessageDelegateSet& delegates);
void CreateRequestDelegates(ClientHandler::RequestDelegateSet& delegates);
// Run the test.
void RunTest(CefRefPtr<CefBrowser> browser);
} // namespace binding_test
#endif // CEF_TESTS_CEFCLIENT_BINDING_TEST_H_

View File

@@ -15,7 +15,6 @@
#include "include/cef_web_plugin.h"
#include "cefclient/client_handler.h"
#include "cefclient/client_switches.h"
#include "cefclient/string_util.h"
#include "cefclient/util.h"
CefRefPtr<ClientHandler> g_handler;

View File

@@ -12,8 +12,6 @@
#include "include/cef_frame.h"
#include "include/cef_runnable.h"
#include "cefclient/client_handler.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
// The global ClientHandler reference.
extern CefRefPtr<ClientHandler> g_handler;

View File

@@ -16,8 +16,6 @@
#include "cefclient/cefclient.h"
#include "cefclient/client_renderer.h"
#include "cefclient/client_switches.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
// Custom menu command Ids.

View File

@@ -1,139 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cefclient/dom_test.h"
#include <sstream>
#include <string>
#include "include/cef_dom.h"
#include "cefclient/util.h"
namespace dom_test {
const char kTestUrl[] = "http://tests/domaccess";
namespace {
const char* kMessageName = "DOMTest.Message";
class ClientDOMEventListener : public CefDOMEventListener {
public:
ClientDOMEventListener() {
}
virtual void HandleEvent(CefRefPtr<CefDOMEvent> event) OVERRIDE {
CefRefPtr<CefDOMDocument> document = event->GetDocument();
ASSERT(document.get());
std::stringstream ss;
CefRefPtr<CefDOMNode> button = event->GetTarget();
ASSERT(button.get());
std::string buttonValue = button->GetElementAttribute("value");
ss << "You clicked the " << buttonValue.c_str() << " button. ";
if (document->HasSelection()) {
std::string startName, endName;
// Determine the start name by first trying to locate the "id" attribute
// and then defaulting to the tag name.
{
CefRefPtr<CefDOMNode> node = document->GetSelectionStartNode();
if (!node->IsElement())
node = node->GetParent();
if (node->IsElement() && node->HasElementAttribute("id"))
startName = node->GetElementAttribute("id");
else
startName = node->GetName();
}
// Determine the end name by first trying to locate the "id" attribute
// and then defaulting to the tag name.
{
CefRefPtr<CefDOMNode> node = document->GetSelectionEndNode();
if (!node->IsElement())
node = node->GetParent();
if (node->IsElement() && node->HasElementAttribute("id"))
endName = node->GetElementAttribute("id");
else
endName = node->GetName();
}
ss << "The selection is from " <<
startName.c_str() << ":" << document->GetSelectionStartOffset() <<
" to " <<
endName.c_str() << ":" << document->GetSelectionEndOffset();
} else {
ss << "Nothing is selected.";
}
// Update the description.
CefRefPtr<CefDOMNode> desc = document->GetElementById("description");
ASSERT(desc.get());
CefRefPtr<CefDOMNode> text = desc->GetFirstChild();
ASSERT(text.get());
ASSERT(text->IsText());
text->SetValue(ss.str());
}
IMPLEMENT_REFCOUNTING(ClientDOMEventListener);
};
class ClientDOMVisitor : public CefDOMVisitor {
public:
ClientDOMVisitor() {
}
virtual void Visit(CefRefPtr<CefDOMDocument> document) OVERRIDE {
// Register a click listener for the button.
CefRefPtr<CefDOMNode> button = document->GetElementById("button");
ASSERT(button.get());
button->AddEventListener("click", new ClientDOMEventListener(), false);
}
IMPLEMENT_REFCOUNTING(ClientDOMVisitor);
};
class DOMRenderDelegate : public ClientApp::RenderDelegate {
public:
DOMRenderDelegate() {
}
virtual bool OnProcessMessageReceived(
CefRefPtr<ClientApp> app,
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE {
if (message->GetName() == kMessageName) {
// Visit the DOM to attach the event listener.
browser->GetMainFrame()->VisitDOM(new ClientDOMVisitor);
return true;
}
return false;
}
private:
IMPLEMENT_REFCOUNTING(DOMRenderDelegate);
};
} // namespace
void CreateRenderDelegates(ClientApp::RenderDelegateSet& delegates) {
delegates.insert(new DOMRenderDelegate);
}
void RunTest(CefRefPtr<CefBrowser> browser) {
// Load the test URL.
browser->GetMainFrame()->LoadURL(kTestUrl);
}
void OnLoadEnd(CefRefPtr<CefBrowser> browser) {
// Send a message to the render process to continue the test setup.
browser->SendProcessMessage(PID_RENDERER,
CefProcessMessage::Create(kMessageName));
}
} // namespace dom_test

View File

@@ -1,28 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_DOM_TEST_H_
#define CEF_TESTS_CEFCLIENT_DOM_TEST_H_
#pragma once
#include "include/cef_base.h"
#include "cefclient/client_app.h"
namespace dom_test {
// The DOM test URL.
extern const char kTestUrl[];
// Create the render delegate.
void CreateRenderDelegates(ClientApp::RenderDelegateSet& delegates);
// Run the test.
void RunTest(CefRefPtr<CefBrowser> browser);
// Continue the test after the page has loaded.
void OnLoadEnd(CefRefPtr<CefBrowser> browser);
} // namespace dom_test
#endif // CEF_TESTS_CEFCLIENT_DOM_TEST_H_

View File

@@ -1,27 +0,0 @@
<html>
<head>
<title>Binding Test</title>
<script language="JavaScript">
// Register the callback for messages from the browser process.
app.setMessageCallback('binding_test', function(name, args) {
document.getElementById('result').value = "Response: "+args[0];
});
// Send a message to the browser process.
function sendMessage() {
var msg = document.getElementById("message").value;
app.sendMessage('binding_test', [msg]);
}
</script>
</head>
<body>
<form>
Message: <input type="text" id="message" value="My Message">
<br/><input type="button" onclick="sendMessage();" value="Send Message">
<br/>You should see the reverse of your message below:
<br/><textarea rows="10" cols="40" id="result"></textarea>
</form>
</body>
</html>

View File

@@ -1,45 +0,0 @@
<html>
<head>
<title>Dialog Test</title>
<script>
function show_alert() {
alert("I am an alert box!");
}
function show_confirm() {
var r = confirm("Press a button");
var msg = r ? "You pressed OK!" : "You pressed Cancel!";
document.getElementById('cm').innerText = msg;
}
function show_prompt() {
var name = prompt("Please enter your name" ,"Harry Potter");
if (name != null && name != "")
document.getElementById('pm').innerText = "Hello " + name + "!";
}
window.onbeforeunload = function() {
return 'This is an onbeforeunload message.';
}
function update_time() {
document.getElementById('time').innerText = new Date().toLocaleString();
}
function setup() {
setInterval(update_time, 1000);
}
window.addEventListener('load', setup, false);
</script>
</head>
<body>
<form>
Click a button to show the associated dialog type.
<br/><input type="button" onclick="show_alert();" value="Show Alert">
<br/><input type="button" onclick="show_confirm();" value="Show Confirm"> <span id="cm"></span>
<br/><input type="button" onclick="show_prompt();" value="Show Prompt"> <span id="pm"></span>
<p id="time"></p>
</form>
</body>
</html>

View File

@@ -1,13 +0,0 @@
<html>
<body>
<p id="instructions">Select some portion of the below page content and click the "Describe Selection" button. The selected region will then be described below.</p>
<p id="p1">This is p1</p>
<p id="p2">This is p2</p>
<p id="p3">This is p3</p>
<p id="p4">This is p4</p>
<form>
<input type="button" id="button" value="Describe Selection">
<p id="description">The description will appear here.</p>
</form>
</body>
</html>

View File

@@ -1,24 +0,0 @@
<html>
<body>
<script language="JavaScript">
var val = window.localStorage.getItem('val');
function addLine() {
if(val == null)
val = '<br/>One Line.';
else
val += '<br/>Another Line.';
window.localStorage.setItem('val', val);
document.getElementById('out').innerHTML = val;
}
</script>
Click the "Add Line" button to add a line or the "Clear" button to clear.<br/>
This data will persist across sessions if a cache path was specified.<br/>
<input type="button" value="Add Line" onClick="addLine();"/>
<input type="button" value="Clear" onClick="window.localStorage.removeItem('val'); window.location.reload();"/>
<div id="out"></div>
<script language="JavaScript">
if(val != null)
document.getElementById('out').innerHTML = val;
</script>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

View File

@@ -1,19 +0,0 @@
<html>
<body>
<script language="JavaScript">
function execXMLHttpRequest()
{
xhr = new XMLHttpRequest();
xhr.open("GET",document.getElementById("url").value,false);
xhr.setRequestHeader('My-Custom-Header', 'Some Value');
xhr.send();
document.getElementById('ta').value = "Status Code: "+xhr.status+"\n\n"+xhr.responseText;
}
</script>
<form>
URL: <input type="text" id="url" value="http://tests/request">
<br/><input type="button" onclick="execXMLHttpRequest();" value="Execute XMLHttpRequest">
<br/><textarea rows="10" cols="40" id="ta"></textarea>
</form>
</body>
</html>

View File

@@ -1,69 +0,0 @@
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by cefclient.rc
//
#define BINARY 256
#define IDC_MYICON 2
#define IDD_CEFCLIENT_DIALOG 102
#define IDS_APP_TITLE 103
#define IDD_ABOUTBOX 103
#define IDM_ABOUT 104
#define IDM_EXIT 105
#define IDI_CEFCLIENT 107
#define IDI_SMALL 108
#define IDC_CEFCLIENT 109
#define IDR_MAINFRAME 128
#define IDC_NAV_BACK 200
#define IDC_NAV_FORWARD 201
#define IDC_NAV_RELOAD 202
#define IDC_NAV_STOP 203
#define ID_WARN_CONSOLEMESSAGE 32000
#define ID_WARN_DOWNLOADCOMPLETE 32001
#define ID_WARN_DOWNLOADERROR 32002
#define ID_TESTS_GETSOURCE 32760
#define ID_TESTS_GETTEXT 32761
#define ID_TESTS_POPUP 32762
#define ID_TESTS_REQUEST 32763
#define ID_TESTS_SCHEME_HANDLER 32764
#define ID_TESTS_LOCALSTORAGE 32765
#define ID_TESTS_ACCELERATED2DCANVAS 32766
#define ID_TESTS_ACCELERATEDLAYERS 32767
#define ID_TESTS_WEBGL 32768
#define ID_TESTS_HTML5VIDEO 32769
#define ID_TESTS_XMLHTTPREQUEST 32770
#define ID_TESTS_DRAGDROP 32771
#define ID_TESTS_GEOLOCATION 32772
#define ID_TESTS_BINDING 32773
#define ID_TESTS_DIALOGS 32774
#define ID_TESTS_PLUGIN_INFO 32775
#define ID_TESTS_DOM_ACCESS 32776
#define ID_TESTS_ZOOM_IN 32777
#define ID_TESTS_ZOOM_OUT 32778
#define ID_TESTS_ZOOM_RESET 32779
#define IDC_STATIC -1
#define IDS_BINDING 1000
#define IDS_DIALOGS 1001
#define IDS_LOGO 1002
#define IDS_LOGOBALL 1003
#define IDS_LOCALSTORAGE 1004
#define IDS_XMLHTTPREQUEST 1005
#define IDS_DOMACCESS 1006
// Avoid files associated with MacOS
#define _X86_
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 130
#define _APS_NEXT_COMMAND_VALUE 32774
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 110
#endif
#endif

View File

@@ -1,32 +0,0 @@
// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_
#define CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_
#pragma once
#include "include/cef_base.h"
class CefStreamReader;
#if defined(OS_WIN)
#include "cefclient/resource.h"
// Load a resource of type BINARY
bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes);
CefRefPtr<CefStreamReader> GetBinaryResourceReader(int binaryId);
#elif defined(OS_MACOSX) || defined(OS_POSIX)
#include <string> // NOLINT(build/include_order)
// Load the resource with the specified name.
bool LoadBinaryResource(const char* resource_name, std::string& resource_data);
#endif
CefRefPtr<CefStreamReader> GetBinaryResourceReader(const char* resource_name);
#endif // CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_

View File

@@ -1,67 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cefclient/resource_util.h"
#include <stdio.h>
#include <string>
#include "include/cef_stream.h"
#include "cefclient/util.h"
bool GetResourceDir(std::string& dir) {
char buff[1024];
// Retrieve the executable path.
ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1);
if (len == -1)
return false;
buff[len] = 0;
// Remove the executable name from the path.
char* pos = strrchr(buff, '/');
if (!pos)
return false;
// Add "files" to the path.
strcpy(pos+1, "files"); // NOLINT(runtime/printf)
dir = std::string(buff);
return true;
}
bool LoadBinaryResource(const char* resource_name, std::string& resource_data) {
std::string path;
if (!GetResourceDir(path))
return false;
path.append("/");
path.append(resource_name);
FILE* f = fopen(path.c_str(), "rb");
if (!f)
return false;
size_t bytes_read;
char buff[1024*8];
do {
bytes_read = fread(buff, 1, sizeof(buff)-1, f);
if (bytes_read > 0)
resource_data.append(buff, bytes_read);
} while (bytes_read > 0);
fclose(f);
return true;
}
CefRefPtr<CefStreamReader> GetBinaryResourceReader(const char* resource_name) {
std::string path;
if (!GetResourceDir(path))
return NULL;
path.append("/");
path.append(resource_name);
return CefStreamReader::CreateForFile(path);
}

View File

@@ -1,97 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#include <mach-o/dyld.h>
#include <stdio.h>
#include "cefclient/resource_util.h"
#include "include/cef_stream.h"
#include "cefclient/util.h"
namespace {
bool AmIBundled() {
// Implementation adapted from Chromium's base/mac/foundation_util.mm
ProcessSerialNumber psn = {0, kCurrentProcess};
FSRef fsref;
OSStatus pbErr;
if ((pbErr = GetProcessBundleLocation(&psn, &fsref)) != noErr) {
ASSERT(false);
return false;
}
FSCatalogInfo info;
OSErr fsErr;
if ((fsErr = FSGetCatalogInfo(&fsref, kFSCatInfoNodeFlags, &info,
NULL, NULL, NULL)) != noErr) {
ASSERT(false);
return false;
}
return (info.nodeFlags & kFSNodeIsDirectoryMask);
}
bool GetResourceDir(std::string& dir) {
// Implementation adapted from Chromium's base/base_path_mac.mm
if (AmIBundled()) {
// Retrieve the executable directory.
uint32_t pathSize = 0;
_NSGetExecutablePath(NULL, &pathSize);
if (pathSize > 0) {
dir.resize(pathSize);
_NSGetExecutablePath(const_cast<char*>(dir.c_str()), &pathSize);
}
// Trim executable name up to the last separator
std::string::size_type last_separator = dir.find_last_of("/");
dir.resize(last_separator);
dir.append("/../Resources");
return true;
} else {
// TODO: Provide unbundled path
ASSERT(false);
return false;
}
}
bool ReadFileToString(const char* path, std::string& data) {
// Implementation adapted from base/file_util.cc
FILE* file = fopen(path, "rb");
if (!file)
return false;
char buf[1 << 16];
size_t len;
while ((len = fread(buf, 1, sizeof(buf), file)) > 0)
data.append(buf, len);
fclose(file);
return true;
}
} // namespace
bool LoadBinaryResource(const char* resource_name, std::string& resource_data) {
std::string path;
if (!GetResourceDir(path))
return false;
path.append("/");
path.append(resource_name);
return ReadFileToString(path.c_str(), resource_data);
}
CefRefPtr<CefStreamReader> GetBinaryResourceReader(const char* resource_name) {
std::string path;
if (!GetResourceDir(path))
return NULL;
path.append("/");
path.append(resource_name);
return CefStreamReader::CreateForFile(path);
}

View File

@@ -1,64 +0,0 @@
// Copyright (c) 2008-2009 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cefclient/resource_util.h"
#include "include/cef_stream.h"
#include "include/wrapper/cef_byte_read_handler.h"
#include "cefclient/util.h"
#if defined(OS_WIN)
bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes) {
extern HINSTANCE hInst;
HRSRC hRes = FindResource(hInst, MAKEINTRESOURCE(binaryId),
MAKEINTRESOURCE(256));
if (hRes) {
HGLOBAL hGlob = LoadResource(hInst, hRes);
if (hGlob) {
dwSize = SizeofResource(hInst, hRes);
pBytes = (LPBYTE)LockResource(hGlob);
if (dwSize > 0 && pBytes)
return true;
}
}
return false;
}
CefRefPtr<CefStreamReader> GetBinaryResourceReader(int binaryId) {
DWORD dwSize;
LPBYTE pBytes;
if (LoadBinaryResource(binaryId, dwSize, pBytes)) {
return CefStreamReader::CreateForHandler(
new CefByteReadHandler(pBytes, dwSize, NULL));
}
ASSERT(FALSE); // The resource should be found.
return NULL;
}
CefRefPtr<CefStreamReader> GetBinaryResourceReader(const char* resource_name) {
// Map of resource labels to BINARY id values.
static struct _resource_map {
char* name;
int id;
} resource_map[] = {
{"binding.html", IDS_BINDING},
{"dialogs.html", IDS_DIALOGS},
{"domaccess.html", IDS_DOMACCESS},
{"localstorage.html", IDS_LOCALSTORAGE},
{"xmlhttprequest.html", IDS_XMLHTTPREQUEST},
};
for (int i = 0; i < sizeof(resource_map)/sizeof(_resource_map); ++i) {
if (!strcmp(resource_map[i].name, resource_name))
return GetBinaryResourceReader(resource_map[i].id);
}
ASSERT(FALSE); // The resource should be found.
return NULL;
}
#endif // OS_WIN

View File

@@ -1,182 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cefclient/scheme_test.h"
#include <algorithm>
#include <string>
#include "include/cef_browser.h"
#include "include/cef_callback.h"
#include "include/cef_frame.h"
#include "include/cef_resource_handler.h"
#include "include/cef_response.h"
#include "include/cef_request.h"
#include "include/cef_scheme.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
#include "cefclient/util.h"
#if defined(OS_WIN)
#include "cefclient/resource.h"
#endif
namespace scheme_test {
namespace {
// Implementation of the schema handler for client:// requests.
class ClientSchemeHandler : public CefResourceHandler {
public:
ClientSchemeHandler() : offset_(0) {}
virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
CefRefPtr<CefCallback> callback)
OVERRIDE {
REQUIRE_IO_THREAD();
bool handled = false;
AutoLock lock_scope(this);
std::string url = request->GetURL();
if (strstr(url.c_str(), "handler.html") != NULL) {
// Build the response html
data_ = "<html><head><title>Client Scheme Handler</title></head><body>"
"This contents of this page page are served by the "
"ClientSchemeHandler class handling the client:// protocol."
"<br/>You should see an image:"
"<br/><img src=\"client://tests/client.png\"><pre>";
// Output a string representation of the request
std::string dump;
DumpRequestContents(request, dump);
data_.append(dump);
data_.append("</pre><br/>Try the test form:"
"<form method=\"POST\" action=\"handler.html\">"
"<input type=\"text\" name=\"field1\">"
"<input type=\"text\" name=\"field2\">"
"<input type=\"submit\">"
"</form></body></html>");
handled = true;
// Set the resulting mime type
mime_type_ = "text/html";
} else if (strstr(url.c_str(), "client.png") != NULL) {
// Load the response image
#if defined(OS_WIN)
DWORD dwSize;
LPBYTE pBytes;
if (LoadBinaryResource(IDS_LOGO, dwSize, pBytes)) {
data_ = std::string(reinterpret_cast<const char*>(pBytes), dwSize);
handled = true;
// Set the resulting mime type
mime_type_ = "image/jpg";
}
#elif defined(OS_MACOSX) || defined(OS_LINUX)
if (LoadBinaryResource("logo.png", data_)) {
handled = true;
// Set the resulting mime type
mime_type_ = "image/png";
}
#else
#error "Unsupported platform"
#endif
}
if (handled) {
// Indicate the headers are available.
callback->Continue();
return true;
}
return false;
}
virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
int64& response_length,
CefString& redirectUrl) OVERRIDE {
REQUIRE_IO_THREAD();
ASSERT(!data_.empty());
response->SetMimeType(mime_type_);
response->SetStatus(200);
// Set the resulting response length
response_length = data_.length();
}
virtual void Cancel() OVERRIDE {
REQUIRE_IO_THREAD();
}
virtual bool ReadResponse(void* data_out,
int bytes_to_read,
int& bytes_read,
CefRefPtr<CefCallback> callback)
OVERRIDE {
REQUIRE_IO_THREAD();
bool has_data = false;
bytes_read = 0;
AutoLock lock_scope(this);
if (offset_ < data_.length()) {
// Copy the next block of data into the buffer.
int transfer_size =
std::min(bytes_to_read, static_cast<int>(data_.length() - offset_));
memcpy(data_out, data_.c_str() + offset_, transfer_size);
offset_ += transfer_size;
bytes_read = transfer_size;
has_data = true;
}
return has_data;
}
private:
std::string data_;
std::string mime_type_;
size_t offset_;
IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
IMPLEMENT_LOCKING(ClientSchemeHandler);
};
// Implementation of the factory for for creating schema handlers.
class ClientSchemeHandlerFactory : public CefSchemeHandlerFactory {
public:
// Return a new scheme handler instance to handle the request.
virtual CefRefPtr<CefResourceHandler> Create(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& scheme_name,
CefRefPtr<CefRequest> request)
OVERRIDE {
REQUIRE_IO_THREAD();
return new ClientSchemeHandler();
}
IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
};
} // namespace
void RegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes) {
registrar->AddCustomScheme("client", true, false, false);
}
void InitTest() {
CefRegisterSchemeHandlerFactory("client", "tests",
new ClientSchemeHandlerFactory());
}
void RunTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL("client://tests/handler.html");
}
} // namespace scheme_test

View File

@@ -1,29 +0,0 @@
// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_
#define CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_
#pragma once
#include <vector>
#include "include/cef_base.h"
class CefBrowser;
class CefSchemeRegistrar;
namespace scheme_test {
// Register the scheme.
void RegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes);
// Create the scheme handler.
void InitTest();
// Run the test.
void RunTest(CefRefPtr<CefBrowser> browser);
} // namespace scheme_test
#endif // CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_

View File

@@ -1,8 +0,0 @@
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "cefclient/string_util.h"
#include <sstream>
#include <string>
#include "include/cef_request.h"

View File

@@ -1,14 +0,0 @@
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_STRING_UTIL_H_
#define CEF_TESTS_CEFCLIENT_STRING_UTIL_H_
#pragma once
#include <string>
#include "include/cef_base.h"
class CefRequest;
#endif // CEF_TESTS_CEFCLIENT_STRING_UTIL_H_

View File

@@ -1,48 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "tests/cefclient/client_app.h"
// static
void ClientApp::CreateRenderDelegates(RenderDelegateSet& delegates) {
// Bring in the process message tests.
extern void CreateProcessMessageRendererTests(
ClientApp::RenderDelegateSet& delegates);
CreateProcessMessageRendererTests(delegates);
// Bring in the V8 tests.
extern void CreateV8RendererTests(RenderDelegateSet& delegates);
CreateV8RendererTests(delegates);
// Bring in the DOM tests.
extern void CreateDOMRendererTests(RenderDelegateSet& delegates);
CreateDOMRendererTests(delegates);
// Bring in the URLRequest tests.
extern void CreateURLRequestRendererTests(RenderDelegateSet& delegates);
CreateURLRequestRendererTests(delegates);
}
// static
void ClientApp::RegisterCustomSchemes(
CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes) {
// Bring in the scheme handler tests.
extern void RegisterSchemeHandlerCustomSchemes(
CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes);
RegisterSchemeHandlerCustomSchemes(registrar, cookiable_schemes);
// Bring in the cookie tests.
extern void RegisterCookieCustomSchemes(
CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes);
RegisterCookieCustomSchemes(registrar, cookiable_schemes);
// Bring in the URLRequest tests.
extern void RegisterURLRequestCustomSchemes(
CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes);
RegisterURLRequestCustomSchemes(registrar, cookiable_schemes);
}

View File

@@ -1,118 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_command_line.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void VerifyCommandLine(CefRefPtr<CefCommandLine> command_line) {
std::string program = command_line->GetProgram();
EXPECT_EQ("test.exe", program);
EXPECT_TRUE(command_line->HasSwitches());
EXPECT_TRUE(command_line->HasSwitch("switch1"));
std::string switch1 = command_line->GetSwitchValue("switch1");
EXPECT_EQ("", switch1);
EXPECT_TRUE(command_line->HasSwitch("switch2"));
std::string switch2 = command_line->GetSwitchValue("switch2");
EXPECT_EQ("val2", switch2);
EXPECT_TRUE(command_line->HasSwitch("switch3"));
std::string switch3 = command_line->GetSwitchValue("switch3");
EXPECT_EQ("val3", switch3);
EXPECT_TRUE(command_line->HasSwitch("switch4"));
std::string switch4 = command_line->GetSwitchValue("switch4");
EXPECT_EQ("val 4", switch4);
EXPECT_FALSE(command_line->HasSwitch("switchnoexist"));
CefCommandLine::SwitchMap switches;
command_line->GetSwitches(switches);
EXPECT_EQ((size_t)4, switches.size());
bool has1 = false, has2 = false, has3 = false, has4 = false;
CefCommandLine::SwitchMap::const_iterator it = switches.begin();
for (; it != switches.end(); ++it) {
std::string name = it->first;
std::string val = it->second;
if (name == "switch1") {
has1 = true;
EXPECT_EQ("", val);
} else if (name == "switch2") {
has2 = true;
EXPECT_EQ("val2", val);
} else if (name == "switch3") {
has3 = true;
EXPECT_EQ("val3", val);
} else if (name == "switch4") {
has4 = true;
EXPECT_EQ("val 4", val);
}
}
EXPECT_TRUE(has1);
EXPECT_TRUE(has2);
EXPECT_TRUE(has3);
EXPECT_TRUE(has4);
EXPECT_TRUE(command_line->HasArguments());
CefCommandLine::ArgumentList args;
command_line->GetArguments(args);
EXPECT_EQ((size_t)2, args.size());
std::string arg0 = args[0];
EXPECT_EQ("arg1", arg0);
std::string arg1 = args[1];
EXPECT_EQ("arg 2", arg1);
command_line->Reset();
EXPECT_FALSE(command_line->HasSwitches());
EXPECT_FALSE(command_line->HasArguments());
std::string cur_program = command_line->GetProgram();
EXPECT_EQ(program, cur_program);
}
} // namespace
// Test creating a command line from argc/argv or string.
TEST(CommandLineTest, Init) {
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
EXPECT_TRUE(command_line.get() != NULL);
#if defined(OS_WIN)
command_line->InitFromString("test.exe --switch1 -switch2=val2 /switch3=val3 "
"-switch4=\"val 4\" arg1 \"arg 2\"");
#else
const char* args[] = {
"test.exe",
"--switch1",
"-switch2=val2",
"-switch3=val3",
"-switch4=val 4",
"arg1",
"arg 2"
};
command_line->InitFromArgv(sizeof(args) / sizeof(char*), args);
#endif
VerifyCommandLine(command_line);
}
// Test creating a command line using set and append methods.
TEST(CommandLineTest, Manual) {
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
EXPECT_TRUE(command_line.get() != NULL);
command_line->SetProgram("test.exe");
command_line->AppendSwitch("switch1");
command_line->AppendSwitchWithValue("switch2", "val2");
command_line->AppendSwitchWithValue("switch3", "val3");
command_line->AppendSwitchWithValue("switch4", "val 4");
command_line->AppendArgument("arg1");
command_line->AppendArgument("arg 2");
VerifyCommandLine(command_line);
}

View File

@@ -1,962 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include <vector>
#include "include/cef_cookie.h"
#include "include/cef_runnable.h"
#include "include/cef_scheme.h"
#include "tests/unittests/test_handler.h"
#include "tests/unittests/test_suite.h"
#include "base/scoped_temp_dir.h"
#include "base/synchronization/waitable_event.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char* kTestUrl = "http://www.test.com/path/to/cookietest/foo.html";
const char* kTestDomain = "www.test.com";
const char* kTestPath = "/path/to/cookietest";
typedef std::vector<CefCookie> CookieVector;
void IOT_Set(CefRefPtr<CefCookieManager> manager,
const CefString& url, CookieVector* cookies,
base::WaitableEvent* event) {
CookieVector::const_iterator it = cookies->begin();
for (; it != cookies->end(); ++it)
EXPECT_TRUE(manager->SetCookie(url, *it));
event->Signal();
}
void IOT_Delete(CefRefPtr<CefCookieManager> manager,
const CefString& url, const CefString& cookie_name,
base::WaitableEvent* event) {
EXPECT_TRUE(manager->DeleteCookies(url, cookie_name));
event->Signal();
}
class TestVisitor : public CefCookieVisitor {
public:
TestVisitor(CookieVector* cookies, bool deleteCookies,
base::WaitableEvent* event)
: cookies_(cookies),
delete_cookies_(deleteCookies),
event_(event) {
}
virtual ~TestVisitor() {
event_->Signal();
}
virtual bool Visit(const CefCookie& cookie, int count, int total,
bool& deleteCookie) {
cookies_->push_back(cookie);
if (delete_cookies_)
deleteCookie = true;
return true;
}
CookieVector* cookies_;
bool delete_cookies_;
base::WaitableEvent* event_;
IMPLEMENT_REFCOUNTING(TestVisitor);
};
// Set the cookies.
void SetCookies(CefRefPtr<CefCookieManager> manager,
const CefString& url, CookieVector& cookies,
base::WaitableEvent& event) {
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Set, manager, url,
&cookies, &event));
event.Wait();
}
// Delete the cookie.
void DeleteCookies(CefRefPtr<CefCookieManager> manager,
const CefString& url, const CefString& cookie_name,
base::WaitableEvent& event) {
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, manager, url,
cookie_name, &event));
event.Wait();
}
// Create a test cookie. If |withDomain| is true a domain cookie will be
// created, otherwise a host cookie will be created.
void CreateCookie(CefRefPtr<CefCookieManager> manager,
CefCookie& cookie, bool withDomain,
base::WaitableEvent& event) {
CefString(&cookie.name).FromASCII("my_cookie");
CefString(&cookie.value).FromASCII("My Value");
if (withDomain)
CefString(&cookie.domain).FromASCII(kTestDomain);
CefString(&cookie.path).FromASCII(kTestPath);
cookie.has_expires = true;
cookie.expires.year = 2200;
cookie.expires.month = 4;
cookie.expires.day_of_week = 5;
cookie.expires.day_of_month = 11;
CookieVector cookies;
cookies.push_back(cookie);
SetCookies(manager, kTestUrl, cookies, event);
}
// Retrieve the test cookie. If |withDomain| is true check that the cookie
// is a domain cookie, otherwise a host cookie. if |deleteCookies| is true
// the cookie will be deleted when it's retrieved.
void GetCookie(CefRefPtr<CefCookieManager> manager,
const CefCookie& cookie, bool withDomain,
base::WaitableEvent& event, bool deleteCookies) {
CookieVector cookies;
// Get the cookie and delete it.
EXPECT_TRUE(manager->VisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, deleteCookies, &event)));
event.Wait();
EXPECT_EQ((CookieVector::size_type)1, cookies.size());
const CefCookie& cookie_read = cookies[0];
EXPECT_EQ(CefString(&cookie_read.name), "my_cookie");
EXPECT_EQ(CefString(&cookie_read.value), "My Value");
if (withDomain)
EXPECT_EQ(CefString(&cookie_read.domain), ".www.test.com");
else
EXPECT_EQ(CefString(&cookie_read.domain), kTestDomain);
EXPECT_EQ(CefString(&cookie_read.path), kTestPath);
EXPECT_TRUE(cookie_read.has_expires);
EXPECT_EQ(cookie.expires.year, cookie_read.expires.year);
EXPECT_EQ(cookie.expires.month, cookie_read.expires.month);
EXPECT_EQ(cookie.expires.day_of_week, cookie_read.expires.day_of_week);
EXPECT_EQ(cookie.expires.day_of_month, cookie_read.expires.day_of_month);
EXPECT_EQ(cookie.expires.hour, cookie_read.expires.hour);
EXPECT_EQ(cookie.expires.minute, cookie_read.expires.minute);
EXPECT_EQ(cookie.expires.second, cookie_read.expires.second);
EXPECT_EQ(cookie.expires.millisecond, cookie_read.expires.millisecond);
}
// Visit URL cookies.
void VisitUrlCookies(CefRefPtr<CefCookieManager> manager,
const CefString& url,
bool includeHttpOnly,
CookieVector& cookies,
bool deleteCookies,
base::WaitableEvent& event) {
EXPECT_TRUE(manager->VisitUrlCookies(url, includeHttpOnly,
new TestVisitor(&cookies, deleteCookies, &event)));
event.Wait();
}
// Visit all cookies.
void VisitAllCookies(CefRefPtr<CefCookieManager> manager,
CookieVector& cookies,
bool deleteCookies,
base::WaitableEvent& event) {
EXPECT_TRUE(manager->VisitAllCookies(
new TestVisitor(&cookies, deleteCookies, &event)));
event.Wait();
}
// Verify that no cookies exist. If |withUrl| is true it will only check for
// cookies matching the URL.
void VerifyNoCookies(CefRefPtr<CefCookieManager> manager,
base::WaitableEvent& event, bool withUrl) {
CookieVector cookies;
// Verify that the cookie has been deleted.
if (withUrl) {
EXPECT_TRUE(manager->VisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, false, &event)));
} else {
EXPECT_TRUE(manager->VisitAllCookies(
new TestVisitor(&cookies, false, &event)));
}
event.Wait();
EXPECT_EQ((CookieVector::size_type)0, cookies.size());
}
// Delete all system cookies.
void DeleteAllCookies(CefRefPtr<CefCookieManager> manager,
base::WaitableEvent& event) {
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, manager, CefString(),
CefString(), &event));
event.Wait();
}
void TestDomainCookie(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
CefCookie cookie;
// Create a domain cookie.
CreateCookie(manager, cookie, true, event);
// Retrieve, verify and delete the domain cookie.
GetCookie(manager, cookie, true, event, true);
// Verify that the cookie was deleted.
VerifyNoCookies(manager, event, true);
}
void TestHostCookie(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
CefCookie cookie;
// Create a host cookie.
CreateCookie(manager, cookie, false, event);
// Retrieve, verify and delete the host cookie.
GetCookie(manager, cookie, false, event, true);
// Verify that the cookie was deleted.
VerifyNoCookies(manager, event, true);
}
void TestMultipleCookies(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
std::stringstream ss;
int i;
CookieVector cookies;
const int kNumCookies = 4;
// Create the cookies.
for (i = 0; i < kNumCookies; i++) {
CefCookie cookie;
ss << "my_cookie" << i;
CefString(&cookie.name).FromASCII(ss.str().c_str());
ss.str("");
ss << "My Value " << i;
CefString(&cookie.value).FromASCII(ss.str().c_str());
ss.str("");
cookies.push_back(cookie);
}
// Set the cookies.
SetCookies(manager, kTestUrl, cookies, event);
cookies.clear();
// Get the cookies without deleting them.
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)kNumCookies, cookies.size());
CookieVector::const_iterator it = cookies.begin();
for (i = 0; it != cookies.end(); ++it, ++i) {
const CefCookie& cookie = *it;
ss << "my_cookie" << i;
EXPECT_EQ(CefString(&cookie.name), ss.str());
ss.str("");
ss << "My Value " << i;
EXPECT_EQ(CefString(&cookie.value), ss.str());
ss.str("");
}
cookies.clear();
// Delete the 2nd cookie.
DeleteCookies(manager, kTestUrl, CefString("my_cookie1"), event);
// Verify that the cookie has been deleted.
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)3, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie0");
EXPECT_EQ(CefString(&cookies[1].name), "my_cookie2");
EXPECT_EQ(CefString(&cookies[2].name), "my_cookie3");
cookies.clear();
// Delete the rest of the cookies.
DeleteCookies(manager, kTestUrl, CefString(), event);
// Verify that the cookies have been deleted.
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)0, cookies.size());
// Create the cookies.
for (i = 0; i < kNumCookies; i++) {
CefCookie cookie;
ss << "my_cookie" << i;
CefString(&cookie.name).FromASCII(ss.str().c_str());
ss.str("");
ss << "My Value " << i;
CefString(&cookie.value).FromASCII(ss.str().c_str());
ss.str("");
cookies.push_back(cookie);
}
// Delete all of the cookies using the visitor.
VisitUrlCookies(manager, kTestUrl, false, cookies, true, event);
cookies.clear();
// Verify that the cookies have been deleted.
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)0, cookies.size());
}
void TestAllCookies(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
CookieVector cookies;
// Delete all system cookies just in case something is left over from a
// different test.
DeleteCookies(manager, CefString(), CefString(), event);
// Verify that all system cookies have been deleted.
VisitAllCookies(manager, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)0, cookies.size());
// Create cookies with 2 separate hosts.
CefCookie cookie1;
const char* kUrl1 = "http://www.foo.com";
CefString(&cookie1.name).FromASCII("my_cookie1");
CefString(&cookie1.value).FromASCII("My Value 1");
cookies.push_back(cookie1);
SetCookies(manager, kUrl1, cookies, event);
cookies.clear();
CefCookie cookie2;
const char* kUrl2 = "http://www.bar.com";
CefString(&cookie2.name).FromASCII("my_cookie2");
CefString(&cookie2.value).FromASCII("My Value 2");
cookies.push_back(cookie2);
SetCookies(manager, kUrl2, cookies, event);
cookies.clear();
// Verify that all system cookies can be retrieved.
VisitAllCookies(manager, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)2, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie1");
EXPECT_EQ(CefString(&cookies[0].value), "My Value 1");
EXPECT_EQ(CefString(&cookies[0].domain), "www.foo.com");
EXPECT_EQ(CefString(&cookies[1].name), "my_cookie2");
EXPECT_EQ(CefString(&cookies[1].value), "My Value 2");
EXPECT_EQ(CefString(&cookies[1].domain), "www.bar.com");
cookies.clear();
// Verify that the cookies can be retrieved separately.
VisitUrlCookies(manager, kUrl1, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)1, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie1");
EXPECT_EQ(CefString(&cookies[0].value), "My Value 1");
EXPECT_EQ(CefString(&cookies[0].domain), "www.foo.com");
cookies.clear();
VisitUrlCookies(manager, kUrl2, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)1, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie2");
EXPECT_EQ(CefString(&cookies[0].value), "My Value 2");
EXPECT_EQ(CefString(&cookies[0].domain), "www.bar.com");
cookies.clear();
// Delete all of the system cookies.
DeleteAllCookies(manager, event);
// Verify that all system cookies have been deleted.
VerifyNoCookies(manager, event, false);
}
void TestChangeDirectory(CefRefPtr<CefCookieManager> manager,
const CefString& original_dir) {
base::WaitableEvent event(false, false);
CefCookie cookie;
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
// Delete all of the system cookies.
DeleteAllCookies(manager, event);
// Set the new temporary directory as the storage location.
EXPECT_TRUE(manager->SetStoragePath(temp_dir.path().value()));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
// Verify that no cookies exist.
VerifyNoCookies(manager, event, true);
// Create a domain cookie.
CreateCookie(manager, cookie, true, event);
// Retrieve and verify the domain cookie.
GetCookie(manager, cookie, true, event, false);
// Restore the original storage location.
EXPECT_TRUE(manager->SetStoragePath(original_dir));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
// Verify that no cookies exist.
VerifyNoCookies(manager, event, true);
// Set the new temporary directory as the storage location.
EXPECT_TRUE(manager->SetStoragePath(temp_dir.path().value()));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
// Retrieve and verify the domain cookie that was set previously.
GetCookie(manager, cookie, true, event, false);
// Restore the original storage location.
EXPECT_TRUE(manager->SetStoragePath(original_dir));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
}
} // namespace
// Test creation of a domain cookie.
TEST(CookieTest, DomainCookieGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestDomainCookie(manager);
}
// Test creation of a domain cookie.
TEST(CookieTest, DomainCookieInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestDomainCookie(manager);
}
// Test creation of a domain cookie.
TEST(CookieTest, DomainCookieOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestDomainCookie(manager);
}
// Test creation of a host cookie.
TEST(CookieTest, HostCookieGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestHostCookie(manager);
}
// Test creation of a host cookie.
TEST(CookieTest, HostCookieInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestHostCookie(manager);
}
// Test creation of a host cookie.
TEST(CookieTest, HostCookieOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestHostCookie(manager);
}
// Test creation of multiple cookies.
TEST(CookieTest, MultipleCookiesGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestMultipleCookies(manager);
}
// Test creation of multiple cookies.
TEST(CookieTest, MultipleCookiesInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestMultipleCookies(manager);
}
// Test creation of multiple cookies.
TEST(CookieTest, MultipleCookiesOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestMultipleCookies(manager);
}
TEST(CookieTest, AllCookiesGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestAllCookies(manager);
}
TEST(CookieTest, AllCookiesInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestAllCookies(manager);
}
TEST(CookieTest, AllCookiesOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestAllCookies(manager);
}
TEST(CookieTest, ChangeDirectoryGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
std::string cache_path;
CefTestSuite::GetCachePath(cache_path);
TestChangeDirectory(manager, cache_path);
}
TEST(CookieTest, ChangeDirectoryCreated) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestChangeDirectory(manager, CefString());
}
namespace {
const char* kCookieJSUrl1 = "http://tests/cookie1.html";
const char* kCookieJSUrl2 = "http://tests/cookie2.html";
class CookieTestJSHandler : public TestHandler {
public:
CookieTestJSHandler() {}
virtual void RunTest() OVERRIDE {
// Create =new in-memory managers.
manager1_ = CefCookieManager::CreateManager(CefString());
manager2_ = CefCookieManager::CreateManager(CefString());
std::string page =
"<html><head>"
"<script>"
"document.cookie='name1=value1';"
"</script>"
"</head><body>COOKIE TEST1</body></html>";
AddResource(kCookieJSUrl1, page, "text/html");
page =
"<html><head>"
"<script>"
"document.cookie='name2=value2';"
"</script>"
"</head><body>COOKIE TEST2</body></html>";
AddResource(kCookieJSUrl2, page, "text/html");
// Create the browser
CreateBrowser(kCookieJSUrl1);
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
std::string url = frame->GetURL();
if (url == kCookieJSUrl1) {
got_load_end1_.yes();
VerifyCookie(manager1_, url, "name1", "value1", got_cookie1_);
// Go to the next URL
frame->LoadURL(kCookieJSUrl2);
} else {
got_load_end2_.yes();
VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_);
DestroyTest();
}
}
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser,
const CefString& main_url) OVERRIDE {
if (main_url == kCookieJSUrl1) {
// Return the first cookie manager.
got_cookie_manager1_.yes();
return manager1_;
} else {
// Return the second cookie manager.
got_cookie_manager2_.yes();
return manager2_;
}
}
// Verify that the cookie was set successfully.
void VerifyCookie(CefRefPtr<CefCookieManager> manager,
const std::string& url,
const std::string& name,
const std::string& value,
TrackCallback& callback) {
base::WaitableEvent event(false, false);
CookieVector cookies;
// Get the cookie.
VisitUrlCookies(manager, url, false, cookies, false, event);
if (cookies.size() == 1 && CefString(&cookies[0].name) == name &&
CefString(&cookies[0].value) == value) {
callback.yes();
}
}
CefRefPtr<CefCookieManager> manager1_;
CefRefPtr<CefCookieManager> manager2_;
TrackCallback got_cookie_manager1_;
TrackCallback got_cookie_manager2_;
TrackCallback got_load_end1_;
TrackCallback got_load_end2_;
TrackCallback got_cookie1_;
TrackCallback got_cookie2_;
};
} // namespace
// Verify use of multiple cookie managers vis JS.
TEST(CookieTest, GetCookieManagerJS) {
CefRefPtr<CookieTestJSHandler> handler = new CookieTestJSHandler();
handler->ExecuteTest();
EXPECT_TRUE(handler->got_cookie_manager1_);
EXPECT_TRUE(handler->got_cookie_manager2_);
EXPECT_TRUE(handler->got_load_end1_);
EXPECT_TRUE(handler->got_load_end2_);
EXPECT_TRUE(handler->got_cookie1_);
EXPECT_TRUE(handler->got_cookie2_);
}
namespace {
class CookieTestSchemeHandler : public TestHandler {
public:
class SchemeHandler : public CefResourceHandler {
public:
explicit SchemeHandler(CookieTestSchemeHandler* handler)
: handler_(handler),
offset_(0) {}
virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
CefRefPtr<CefCallback> callback)
OVERRIDE {
std::string url = request->GetURL();
if (url == handler_->url1_) {
content_ = "<html><body>COOKIE TEST1</body></html>";
cookie_ = "name1=value1";
handler_->got_process_request1_.yes();
} else if (url == handler_->url2_) {
content_ = "<html><body>COOKIE TEST2</body></html>";
cookie_ = "name2=value2";
handler_->got_process_request2_.yes();
} else if (url == handler_->url3_) {
content_ = "<html><body>COOKIE TEST3</body></html>";
handler_->got_process_request3_.yes();
// Verify that the cookie was passed in.
CefRequest::HeaderMap headerMap;
request->GetHeaderMap(headerMap);
CefRequest::HeaderMap::iterator it = headerMap.find("Cookie");
if (it != headerMap.end() && it->second == "name2=value2")
handler_->got_process_request_cookie_.yes();
}
callback->Continue();
return true;
}
virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
int64& response_length,
CefString& redirectUrl) OVERRIDE {
response_length = content_.size();
response->SetStatus(200);
response->SetMimeType("text/html");
if (!cookie_.empty()) {
CefResponse::HeaderMap headerMap;
response->GetHeaderMap(headerMap);
headerMap.insert(std::make_pair("Set-Cookie", cookie_));
response->SetHeaderMap(headerMap);
}
}
virtual bool ReadResponse(void* data_out,
int bytes_to_read,
int& bytes_read,
CefRefPtr<CefCallback> callback)
OVERRIDE {
bool has_data = false;
bytes_read = 0;
size_t size = content_.size();
if (offset_ < size) {
int transfer_size =
std::min(bytes_to_read, static_cast<int>(size - offset_));
memcpy(data_out, content_.c_str() + offset_, transfer_size);
offset_ += transfer_size;
bytes_read = transfer_size;
has_data = true;
}
return has_data;
}
virtual void Cancel() OVERRIDE {
}
private:
CookieTestSchemeHandler* handler_;
std::string content_;
size_t offset_;
std::string cookie_;
IMPLEMENT_REFCOUNTING(SchemeHandler);
};
class SchemeHandlerFactory : public CefSchemeHandlerFactory {
public:
explicit SchemeHandlerFactory(CookieTestSchemeHandler* handler)
: handler_(handler) {}
virtual CefRefPtr<CefResourceHandler> Create(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& scheme_name,
CefRefPtr<CefRequest> request) OVERRIDE {
std::string url = request->GetURL();
if (url == handler_->url3_) {
// Verify that the cookie was not passed in.
CefRequest::HeaderMap headerMap;
request->GetHeaderMap(headerMap);
CefRequest::HeaderMap::iterator it = headerMap.find("Cookie");
if (it != headerMap.end() && it->second == "name2=value2")
handler_->got_create_cookie_.yes();
}
return new SchemeHandler(handler_);
}
private:
CookieTestSchemeHandler* handler_;
IMPLEMENT_REFCOUNTING(SchemeHandlerFactory);
};
CookieTestSchemeHandler(const std::string& scheme) : scheme_(scheme) {
url1_ = scheme + "://cookie-tests/cookie1.html";
url2_ = scheme + "://cookie-tests/cookie2.html";
url3_ = scheme + "://cookie-tests/cookie3.html";
}
virtual void RunTest() OVERRIDE {
// Create new in-memory managers.
manager1_ = CefCookieManager::CreateManager(CefString());
manager2_ = CefCookieManager::CreateManager(CefString());
if (scheme_ != "http") {
std::vector<CefString> schemes;
schemes.push_back("http");
schemes.push_back("https");
schemes.push_back(scheme_);
manager1_->SetSupportedSchemes(schemes);
manager2_->SetSupportedSchemes(schemes);
}
// Register the scheme handler.
CefRegisterSchemeHandlerFactory(scheme_, "cookie-tests",
new SchemeHandlerFactory(this));
// Create the browser
CreateBrowser(url1_);
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
std::string url = frame->GetURL();
if (url == url1_) {
got_load_end1_.yes();
VerifyCookie(manager1_, url, "name1", "value1", got_cookie1_);
// Go to the next URL
frame->LoadURL(url2_);
} else if (url == url2_) {
got_load_end2_.yes();
VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_);
// Go to the next URL
frame->LoadURL(url3_);
} else {
got_load_end3_.yes();
VerifyCookie(manager2_, url, "name2", "value2", got_cookie3_);
// Unregister the scheme handler.
CefRegisterSchemeHandlerFactory(scheme_, "cookie-tests", NULL);
DestroyTest();
}
}
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser,
const CefString& main_url) OVERRIDE {
if (main_url == url1_) {
// Return the first cookie manager.
got_cookie_manager1_.yes();
return manager1_;
} else {
// Return the second cookie manager.
got_cookie_manager2_.yes();
return manager2_;
}
}
// Verify that the cookie was set successfully.
void VerifyCookie(CefRefPtr<CefCookieManager> manager,
const std::string& url,
const std::string& name,
const std::string& value,
TrackCallback& callback) {
base::WaitableEvent event(false, false);
CookieVector cookies;
// Get the cookie.
VisitUrlCookies(manager, url, false, cookies, false, event);
if (cookies.size() == 1 && CefString(&cookies[0].name) == name &&
CefString(&cookies[0].value) == value) {
callback.yes();
}
}
std::string scheme_;
std::string url1_;
std::string url2_;
std::string url3_;
CefRefPtr<CefCookieManager> manager1_;
CefRefPtr<CefCookieManager> manager2_;
TrackCallback got_process_request1_;
TrackCallback got_process_request2_;
TrackCallback got_process_request3_;
TrackCallback got_create_cookie_;
TrackCallback got_process_request_cookie_;
TrackCallback got_cookie_manager1_;
TrackCallback got_cookie_manager2_;
TrackCallback got_load_end1_;
TrackCallback got_load_end2_;
TrackCallback got_load_end3_;
TrackCallback got_cookie1_;
TrackCallback got_cookie2_;
TrackCallback got_cookie3_;
};
} // namespace
// Verify use of multiple cookie managers via HTTP.
TEST(CookieTest, GetCookieManagerHttp) {
CefRefPtr<CookieTestSchemeHandler> handler =
new CookieTestSchemeHandler("http");
handler->ExecuteTest();
EXPECT_TRUE(handler->got_process_request1_);
EXPECT_TRUE(handler->got_process_request2_);
EXPECT_TRUE(handler->got_process_request3_);
EXPECT_FALSE(handler->got_create_cookie_);
EXPECT_TRUE(handler->got_process_request_cookie_);
EXPECT_TRUE(handler->got_cookie_manager1_);
EXPECT_TRUE(handler->got_cookie_manager2_);
EXPECT_TRUE(handler->got_load_end1_);
EXPECT_TRUE(handler->got_load_end2_);
EXPECT_TRUE(handler->got_load_end3_);
EXPECT_TRUE(handler->got_cookie1_);
EXPECT_TRUE(handler->got_cookie2_);
EXPECT_TRUE(handler->got_cookie3_);
}
// Verify use of multiple cookie managers via a custom scheme.
TEST(CookieTest, GetCookieManagerCustom) {
CefRefPtr<CookieTestSchemeHandler> handler =
new CookieTestSchemeHandler("ccustom");
handler->ExecuteTest();
EXPECT_TRUE(handler->got_process_request1_);
EXPECT_TRUE(handler->got_process_request2_);
EXPECT_TRUE(handler->got_process_request3_);
EXPECT_FALSE(handler->got_create_cookie_);
EXPECT_TRUE(handler->got_process_request_cookie_);
EXPECT_TRUE(handler->got_cookie_manager1_);
EXPECT_TRUE(handler->got_cookie_manager2_);
EXPECT_TRUE(handler->got_load_end1_);
EXPECT_TRUE(handler->got_load_end2_);
EXPECT_TRUE(handler->got_load_end3_);
EXPECT_TRUE(handler->got_cookie1_);
EXPECT_TRUE(handler->got_cookie2_);
EXPECT_TRUE(handler->got_cookie3_);
}
// Entry point for registering custom schemes.
// Called from client_app_delegates.cc.
void RegisterCookieCustomSchemes(
CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes) {
// Used by GetCookieManagerCustom test.
registrar->AddCustomScheme("ccustom", true, false, false);
}

View File

@@ -1,332 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_dom.h"
#include "tests/cefclient/client_app.h"
#include "tests/unittests/test_handler.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char* kTestUrl = "http://tests/DOMTest.Test";
const char* kTestMessage = "DOMTest.Message";
enum DOMTestType {
DOM_TEST_STRUCTURE,
DOM_TEST_MODIFY,
};
class TestDOMVisitor : public CefDOMVisitor {
public:
explicit TestDOMVisitor(CefRefPtr<CefBrowser> browser, DOMTestType test_type)
: browser_(browser),
test_type_(test_type) {
}
void TestHeadNodeStructure(CefRefPtr<CefDOMNode> headNode) {
EXPECT_TRUE(headNode.get());
EXPECT_TRUE(headNode->IsElement());
EXPECT_FALSE(headNode->IsText());
EXPECT_EQ(headNode->GetName(), "HEAD");
EXPECT_EQ(headNode->GetElementTagName(), "HEAD");
EXPECT_TRUE(headNode->HasChildren());
EXPECT_FALSE(headNode->HasElementAttributes());
CefRefPtr<CefDOMNode> titleNode = headNode->GetFirstChild();
EXPECT_TRUE(titleNode.get());
EXPECT_TRUE(titleNode->IsElement());
EXPECT_FALSE(titleNode->IsText());
EXPECT_EQ(titleNode->GetName(), "TITLE");
EXPECT_EQ(titleNode->GetElementTagName(), "TITLE");
EXPECT_TRUE(titleNode->GetParent()->IsSame(headNode));
EXPECT_FALSE(titleNode->GetNextSibling().get());
EXPECT_FALSE(titleNode->GetPreviousSibling().get());
EXPECT_TRUE(titleNode->HasChildren());
EXPECT_FALSE(titleNode->HasElementAttributes());
CefRefPtr<CefDOMNode> textNode = titleNode->GetFirstChild();
EXPECT_TRUE(textNode.get());
EXPECT_FALSE(textNode->IsElement());
EXPECT_TRUE(textNode->IsText());
EXPECT_EQ(textNode->GetValue(), "The Title");
EXPECT_TRUE(textNode->GetParent()->IsSame(titleNode));
EXPECT_FALSE(textNode->GetNextSibling().get());
EXPECT_FALSE(textNode->GetPreviousSibling().get());
EXPECT_FALSE(textNode->HasChildren());
}
void TestBodyNodeStructure(CefRefPtr<CefDOMNode> bodyNode) {
EXPECT_TRUE(bodyNode.get());
EXPECT_TRUE(bodyNode->IsElement());
EXPECT_FALSE(bodyNode->IsText());
EXPECT_EQ(bodyNode->GetName(), "BODY");
EXPECT_EQ(bodyNode->GetElementTagName(), "BODY");
EXPECT_TRUE(bodyNode->HasChildren());
EXPECT_FALSE(bodyNode->HasElementAttributes());
CefRefPtr<CefDOMNode> h1Node = bodyNode->GetFirstChild();
EXPECT_TRUE(h1Node.get());
EXPECT_TRUE(h1Node->IsElement());
EXPECT_FALSE(h1Node->IsText());
EXPECT_EQ(h1Node->GetName(), "H1");
EXPECT_EQ(h1Node->GetElementTagName(), "H1");
EXPECT_FALSE(h1Node->GetNextSibling().get());
EXPECT_FALSE(h1Node->GetPreviousSibling().get());
EXPECT_TRUE(h1Node->HasChildren());
EXPECT_FALSE(h1Node->HasElementAttributes());
CefRefPtr<CefDOMNode> textNode = h1Node->GetFirstChild();
EXPECT_TRUE(textNode.get());
EXPECT_FALSE(textNode->IsElement());
EXPECT_TRUE(textNode->IsText());
EXPECT_EQ(textNode->GetValue(), "Hello From");
EXPECT_FALSE(textNode->GetPreviousSibling().get());
EXPECT_FALSE(textNode->HasChildren());
CefRefPtr<CefDOMNode> brNode = textNode->GetNextSibling();
EXPECT_TRUE(brNode.get());
EXPECT_TRUE(brNode->IsElement());
EXPECT_FALSE(brNode->IsText());
EXPECT_EQ(brNode->GetName(), "BR");
EXPECT_EQ(brNode->GetElementTagName(), "BR");
EXPECT_FALSE(brNode->HasChildren());
EXPECT_TRUE(brNode->HasElementAttributes());
EXPECT_TRUE(brNode->HasElementAttribute("class"));
EXPECT_EQ(brNode->GetElementAttribute("class"), "some_class");
EXPECT_TRUE(brNode->HasElementAttribute("id"));
EXPECT_EQ(brNode->GetElementAttribute("id"), "some_id");
EXPECT_FALSE(brNode->HasElementAttribute("no_existing"));
CefDOMNode::AttributeMap map;
brNode->GetElementAttributes(map);
ASSERT_EQ(map.size(), (size_t)2);
EXPECT_EQ(map["class"], "some_class");
EXPECT_EQ(map["id"], "some_id");
// Can also retrieve by ID.
brNode = bodyNode->GetDocument()->GetElementById("some_id");
EXPECT_TRUE(brNode.get());
EXPECT_TRUE(brNode->IsElement());
EXPECT_FALSE(brNode->IsText());
EXPECT_EQ(brNode->GetName(), "BR");
EXPECT_EQ(brNode->GetElementTagName(), "BR");
textNode = brNode->GetNextSibling();
EXPECT_TRUE(textNode.get());
EXPECT_FALSE(textNode->IsElement());
EXPECT_TRUE(textNode->IsText());
EXPECT_EQ(textNode->GetValue(), "Main Frame");
EXPECT_FALSE(textNode->GetNextSibling().get());
EXPECT_FALSE(textNode->HasChildren());
}
// Test document structure by iterating through the DOM tree.
void TestStructure(CefRefPtr<CefDOMDocument> document) {
EXPECT_EQ(document->GetTitle(), "The Title");
EXPECT_EQ(document->GetBaseURL(), kTestUrl);
EXPECT_EQ(document->GetCompleteURL("foo.html"), "http://tests/foo.html");
// Navigate the complete document structure.
CefRefPtr<CefDOMNode> docNode = document->GetDocument();
EXPECT_TRUE(docNode.get());
EXPECT_FALSE(docNode->IsElement());
EXPECT_FALSE(docNode->IsText());
CefRefPtr<CefDOMNode> htmlNode = docNode->GetFirstChild();
EXPECT_TRUE(htmlNode.get());
EXPECT_TRUE(htmlNode->IsElement());
EXPECT_FALSE(htmlNode->IsText());
EXPECT_EQ(htmlNode->GetName(), "HTML");
EXPECT_EQ(htmlNode->GetElementTagName(), "HTML");
EXPECT_TRUE(htmlNode->HasChildren());
EXPECT_FALSE(htmlNode->HasElementAttributes());
CefRefPtr<CefDOMNode> headNode = htmlNode->GetFirstChild();
TestHeadNodeStructure(headNode);
CefRefPtr<CefDOMNode> bodyNode = headNode->GetNextSibling();
TestBodyNodeStructure(bodyNode);
// Retrieve the head node directly.
headNode = document->GetHead();
TestHeadNodeStructure(headNode);
// Retrieve the body node directly.
bodyNode = document->GetBody();
TestBodyNodeStructure(bodyNode);
}
// Test document modification by changing the H1 tag.
void TestModify(CefRefPtr<CefDOMDocument> document) {
CefRefPtr<CefDOMNode> bodyNode = document->GetBody();
CefRefPtr<CefDOMNode> h1Node = bodyNode->GetFirstChild();
ASSERT_EQ(h1Node->GetAsMarkup(),
"<h1>Hello From<br class=\"some_class\" id=\"some_id\">"
"Main Frame</h1>");
CefRefPtr<CefDOMNode> textNode = h1Node->GetFirstChild();
ASSERT_EQ(textNode->GetValue(), "Hello From");
ASSERT_TRUE(textNode->SetValue("A Different Message From"));
ASSERT_EQ(textNode->GetValue(), "A Different Message From");
CefRefPtr<CefDOMNode> brNode = textNode->GetNextSibling();
EXPECT_EQ(brNode->GetElementAttribute("class"), "some_class");
EXPECT_TRUE(brNode->SetElementAttribute("class", "a_different_class"));
EXPECT_EQ(brNode->GetElementAttribute("class"), "a_different_class");
ASSERT_EQ(h1Node->GetAsMarkup(),
"<h1>A Different Message From<br class=\"a_different_class\" "
"id=\"some_id\">Main Frame</h1>");
ASSERT_FALSE(h1Node->SetValue("Something Different"));
}
virtual void Visit(CefRefPtr<CefDOMDocument> document) OVERRIDE {
if (test_type_ == DOM_TEST_STRUCTURE)
TestStructure(document);
else if (test_type_ == DOM_TEST_MODIFY)
TestModify(document);
DestroyTest();
}
protected:
// Return from the test.
void DestroyTest() {
// Check if the test has failed.
bool result = !TestFailed();
// Return the result to the browser process.
CefRefPtr<CefProcessMessage> return_msg =
CefProcessMessage::Create(kTestMessage);
EXPECT_TRUE(return_msg->GetArgumentList()->SetBool(0, result));
EXPECT_TRUE(browser_->SendProcessMessage(PID_BROWSER, return_msg));
}
CefRefPtr<CefBrowser> browser_;
DOMTestType test_type_;
IMPLEMENT_REFCOUNTING(TestDOMVisitor);
};
// Used in the render process.
class DOMRendererTest : public ClientApp::RenderDelegate {
public:
DOMRendererTest() {
}
virtual bool OnProcessMessageReceived(
CefRefPtr<ClientApp> app,
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE {
if (message->GetName() == kTestMessage) {
EXPECT_EQ(message->GetArgumentList()->GetSize(), (size_t)1);
int test_type = message->GetArgumentList()->GetInt(0);
browser->GetMainFrame()->VisitDOM(
new TestDOMVisitor(browser, static_cast<DOMTestType>(test_type)));
return true;
}
return false;
}
private:
IMPLEMENT_REFCOUNTING(DOMRendererTest);
};
// Used in the browser process.
class TestDOMHandler : public TestHandler {
public:
explicit TestDOMHandler(DOMTestType test)
: test_type_(test) {
}
virtual void RunTest() OVERRIDE {
std::stringstream mainHtml;
mainHtml <<
"<html>"
"<head><title>The Title</title></head>"
"<body>"
"<h1>Hello From<br class=\"some_class\"/ id=\"some_id\"/>"
"Main Frame</h1>"
"</body>"
"</html>";
AddResource(kTestUrl, mainHtml.str(), "text/html");
CreateBrowser(kTestUrl);
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
if (frame->IsMain()) {
// Start the test in the render process.
CefRefPtr<CefProcessMessage> message(
CefProcessMessage::Create(kTestMessage));
message->GetArgumentList()->SetInt(0, test_type_);
EXPECT_TRUE(browser->SendProcessMessage(PID_RENDERER, message));
}
}
virtual bool OnProcessMessageReceived(
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE {
EXPECT_STREQ(message->GetName().ToString().c_str(), kTestMessage);
got_message_.yes();
if (message->GetArgumentList()->GetBool(0))
got_success_.yes();
// Test is complete.
DestroyTest();
return true;
}
DOMTestType test_type_;
TrackCallback got_message_;
TrackCallback got_success_;
};
} // namespace
// Test DOM structure reading.
TEST(DOMTest, Read) {
CefRefPtr<TestDOMHandler> handler =
new TestDOMHandler(DOM_TEST_STRUCTURE);
handler->ExecuteTest();
EXPECT_TRUE(handler->got_message_);
EXPECT_TRUE(handler->got_success_);
}
// Test DOM modifications.
TEST(DOMTest, Modify) {
CefRefPtr<TestDOMHandler> handler =
new TestDOMHandler(DOM_TEST_MODIFY);
handler->ExecuteTest();
EXPECT_TRUE(handler->got_message_);
EXPECT_TRUE(handler->got_success_);
}
// Entry point for creating DOM renderer test objects.
// Called from client_app_delegates.cc.
void CreateDOMRendererTests(ClientApp::RenderDelegateSet& delegates) {
delegates.insert(new DOMRendererTest);
}

View File

@@ -1,413 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_runnable.h"
#include "tests/unittests/test_handler.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char* kStartUrl = "http://tests/JSDialogTestHandler.Start";
const char* kEndUrl = "http://tests/JSDialogTestHandler.End?r=";
class JSDialogTestHandler : public TestHandler {
public:
enum TestType {
TYPE_ALERT,
TYPE_CONFIRM,
TYPE_PROMPT,
TYPE_ONBEFOREUNLOAD,
};
enum TestMode {
MODE_SUPPRESS,
MODE_RUN_IMMEDIATE,
MODE_RUN_DELAYED,
};
JSDialogTestHandler(TestType type,
TestMode mode,
bool success,
const std::string& user_input,
const std::string& result)
: type_(type),
mode_(mode),
success_(success),
user_input_(user_input),
result_(result) {
}
virtual void RunTest() OVERRIDE {
std::string content = "<html><head><body>START<script>";
if (type_ == TYPE_ALERT) {
content += "alert('My alert message'); "
"document.location='"+std::string(kEndUrl)+"';";
} else if (type_ == TYPE_CONFIRM) {
content += "var r = confirm('My confirm message')?'ok':'cancel'; "
"document.location='"+std::string(kEndUrl)+"'+r;";
} else if (type_ == TYPE_PROMPT) {
content += "var r = prompt('My prompt message','my default'); "
"document.location='"+std::string(kEndUrl)+"'+r;";
} else if (type_ == TYPE_ONBEFOREUNLOAD) {
content += "window.onbeforeunload=function() {"
" return 'My unload message'; };";
}
content += "</script></body></html>";
AddResource(kStartUrl, content, "text/html");
AddResource(kEndUrl, "<html><body>END</body></html>", "text/html");
// Create the browser
CreateBrowser(kStartUrl);
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
if (!frame->IsMain())
return;
std::string url = frame->GetURL();
if (url.find(kEndUrl) == 0) {
got_onloadend_.yes();
std::string result = url.substr(strlen(kEndUrl));
EXPECT_STREQ(result_.c_str(), result.c_str());
DestroyTest();
} else if (type_ == TYPE_ONBEFOREUNLOAD) {
// Trigger the onunload handler.
frame->LoadURL(kEndUrl);
}
}
virtual void Continue(CefRefPtr<CefJSDialogCallback> callback) {
callback->Continue(success_, user_input_);
}
virtual bool OnJSDialog(CefRefPtr<CefBrowser> browser,
const CefString& origin_url,
const CefString& accept_lang,
JSDialogType dialog_type,
const CefString& message_text,
const CefString& default_prompt_text,
CefRefPtr<CefJSDialogCallback> callback,
bool& suppress_message) OVERRIDE {
got_onjsdialog_.yes();
EXPECT_STREQ("http://tests/", origin_url.ToString().c_str());
EXPECT_TRUE(accept_lang.empty());
if (type_ == TYPE_ALERT) {
EXPECT_EQ(JSDIALOGTYPE_ALERT, dialog_type);
EXPECT_STREQ("My alert message", message_text.ToString().c_str());
EXPECT_TRUE(default_prompt_text.empty());
} else if (type_ == TYPE_CONFIRM) {
EXPECT_EQ(JSDIALOGTYPE_CONFIRM, dialog_type);
EXPECT_STREQ("My confirm message", message_text.ToString().c_str());
EXPECT_TRUE(default_prompt_text.empty());
} else if (type_ == TYPE_PROMPT) {
EXPECT_EQ(JSDIALOGTYPE_PROMPT, dialog_type);
EXPECT_STREQ("My prompt message", message_text.ToString().c_str());
EXPECT_STREQ("my default", default_prompt_text.ToString().c_str());
}
EXPECT_FALSE(suppress_message);
if (mode_ == MODE_SUPPRESS) {
// Suppress the dialog.
suppress_message = true;
return false;
} else if (mode_ == MODE_RUN_IMMEDIATE) {
// Continue immediately.
callback->Continue(success_, user_input_);
} else if (mode_ == MODE_RUN_DELAYED) {
// Continue asynchronously.
CefPostTask(TID_UI,
NewCefRunnableMethod(this, &JSDialogTestHandler::Continue, callback));
}
return true;
}
virtual bool OnBeforeUnloadDialog(CefRefPtr<CefBrowser> browser,
const CefString& message_text,
bool is_reload,
CefRefPtr<CefJSDialogCallback> callback)
OVERRIDE {
got_onbeforeunloaddialog_.yes();
if (type_ == TYPE_ONBEFOREUNLOAD) {
EXPECT_STREQ("My unload message", message_text.ToString().c_str());
EXPECT_FALSE(is_reload);
}
if (mode_ == MODE_RUN_IMMEDIATE) {
// Continue immediately.
callback->Continue(success_, user_input_);
} else if (mode_ == MODE_RUN_DELAYED) {
// Continue asynchronously.
CefPostTask(TID_UI,
NewCefRunnableMethod(this, &JSDialogTestHandler::Continue, callback));
}
return true;
}
virtual void OnResetDialogState(CefRefPtr<CefBrowser> browser) OVERRIDE {
got_onresetdialogstate_.yes();
}
TestType type_;
TestMode mode_;
bool success_;
std::string user_input_;
std::string result_;
TrackCallback got_onjsdialog_;
TrackCallback got_onbeforeunloaddialog_;
TrackCallback got_onresetdialogstate_;
TrackCallback got_onloadend_;
};
} // namespace
// Alert dialog with suppression.
TEST(JSDialogTest, AlertSuppress) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_ALERT,
JSDialogTestHandler::MODE_SUPPRESS,
true, // success
"", // user_input
""); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Alert dialog with immediate callback.
TEST(JSDialogTest, AlertRunImmediate) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_ALERT,
JSDialogTestHandler::MODE_RUN_IMMEDIATE,
true, // success
"", // user_input
""); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Alert dialog with delayed callback.
TEST(JSDialogTest, AlertRunDelayed) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_ALERT,
JSDialogTestHandler::MODE_RUN_DELAYED,
true, // success
"", // user_input
""); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Confirm dialog with suppression.
TEST(JSDialogTest, ConfirmSuppress) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_CONFIRM,
JSDialogTestHandler::MODE_SUPPRESS,
true, // success
"", // user_input
"cancel"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Confirm dialog run immediately return OK.
TEST(JSDialogTest, ConfirmRunImmediateOk) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_CONFIRM,
JSDialogTestHandler::MODE_RUN_IMMEDIATE,
true, // success
"", // user_input
"ok"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Confirm dialog run immediately return Cancel.
TEST(JSDialogTest, ConfirmRunImmediateCancel) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_CONFIRM,
JSDialogTestHandler::MODE_RUN_IMMEDIATE,
false, // success
"", // user_input
"cancel"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Confirm dialog run delayed return OK.
TEST(JSDialogTest, ConfirmRunDelayedOk) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_CONFIRM,
JSDialogTestHandler::MODE_RUN_DELAYED,
true, // success
"", // user_input
"ok"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Confirm dialog run delayed return Cancel.
TEST(JSDialogTest, ConfirmRunDelayedCancel) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_CONFIRM,
JSDialogTestHandler::MODE_RUN_DELAYED,
false, // success
"", // user_input
"cancel"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Prompt dialog with suppression.
TEST(JSDialogTest, PromptSuppress) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_PROMPT,
JSDialogTestHandler::MODE_SUPPRESS,
true, // success
"some_value", // user_input
"null"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Prompt dialog run immediately return OK.
TEST(JSDialogTest, PromptRunImmediateOk) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_PROMPT,
JSDialogTestHandler::MODE_RUN_IMMEDIATE,
true, // success
"some_value", // user_input
"some_value"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Prompt dialog run immediately return Cancel.
TEST(JSDialogTest, PromptRunImmediateCancel) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_PROMPT,
JSDialogTestHandler::MODE_RUN_IMMEDIATE,
false, // success
"some_value", // user_input
"null"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Prompt dialog run delayed return OK.
TEST(JSDialogTest, PromptRunDelayedOk) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_PROMPT,
JSDialogTestHandler::MODE_RUN_DELAYED,
true, // success
"some_value", // user_input
"some_value"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// Prompt dialog run delayed return Cancel.
TEST(JSDialogTest, PromptRunDelayedCancel) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_PROMPT,
JSDialogTestHandler::MODE_RUN_DELAYED,
false, // success
"some_value", // user_input
"null"); // result
handler->ExecuteTest();
EXPECT_TRUE(handler->got_onjsdialog_);
EXPECT_FALSE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// OnBeforeUnload dialog with immediate callback.
TEST(JSDialogTest, OnBeforeUnloadRunImmediate) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_ONBEFOREUNLOAD,
JSDialogTestHandler::MODE_RUN_IMMEDIATE,
true, // success
"", // user_input
""); // result
handler->ExecuteTest();
EXPECT_FALSE(handler->got_onjsdialog_);
EXPECT_TRUE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}
// OnBeforeUnload dialog with delayed callback.
TEST(JSDialogTest, OnBeforeUnloadRunDelayed) {
CefRefPtr<JSDialogTestHandler> handler =
new JSDialogTestHandler(JSDialogTestHandler::TYPE_ONBEFOREUNLOAD,
JSDialogTestHandler::MODE_RUN_DELAYED,
true, // success
"", // user_input
""); // result
handler->ExecuteTest();
EXPECT_FALSE(handler->got_onjsdialog_);
EXPECT_TRUE(handler->got_onbeforeunloaddialog_);
EXPECT_TRUE(handler->got_onresetdialogstate_);
EXPECT_TRUE(handler->got_onloadend_);
}

View File

@@ -1,3 +0,0 @@
/* Localized versions of Info.plist keys */
NSHumanReadableCopyright = "© Chromium Embedded Framework Authors, 2010";

File diff suppressed because it is too large Load Diff

View File

@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string>unittests.icns</string>
<key>CFBundleIdentifier</key>
<string>org.cef.unittests</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>

Binary file not shown.

View File

@@ -1,605 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_callback.h"
#include "include/cef_scheme.h"
#include "tests/unittests/test_handler.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
static const char* kNav1 = "http://tests/nav1.html";
static const char* kNav2 = "http://tests/nav2.html";
static const char* kNav3 = "http://tests/nav3.html";
static const char* kNav4 = "http://tests/nav4.html";
enum NavAction {
NA_LOAD = 1,
NA_BACK,
NA_FORWARD,
NA_CLEAR
};
typedef struct {
NavAction action; // What to do
const char* target; // Where to be after navigation
bool can_go_back; // After navigation, can go back?
bool can_go_forward; // After navigation, can go forward?
} NavListItem;
// Array of navigation actions: X = current page, . = history exists
static NavListItem kNavList[] = {
// kNav1 | kNav2 | kNav3
{NA_LOAD, kNav1, false, false}, // X
{NA_LOAD, kNav2, true, false}, // . X
{NA_BACK, kNav1, false, true}, // X .
{NA_FORWARD, kNav2, true, false}, // . X
{NA_LOAD, kNav3, true, false}, // . . X
{NA_BACK, kNav2, true, true}, // . X .
// TODO(cef): Enable once ClearHistory is implemented
// {NA_CLEAR, kNav2, false, false}, // X
};
#define NAV_LIST_SIZE() (sizeof(kNavList) / sizeof(NavListItem))
class HistoryNavTestHandler : public TestHandler {
public:
HistoryNavTestHandler() : nav_(0) {}
virtual void RunTest() OVERRIDE {
// Add the resources that we will navigate to/from.
AddResource(kNav1, "<html>Nav1</html>", "text/html");
AddResource(kNav2, "<html>Nav2</html>", "text/html");
AddResource(kNav3, "<html>Nav3</html>", "text/html");
// Create the browser.
CreateBrowser(CefString());
}
void RunNav(CefRefPtr<CefBrowser> browser) {
if (nav_ == NAV_LIST_SIZE()) {
// End of the nav list.
DestroyTest();
return;
}
const NavListItem& item = kNavList[nav_];
// Perform the action.
switch (item.action) {
case NA_LOAD:
browser->GetMainFrame()->LoadURL(item.target);
break;
case NA_BACK:
browser->GoBack();
break;
case NA_FORWARD:
browser->GoForward();
break;
case NA_CLEAR:
// TODO(cef): Enable once ClearHistory is implemented
// browser->GetHost()->ClearHistory();
// Not really a navigation action so go to the next one.
nav_++;
RunNav(browser);
break;
default:
break;
}
}
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE {
TestHandler::OnAfterCreated(browser);
RunNav(browser);
}
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
const NavListItem& item = kNavList[nav_];
got_before_resource_load_[nav_].yes();
std::string url = request->GetURL();
if (url == item.target)
got_correct_target_[nav_].yes();
return false;
}
virtual void OnLoadingStateChange(CefRefPtr<CefBrowser> browser,
bool isLoading,
bool canGoBack,
bool canGoForward) OVERRIDE {
const NavListItem& item = kNavList[nav_];
got_loading_state_change_[nav_].yes();
if (item.can_go_back == canGoBack)
got_correct_can_go_back_[nav_].yes();
if (item.can_go_forward == canGoForward)
got_correct_can_go_forward_[nav_].yes();
}
virtual void OnLoadStart(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame) OVERRIDE {
if(browser->IsPopup() || !frame->IsMain())
return;
const NavListItem& item = kNavList[nav_];
got_load_start_[nav_].yes();
std::string url1 = browser->GetMainFrame()->GetURL();
std::string url2 = frame->GetURL();
if (url1 == item.target && url2 == item.target)
got_correct_load_start_url_[nav_].yes();
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
if (browser->IsPopup() || !frame->IsMain())
return;
const NavListItem& item = kNavList[nav_];
got_load_end_[nav_].yes();
std::string url1 = browser->GetMainFrame()->GetURL();
std::string url2 = frame->GetURL();
if (url1 == item.target && url2 == item.target)
got_correct_load_end_url_[nav_].yes();
if (item.can_go_back == browser->CanGoBack())
got_correct_can_go_back2_[nav_].yes();
if (item.can_go_forward == browser->CanGoForward())
got_correct_can_go_forward2_[nav_].yes();
nav_++;
RunNav(browser);
}
int nav_;
TrackCallback got_before_resource_load_[NAV_LIST_SIZE()];
TrackCallback got_correct_target_[NAV_LIST_SIZE()];
TrackCallback got_loading_state_change_[NAV_LIST_SIZE()];
TrackCallback got_correct_can_go_back_[NAV_LIST_SIZE()];
TrackCallback got_correct_can_go_forward_[NAV_LIST_SIZE()];
TrackCallback got_load_start_[NAV_LIST_SIZE()];
TrackCallback got_correct_load_start_url_[NAV_LIST_SIZE()];
TrackCallback got_load_end_[NAV_LIST_SIZE()];
TrackCallback got_correct_load_end_url_[NAV_LIST_SIZE()];
TrackCallback got_correct_can_go_back2_[NAV_LIST_SIZE()];
TrackCallback got_correct_can_go_forward2_[NAV_LIST_SIZE()];
};
} // namespace
// Verify history navigation.
TEST(NavigationTest, History) {
CefRefPtr<HistoryNavTestHandler> handler =
new HistoryNavTestHandler();
handler->ExecuteTest();
for (size_t i = 0; i < NAV_LIST_SIZE(); ++i) {
if (kNavList[i].action != NA_CLEAR) {
ASSERT_TRUE(handler->got_before_resource_load_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_correct_target_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_load_start_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_correct_load_start_url_[i]) << "i = " << i;
}
ASSERT_TRUE(handler->got_loading_state_change_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_correct_can_go_back_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_correct_can_go_forward_[i]) << "i = " << i;
if (kNavList[i].action != NA_CLEAR) {
ASSERT_TRUE(handler->got_load_end_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_correct_load_end_url_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_correct_can_go_back2_[i]) << "i = " << i;
ASSERT_TRUE(handler->got_correct_can_go_forward2_[i]) << "i = " << i;
}
}
}
namespace {
class FrameNameIdentNavTestHandler : public TestHandler {
public:
FrameNameIdentNavTestHandler() : browse_ct_(0) {}
virtual void RunTest() OVERRIDE {
// Add the frame resources.
std::stringstream ss;
// Page with named frame
ss << "<html>Nav1<iframe src=\"" << kNav2 << "\" name=\"nav2\"></html>";
AddResource(kNav1, ss.str(), "text/html");
ss.str("");
// Page with unnamed frame
ss << "<html>Nav2<iframe src=\"" << kNav3 << "\"></html>";
AddResource(kNav2, ss.str(), "text/html");
ss.str("");
AddResource(kNav3, "<html>Nav3</html>", "text/html");
// Create the browser.
CreateBrowser(kNav1);
}
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
std::string name = frame->GetName();
CefRefPtr<CefFrame> parent = frame->GetParent();
std::string url = request->GetURL();
if (url == kNav1) {
frame1_ident_ = frame->GetIdentifier();
if (name == "") {
frame1_name_ = name;
got_frame1_name_.yes();
}
if (!parent.get())
got_frame1_ident_parent_before_.yes();
} else if (url == kNav2) {
frame2_ident_ = frame->GetIdentifier();
if (name == "nav2") {
frame2_name_ = name;
got_frame2_name_.yes();
}
if (parent.get() && frame1_ident_ == parent->GetIdentifier())
got_frame2_ident_parent_before_.yes();
} else if (url == kNav3) {
frame3_ident_ = frame->GetIdentifier();
if (name == "<!--framePath //nav2/<!--frame0-->-->") {
frame3_name_ = name;
got_frame3_name_.yes();
}
if (parent.get() && frame2_ident_ == parent->GetIdentifier())
got_frame3_ident_parent_before_.yes();
}
return false;
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
std::string url = frame->GetURL();
CefRefPtr<CefFrame> parent = frame->GetParent();
if (url == kNav1) {
if (frame1_ident_ == frame->GetIdentifier())
got_frame1_ident_.yes();
if (!parent.get())
got_frame1_ident_parent_after_.yes();
} else if (url == kNav2) {
if (frame2_ident_ == frame->GetIdentifier())
got_frame2_ident_.yes();
if (parent.get() && frame1_ident_ == parent->GetIdentifier())
got_frame2_ident_parent_after_.yes();
} else if (url == kNav3) {
if (frame3_ident_ == frame->GetIdentifier())
got_frame3_ident_.yes();
if (parent.get() && frame2_ident_ == parent->GetIdentifier())
got_frame3_ident_parent_after_.yes();
}
if (++browse_ct_ == 3) {
// Test GetFrameNames
std::vector<CefString> names;
browser->GetFrameNames(names);
EXPECT_EQ((size_t)3, names.size());
EXPECT_STREQ(frame1_name_.c_str(), names[0].ToString().c_str());
EXPECT_STREQ(frame2_name_.c_str(), names[1].ToString().c_str());
EXPECT_STREQ(frame3_name_.c_str(), names[2].ToString().c_str());
// Test GetFrameIdentifiers
std::vector<int64> idents;
browser->GetFrameIdentifiers(idents);
EXPECT_EQ((size_t)3, idents.size());
EXPECT_EQ(frame1_ident_, idents[0]);
EXPECT_EQ(frame2_ident_, idents[1]);
EXPECT_EQ(frame3_ident_, idents[2]);
DestroyTest();
}
}
int browse_ct_;
int64 frame1_ident_;
std::string frame1_name_;
int64 frame2_ident_;
std::string frame2_name_;
int64 frame3_ident_;
std::string frame3_name_;
TrackCallback got_frame1_name_;
TrackCallback got_frame2_name_;
TrackCallback got_frame3_name_;
TrackCallback got_frame1_ident_;
TrackCallback got_frame2_ident_;
TrackCallback got_frame3_ident_;
TrackCallback got_frame1_ident_parent_before_;
TrackCallback got_frame2_ident_parent_before_;
TrackCallback got_frame3_ident_parent_before_;
TrackCallback got_frame1_ident_parent_after_;
TrackCallback got_frame2_ident_parent_after_;
TrackCallback got_frame3_ident_parent_after_;
};
} // namespace
// Verify frame names and identifiers.
TEST(NavigationTest, FrameNameIdent) {
CefRefPtr<FrameNameIdentNavTestHandler> handler =
new FrameNameIdentNavTestHandler();
handler->ExecuteTest();
ASSERT_GT(handler->frame1_ident_, 0);
ASSERT_GT(handler->frame2_ident_, 0);
ASSERT_GT(handler->frame3_ident_, 0);
ASSERT_TRUE(handler->got_frame1_name_);
ASSERT_TRUE(handler->got_frame2_name_);
ASSERT_TRUE(handler->got_frame3_name_);
ASSERT_TRUE(handler->got_frame1_ident_);
ASSERT_TRUE(handler->got_frame2_ident_);
ASSERT_TRUE(handler->got_frame3_ident_);
ASSERT_TRUE(handler->got_frame1_ident_parent_before_);
ASSERT_TRUE(handler->got_frame2_ident_parent_before_);
ASSERT_TRUE(handler->got_frame3_ident_parent_before_);
ASSERT_TRUE(handler->got_frame1_ident_parent_after_);
ASSERT_TRUE(handler->got_frame2_ident_parent_after_);
ASSERT_TRUE(handler->got_frame3_ident_parent_after_);
}
namespace {
bool g_got_nav1_request = false;
bool g_got_nav3_request = false;
bool g_got_nav4_request = false;
bool g_got_invalid_request = false;
class RedirectSchemeHandler : public CefResourceHandler {
public:
RedirectSchemeHandler() : offset_(0), status_(0) {}
virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
CefRefPtr<CefCallback> callback) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
std::string url = request->GetURL();
if (url == kNav1) {
// Redirect using HTTP 302
g_got_nav1_request = true;
status_ = 302;
location_ = kNav2;
content_ = "<html><body>Redirected Nav1</body></html>";
} else if (url == kNav3) {
// Redirect using redirectUrl
g_got_nav3_request = true;
status_ = -1;
location_ = kNav4;
content_ = "<html><body>Redirected Nav3</body></html>";
} else if (url == kNav4) {
g_got_nav4_request = true;
status_ = 200;
content_ = "<html><body>Nav4</body></html>";
}
if (status_ != 0) {
callback->Continue();
return true;
} else {
g_got_invalid_request = true;
return false;
}
}
virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
int64& response_length,
CefString& redirectUrl) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
EXPECT_NE(status_, 0);
response->SetStatus(status_);
response->SetMimeType("text/html");
response_length = content_.size();
if (status_ == 302) {
// Redirect using HTTP 302
EXPECT_GT(location_.size(), static_cast<size_t>(0));
response->SetStatusText("Found");
CefResponse::HeaderMap headers;
response->GetHeaderMap(headers);
headers.insert(std::make_pair("Location", location_));
response->SetHeaderMap(headers);
} else if (status_ == -1) {
// Rdirect using redirectUrl
EXPECT_GT(location_.size(), static_cast<size_t>(0));
redirectUrl = location_;
}
}
virtual void Cancel() OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
}
virtual bool ReadResponse(void* data_out,
int bytes_to_read,
int& bytes_read,
CefRefPtr<CefCallback> callback) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
size_t size = content_.size();
if (offset_ < size) {
int transfer_size =
std::min(bytes_to_read, static_cast<int>(size - offset_));
memcpy(data_out, content_.c_str() + offset_, transfer_size);
offset_ += transfer_size;
bytes_read = transfer_size;
return true;
}
return false;
}
protected:
std::string content_;
size_t offset_;
int status_;
std::string location_;
IMPLEMENT_REFCOUNTING(RedirectSchemeHandler);
};
class RedirectSchemeHandlerFactory : public CefSchemeHandlerFactory {
public:
RedirectSchemeHandlerFactory() {}
virtual CefRefPtr<CefResourceHandler> Create(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& scheme_name,
CefRefPtr<CefRequest> request) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
return new RedirectSchemeHandler();
}
IMPLEMENT_REFCOUNTING(RedirectSchemeHandlerFactory);
};
class RedirectTestHandler : public TestHandler {
public:
RedirectTestHandler() {}
virtual void RunTest() OVERRIDE {
// Create the browser.
CreateBrowser(kNav1);
}
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
// Should be called for all but the second URL.
std::string url = request->GetURL();
if (url == kNav1) {
got_nav1_before_resource_load_.yes();
} else if (url == kNav3) {
got_nav3_before_resource_load_.yes();
} else if (url == kNav4) {
got_nav4_before_resource_load_.yes();
} else {
got_invalid_before_resource_load_.yes();
}
return false;
}
virtual void OnResourceRedirect(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& old_url,
CefString& new_url) OVERRIDE {
// Should be called for each redirected URL.
if (old_url == kNav1 && new_url == kNav2) {
// Called due to the nav1 redirect response.
got_nav1_redirect_.yes();
// Change the redirect to the 3rd URL.
new_url = kNav3;
} else if (old_url == kNav1 && new_url == kNav3) {
// Called due to the redirect change above.
got_nav2_redirect_.yes();
} else if (old_url == kNav3 && new_url == kNav4) {
// Called due to the nav3 redirect response.
got_nav3_redirect_.yes();
} else {
got_invalid_redirect_.yes();
}
}
virtual void OnLoadStart(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame) OVERRIDE {
// Should only be called for the final loaded URL.
std::string url = frame->GetURL();
if (url == kNav4) {
got_nav4_load_start_.yes();
} else {
got_invalid_load_start_.yes();
}
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
// Should only be called for the final loaded URL.
std::string url = frame->GetURL();
if (url == kNav4) {
got_nav4_load_end_.yes();
DestroyTest();
} else {
got_invalid_load_end_.yes();
}
}
TrackCallback got_nav1_before_resource_load_;
TrackCallback got_nav3_before_resource_load_;
TrackCallback got_nav4_before_resource_load_;
TrackCallback got_invalid_before_resource_load_;
TrackCallback got_nav4_load_start_;
TrackCallback got_invalid_load_start_;
TrackCallback got_nav4_load_end_;
TrackCallback got_invalid_load_end_;
TrackCallback got_nav1_redirect_;
TrackCallback got_nav2_redirect_;
TrackCallback got_nav3_redirect_;
TrackCallback got_invalid_redirect_;
};
} // namespace
// Verify frame names and identifiers.
TEST(NavigationTest, Redirect) {
CefRegisterSchemeHandlerFactory("http", "tests",
new RedirectSchemeHandlerFactory());
WaitForIOThread();
CefRefPtr<RedirectTestHandler> handler =
new RedirectTestHandler();
handler->ExecuteTest();
CefClearSchemeHandlerFactories();
WaitForIOThread();
ASSERT_TRUE(handler->got_nav1_before_resource_load_);
ASSERT_TRUE(handler->got_nav3_before_resource_load_);
ASSERT_TRUE(handler->got_nav4_before_resource_load_);
ASSERT_FALSE(handler->got_invalid_before_resource_load_);
ASSERT_TRUE(handler->got_nav4_load_start_);
ASSERT_FALSE(handler->got_invalid_load_start_);
ASSERT_TRUE(handler->got_nav4_load_end_);
ASSERT_FALSE(handler->got_invalid_load_end_);
ASSERT_TRUE(handler->got_nav1_redirect_);
ASSERT_TRUE(handler->got_nav2_redirect_);
ASSERT_TRUE(handler->got_nav3_redirect_);
ASSERT_FALSE(handler->got_invalid_redirect_);
ASSERT_TRUE(g_got_nav1_request);
ASSERT_TRUE(g_got_nav3_request);
ASSERT_TRUE(g_got_nav4_request);
ASSERT_FALSE(g_got_invalid_request);
}

View File

@@ -1,184 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_process_message.h"
#include "include/cef_task.h"
#include "tests/cefclient/client_app.h"
#include "tests/unittests/test_handler.h"
#include "tests/unittests/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Unique values for the SendRecv test.
const char* kSendRecvUrlNative =
"http://tests/ProcessMessageTest.SendRecv/Native";
const char* kSendRecvUrlJavaScript =
"http://tests/ProcessMessageTest.SendRecv/JavaScript";
const char* kSendRecvMsg = "ProcessMessageTest.SendRecv";
// Creates a test message.
CefRefPtr<CefProcessMessage> CreateTestMessage() {
CefRefPtr<CefProcessMessage> msg = CefProcessMessage::Create(kSendRecvMsg);
EXPECT_TRUE(msg.get());
CefRefPtr<CefListValue> args = msg->GetArgumentList();
EXPECT_TRUE(args.get());
int index = 0;
args->SetNull(index++);
args->SetInt(index++, 5);
args->SetDouble(index++, 10.543);
args->SetBool(index++, true);
args->SetString(index++, "test string");
args->SetList(index++, args->Copy());
EXPECT_EQ((size_t)index, args->GetSize());
return msg;
}
// Renderer side.
class SendRecvRendererTest : public ClientApp::RenderDelegate {
public:
SendRecvRendererTest() {}
virtual bool OnProcessMessageReceived(
CefRefPtr<ClientApp> app,
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE {
if (message->GetName() == kSendRecvMsg) {
EXPECT_TRUE(browser.get());
EXPECT_EQ(PID_BROWSER, source_process);
EXPECT_TRUE(message.get());
std::string url = browser->GetMainFrame()->GetURL();
if (url == kSendRecvUrlNative) {
// Echo the message back to the sender natively.
EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, message));
return true;
}
}
// Message not handled.
return false;
}
IMPLEMENT_REFCOUNTING(SendRecvRendererTest);
};
// Browser side.
class SendRecvTestHandler : public TestHandler {
public:
explicit SendRecvTestHandler(bool native)
: native_(native) {
}
virtual void RunTest() OVERRIDE {
message_ = CreateTestMessage();
if (native_) {
// Native test.
AddResource(kSendRecvUrlNative, "<html><body>TEST NATIVE</body></html>",
"text/html");
CreateBrowser(kSendRecvUrlNative);
} else {
// JavaScript test.
std::string content =
"<html><head>\n"
"<script>\n"
"function cb(name, args) {\n"
" app.sendMessage(name, args);\n"
"}\n"
"app.setMessageCallback('"+std::string(kSendRecvMsg)+"', cb);\n"
"</script>\n"
"<body>TEST JAVASCRIPT</body>\n"
"</head></html>";
AddResource(kSendRecvUrlJavaScript, content, "text/html");
CreateBrowser(kSendRecvUrlJavaScript);
}
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
// Send the message to the renderer process.
EXPECT_TRUE(browser->SendProcessMessage(PID_RENDERER, message_));
}
virtual bool OnProcessMessageReceived(
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE {
EXPECT_TRUE(browser.get());
EXPECT_EQ(PID_RENDERER, source_process);
EXPECT_TRUE(message.get());
EXPECT_TRUE(message->IsReadOnly());
// Verify that the recieved message is the same as the sent message.
TestProcessMessageEqual(message_, message);
got_message_.yes();
// Test is complete.
DestroyTest();
return true;
}
bool native_;
CefRefPtr<CefProcessMessage> message_;
TrackCallback got_message_;
};
} // namespace
// Verify native send and recieve
TEST(ProcessMessageTest, SendRecvNative) {
CefRefPtr<SendRecvTestHandler> handler = new SendRecvTestHandler(true);
handler->ExecuteTest();
EXPECT_TRUE(handler->got_message_);
}
// Verify JavaScript send and recieve
TEST(ProcessMessageTest, SendRecvJavaScript) {
CefRefPtr<SendRecvTestHandler> handler = new SendRecvTestHandler(false);
handler->ExecuteTest();
EXPECT_TRUE(handler->got_message_);
}
// Verify create
TEST(ProcessMessageTest, Create) {
CefRefPtr<CefProcessMessage> message =
CefProcessMessage::Create(kSendRecvMsg);
EXPECT_TRUE(message.get());
EXPECT_TRUE(message->IsValid());
EXPECT_FALSE(message->IsReadOnly());
EXPECT_STREQ(kSendRecvMsg, message->GetName().ToString().c_str());
CefRefPtr<CefListValue> args = message->GetArgumentList();
EXPECT_TRUE(args.get());
EXPECT_TRUE(args->IsValid());
EXPECT_TRUE(args->IsOwned());
EXPECT_FALSE(args->IsReadOnly());
}
// Verify copy
TEST(ProcessMessageTest, Copy) {
CefRefPtr<CefProcessMessage> message = CreateTestMessage();
CefRefPtr<CefProcessMessage> message2 = message->Copy();
TestProcessMessageEqual(message, message2);
}
// Entry point for creating process message renderer test objects.
// Called from client_app_delegates.cc.
void CreateProcessMessageRendererTests(
ClientApp::RenderDelegateSet& delegates) {
// For ProcessMessageTest.SendRecv
delegates.insert(new SendRecvRendererTest);
}

View File

@@ -1,192 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_request.h"
#include "tests/unittests/test_handler.h"
#include "tests/unittests/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
// Verify Set/Get methods for CefRequest, CefPostData and CefPostDataElement.
TEST(RequestTest, SetGet) {
// CefRequest CreateRequest
CefRefPtr<CefRequest> request(CefRequest::Create());
ASSERT_TRUE(request.get() != NULL);
CefString url = "http://tests/run.html";
CefString method = "POST";
CefRequest::HeaderMap setHeaders, getHeaders;
setHeaders.insert(std::make_pair("HeaderA", "ValueA"));
setHeaders.insert(std::make_pair("HeaderB", "ValueB"));
// CefPostData CreatePostData
CefRefPtr<CefPostData> postData(CefPostData::Create());
ASSERT_TRUE(postData.get() != NULL);
// CefPostDataElement CreatePostDataElement
CefRefPtr<CefPostDataElement> element1(CefPostDataElement::Create());
ASSERT_TRUE(element1.get() != NULL);
CefRefPtr<CefPostDataElement> element2(CefPostDataElement::Create());
ASSERT_TRUE(element2.get() != NULL);
// CefPostDataElement SetToFile
CefString file = "c:\\path\\to\\file.ext";
element1->SetToFile(file);
ASSERT_EQ(PDE_TYPE_FILE, element1->GetType());
ASSERT_EQ(file, element1->GetFile());
// CefPostDataElement SetToBytes
char bytes[] = "Test Bytes";
element2->SetToBytes(sizeof(bytes), bytes);
ASSERT_EQ(PDE_TYPE_BYTES, element2->GetType());
ASSERT_EQ(sizeof(bytes), element2->GetBytesCount());
char bytesOut[sizeof(bytes)];
element2->GetBytes(sizeof(bytes), bytesOut);
ASSERT_TRUE(!memcmp(bytes, bytesOut, sizeof(bytes)));
// CefPostData AddElement
postData->AddElement(element1);
postData->AddElement(element2);
ASSERT_EQ((size_t)2, postData->GetElementCount());
// CefPostData RemoveElement
postData->RemoveElement(element1);
ASSERT_EQ((size_t)1, postData->GetElementCount());
// CefPostData RemoveElements
postData->RemoveElements();
ASSERT_EQ((size_t)0, postData->GetElementCount());
postData->AddElement(element1);
postData->AddElement(element2);
ASSERT_EQ((size_t)2, postData->GetElementCount());
CefPostData::ElementVector elements;
postData->GetElements(elements);
CefPostData::ElementVector::const_iterator it = elements.begin();
for (size_t i = 0; it != elements.end(); ++it, ++i) {
if (i == 0)
TestPostDataElementEqual(element1, (*it).get());
else if (i == 1)
TestPostDataElementEqual(element2, (*it).get());
}
// CefRequest SetURL
request->SetURL(url);
ASSERT_EQ(url, request->GetURL());
// CefRequest SetMethod
request->SetMethod(method);
ASSERT_EQ(method, request->GetMethod());
// CefRequest SetHeaderMap
request->SetHeaderMap(setHeaders);
request->GetHeaderMap(getHeaders);
TestMapEqual(setHeaders, getHeaders, false);
getHeaders.clear();
// CefRequest SetPostData
request->SetPostData(postData);
TestPostDataEqual(postData, request->GetPostData());
request = CefRequest::Create();
ASSERT_TRUE(request.get() != NULL);
// CefRequest Set
request->Set(url, method, postData, setHeaders);
ASSERT_EQ(url, request->GetURL());
ASSERT_EQ(method, request->GetMethod());
request->GetHeaderMap(getHeaders);
TestMapEqual(setHeaders, getHeaders, false);
getHeaders.clear();
TestPostDataEqual(postData, request->GetPostData());
}
namespace {
void CreateRequest(CefRefPtr<CefRequest>& request) {
request = CefRequest::Create();
ASSERT_TRUE(request.get() != NULL);
request->SetURL("http://tests/run.html");
request->SetMethod("POST");
CefRequest::HeaderMap headers;
headers.insert(std::make_pair("HeaderA", "ValueA"));
headers.insert(std::make_pair("HeaderB", "ValueB"));
request->SetHeaderMap(headers);
CefRefPtr<CefPostData> postData(CefPostData::Create());
ASSERT_TRUE(postData.get() != NULL);
CefRefPtr<CefPostDataElement> element1(
CefPostDataElement::Create());
ASSERT_TRUE(element1.get() != NULL);
char bytes[] = "Test Bytes";
element1->SetToBytes(sizeof(bytes), bytes);
postData->AddElement(element1);
request->SetPostData(postData);
}
class RequestSendRecvTestHandler : public TestHandler {
public:
RequestSendRecvTestHandler() {}
virtual void RunTest() OVERRIDE {
// Create the test request
CreateRequest(request_);
// Create the browser
CreateBrowser("about:blank");
}
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE {
TestHandler::OnAfterCreated(browser);
// Load the test request
browser->GetMainFrame()->LoadRequest(request_);
}
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
// Verify that the request is the same
TestRequestEqual(request_, request, true);
got_before_resource_load_.yes();
return false;
}
virtual CefRefPtr<CefResourceHandler> GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
// Verify that the request is the same
TestRequestEqual(request_, request, true);
got_resource_handler_.yes();
DestroyTest();
// No results
return NULL;
}
CefRefPtr<CefRequest> request_;
TrackCallback got_before_resource_load_;
TrackCallback got_resource_handler_;
};
} // namespace
// Verify send and recieve
TEST(RequestTest, SendRecv) {
CefRefPtr<RequestSendRecvTestHandler> handler =
new RequestSendRecvTestHandler();
handler->ExecuteTest();
ASSERT_TRUE(handler->got_before_resource_load_);
ASSERT_TRUE(handler->got_resource_handler_);
}

View File

@@ -1,119 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_app.h"
#include "include/cef_task.h"
#include "tests/cefclient/client_app.h"
#include "tests/unittests/test_suite.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/threading/thread.h"
// Include after base/bind.h to avoid name collisions with cef_tuple.h.
#include "include/cef_runnable.h"
namespace {
// Thread used to run the test suite.
class CefTestThread : public base::Thread {
public:
explicit CefTestThread(CefTestSuite* test_suite)
: base::Thread("test_thread"),
test_suite_(test_suite) {
}
void RunTests() {
// Run the test suite.
retval_ = test_suite_->Run();
// Quit the CEF message loop.
CefPostTask(TID_UI, NewCefRunnableFunction(CefQuitMessageLoop));
}
int retval() { return retval_; }
protected:
CefTestSuite* test_suite_;
int retval_;
};
// Called on the UI thread.
void RunTests(CefTestThread* thread) {
// Run the test suite on the test thread.
thread->message_loop()->PostTask(FROM_HERE,
base::Bind(&CefTestThread::RunTests, base::Unretained(thread)));
}
} // namespace
int main(int argc, char* argv[]) {
#if defined(OS_WIN)
CefMainArgs main_args(::GetModuleHandle(NULL));
#else
CefMainArgs main_args(argc, argv);
#endif
CefRefPtr<CefApp> app(new ClientApp);
// Execute the secondary process, if any.
int exit_code = CefExecuteProcess(main_args, app);
if (exit_code >= 0)
return exit_code;
// Initialize the CommandLine object.
CefTestSuite::InitCommandLine(argc, argv);
CefSettings settings;
CefTestSuite::GetSettings(settings);
#if defined(OS_MACOSX)
// Platform-specific initialization.
extern void PlatformInit();
PlatformInit();
#endif
// Initialize CEF.
CefInitialize(main_args, settings, app);
// Create the test suite object.
CefTestSuite test_suite(argc, argv);
int retval;
if (settings.multi_threaded_message_loop) {
// Run the test suite on the main thread.
retval = test_suite.Run();
} else {
// Create the test thread.
scoped_ptr<CefTestThread> thread;
thread.reset(new CefTestThread(&test_suite));
if (!thread->Start())
return 1;
// Start the tests from the UI thread so that any pending UI tasks get a
// chance to execute first.
CefPostTask(TID_UI, NewCefRunnableFunction(RunTests, thread.get()));
// Run the CEF message loop.
CefRunMessageLoop();
// The test suite has completed.
retval = thread->retval();
// Terminate the test thread.
thread.reset();
}
// Shut down CEF.
CefShutdown();
#if defined(OS_MACOSX)
// Platform-specific cleanup.
extern void PlatformCleanup();
PlatformCleanup();
#endif
return retval;
}

View File

@@ -1,45 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_app.h"
#import "include/cef_application_mac.h"
// Memory AutoRelease pool.
static NSAutoreleasePool* g_autopool = nil;
// Provide the CefAppProtocol implementation required by CEF.
@interface TestApplication : NSApplication<CefAppProtocol> {
@private
BOOL handlingSendEvent_;
}
@end
@implementation TestApplication
- (BOOL)isHandlingSendEvent {
return handlingSendEvent_;
}
- (void)setHandlingSendEvent:(BOOL)handlingSendEvent {
handlingSendEvent_ = handlingSendEvent;
}
- (void)sendEvent:(NSEvent*)event {
CefScopedSendingEvent sendingEventScoper;
[super sendEvent:event];
}
@end
void PlatformInit() {
// Initialize the AutoRelease pool.
g_autopool = [[NSAutoreleasePool alloc] init];
// Initialize the TestApplication instance.
[TestApplication sharedApplication];
}
void PlatformCleanup() {
// Release the AutoRelease pool.
[g_autopool release];
}

View File

@@ -1,960 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_origin_whitelist.h"
#include "include/cef_callback.h"
#include "include/cef_runnable.h"
#include "include/cef_scheme.h"
#include "tests/unittests/test_handler.h"
namespace {
class TestResults {
public:
TestResults()
: status_code(0),
sub_status_code(0),
delay(0) {
}
void reset() {
url.clear();
html.clear();
status_code = 0;
redirect_url.clear();
sub_url.clear();
sub_html.clear();
sub_status_code = 0;
sub_allow_origin.clear();
exit_url.clear();
delay = 0;
got_request.reset();
got_read.reset();
got_output.reset();
got_redirect.reset();
got_error.reset();
got_sub_request.reset();
got_sub_read.reset();
got_sub_success.reset();
}
std::string url;
std::string html;
int status_code;
// Used for testing redirects
std::string redirect_url;
// Used for testing XHR requests
std::string sub_url;
std::string sub_html;
int sub_status_code;
std::string sub_allow_origin;
std::string exit_url;
// Delay for returning scheme handler results.
int delay;
TrackCallback
got_request,
got_read,
got_output,
got_redirect,
got_error,
got_sub_request,
got_sub_read,
got_sub_success;
};
// Current scheme handler object. Used when destroying the test from
// ClientSchemeHandler::ProcessRequest().
class TestSchemeHandler;
TestSchemeHandler* g_current_handler = NULL;
class TestSchemeHandler : public TestHandler {
public:
explicit TestSchemeHandler(TestResults* tr)
: test_results_(tr) {
g_current_handler = this;
}
virtual void RunTest() OVERRIDE {
CreateBrowser(test_results_->url);
}
// Necessary to make the method public in order to destroy the test from
// ClientSchemeHandler::ProcessRequest().
void DestroyTest() {
TestHandler::DestroyTest();
}
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE {
std::string newUrl = request->GetURL();
if (!test_results_->exit_url.empty() &&
newUrl.find(test_results_->exit_url) != std::string::npos) {
// XHR tests use an exit URL to destroy the test.
if (newUrl.find("SUCCESS") != std::string::npos)
test_results_->got_sub_success.yes();
DestroyTest();
return true;
}
if (newUrl == test_results_->redirect_url) {
test_results_->got_redirect.yes();
// No read should have occurred for the redirect.
EXPECT_TRUE(test_results_->got_request);
EXPECT_FALSE(test_results_->got_read);
// Now loading the redirect URL.
test_results_->url = test_results_->redirect_url;
test_results_->redirect_url.clear();
}
return false;
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
std::string url = frame->GetURL();
if (url == test_results_->url || test_results_->status_code != 200) {
test_results_->got_output.yes();
// Test that the status code is correct.
// TODO(cef): Enable this check once the HTTP status code is passed
// correctly.
// EXPECT_EQ(httpStatusCode, test_results_->status_code);
if (test_results_->sub_url.empty())
DestroyTest();
}
}
virtual void OnLoadError(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
ErrorCode errorCode,
const CefString& errorText,
const CefString& failedUrl) OVERRIDE {
test_results_->got_error.yes();
DestroyTest();
}
protected:
TestResults* test_results_;
};
class ClientSchemeHandler : public CefResourceHandler {
public:
explicit ClientSchemeHandler(TestResults* tr)
: test_results_(tr),
offset_(0),
is_sub_(false),
has_delayed_(false) {
}
virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
CefRefPtr<CefCallback> callback) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
bool handled = false;
std::string url = request->GetURL();
is_sub_ = (!test_results_->sub_url.empty() &&
test_results_->sub_url == url);
if (is_sub_) {
test_results_->got_sub_request.yes();
if (!test_results_->sub_html.empty())
handled = true;
} else {
EXPECT_EQ(url, test_results_->url);
test_results_->got_request.yes();
if (!test_results_->html.empty())
handled = true;
}
if (handled) {
if (test_results_->delay > 0) {
// Continue after the delay.
CefPostDelayedTask(TID_IO,
NewCefRunnableMethod(callback.get(), &CefCallback::Continue),
test_results_->delay);
} else {
// Continue immediately.
callback->Continue();
}
return true;
}
// Response was canceled.
if (g_current_handler)
g_current_handler->DestroyTest();
return false;
}
virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
int64& response_length,
CefString& redirectUrl) OVERRIDE {
if (is_sub_) {
response->SetStatus(test_results_->sub_status_code);
if (!test_results_->sub_allow_origin.empty()) {
// Set the Access-Control-Allow-Origin header to allow cross-domain
// scripting.
CefResponse::HeaderMap headers;
headers.insert(std::make_pair("Access-Control-Allow-Origin",
test_results_->sub_allow_origin));
response->SetHeaderMap(headers);
}
if (!test_results_->sub_html.empty()) {
response->SetMimeType("text/html");
response_length = test_results_->sub_html.size();
}
} else if (!test_results_->redirect_url.empty()) {
redirectUrl = test_results_->redirect_url;
} else {
response->SetStatus(test_results_->status_code);
if (!test_results_->html.empty()) {
response->SetMimeType("text/html");
response_length = test_results_->html.size();
}
}
}
virtual void Cancel() OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
}
virtual bool ReadResponse(void* data_out,
int bytes_to_read,
int& bytes_read,
CefRefPtr<CefCallback> callback) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
if (test_results_->delay > 0) {
if (!has_delayed_) {
// Continue after a delay.
CefPostDelayedTask(TID_IO,
NewCefRunnableMethod(this,
&ClientSchemeHandler::ContinueAfterDelay, callback),
test_results_->delay);
bytes_read = 0;
return true;
}
has_delayed_ = false;
}
std::string* data;
if (is_sub_) {
test_results_->got_sub_read.yes();
data = &test_results_->sub_html;
} else {
test_results_->got_read.yes();
data = &test_results_->html;
}
bool has_data = false;
bytes_read = 0;
AutoLock lock_scope(this);
size_t size = data->size();
if (offset_ < size) {
int transfer_size =
std::min(bytes_to_read, static_cast<int>(size - offset_));
memcpy(data_out, data->c_str() + offset_, transfer_size);
offset_ += transfer_size;
bytes_read = transfer_size;
has_data = true;
}
return has_data;
}
private:
void ContinueAfterDelay(CefRefPtr<CefCallback> callback) {
has_delayed_ = true;
callback->Continue();
}
TestResults* test_results_;
size_t offset_;
bool is_sub_;
bool has_delayed_;
IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
IMPLEMENT_LOCKING(ClientSchemeHandler);
};
class ClientSchemeHandlerFactory : public CefSchemeHandlerFactory {
public:
explicit ClientSchemeHandlerFactory(TestResults* tr)
: test_results_(tr) {
}
virtual CefRefPtr<CefResourceHandler> Create(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& scheme_name,
CefRefPtr<CefRequest> request)
OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_IO));
return new ClientSchemeHandler(test_results_);
}
TestResults* test_results_;
IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
};
// Global test results object.
TestResults g_TestResults;
// If |domain| is empty the scheme will be registered as non-standard.
void RegisterTestScheme(const std::string& scheme, const std::string& domain) {
g_TestResults.reset();
EXPECT_TRUE(CefRegisterSchemeHandlerFactory(scheme, domain,
new ClientSchemeHandlerFactory(&g_TestResults)));
WaitForIOThread();
}
void ClearTestSchemes() {
EXPECT_TRUE(CefClearSchemeHandlerFactories());
WaitForIOThread();
}
void SetUpXHR(const std::string& url, const std::string& sub_url,
const std::string& sub_allow_origin = std::string()) {
g_TestResults.sub_url = sub_url;
g_TestResults.sub_html = "SUCCESS";
g_TestResults.sub_status_code = 200;
g_TestResults.sub_allow_origin = sub_allow_origin;
g_TestResults.url = url;
std::stringstream ss;
ss << "<html><head>"
"<script language=\"JavaScript\">"
"function execXMLHttpRequest() {"
" var result = 'FAILURE';"
" try {"
" xhr = new XMLHttpRequest();"
" xhr.open(\"GET\", \"" << sub_url.c_str() << "\", false);"
" xhr.send();"
" result = xhr.responseText;"
" } catch(e) {}"
" document.location = \"http://tests/exit?result=\"+result;"
"}"
"</script>"
"</head><body onload=\"execXMLHttpRequest();\">"
"Running execXMLHttpRequest..."
"</body></html>";
g_TestResults.html = ss.str();
g_TestResults.status_code = 200;
g_TestResults.exit_url = "http://tests/exit";
}
void SetUpXSS(const std::string& url, const std::string& sub_url,
const std::string& domain = std::string()) {
// 1. Load |url| which contains an iframe.
// 2. The iframe loads |xss_url|.
// 3. |xss_url| tries to call a JS function in |url|.
// 4. |url| tries to call a JS function in |xss_url|.
std::stringstream ss;
std::string domain_line;
if (!domain.empty())
domain_line = "document.domain = '" + domain + "';";
g_TestResults.sub_url = sub_url;
ss << "<html><head>"
"<script language=\"JavaScript\">" << domain_line <<
"function getResult() {"
" return 'SUCCESS';"
"}"
"function execXSSRequest() {"
" var result = 'FAILURE';"
" try {"
" result = parent.getResult();"
" } catch(e) {}"
" document.location = \"http://tests/exit?result=\"+result;"
"}"
"</script>"
"</head><body onload=\"execXSSRequest();\">"
"Running execXSSRequest..."
"</body></html>";
g_TestResults.sub_html = ss.str();
g_TestResults.sub_status_code = 200;
g_TestResults.url = url;
ss.str("");
ss << "<html><head>"
"<script language=\"JavaScript\">" << domain_line << ""
"function getResult() {"
" try {"
" return document.getElementById('s').contentWindow.getResult();"
" } catch(e) {}"
" return 'FAILURE';"
"}"
"</script>"
"</head><body>"
"<iframe src=\"" << sub_url.c_str() << "\" id=\"s\">"
"</body></html>";
g_TestResults.html = ss.str();
g_TestResults.status_code = 200;
g_TestResults.exit_url = "http://tests/exit";
}
} // namespace
// Test that scheme registration/unregistration works as expected.
TEST(SchemeHandlerTest, Registration) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd://test/run.html";
g_TestResults.html =
"<html><head></head><body><h1>Success!</h1></body></html>";
g_TestResults.status_code = 200;
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
// Unregister the handler.
EXPECT_TRUE(CefRegisterSchemeHandlerFactory("customstd", "test", NULL));
WaitForIOThread();
g_TestResults.got_request.reset();
g_TestResults.got_read.reset();
g_TestResults.got_output.reset();
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_error);
EXPECT_FALSE(g_TestResults.got_request);
EXPECT_FALSE(g_TestResults.got_read);
EXPECT_FALSE(g_TestResults.got_output);
// Re-register the handler.
EXPECT_TRUE(CefRegisterSchemeHandlerFactory("customstd", "test",
new ClientSchemeHandlerFactory(&g_TestResults)));
WaitForIOThread();
g_TestResults.got_error.reset();
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom standard scheme can return normal results.
TEST(SchemeHandlerTest, CustomStandardNormalResponse) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd://test/run.html";
g_TestResults.html =
"<html><head></head><body><h1>Success!</h1></body></html>";
g_TestResults.status_code = 200;
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom standard scheme can return normal results with delayed
// responses.
TEST(SchemeHandlerTest, CustomStandardNormalResponseDelayed) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd://test/run.html";
g_TestResults.html =
"<html><head></head><body><h1>Success!</h1></body></html>";
g_TestResults.status_code = 200;
g_TestResults.delay = 100;
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom nonstandard scheme can return normal results.
TEST(SchemeHandlerTest, CustomNonStandardNormalResponse) {
RegisterTestScheme("customnonstd", std::string());
g_TestResults.url = "customnonstd:some%20value";
g_TestResults.html =
"<html><head></head><body><h1>Success!</h1></body></html>";
g_TestResults.status_code = 200;
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom standard scheme can return an error code.
TEST(SchemeHandlerTest, CustomStandardErrorResponse) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd://test/run.html";
g_TestResults.html =
"<html><head></head><body><h1>404</h1></body></html>";
g_TestResults.status_code = 404;
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom nonstandard scheme can return an error code.
TEST(SchemeHandlerTest, CustomNonStandardErrorResponse) {
RegisterTestScheme("customnonstd", std::string());
g_TestResults.url = "customnonstd:some%20value";
g_TestResults.html =
"<html><head></head><body><h1>404</h1></body></html>";
g_TestResults.status_code = 404;
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that custom standard scheme handling fails when the scheme name is
// incorrect.
TEST(SchemeHandlerTest, CustomStandardNameNotHandled) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd2://test/run.html";
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_FALSE(g_TestResults.got_request);
EXPECT_FALSE(g_TestResults.got_read);
EXPECT_FALSE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that custom nonstandard scheme handling fails when the scheme name is
// incorrect.
TEST(SchemeHandlerTest, CustomNonStandardNameNotHandled) {
RegisterTestScheme("customnonstd", std::string());
g_TestResults.url = "customnonstd2:some%20value";
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_FALSE(g_TestResults.got_request);
EXPECT_FALSE(g_TestResults.got_read);
EXPECT_FALSE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that custom standard scheme handling fails when the domain name is
// incorrect.
TEST(SchemeHandlerTest, CustomStandardDomainNotHandled) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd://noexist/run.html";
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_FALSE(g_TestResults.got_request);
EXPECT_FALSE(g_TestResults.got_read);
EXPECT_FALSE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom standard scheme can return no response.
TEST(SchemeHandlerTest, CustomStandardNoResponse) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd://test/run.html";
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_FALSE(g_TestResults.got_read);
EXPECT_FALSE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom nonstandard scheme can return no response.
TEST(SchemeHandlerTest, CustomNonStandardNoResponse) {
RegisterTestScheme("customnonstd", std::string());
g_TestResults.url = "customnonstd:some%20value";
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_FALSE(g_TestResults.got_read);
EXPECT_FALSE(g_TestResults.got_output);
ClearTestSchemes();
}
// Test that a custom standard scheme can generate redirects.
TEST(SchemeHandlerTest, CustomStandardRedirect) {
RegisterTestScheme("customstd", "test");
g_TestResults.url = "customstd://test/run.html";
g_TestResults.redirect_url = "customstd://test/redirect.html";
g_TestResults.html =
"<html><head></head><body><h1>Redirected</h1></body></html>";
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_redirect);
ClearTestSchemes();
}
// Test that a custom nonstandard scheme can generate redirects.
TEST(SchemeHandlerTest, CustomNonStandardRedirect) {
RegisterTestScheme("customnonstd", std::string());
g_TestResults.url = "customnonstd:some%20value";
g_TestResults.redirect_url = "customnonstd:some%20other%20value";
g_TestResults.html =
"<html><head></head><body><h1>Redirected</h1></body></html>";
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_redirect);
ClearTestSchemes();
}
// Test that a custom standard scheme can generate same origin XHR requests.
TEST(SchemeHandlerTest, CustomStandardXHRSameOrigin) {
RegisterTestScheme("customstd", "test");
SetUpXHR("customstd://test/run.html",
"customstd://test/xhr.html");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom nonstandard scheme can generate same origin XHR requests.
TEST(SchemeHandlerTest, CustomNonStandardXHRSameOrigin) {
RegisterTestScheme("customnonstd", std::string());
SetUpXHR("customnonstd:some%20value",
"customnonstd:xhr%20value");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom standard scheme can generate same origin XSS requests.
TEST(SchemeHandlerTest, CustomStandardXSSSameOrigin) {
RegisterTestScheme("customstd", "test");
SetUpXSS("customstd://test/run.html",
"customstd://test/iframe.html");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom nonstandard scheme can generate same origin XSS requests.
TEST(SchemeHandlerTest, CustomNonStandardXSSSameOrigin) {
RegisterTestScheme("customnonstd", std::string());
SetUpXSS("customnonstd:some%20value",
"customnonstd:xhr%20value");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom standard scheme cannot generate cross-domain XHR requests
// by default.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOrigin) {
RegisterTestScheme("customstd", "test1");
RegisterTestScheme("customstd", "test2");
SetUpXHR("customstd://test1/run.html",
"customstd://test2/xhr.html");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_FALSE(g_TestResults.got_sub_request);
EXPECT_FALSE(g_TestResults.got_sub_read);
EXPECT_FALSE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom standard scheme cannot generate cross-domain XSS requests
// by default.
TEST(SchemeHandlerTest, CustomStandardXSSDifferentOrigin) {
RegisterTestScheme("customstd", "test1");
RegisterTestScheme("customstd", "test2");
SetUpXSS("customstd://test1/run.html",
"customstd://test2/iframe.html");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_FALSE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that an HTTP scheme cannot generate cross-domain XHR requests by
// default.
TEST(SchemeHandlerTest, HttpXHRDifferentOrigin) {
RegisterTestScheme("http", "test1");
RegisterTestScheme("http", "test2");
SetUpXHR("http://test1/run.html",
"http://test2/xhr.html");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_FALSE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that an HTTP scheme cannot generate cross-domain XSS requests by
// default.
TEST(SchemeHandlerTest, HttpXSSDifferentOrigin) {
RegisterTestScheme("http", "test1");
RegisterTestScheme("http", "test2");
SetUpXHR("http://test1/run.html",
"http://test2/xhr.html");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_FALSE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom standard scheme cannot generate cross-domain XHR requests
// even when setting the Access-Control-Allow-Origin header.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithHeader) {
RegisterTestScheme("customstd", "test1");
RegisterTestScheme("customstd", "test2");
SetUpXHR("customstd://test1/run.html",
"customstd://test2/xhr.html",
"customstd://test1");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_FALSE(g_TestResults.got_sub_request);
EXPECT_FALSE(g_TestResults.got_sub_read);
EXPECT_FALSE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom standard scheme can generate cross-domain XHR requests
// when using the cross-origin whitelist.
TEST(SchemeHandlerTest, CustomStandardXHRDifferentOriginWithWhitelist) {
RegisterTestScheme("customstd", "test1");
RegisterTestScheme("customstd", "test2");
SetUpXHR("customstd://test1/run.html",
"customstd://test2/xhr.html");
EXPECT_TRUE(CefAddCrossOriginWhitelistEntry("customstd://test1", "customstd",
"test2", false));
WaitForUIThread();
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
EXPECT_TRUE(CefClearCrossOriginWhitelist());
WaitForUIThread();
ClearTestSchemes();
}
// Test that an HTTP scheme can generate cross-domain XHR requests when setting
// the Access-Control-Allow-Origin header.
TEST(SchemeHandlerTest, HttpXHRDifferentOriginWithHeader) {
RegisterTestScheme("http", "test1");
RegisterTestScheme("http", "test2");
SetUpXHR("http://test1/run.html",
"http://test2/xhr.html",
"http://test1");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that a custom standard scheme can generate cross-domain XSS requests
// when using document.domain.
TEST(SchemeHandlerTest, CustomStandardXSSDifferentOriginWithDomain) {
RegisterTestScheme("customstd", "a.test");
RegisterTestScheme("customstd", "b.test");
SetUpXSS("customstd://a.test/run.html",
"customstd://b.test/iframe.html",
"test");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Test that an HTTP scheme can generate cross-domain XSS requests when using
// document.domain.
TEST(SchemeHandlerTest, HttpXSSDifferentOriginWithDomain) {
RegisterTestScheme("http", "a.test");
RegisterTestScheme("http", "b.test");
SetUpXSS("http://a.test/run.html",
"http://b.test/iframe.html",
"test");
CefRefPtr<TestSchemeHandler> handler = new TestSchemeHandler(&g_TestResults);
handler->ExecuteTest();
EXPECT_TRUE(g_TestResults.got_request);
EXPECT_TRUE(g_TestResults.got_read);
EXPECT_TRUE(g_TestResults.got_output);
EXPECT_TRUE(g_TestResults.got_sub_request);
EXPECT_TRUE(g_TestResults.got_sub_read);
EXPECT_TRUE(g_TestResults.got_sub_success);
ClearTestSchemes();
}
// Entry point for registering custom schemes.
// Called from client_app_delegates.cc.
void RegisterSchemeHandlerCustomSchemes(
CefRefPtr<CefSchemeRegistrar> registrar,
std::vector<CefString>& cookiable_schemes) {
// Add a custom standard scheme.
registrar->AddCustomScheme("customstd", true, false, false);
// Ad a custom non-standard scheme.
registrar->AddCustomScheme("customnonstd", false, false, false);
}

View File

@@ -1,363 +0,0 @@
// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_stream.h"
#include "testing/gtest/include/gtest/gtest.h"
static void VerifyStreamReadBehavior(CefRefPtr<CefStreamReader> stream,
const std::string& contents) {
int contentSize = static_cast<int>(contents.size());
const char* contentStr = contents.c_str();
// Move to the beginning of the stream
ASSERT_EQ(0, stream->Seek(0, SEEK_SET));
ASSERT_EQ(0, stream->Tell());
// Move to the end of the stream
ASSERT_EQ(0, stream->Seek(0, SEEK_END));
ASSERT_EQ(contentSize, stream->Tell());
// Move to the beginning of the stream
ASSERT_EQ(0, stream->Seek(-contentSize, SEEK_CUR));
ASSERT_EQ(0, stream->Tell());
// Read 10 characters at a time and verify the result
char buff[10];
int res, read, offset = 0;
do {
read = std::min(static_cast<int>(sizeof(buff)), contentSize-offset);
res = stream->Read(buff, 1, read);
ASSERT_EQ(read, res);
ASSERT_TRUE(!memcmp(contentStr+offset, buff, res));
offset += res;
} while (offset < contentSize);
// Read past the end of the file
stream->Read(buff, 1, 1);
ASSERT_TRUE(stream->Eof());
}
static void VerifyStreamWriteBehavior(CefRefPtr<CefStreamWriter> stream,
const std::string& contents) {
int contentSize = static_cast<int>(contents.size());
const char* contentStr = contents.c_str();
// Write 10 characters at a time and verify the result
int res, write, offset = 0;
do {
write = std::min(10, contentSize-offset);
res = stream->Write(contentStr+offset, 1, write);
ASSERT_EQ(write, res);
offset += res;
ASSERT_EQ(offset, stream->Tell());
} while (offset < contentSize);
// Move to the beginning of the stream
ASSERT_EQ(0, stream->Seek(-contentSize, SEEK_CUR));
ASSERT_EQ(0, stream->Tell());
// Move to the end of the stream
ASSERT_EQ(0, stream->Seek(0, SEEK_END));
ASSERT_EQ(contentSize, stream->Tell());
// Move to the beginning of the stream
ASSERT_EQ(0, stream->Seek(0, SEEK_SET));
ASSERT_EQ(0, stream->Tell());
}
TEST(StreamTest, ReadFile) {
const char* fileName = "StreamTest.VerifyReadFile.txt";
CefString fileNameStr = "StreamTest.VerifyReadFile.txt";
std::string contents = "This is my test\ncontents for the file";
// Create the file
FILE* f = NULL;
#ifdef _WIN32
fopen_s(&f, fileName, "wb");
#else
f = fopen(fileName, "wb");
#endif
ASSERT_TRUE(f != NULL);
ASSERT_EQ((size_t)1, fwrite(contents.c_str(), contents.size(), 1, f));
fclose(f);
// Test the stream
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForFile(fileNameStr));
ASSERT_TRUE(stream.get() != NULL);
VerifyStreamReadBehavior(stream, contents);
// Release the file pointer
stream = NULL;
// Delete the file
#ifdef _WIN32
ASSERT_EQ(0, _unlink(fileName));
#else
ASSERT_EQ(0, unlink(fileName));
#endif
}
TEST(StreamTest, ReadData) {
std::string contents = "This is my test\ncontents for the file";
// Test the stream
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(contents.c_str())),
contents.size()));
ASSERT_TRUE(stream.get() != NULL);
VerifyStreamReadBehavior(stream, contents);
}
TEST(StreamTest, WriteFile) {
const char* fileName = "StreamTest.VerifyWriteFile.txt";
CefString fileNameStr = "StreamTest.VerifyWriteFile.txt";
std::string contents = "This is my test\ncontents for the file";
// Test the stream
CefRefPtr<CefStreamWriter> stream(
CefStreamWriter::CreateForFile(fileNameStr));
ASSERT_TRUE(stream.get() != NULL);
VerifyStreamWriteBehavior(stream, contents);
// Release the file pointer
stream = NULL;
// Read the file that was written
FILE* f = NULL;
char* buff = new char[contents.size()];
#ifdef _WIN32
fopen_s(&f, fileName, "rb");
#else
f = fopen(fileName, "rb");
#endif
ASSERT_TRUE(f != NULL);
ASSERT_EQ((size_t)1, fread(buff, contents.size(), 1, f));
// Read past the end of the file
fgetc(f);
ASSERT_TRUE(feof(f));
fclose(f);
// Verify the file contents
ASSERT_TRUE(!memcmp(contents.c_str(), buff, contents.size()));
delete [] buff;
// Delete the file
#ifdef _WIN32
ASSERT_EQ(0, _unlink(fileName));
#else
ASSERT_EQ(0, unlink(fileName));
#endif
}
bool g_ReadHandlerTesterDeleted = false;
class ReadHandlerTester : public CefReadHandler {
public:
ReadHandlerTester()
: read_called_(false),
read_ptr_(NULL),
read_size_(0),
read_n_(0),
seek_called_(false),
seek_offset_(0),
seek_whence_(0),
tell_called_(false),
eof_called_(false) {
}
virtual ~ReadHandlerTester() {
g_ReadHandlerTesterDeleted = true;
}
virtual size_t Read(void* ptr, size_t size, size_t n) {
read_called_ = true;
read_ptr_ = ptr;
read_size_ = size;
read_n_ = n;
return 10;
}
virtual int Seek(int64 offset, int whence) {
seek_called_ = true;
seek_offset_ = offset;
seek_whence_ = whence;
return 10;
}
virtual int64 Tell() {
tell_called_ = true;
return 10;
}
virtual int Eof() {
eof_called_ = true;
return 10;
}
bool read_called_;
const void* read_ptr_;
size_t read_size_;
size_t read_n_;
bool seek_called_;
int64 seek_offset_;
int seek_whence_;
bool tell_called_;
bool eof_called_;
IMPLEMENT_REFCOUNTING(ReadHandlerTester);
};
TEST(StreamTest, ReadHandler) {
ReadHandlerTester* handler = new ReadHandlerTester();
ASSERT_TRUE(handler != NULL);
CefRefPtr<CefStreamReader> stream(CefStreamReader::CreateForHandler(handler));
ASSERT_TRUE(stream.get() != NULL);
// CefReadHandler Read
const char* read_ptr = "My data";
size_t read_size = sizeof(read_ptr);
size_t read_n = 1;
size_t read_res = stream->Read(
static_cast<void*>(const_cast<char*>(read_ptr)), read_size, read_n);
ASSERT_TRUE(handler->read_called_);
ASSERT_EQ((size_t)10, read_res);
ASSERT_EQ(read_ptr, handler->read_ptr_);
ASSERT_EQ(read_size, handler->read_size_);
ASSERT_EQ(read_n, handler->read_n_);
// CefReadHandler Seek
int64 seek_offset = 10;
int seek_whence = SEEK_CUR;
int seek_res = stream->Seek(seek_offset, seek_whence);
ASSERT_TRUE(handler->seek_called_);
ASSERT_EQ(10, seek_res);
ASSERT_EQ(seek_offset, handler->seek_offset_);
ASSERT_EQ(seek_whence, handler->seek_whence_);
// CefReadHandler Tell
int64 tell_res = stream->Tell();
ASSERT_TRUE(handler->tell_called_);
ASSERT_EQ(10, tell_res);
// CefReadHandler Eof
int eof_res = stream->Eof();
ASSERT_TRUE(handler->eof_called_);
ASSERT_EQ(10, eof_res);
// Delete the stream
stream = NULL;
// Verify that the handler object was deleted
ASSERT_TRUE(g_ReadHandlerTesterDeleted);
}
bool g_WriteHandlerTesterDeleted = false;
class WriteHandlerTester : public CefWriteHandler {
public:
WriteHandlerTester()
: write_called_(false),
write_ptr_(NULL),
write_size_(0),
write_n_(0),
seek_called_(false),
seek_offset_(0),
seek_whence_(0),
tell_called_(false),
flush_called_(false) {
}
virtual ~WriteHandlerTester() {
g_WriteHandlerTesterDeleted = true;
}
virtual size_t Write(const void* ptr, size_t size, size_t n) {
write_called_ = true;
write_ptr_ = ptr;
write_size_ = size;
write_n_ = n;
return 10;
}
virtual int Seek(int64 offset, int whence) {
seek_called_ = true;
seek_offset_ = offset;
seek_whence_ = whence;
return 10;
}
virtual int64 Tell() {
tell_called_ = true;
return 10;
}
virtual int Flush() {
flush_called_ = true;
return 10;
}
bool write_called_;
const void* write_ptr_;
size_t write_size_;
size_t write_n_;
bool seek_called_;
int64 seek_offset_;
int seek_whence_;
bool tell_called_;
bool flush_called_;
IMPLEMENT_REFCOUNTING(WriteHandlerTester);
};
TEST(StreamTest, WriteHandler) {
WriteHandlerTester* handler = new WriteHandlerTester();
ASSERT_TRUE(handler != NULL);
CefRefPtr<CefStreamWriter> stream(CefStreamWriter::CreateForHandler(handler));
ASSERT_TRUE(stream.get() != NULL);
// CefWriteHandler Write
const char* write_ptr = "My data";
size_t write_size = sizeof(write_ptr);
size_t write_n = 1;
size_t write_res = stream->Write(write_ptr, write_size, write_n);
ASSERT_TRUE(handler->write_called_);
ASSERT_EQ((size_t)10, write_res);
ASSERT_EQ(write_ptr, handler->write_ptr_);
ASSERT_EQ(write_size, handler->write_size_);
ASSERT_EQ(write_n, handler->write_n_);
// CefWriteHandler Seek
int64 seek_offset = 10;
int seek_whence = SEEK_CUR;
int seek_res = stream->Seek(seek_offset, seek_whence);
ASSERT_TRUE(handler->seek_called_);
ASSERT_EQ(10, seek_res);
ASSERT_EQ(seek_offset, handler->seek_offset_);
ASSERT_EQ(seek_whence, handler->seek_whence_);
// CefWriteHandler Tell
int64 tell_res = stream->Tell();
ASSERT_TRUE(handler->tell_called_);
ASSERT_EQ(10, tell_res);
// CefWriteHandler Flush
int flush_res = stream->Flush();
ASSERT_TRUE(handler->flush_called_);
ASSERT_EQ(10, flush_res);
// Delete the stream
stream = NULL;
// Verify that the handler object was deleted
ASSERT_TRUE(g_WriteHandlerTesterDeleted);
}

View File

@@ -1,340 +0,0 @@
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include <map>
#include <vector>
#include "include/internal/cef_string.h"
#include "include/internal/cef_string_list.h"
#include "include/internal/cef_string_map.h"
#include "include/internal/cef_string_multimap.h"
#include "testing/gtest/include/gtest/gtest.h"
// Test UTF8 strings.
TEST(StringTest, UTF8) {
CefStringUTF8 str1("Test String");
ASSERT_EQ(str1.length(), (size_t)11);
ASSERT_FALSE(str1.empty());
ASSERT_TRUE(str1.IsOwner());
// Test equality.
CefStringUTF8 str2("Test String");
ASSERT_EQ(str1, str2);
ASSERT_LE(str1, str2);
ASSERT_GE(str1, str2);
str2 = "Test Test";
ASSERT_LT(str1, str2);
ASSERT_GT(str2, str1);
// When strings are the same but of unequal length, the longer string is
// greater.
str2 = "Test";
ASSERT_LT(str2, str1);
ASSERT_GT(str1, str2);
// Test conversions.
str2 = str1.ToString();
ASSERT_EQ(str1, str2);
str2 = str1.ToWString();
ASSERT_EQ(str1, str2);
// Test userfree assignment.
cef_string_userfree_utf8_t uf = str2.DetachToUserFree();
ASSERT_TRUE(uf != NULL);
ASSERT_TRUE(str2.empty());
str2.AttachToUserFree(uf);
ASSERT_FALSE(str2.empty());
ASSERT_EQ(str1, str2);
}
// Test UTF16 strings.
TEST(StringTest, UTF16) {
CefStringUTF16 str1("Test String");
ASSERT_EQ(str1.length(), (size_t)11);
ASSERT_FALSE(str1.empty());
ASSERT_TRUE(str1.IsOwner());
// Test equality.
CefStringUTF16 str2("Test String");
ASSERT_EQ(str1, str2);
ASSERT_LE(str1, str2);
ASSERT_GE(str1, str2);
str2 = "Test Test";
ASSERT_LT(str1, str2);
ASSERT_GT(str2, str1);
// When strings are the same but of unequal length, the longer string is
// greater.
str2 = "Test";
ASSERT_LT(str2, str1);
ASSERT_GT(str1, str2);
// Test conversions.
str2 = str1.ToString();
ASSERT_EQ(str1, str2);
str2 = str1.ToWString();
ASSERT_EQ(str1, str2);
// Test userfree assignment.
cef_string_userfree_utf16_t uf = str2.DetachToUserFree();
ASSERT_TRUE(uf != NULL);
ASSERT_TRUE(str2.empty());
str2.AttachToUserFree(uf);
ASSERT_FALSE(str2.empty());
ASSERT_EQ(str1, str2);
}
// Test wide strings.
TEST(StringTest, Wide) {
CefStringWide str1("Test String");
ASSERT_EQ(str1.length(), (size_t)11);
ASSERT_FALSE(str1.empty());
ASSERT_TRUE(str1.IsOwner());
// Test equality.
CefStringWide str2("Test String");
ASSERT_EQ(str1, str2);
ASSERT_LE(str1, str2);
ASSERT_GE(str1, str2);
str2 = "Test Test";
ASSERT_LT(str1, str2);
ASSERT_GT(str2, str1);
// When strings are the same but of unequal length, the longer string is
// greater.
str2 = "Test";
ASSERT_LT(str2, str1);
ASSERT_GT(str1, str2);
// Test conversions.
str2 = str1.ToString();
ASSERT_EQ(str1, str2);
str2 = str1.ToWString();
ASSERT_EQ(str1, str2);
// Test userfree assignment.
cef_string_userfree_wide_t uf = str2.DetachToUserFree();
ASSERT_TRUE(uf != NULL);
ASSERT_TRUE(str2.empty());
str2.AttachToUserFree(uf);
ASSERT_FALSE(str2.empty());
ASSERT_EQ(str1, str2);
}
// Test string lists.
TEST(StringTest, List) {
typedef std::vector<CefString> ListType;
ListType list;
list.push_back("String 1");
list.push_back("String 2");
list.push_back("String 3");
ASSERT_EQ(list[0], "String 1");
ASSERT_EQ(list[1], "String 2");
ASSERT_EQ(list[2], "String 3");
cef_string_list_t listPtr = cef_string_list_alloc();
ASSERT_TRUE(listPtr != NULL);
ListType::const_iterator it = list.begin();
for (; it != list.end(); ++it)
cef_string_list_append(listPtr, it->GetStruct());
CefString str;
int ret;
ASSERT_EQ(cef_string_list_size(listPtr), 3);
ret = cef_string_list_value(listPtr, 0, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 1");
ret = cef_string_list_value(listPtr, 1, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 2");
ret = cef_string_list_value(listPtr, 2, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 3");
cef_string_list_t listPtr2 = cef_string_list_copy(listPtr);
cef_string_list_clear(listPtr);
ASSERT_EQ(cef_string_list_size(listPtr), 0);
cef_string_list_free(listPtr);
ASSERT_EQ(cef_string_list_size(listPtr2), 3);
ret = cef_string_list_value(listPtr2, 0, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 1");
ret = cef_string_list_value(listPtr2, 1, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 2");
ret = cef_string_list_value(listPtr2, 2, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 3");
cef_string_list_free(listPtr2);
}
// Test string maps.
TEST(StringTest, Map) {
typedef std::map<CefString, CefString> MapType;
MapType map;
map.insert(std::make_pair("Key 1", "String 1"));
map.insert(std::make_pair("Key 2", "String 2"));
map.insert(std::make_pair("Key 3", "String 3"));
MapType::const_iterator it;
it = map.find("Key 2");
ASSERT_TRUE(it != map.end());
ASSERT_EQ(it->first, "Key 2");
ASSERT_EQ(it->second, "String 2");
it = map.find(L"Key 2");
ASSERT_TRUE(it != map.end());
ASSERT_EQ(it->first, L"Key 2");
ASSERT_EQ(it->second, L"String 2");
ASSERT_EQ(map["Key 1"], "String 1");
ASSERT_EQ(map["Key 2"], "String 2");
ASSERT_EQ(map["Key 3"], "String 3");
cef_string_map_t mapPtr = cef_string_map_alloc();
it = map.begin();
for (; it != map.end(); ++it) {
cef_string_map_append(mapPtr, it->first.GetStruct(),
it->second.GetStruct());
}
CefString str;
int ret;
ASSERT_EQ(cef_string_map_size(mapPtr), 3);
ret = cef_string_map_key(mapPtr, 0, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "Key 1");
ret = cef_string_map_value(mapPtr, 0, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 1");
ret = cef_string_map_key(mapPtr, 1, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "Key 2");
ret = cef_string_map_value(mapPtr, 1, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 2");
ret = cef_string_map_key(mapPtr, 2, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "Key 3");
ret = cef_string_map_value(mapPtr, 2, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 3");
CefString key;
key.FromASCII("Key 2");
ret = cef_string_map_find(mapPtr, key.GetStruct(), str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 2");
cef_string_map_clear(mapPtr);
ASSERT_EQ(cef_string_map_size(mapPtr), 0);
cef_string_map_free(mapPtr);
}
// Test string maps.
TEST(StringTest, Multimap) {
typedef std::multimap<CefString, CefString> MapType;
MapType map;
map.insert(std::make_pair("Key 1", "String 1"));
map.insert(std::make_pair("Key 2", "String 2"));
map.insert(std::make_pair("Key 2", "String 2.1"));
map.insert(std::make_pair("Key 3", "String 3"));
MapType::const_iterator it;
it = map.find("Key 2");
ASSERT_TRUE(it != map.end());
ASSERT_EQ(it->first, "Key 2");
ASSERT_EQ(it->second, "String 2");
std::pair<MapType::const_iterator, MapType::const_iterator>
range_it = map.equal_range("Key 2");
ASSERT_TRUE(range_it.first != range_it.second);
MapType::const_iterator same_key_it = range_it.first;
// Either of "String 2" or "String 2.1" is fine since
// std::multimap provides no guarantee wrt the order of
// values with the same key.
ASSERT_EQ(same_key_it->second.ToString().find("String 2"), (size_t)0);
ASSERT_EQ((++same_key_it)->second.ToString().find("String 2"), (size_t)0);
ASSERT_EQ(map.count("Key 2"), (size_t)2);
ASSERT_EQ(map.find("Key 1")->second, "String 1");
ASSERT_EQ(map.find("Key 3")->second, "String 3");
cef_string_multimap_t mapPtr = cef_string_multimap_alloc();
it = map.begin();
for (; it != map.end(); ++it) {
cef_string_multimap_append(mapPtr, it->first.GetStruct(),
it->second.GetStruct());
}
CefString str;
int ret;
ASSERT_EQ(cef_string_multimap_size(mapPtr), 4);
ret = cef_string_multimap_key(mapPtr, 0, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "Key 1");
ret = cef_string_multimap_value(mapPtr, 0, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 1");
ret = cef_string_multimap_key(mapPtr, 1, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "Key 2");
ret = cef_string_multimap_value(mapPtr, 1, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str.ToString().find("String 2"), (size_t)0);
ret = cef_string_multimap_key(mapPtr, 2, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "Key 2");
ret = cef_string_multimap_value(mapPtr, 2, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str.ToString().find("String 2"), (size_t)0);
ret = cef_string_multimap_key(mapPtr, 3, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "Key 3");
ret = cef_string_multimap_value(mapPtr, 3, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str, "String 3");
CefString key;
key.FromASCII("Key 2");
ret = cef_string_multimap_find_count(mapPtr, key.GetStruct());
ASSERT_EQ(ret, 2);
ret = cef_string_multimap_enumerate(mapPtr,
key.GetStruct(), 0, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str.ToString().find("String 2"), (size_t)0);
ret = cef_string_multimap_enumerate(mapPtr,
key.GetStruct(), 1, str.GetWritableStruct());
ASSERT_TRUE(ret);
ASSERT_EQ(str.ToString().find("String 2"), (size_t)0);
cef_string_multimap_clear(mapPtr);
ASSERT_EQ(cef_string_multimap_size(mapPtr), 0);
cef_string_multimap_free(mapPtr);
}

View File

@@ -1,144 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "tests/unittests/test_handler.h"
#include "include/cef_command_line.h"
#include "include/cef_runnable.h"
#include "include/cef_stream.h"
#include "include/wrapper/cef_stream_resource_handler.h"
namespace {
void NotifyEvent(base::WaitableEvent* event) {
event->Signal();
}
} // namespace
// TestHandler
TestHandler::TestHandler()
: browser_id_(0),
completion_event_(true, false) {
}
TestHandler::~TestHandler() {
}
void TestHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
AutoLock lock_scope(this);
if (!browser->IsPopup()) {
// Keep the main child window, but not popup windows
browser_ = browser;
browser_id_ = browser->GetIdentifier();
}
}
void TestHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
AutoLock lock_scope(this);
if (browser_id_ == browser->GetIdentifier()) {
// Free the browser pointer so that the browser can be destroyed
browser_ = NULL;
browser_id_ = 0;
// Signal that the test is now complete.
completion_event_.Signal();
}
}
CefRefPtr<CefResourceHandler> TestHandler::GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) {
AutoLock lock_scope(this);
if (resource_map_.size() > 0) {
CefString url = request->GetURL();
// Ignore the query component, if any.
std::string urlStr = url;
int idx = urlStr.find('?');
if (idx > 0)
urlStr = urlStr.substr(0, idx);
ResourceMap::const_iterator it = resource_map_.find(urlStr);
if (it != resource_map_.end()) {
// Return the previously mapped resource
CefRefPtr<CefStreamReader> stream =
CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(it->second.first.c_str())),
it->second.first.length());
return new CefStreamResourceHandler(it->second.second, stream);
}
}
return NULL;
}
void TestHandler::ExecuteTest() {
// Run the test
RunTest();
// Wait for the test to complete
completion_event_.Wait();
// Reset the event so the same test can be executed again.
completion_event_.Reset();
}
void TestHandler::DestroyTest() {
AutoLock lock_scope(this);
if (browser_id_ != 0)
browser_->GetHost()->CloseBrowser();
}
void TestHandler::CreateBrowser(const CefString& url) {
CefWindowInfo windowInfo;
CefBrowserSettings settings;
#if defined(OS_WIN)
windowInfo.SetAsPopup(NULL, "CefUnitTest");
windowInfo.style |= WS_VISIBLE;
#endif
CefBrowserHost::CreateBrowser(windowInfo, this, url, settings);
}
void TestHandler::AddResource(const std::string& url,
const std::string& content,
const std::string& mimeType) {
// Ignore the query component, if any.
std::string urlStr = url;
int idx = urlStr.find('?');
if (idx > 0)
urlStr = urlStr.substr(0, idx);
resource_map_.insert(
std::make_pair(urlStr, std::make_pair(content, mimeType)));
}
void TestHandler::ClearResources() {
resource_map_.clear();
}
// global functions
void WaitForThread(CefThreadId thread_id) {
base::WaitableEvent event(true, false);
CefPostTask(thread_id, NewCefRunnableFunction(&NotifyEvent, &event));
event.Wait();
}
bool TestFailed() {
CefRefPtr<CefCommandLine> command_line =
CefCommandLine::GetGlobalCommandLine();
if (command_line->HasSwitch("single-process")) {
// Check for a failure on the current test only.
return ::testing::UnitTest::GetInstance()->current_test_info()->result()->
Failed();
} else {
// Check for any global failure.
return ::testing::UnitTest::GetInstance()->Failed();
}
}

View File

@@ -1,125 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_UNITTESTS_TEST_HANDLER_H_
#define CEF_TESTS_UNITTESTS_TEST_HANDLER_H_
#pragma once
#include <map>
#include <string>
#include <utility>
#include "include/cef_browser.h"
#include "include/cef_client.h"
#include "include/cef_frame.h"
#include "include/cef_task.h"
#include "base/synchronization/waitable_event.h"
#include "testing/gtest/include/gtest/gtest.h"
class TrackCallback {
public:
TrackCallback(): gotit_(false) {}
void yes() { gotit_ = true; }
bool isSet() { return gotit_; }
void reset() { gotit_ = false; }
operator bool() const { return gotit_; }
protected:
bool gotit_;
};
// Base implementation of CefClient for unit tests. Add new interfaces as needed
// by test cases.
class TestHandler : public CefClient,
public CefDisplayHandler,
public CefJSDialogHandler,
public CefLifeSpanHandler,
public CefLoadHandler,
public CefRequestHandler {
public:
TestHandler();
virtual ~TestHandler();
// Implement this method to run the test
virtual void RunTest() =0;
// CefClient methods. Add new methods as needed by test cases.
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefJSDialogHandler> GetJSDialogHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefRequestHandler> GetRequestHandler() OVERRIDE {
return this;
}
// CefLifeSpanHandler methods
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefRequestHandler methods
virtual CefRefPtr<CefResourceHandler> GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) OVERRIDE;
CefRefPtr<CefBrowser> GetBrowser() { return browser_; }
int GetBrowserId() { return browser_id_; }
// Called by the test function to execute the test. This method blocks until
// the test is complete. Do not reference the object after this method
// returns.
void ExecuteTest();
protected:
// Destroy the browser window. Once the window is destroyed test completion
// will be signaled.
void DestroyTest();
void CreateBrowser(const CefString& url);
void AddResource(const std::string& url,
const std::string& content,
const std::string& mimeType);
void ClearResources();
private:
// The child browser window
CefRefPtr<CefBrowser> browser_;
// The browser window identifier
int browser_id_;
// Handle used to notify when the test is complete
base::WaitableEvent completion_event_;
// Map of resources that can be automatically loaded
typedef std::map<std::string, std::pair<std::string, std::string> >
ResourceMap;
ResourceMap resource_map_;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(TestHandler);
// Include the default locking implementation.
IMPLEMENT_LOCKING(TestHandler);
};
// Post a task to the specified thread and wait for the task to execute as
// indication that all previously pending tasks on that thread have completed.
void WaitForThread(CefThreadId thread_id);
#define WaitForIOThread() WaitForThread(TID_IO)
#define WaitForUIThread() WaitForThread(TID_UI)
// Returns true if the currently running test has failed.
bool TestFailed();
#endif // CEF_TESTS_UNITTESTS_TEST_HANDLER_H_

View File

@@ -1,112 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "tests/unittests/test_suite.h"
#include "tests/cefclient/client_switches.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/test/test_suite.h"
#if defined(OS_MACOSX)
#include "base/file_path.h"
#include "base/i18n/icu_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/test/test_timeouts.h"
#endif
CommandLine* CefTestSuite::commandline_ = NULL;
CefTestSuite::CefTestSuite(int argc, char** argv)
: TestSuite(argc, argv) {
}
// static
void CefTestSuite::InitCommandLine(int argc, const char* const* argv) {
if (commandline_) {
// If this is intentional, Reset() must be called first. If we are using
// the shared build mode, we have to share a single object across multiple
// shared libraries.
return;
}
commandline_ = new CommandLine(CommandLine::NO_PROGRAM);
#if defined(OS_WIN)
commandline_->ParseFromString(::GetCommandLineW());
#elif defined(OS_POSIX)
commandline_->InitFromArgv(argc, argv);
#endif
}
// static
void CefTestSuite::GetSettings(CefSettings& settings) {
#if defined(OS_WIN)
settings.multi_threaded_message_loop =
commandline_->HasSwitch(cefclient::kMultiThreadedMessageLoop);
#endif
CefString(&settings.cache_path) =
commandline_->GetSwitchValueASCII(cefclient::kCachePath);
// Always expose the V8 gc() function to give tests finer-grained control over
// memory management.
std::string javascript_flags = "--expose-gc";
// Value of kJavascriptFlags switch.
std::string other_javascript_flags =
commandline_->GetSwitchValueASCII("js-flags");
if (!other_javascript_flags.empty())
javascript_flags += " " + other_javascript_flags;
CefString(&settings.javascript_flags) = javascript_flags;
}
// static
bool CefTestSuite::GetCachePath(std::string& path) {
DCHECK(commandline_);
if (commandline_->HasSwitch(cefclient::kCachePath)) {
// Set the cache_path value.
path = commandline_->GetSwitchValueASCII(cefclient::kCachePath);
return true;
}
return false;
}
#if defined(OS_MACOSX)
void CefTestSuite::Initialize() {
// The below code is copied from base/test/test_suite.cc to avoid calling
// RegisterMockCrApp() on Mac.
// Initialize logging.
FilePath exe;
PathService::Get(base::FILE_EXE, &exe);
FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
logging::InitLogging(
log_filename.value().c_str(),
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE,
logging::DELETE_OLD_LOG_FILE,
logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
// We want process and thread IDs because we may have multiple processes.
// Note: temporarily enabled timestamps in an effort to catch bug 6361.
logging::SetLogItems(true, true, true, true);
CHECK(base::EnableInProcessStackDumping());
// In some cases, we do not want to see standard error dialogs.
if (!base::debug::BeingDebugged() &&
!CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) {
SuppressErrorDialogs();
base::debug::SetSuppressDebugUI(true);
logging::SetLogAssertHandler(UnitTestAssertHandler);
}
icu_util::Initialize();
CatchMaybeTests();
ResetCommandLine();
TestTimeouts::Initialize();
}
#endif // defined(OS_MACOSX)

View File

@@ -1,37 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_UNITTESTS_TEST_SUITE_H_
#define CEF_TESTS_UNITTESTS_TEST_SUITE_H_
#pragma once
#include <string>
#include "include/internal/cef_types_wrappers.h"
#include "base/test/test_suite.h"
class CommandLine;
class CefTestSuite : public TestSuite {
public:
CefTestSuite(int argc, char** argv);
// Initialize the current process CommandLine singleton. On Windows, ignores
// its arguments (we instead parse GetCommandLineW() directly) because we
// don't trust the CRT's parsing of the command line, but it still must be
// called to set up the command line.
static void InitCommandLine(int argc, const char* const* argv);
static void GetSettings(CefSettings& settings);
static bool GetCachePath(std::string& path);
protected:
#if defined(OS_MACOSX)
virtual void Initialize();
#endif
// The singleton CommandLine representing the current process's command line.
static CommandLine* commandline_;
};
#endif // CEF_TESTS_UNITTESTS_TEST_SUITE_H_

View File

@@ -1,227 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "tests/unittests/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
void TestMapEqual(CefRequest::HeaderMap& map1,
CefRequest::HeaderMap& map2,
bool allowExtras) {
if (!allowExtras)
EXPECT_EQ(map1.size(), map2.size());
CefRequest::HeaderMap::const_iterator it1, it2;
for (it1 = map1.begin(); it1 != map1.end(); ++it1) {
it2 = map2.find(it1->first);
EXPECT_TRUE(it2 != map2.end());
if (it2 != map2.end()) {
EXPECT_STREQ(it1->second.ToString().c_str(),
it2->second.ToString().c_str());
}
}
}
void TestPostDataElementEqual(CefRefPtr<CefPostDataElement> elem1,
CefRefPtr<CefPostDataElement> elem2) {
EXPECT_TRUE(elem1.get());
EXPECT_TRUE(elem2.get());
EXPECT_EQ(elem1->GetType(), elem2->GetType());
switch (elem1->GetType()) {
case PDE_TYPE_BYTES: {
EXPECT_EQ(elem1->GetBytesCount(), elem2->GetBytesCount());
size_t bytesCt = elem1->GetBytesCount();
char* buff1 = new char[bytesCt];
char* buff2 = new char[bytesCt];
elem1->GetBytes(bytesCt, buff1);
elem2->GetBytes(bytesCt, buff2);
EXPECT_TRUE(!memcmp(buff1, buff2, bytesCt));
delete [] buff1;
delete [] buff2;
} break;
case PDE_TYPE_FILE:
EXPECT_EQ(elem1->GetFile(), elem2->GetFile());
break;
default:
break;
}
}
void TestPostDataEqual(CefRefPtr<CefPostData> postData1,
CefRefPtr<CefPostData> postData2) {
EXPECT_TRUE(postData1.get());
EXPECT_TRUE(postData2.get());
EXPECT_EQ(postData1->GetElementCount(), postData2->GetElementCount());
CefPostData::ElementVector ev1, ev2;
postData1->GetElements(ev1);
postData1->GetElements(ev2);
ASSERT_EQ(ev1.size(), ev2.size());
CefPostData::ElementVector::const_iterator it1 = ev1.begin();
CefPostData::ElementVector::const_iterator it2 = ev2.begin();
for (; it1 != ev1.end() && it2 != ev2.end(); ++it1, ++it2)
TestPostDataElementEqual((*it1), (*it2));
}
void TestRequestEqual(CefRefPtr<CefRequest> request1,
CefRefPtr<CefRequest> request2,
bool allowExtras) {
EXPECT_TRUE(request1.get());
EXPECT_TRUE(request2.get());
EXPECT_STREQ(request1->GetURL().ToString().c_str(),
request2->GetURL().ToString().c_str());
EXPECT_STREQ(request1->GetMethod().ToString().c_str(),
request2->GetMethod().ToString().c_str());
CefRequest::HeaderMap headers1, headers2;
request1->GetHeaderMap(headers1);
request2->GetHeaderMap(headers2);
TestMapEqual(headers1, headers2, allowExtras);
CefRefPtr<CefPostData> postData1 = request1->GetPostData();
CefRefPtr<CefPostData> postData2 = request2->GetPostData();
EXPECT_EQ(!!(postData1.get()), !!(postData2.get()));
if (postData1.get() && postData2.get())
TestPostDataEqual(postData1, postData2);
}
void TestResponseEqual(CefRefPtr<CefResponse> response1,
CefRefPtr<CefResponse> response2,
bool allowExtras) {
EXPECT_TRUE(response1.get());
EXPECT_TRUE(response2.get());
EXPECT_EQ(response1->GetStatus(), response2->GetStatus());
EXPECT_STREQ(response1->GetStatusText().ToString().c_str(),
response2->GetStatusText().ToString().c_str());
EXPECT_STREQ(response1->GetMimeType().ToString().c_str(),
response2->GetMimeType().ToString().c_str());
CefRequest::HeaderMap headers1, headers2;
response1->GetHeaderMap(headers1);
response2->GetHeaderMap(headers2);
TestMapEqual(headers1, headers2, allowExtras);
}
void TestBinaryEqual(CefRefPtr<CefBinaryValue> val1,
CefRefPtr<CefBinaryValue> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
size_t data_size = val1->GetSize();
EXPECT_EQ(data_size, val2->GetSize());
EXPECT_GT(data_size, (size_t)0);
char* data1 = new char[data_size+1];
char* data2 = new char[data_size+1];
EXPECT_EQ(data_size, val1->GetData(data1, data_size, 0));
data1[data_size] = 0;
EXPECT_EQ(data_size, val2->GetData(data2, data_size, 0));
data2[data_size] = 0;
EXPECT_STREQ(data1, data2);
delete [] data1;
delete [] data2;
}
void TestDictionaryEqual(CefRefPtr<CefDictionaryValue> val1,
CefRefPtr<CefDictionaryValue> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
EXPECT_EQ(val1->GetSize(), val2->GetSize());
CefDictionaryValue::KeyList keys;
EXPECT_TRUE(val1->GetKeys(keys));
CefDictionaryValue::KeyList::const_iterator it = keys.begin();
for (; it != keys.end(); ++it) {
CefString key = *it;
EXPECT_TRUE(val2->HasKey(key));
CefValueType type = val1->GetType(key);
EXPECT_EQ(type, val2->GetType(key));
switch (type) {
case VTYPE_INVALID:
case VTYPE_NULL:
break;
case VTYPE_BOOL:
EXPECT_EQ(val1->GetBool(key), val2->GetBool(key));
break;
case VTYPE_INT:
EXPECT_EQ(val1->GetInt(key), val2->GetInt(key));
break;
case VTYPE_DOUBLE:
EXPECT_EQ(val1->GetDouble(key), val2->GetDouble(key));
break;
case VTYPE_STRING:
EXPECT_EQ(val1->GetString(key), val2->GetString(key));
break;
case VTYPE_BINARY:
TestBinaryEqual(val1->GetBinary(key), val2->GetBinary(key));
break;
case VTYPE_DICTIONARY:
TestDictionaryEqual(val1->GetDictionary(key), val2->GetDictionary(key));
break;
case VTYPE_LIST:
TestListEqual(val1->GetList(key), val2->GetList(key));
break;
}
}
}
void TestListEqual(CefRefPtr<CefListValue> val1,
CefRefPtr<CefListValue> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
size_t size = val1->GetSize();
EXPECT_EQ(size, val2->GetSize());
for (size_t i = 0; i < size; ++i) {
CefValueType type = val1->GetType(i);
EXPECT_EQ(type, val2->GetType(i));
switch (type) {
case VTYPE_INVALID:
case VTYPE_NULL:
break;
case VTYPE_BOOL:
EXPECT_EQ(val1->GetBool(i), val2->GetBool(i));
break;
case VTYPE_INT:
EXPECT_EQ(val1->GetInt(i), val2->GetInt(i));
break;
case VTYPE_DOUBLE:
EXPECT_EQ(val1->GetDouble(i), val2->GetDouble(i));
break;
case VTYPE_STRING:
EXPECT_EQ(val1->GetString(i), val2->GetString(i));
break;
case VTYPE_BINARY:
TestBinaryEqual(val1->GetBinary(i), val2->GetBinary(i));
break;
case VTYPE_DICTIONARY:
TestDictionaryEqual(val1->GetDictionary(i), val2->GetDictionary(i));
break;
case VTYPE_LIST:
TestListEqual(val1->GetList(i), val2->GetList(i));
break;
}
}
}
void TestProcessMessageEqual(CefRefPtr<CefProcessMessage> val1,
CefRefPtr<CefProcessMessage> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
EXPECT_EQ(val1->GetName(), val2->GetName());
TestListEqual(val1->GetArgumentList(), val2->GetArgumentList());
}

View File

@@ -1,59 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_UNITTESTS_TEST_UTIL_H_
#define CEF_TESTS_UNITTESTS_TEST_UTIL_H_
#pragma once
#include "include/cef_process_message.h"
#include "include/cef_request.h"
#include "include/cef_response.h"
#include "include/cef_values.h"
// Test that CefRequest::HeaderMap objects are equal
// If |allowExtras| is true then additional header fields will be allowed in
// |map2|.
void TestMapEqual(CefRequest::HeaderMap& map1,
CefRequest::HeaderMap& map2,
bool allowExtras);
// Test that CefPostDataElement objects are equal
void TestPostDataElementEqual(CefRefPtr<CefPostDataElement> elem1,
CefRefPtr<CefPostDataElement> elem2);
// Test that CefPostData objects are equal
void TestPostDataEqual(CefRefPtr<CefPostData> postData1,
CefRefPtr<CefPostData> postData2);
// Test that CefRequest objects are equal
// If |allowExtras| is true then additional header fields will be allowed in
// |request2|.
void TestRequestEqual(CefRefPtr<CefRequest> request1,
CefRefPtr<CefRequest> request2,
bool allowExtras);
// Test that CefResponse objects are equal
// If |allowExtras| is true then additional header fields will be allowed in
// |response2|.
void TestResponseEqual(CefRefPtr<CefResponse> response1,
CefRefPtr<CefResponse> response2,
bool allowExtras);
// Test if two binary values are equal.
void TestBinaryEqual(CefRefPtr<CefBinaryValue> val1,
CefRefPtr<CefBinaryValue> val2);
// Test if two list values are equal.
void TestListEqual(CefRefPtr<CefListValue> val1,
CefRefPtr<CefListValue> val2);
// Test if two dictionary values are equal.
void TestDictionaryEqual(CefRefPtr<CefDictionaryValue> val1,
CefRefPtr<CefDictionaryValue> val2);
// Test if two process message values are equal.
void TestProcessMessageEqual(CefRefPtr<CefProcessMessage> val1,
CefRefPtr<CefProcessMessage> val2);
#endif // CEF_TESTS_UNITTESTS_TEST_UTIL_H_

View File

@@ -1,183 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_url.h"
#include "testing/gtest/include/gtest/gtest.h"
TEST(URLTest, CreateURL) {
// Create the URL using the spec.
{
CefURLParts parts;
CefString url;
CefString(&parts.spec).FromASCII(
"http://user:pass@www.example.com:88/path/to.html?foo=test&bar=test2");
ASSERT_TRUE(CefCreateURL(parts, url));
ASSERT_EQ(url,
"http://user:pass@www.example.com:88/path/to.html?foo=test&bar=test2");
}
// Test that scheme and host are required.
{
CefURLParts parts;
CefString url;
CefString(&parts.scheme).FromASCII("http");
ASSERT_FALSE(CefCreateURL(parts, url));
}
{
CefURLParts parts;
CefString url;
CefString(&parts.host).FromASCII("www.example.com");
ASSERT_FALSE(CefCreateURL(parts, url));
}
// Create the URL using scheme and host.
{
CefURLParts parts;
CefString url;
CefString(&parts.scheme).FromASCII("http");
CefString(&parts.host).FromASCII("www.example.com");
ASSERT_TRUE(CefCreateURL(parts, url));
ASSERT_EQ(url, "http://www.example.com/");
}
// Create the URL using scheme, host and path.
{
CefURLParts parts;
CefString url;
CefString(&parts.scheme).FromASCII("http");
CefString(&parts.host).FromASCII("www.example.com");
CefString(&parts.path).FromASCII("/path/to.html");
ASSERT_TRUE(CefCreateURL(parts, url));
ASSERT_EQ(url, "http://www.example.com/path/to.html");
}
// Create the URL using scheme, host, path and query.
{
CefURLParts parts;
CefString url;
CefString(&parts.scheme).FromASCII("http");
CefString(&parts.host).FromASCII("www.example.com");
CefString(&parts.path).FromASCII("/path/to.html");
CefString(&parts.query).FromASCII("foo=test&bar=test2");
ASSERT_TRUE(CefCreateURL(parts, url));
ASSERT_EQ(url, "http://www.example.com/path/to.html?foo=test&bar=test2");
}
// Create the URL using all the various components.
{
CefURLParts parts;
CefString url;
CefString(&parts.scheme).FromASCII("http");
CefString(&parts.username).FromASCII("user");
CefString(&parts.password).FromASCII("pass");
CefString(&parts.host).FromASCII("www.example.com");
CefString(&parts.port).FromASCII("88");
CefString(&parts.path).FromASCII("/path/to.html");
CefString(&parts.query).FromASCII("foo=test&bar=test2");
ASSERT_TRUE(CefCreateURL(parts, url));
ASSERT_EQ(url,
"http://user:pass@www.example.com:88/path/to.html?foo=test&bar=test2");
}
}
TEST(URLTest, ParseURL) {
// Parse the URL using scheme and host.
{
CefURLParts parts;
CefString url;
url.FromASCII("http://www.example.com");
ASSERT_TRUE(CefParseURL(url, parts));
CefString spec(&parts.spec);
ASSERT_EQ(spec, "http://www.example.com/");
ASSERT_EQ(parts.username.length, (size_t)0);
ASSERT_EQ(parts.password.length, (size_t)0);
CefString scheme(&parts.scheme);
ASSERT_EQ(scheme, "http");
CefString host(&parts.host);
ASSERT_EQ(host, "www.example.com");
ASSERT_EQ(parts.port.length, (size_t)0);
CefString path(&parts.path);
ASSERT_EQ(path, "/");
ASSERT_EQ(parts.query.length, (size_t)0);
}
// Parse the URL using scheme, host and path.
{
CefURLParts parts;
CefString url;
url.FromASCII("http://www.example.com/path/to.html");
ASSERT_TRUE(CefParseURL(url, parts));
CefString spec(&parts.spec);
ASSERT_EQ(spec, "http://www.example.com/path/to.html");
ASSERT_EQ(parts.username.length, (size_t)0);
ASSERT_EQ(parts.password.length, (size_t)0);
CefString scheme(&parts.scheme);
ASSERT_EQ(scheme, "http");
CefString host(&parts.host);
ASSERT_EQ(host, "www.example.com");
ASSERT_EQ(parts.port.length, (size_t)0);
CefString path(&parts.path);
ASSERT_EQ(path, "/path/to.html");
ASSERT_EQ(parts.query.length, (size_t)0);
}
// Parse the URL using scheme, host, path and query.
{
CefURLParts parts;
CefString url;
url.FromASCII("http://www.example.com/path/to.html?foo=test&bar=test2");
ASSERT_TRUE(CefParseURL(url, parts));
CefString spec(&parts.spec);
ASSERT_EQ(spec, "http://www.example.com/path/to.html?foo=test&bar=test2");
ASSERT_EQ(parts.username.length, (size_t)0);
ASSERT_EQ(parts.password.length, (size_t)0);
CefString scheme(&parts.scheme);
ASSERT_EQ(scheme, "http");
CefString host(&parts.host);
ASSERT_EQ(host, "www.example.com");
ASSERT_EQ(parts.port.length, (size_t)0);
CefString path(&parts.path);
ASSERT_EQ(path, "/path/to.html");
CefString query(&parts.query);
ASSERT_EQ(query, "foo=test&bar=test2");
}
// Parse the URL using all the various components.
{
CefURLParts parts;
CefString url;
url.FromASCII(
"http://user:pass@www.example.com:88/path/to.html?foo=test&bar=test2");
ASSERT_TRUE(CefParseURL(url, parts));
CefString spec(&parts.spec);
ASSERT_EQ(spec,
"http://user:pass@www.example.com:88/path/to.html?foo=test&bar=test2");
CefString scheme(&parts.scheme);
ASSERT_EQ(scheme, "http");
CefString username(&parts.username);
ASSERT_EQ(username, "user");
CefString password(&parts.password);
ASSERT_EQ(password, "pass");
CefString host(&parts.host);
ASSERT_EQ(host, "www.example.com");
CefString port(&parts.port);
ASSERT_EQ(port, "88");
CefString path(&parts.path);
ASSERT_EQ(path, "/path/to.html");
CefString query(&parts.query);
ASSERT_EQ(query, "foo=test&bar=test2");
}
// Parse an invalid URL.
{
CefURLParts parts;
CefString url;
url.FromASCII("www.example.com");
ASSERT_FALSE(CefParseURL(url, parts));
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,734 +0,0 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_task.h"
#include "include/cef_values.h"
#include "tests/unittests/test_handler.h"
#include "tests/unittests/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Dictionary test keys.
const char* kNullKey = "null_key";
const char* kBoolKey = "bool_key";
const char* kIntKey = "int_key";
const char* kDoubleKey = "double_key";
const char* kStringKey = "string_key";
const char* kBinaryKey = "binary_key";
const char* kDictionaryKey = "dict_key";
const char* kListKey = "list_key";
// List test indexes.
enum {
kNullIndex = 0,
kBoolIndex,
kIntIndex,
kDoubleIndex,
kStringIndex,
kBinaryIndex,
kDictionaryIndex,
kListIndex,
};
// Dictionary/list test values.
const bool kBoolValue = true;
const int kIntValue = 12;
const double kDoubleValue = 4.5432;
const char* kStringValue = "My string value";
// BINARY TEST HELPERS
// Test a binary value.
void TestBinary(CefRefPtr<CefBinaryValue> value, char* data, size_t data_size) {
// Testing requires strings longer than 15 characters.
EXPECT_GT(data_size, (size_t)15);
EXPECT_EQ(data_size, value->GetSize());
char* buff = new char[data_size+1];
char old_char;
// Test full read.
memset(buff, 0, data_size+1);
EXPECT_EQ(data_size, value->GetData(buff, data_size, 0));
EXPECT_TRUE(!strcmp(buff, data));
// Test partial read with offset.
memset(buff, 0, data_size+1);
old_char = data[15];
data[15] = 0;
EXPECT_EQ((size_t)10, value->GetData(buff, 10, 5));
EXPECT_TRUE(!strcmp(buff, data+5));
data[15] = old_char;
// Test that changes to the original data have no effect.
memset(buff, 0, data_size+1);
old_char = data[0];
data[0] = '.';
EXPECT_EQ((size_t)1, value->GetData(buff, 1, 0));
EXPECT_EQ(old_char, buff[0]);
data[0] = old_char;
// Test copy.
CefRefPtr<CefBinaryValue> copy = value->Copy();
TestBinaryEqual(copy, value);
delete [] buff;
}
// Used to test access of binary data on a different thread.
class BinaryTask : public CefTask {
public:
BinaryTask(CefRefPtr<CefBinaryValue> value, char* data, size_t data_size)
: value_(value),
data_(data),
data_size_(data_size) {}
virtual void Execute(CefThreadId threadId) OVERRIDE {
TestBinary(value_, data_, data_size_);
}
private:
CefRefPtr<CefBinaryValue> value_;
char* data_;
size_t data_size_;
IMPLEMENT_REFCOUNTING(BinaryTask);
};
// DICTIONARY TEST HELPERS
// Test dictionary null value.
void TestDictionaryNull(CefRefPtr<CefDictionaryValue> value) {
EXPECT_FALSE(value->HasKey(kNullKey));
EXPECT_TRUE(value->SetNull(kNullKey));
EXPECT_TRUE(value->HasKey(kNullKey));
EXPECT_EQ(VTYPE_NULL, value->GetType(kNullKey));
}
// Test dictionary bool value.
void TestDictionaryBool(CefRefPtr<CefDictionaryValue> value) {
EXPECT_FALSE(value->HasKey(kBoolKey));
EXPECT_TRUE(value->SetBool(kBoolKey, kBoolValue));
EXPECT_TRUE(value->HasKey(kBoolKey));
EXPECT_EQ(VTYPE_BOOL, value->GetType(kBoolKey));
EXPECT_EQ(kBoolValue, value->GetBool(kBoolKey));
}
// Test dictionary int value.
void TestDictionaryInt(CefRefPtr<CefDictionaryValue> value) {
EXPECT_FALSE(value->HasKey(kIntKey));
EXPECT_TRUE(value->SetInt(kIntKey, kIntValue));
EXPECT_TRUE(value->HasKey(kIntKey));
EXPECT_EQ(VTYPE_INT, value->GetType(kIntKey));
EXPECT_EQ(kIntValue, value->GetInt(kIntKey));
}
// Test dictionary double value.
void TestDictionaryDouble(CefRefPtr<CefDictionaryValue> value) {
EXPECT_FALSE(value->HasKey(kDoubleKey));
EXPECT_TRUE(value->SetDouble(kDoubleKey, kDoubleValue));
EXPECT_TRUE(value->HasKey(kDoubleKey));
EXPECT_EQ(VTYPE_DOUBLE, value->GetType(kDoubleKey));
EXPECT_EQ(kDoubleValue, value->GetDouble(kDoubleKey));
}
// Test dictionary string value.
void TestDictionaryString(CefRefPtr<CefDictionaryValue> value) {
EXPECT_FALSE(value->HasKey(kStringKey));
EXPECT_TRUE(value->SetString(kStringKey, kStringValue));
EXPECT_TRUE(value->HasKey(kStringKey));
EXPECT_EQ(VTYPE_STRING, value->GetType(kStringKey));
EXPECT_EQ(kStringValue, value->GetString(kStringKey).ToString());
}
// Test dictionary binary value.
void TestDictionaryBinary(CefRefPtr<CefDictionaryValue> value,
char* binary_data, size_t binary_data_size,
CefRefPtr<CefBinaryValue>& binary_value) {
binary_value = CefBinaryValue::Create(binary_data, binary_data_size);
EXPECT_TRUE(binary_value.get());
EXPECT_TRUE(binary_value->IsValid());
EXPECT_FALSE(binary_value->IsOwned());
EXPECT_FALSE(value->HasKey(kBinaryKey));
EXPECT_TRUE(value->SetBinary(kBinaryKey, binary_value));
EXPECT_FALSE(binary_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->HasKey(kBinaryKey));
EXPECT_EQ(VTYPE_BINARY, value->GetType(kBinaryKey));
binary_value = value->GetBinary(kBinaryKey);
EXPECT_TRUE(binary_value.get());
EXPECT_TRUE(binary_value->IsValid());
EXPECT_TRUE(binary_value->IsOwned());
TestBinary(binary_value, binary_data, binary_data_size);
}
// Test dictionary dictionary value.
void TestDictionaryDictionary(CefRefPtr<CefDictionaryValue> value,
CefRefPtr<CefDictionaryValue>& dictionary_value) {
dictionary_value = CefDictionaryValue::Create();
EXPECT_TRUE(dictionary_value.get());
EXPECT_TRUE(dictionary_value->IsValid());
EXPECT_FALSE(dictionary_value->IsOwned());
EXPECT_FALSE(dictionary_value->IsReadOnly());
EXPECT_TRUE(dictionary_value->SetInt(kIntKey, kIntValue));
EXPECT_EQ((size_t)1, dictionary_value->GetSize());
EXPECT_FALSE(value->HasKey(kDictionaryKey));
EXPECT_TRUE(value->SetDictionary(kDictionaryKey, dictionary_value));
EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->HasKey(kDictionaryKey));
EXPECT_EQ(VTYPE_DICTIONARY, value->GetType(kDictionaryKey));
dictionary_value = value->GetDictionary(kDictionaryKey);
EXPECT_TRUE(dictionary_value.get());
EXPECT_TRUE(dictionary_value->IsValid());
EXPECT_TRUE(dictionary_value->IsOwned());
EXPECT_FALSE(dictionary_value->IsReadOnly());
EXPECT_EQ((size_t)1, dictionary_value->GetSize());
EXPECT_EQ(kIntValue, dictionary_value->GetInt(kIntKey));
}
// Test dictionary list value.
void TestDictionaryList(CefRefPtr<CefDictionaryValue> value,
CefRefPtr<CefListValue>& list_value) {
list_value = CefListValue::Create();
EXPECT_TRUE(list_value.get());
EXPECT_TRUE(list_value->IsValid());
EXPECT_FALSE(list_value->IsOwned());
EXPECT_FALSE(list_value->IsReadOnly());
EXPECT_TRUE(list_value->SetInt(0, kIntValue));
EXPECT_EQ((size_t)1, list_value->GetSize());
EXPECT_FALSE(value->HasKey(kListKey));
EXPECT_TRUE(value->SetList(kListKey, list_value));
EXPECT_FALSE(list_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->HasKey(kListKey));
EXPECT_EQ(VTYPE_LIST, value->GetType(kListKey));
list_value = value->GetList(kListKey);
EXPECT_TRUE(list_value.get());
EXPECT_TRUE(list_value->IsValid());
EXPECT_TRUE(list_value->IsOwned());
EXPECT_FALSE(list_value->IsReadOnly());
EXPECT_EQ((size_t)1, list_value->GetSize());
EXPECT_EQ(kIntValue, list_value->GetInt(0));
}
// Test dictionary value.
void TestDictionary(CefRefPtr<CefDictionaryValue> value,
char* binary_data, size_t binary_data_size) {
CefRefPtr<CefBinaryValue> binary_value;
CefRefPtr<CefDictionaryValue> dictionary_value;
CefRefPtr<CefListValue> list_value;
// Test the size.
EXPECT_EQ((size_t)0, value->GetSize());
TestDictionaryNull(value);
TestDictionaryBool(value);
TestDictionaryInt(value);
TestDictionaryDouble(value);
TestDictionaryString(value);
TestDictionaryBinary(value, binary_data, binary_data_size, binary_value);
TestDictionaryDictionary(value, dictionary_value);
TestDictionaryList(value, list_value);
// Test the size.
EXPECT_EQ((size_t)8, value->GetSize());
// Test copy.
CefRefPtr<CefDictionaryValue> copy = value->Copy(false);
TestDictionaryEqual(value, copy);
// Test removal.
EXPECT_TRUE(value->Remove(kNullKey));
EXPECT_FALSE(value->HasKey(kNullKey));
EXPECT_TRUE(value->Remove(kBoolKey));
EXPECT_FALSE(value->HasKey(kBoolKey));
EXPECT_TRUE(value->Remove(kIntKey));
EXPECT_FALSE(value->HasKey(kIntKey));
EXPECT_TRUE(value->Remove(kDoubleKey));
EXPECT_FALSE(value->HasKey(kDoubleKey));
EXPECT_TRUE(value->Remove(kStringKey));
EXPECT_FALSE(value->HasKey(kStringKey));
EXPECT_TRUE(value->Remove(kBinaryKey));
EXPECT_FALSE(value->HasKey(kBinaryKey));
EXPECT_FALSE(binary_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->Remove(kDictionaryKey));
EXPECT_FALSE(value->HasKey(kDictionaryKey));
EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->Remove(kListKey));
EXPECT_FALSE(value->HasKey(kListKey));
EXPECT_FALSE(list_value->IsValid()); // Value should be detached
// Test the size.
EXPECT_EQ((size_t)0, value->GetSize());
// Re-add some values.
TestDictionaryNull(value);
TestDictionaryBool(value);
TestDictionaryDictionary(value, dictionary_value);
// Test the size.
EXPECT_EQ((size_t)3, value->GetSize());
// Clear the values.
EXPECT_TRUE(value->Clear());
EXPECT_EQ((size_t)0, value->GetSize());
EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached
}
// Used to test access of dictionary data on a different thread.
class DictionaryTask : public CefTask {
public:
DictionaryTask(CefRefPtr<CefDictionaryValue> value, char* binary_data,
size_t binary_data_size)
: value_(value),
binary_data_(binary_data),
binary_data_size_(binary_data_size) {}
virtual void Execute(CefThreadId threadId) OVERRIDE {
TestDictionary(value_, binary_data_, binary_data_size_);
}
private:
CefRefPtr<CefDictionaryValue> value_;
char* binary_data_;
size_t binary_data_size_;
IMPLEMENT_REFCOUNTING(DictionaryTask);
};
// LIST TEST HELPERS
// Test list null value.
void TestListNull(CefRefPtr<CefListValue> value, int index) {
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetNull(index));
EXPECT_EQ(VTYPE_NULL, value->GetType(index));
}
// Test list bool value.
void TestListBool(CefRefPtr<CefListValue> value, int index) {
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetBool(index, kBoolValue));
EXPECT_EQ(VTYPE_BOOL, value->GetType(index));
EXPECT_EQ(kBoolValue, value->GetBool(index));
}
// Test list int value.
void TestListInt(CefRefPtr<CefListValue> value, int index) {
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetInt(index, kIntValue));
EXPECT_EQ(VTYPE_INT, value->GetType(index));
EXPECT_EQ(kIntValue, value->GetInt(index));
}
// Test list double value.
void TestListDouble(CefRefPtr<CefListValue> value, int index) {
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetDouble(index, kDoubleValue));
EXPECT_EQ(VTYPE_DOUBLE, value->GetType(index));
EXPECT_EQ(kDoubleValue, value->GetDouble(index));
}
// Test list string value.
void TestListString(CefRefPtr<CefListValue> value, int index) {
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetString(index, kStringValue));
EXPECT_EQ(VTYPE_STRING, value->GetType(index));
EXPECT_EQ(kStringValue, value->GetString(index).ToString());
}
// Test list binary value.
void TestListBinary(CefRefPtr<CefListValue> value, int index,
char* binary_data, size_t binary_data_size,
CefRefPtr<CefBinaryValue>& binary_value) {
binary_value = CefBinaryValue::Create(binary_data, binary_data_size);
EXPECT_TRUE(binary_value.get());
EXPECT_TRUE(binary_value->IsValid());
EXPECT_FALSE(binary_value->IsOwned());
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetBinary(index, binary_value));
EXPECT_FALSE(binary_value->IsValid()); // Value should be detached
EXPECT_EQ(VTYPE_BINARY, value->GetType(index));
binary_value = value->GetBinary(index);
EXPECT_TRUE(binary_value.get());
EXPECT_TRUE(binary_value->IsValid());
EXPECT_TRUE(binary_value->IsOwned());
TestBinary(binary_value, binary_data, binary_data_size);
}
// Test list dictionary value.
void TestListDictionary(CefRefPtr<CefListValue> value, int index,
CefRefPtr<CefDictionaryValue>& dictionary_value) {
dictionary_value = CefDictionaryValue::Create();
EXPECT_TRUE(dictionary_value.get());
EXPECT_TRUE(dictionary_value->IsValid());
EXPECT_FALSE(dictionary_value->IsOwned());
EXPECT_FALSE(dictionary_value->IsReadOnly());
EXPECT_TRUE(dictionary_value->SetInt(kIntKey, kIntValue));
EXPECT_EQ((size_t)1, dictionary_value->GetSize());
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetDictionary(index, dictionary_value));
EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached
EXPECT_EQ(VTYPE_DICTIONARY, value->GetType(index));
dictionary_value = value->GetDictionary(index);
EXPECT_TRUE(dictionary_value.get());
EXPECT_TRUE(dictionary_value->IsValid());
EXPECT_TRUE(dictionary_value->IsOwned());
EXPECT_FALSE(dictionary_value->IsReadOnly());
EXPECT_EQ((size_t)1, dictionary_value->GetSize());
EXPECT_EQ(kIntValue, dictionary_value->GetInt(kIntKey));
}
// Test list list value.
void TestListList(CefRefPtr<CefListValue> value, int index,
CefRefPtr<CefListValue>& list_value) {
list_value = CefListValue::Create();
EXPECT_TRUE(list_value.get());
EXPECT_TRUE(list_value->IsValid());
EXPECT_FALSE(list_value->IsOwned());
EXPECT_FALSE(list_value->IsReadOnly());
EXPECT_TRUE(list_value->SetInt(0, kIntValue));
EXPECT_EQ((size_t)1, list_value->GetSize());
CefValueType type = value->GetType(index);
EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL);
EXPECT_TRUE(value->SetList(index, list_value));
EXPECT_FALSE(list_value->IsValid()); // Value should be detached
EXPECT_EQ(VTYPE_LIST, value->GetType(index));
list_value = value->GetList(index);
EXPECT_TRUE(list_value.get());
EXPECT_TRUE(list_value->IsValid());
EXPECT_TRUE(list_value->IsOwned());
EXPECT_FALSE(list_value->IsReadOnly());
EXPECT_EQ((size_t)1, list_value->GetSize());
EXPECT_EQ(kIntValue, list_value->GetInt(0));
}
// Test list value.
void TestList(CefRefPtr<CefListValue> value,
char* binary_data, size_t binary_data_size) {
CefRefPtr<CefBinaryValue> binary_value;
CefRefPtr<CefDictionaryValue> dictionary_value;
CefRefPtr<CefListValue> list_value;
// Test the size.
EXPECT_EQ((size_t)0, value->GetSize());
// Set the size.
EXPECT_TRUE(value->SetSize(8));
EXPECT_EQ((size_t)8, value->GetSize());
EXPECT_EQ(VTYPE_NULL, value->GetType(kNullIndex));
TestListNull(value, kNullIndex);
EXPECT_EQ(VTYPE_NULL, value->GetType(kBoolIndex));
TestListBool(value, kBoolIndex);
EXPECT_EQ(VTYPE_NULL, value->GetType(kIntIndex));
TestListInt(value, kIntIndex);
EXPECT_EQ(VTYPE_NULL, value->GetType(kDoubleIndex));
TestListDouble(value, kDoubleIndex);
EXPECT_EQ(VTYPE_NULL, value->GetType(kStringIndex));
TestListString(value, kStringIndex);
EXPECT_EQ(VTYPE_NULL, value->GetType(kBinaryIndex));
TestListBinary(value, kBinaryIndex, binary_data, binary_data_size,
binary_value);
EXPECT_EQ(VTYPE_NULL, value->GetType(kDictionaryIndex));
TestListDictionary(value, kDictionaryIndex, dictionary_value);
EXPECT_EQ(VTYPE_NULL, value->GetType(kListIndex));
TestListList(value, kListIndex, list_value);
// Test the size.
EXPECT_EQ((size_t)8, value->GetSize());
// Test copy.
CefRefPtr<CefListValue> copy = value->Copy();
TestListEqual(value, copy);
// Test removal (in reverse order so indexes stay valid).
EXPECT_TRUE(value->Remove(kListIndex));
EXPECT_EQ((size_t)7, value->GetSize());
EXPECT_FALSE(list_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->Remove(kDictionaryIndex));
EXPECT_EQ((size_t)6, value->GetSize());
EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->Remove(kBinaryIndex));
EXPECT_EQ((size_t)5, value->GetSize());
EXPECT_FALSE(binary_value->IsValid()); // Value should be detached
EXPECT_TRUE(value->Remove(kStringIndex));
EXPECT_EQ((size_t)4, value->GetSize());
EXPECT_TRUE(value->Remove(kDoubleIndex));
EXPECT_EQ((size_t)3, value->GetSize());
EXPECT_TRUE(value->Remove(kIntIndex));
EXPECT_EQ((size_t)2, value->GetSize());
EXPECT_TRUE(value->Remove(kBoolIndex));
EXPECT_EQ((size_t)1, value->GetSize());
EXPECT_TRUE(value->Remove(kNullIndex));
EXPECT_EQ((size_t)0, value->GetSize());
// Re-add some values.
EXPECT_EQ(VTYPE_INVALID, value->GetType(0));
TestListNull(value, 0);
EXPECT_EQ(VTYPE_INVALID, value->GetType(1));
TestListBool(value, 1);
EXPECT_EQ(VTYPE_INVALID, value->GetType(2));
TestListList(value, 2, list_value);
// Test the size.
EXPECT_EQ((size_t)3, value->GetSize());
// Clear the values.
EXPECT_TRUE(value->Clear());
EXPECT_EQ((size_t)0, value->GetSize());
EXPECT_FALSE(list_value->IsValid()); // Value should be detached
// Add some values in random order.
EXPECT_EQ(VTYPE_INVALID, value->GetType(2));
TestListInt(value, 2);
EXPECT_EQ(VTYPE_NULL, value->GetType(0));
TestListBool(value, 0);
EXPECT_EQ(VTYPE_NULL, value->GetType(1));
TestListList(value, 1, list_value);
EXPECT_EQ(VTYPE_BOOL, value->GetType(0));
EXPECT_EQ(VTYPE_LIST, value->GetType(1));
EXPECT_EQ(VTYPE_INT, value->GetType(2));
// Test the size.
EXPECT_EQ((size_t)3, value->GetSize());
// Clear some values.
EXPECT_TRUE(value->SetSize(1));
EXPECT_EQ((size_t)1, value->GetSize());
EXPECT_FALSE(list_value->IsValid()); // Value should be detached
EXPECT_EQ(VTYPE_BOOL, value->GetType(0));
EXPECT_EQ(VTYPE_INVALID, value->GetType(1));
EXPECT_EQ(VTYPE_INVALID, value->GetType(2));
// Clear all values.
EXPECT_TRUE(value->Clear());
EXPECT_EQ((size_t)0, value->GetSize());
}
// Used to test access of list data on a different thread.
class ListTask : public CefTask {
public:
ListTask(CefRefPtr<CefListValue> value, char* binary_data,
size_t binary_data_size)
: value_(value),
binary_data_(binary_data),
binary_data_size_(binary_data_size) {}
virtual void Execute(CefThreadId threadId) OVERRIDE {
TestList(value_, binary_data_, binary_data_size_);
}
private:
CefRefPtr<CefListValue> value_;
char* binary_data_;
size_t binary_data_size_;
IMPLEMENT_REFCOUNTING(ListTask);
};
} // namespace
// Test binary value access.
TEST(ValuesTest, BinaryAccess) {
char data[] = "This is my test data";
CefRefPtr<CefBinaryValue> value =
CefBinaryValue::Create(data, sizeof(data)-1);
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
// Test on this thread.
TestBinary(value, data, sizeof(data)-1);
}
// Test binary value access on a different thread.
TEST(ValuesTest, BinaryAccessOtherThread) {
char data[] = "This is my test data";
CefRefPtr<CefBinaryValue> value =
CefBinaryValue::Create(data, sizeof(data)-1);
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
// Test on a different thread.
CefPostTask(TID_UI, new BinaryTask(value, data, sizeof(data)-1));
WaitForUIThread();
}
// Test dictionary value access.
TEST(ValuesTest, DictionaryAccess) {
CefRefPtr<CefDictionaryValue> value = CefDictionaryValue::Create();
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
EXPECT_FALSE(value->IsReadOnly());
char binary_data[] = "This is my test data";
// Test on this thread.
TestDictionary(value, binary_data, sizeof(binary_data)-1);
}
// Test dictionary value access on a different thread.
TEST(ValuesTest, DictionaryAccessOtherThread) {
CefRefPtr<CefDictionaryValue> value = CefDictionaryValue::Create();
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
EXPECT_FALSE(value->IsReadOnly());
char binary_data[] = "This is my test data";
// Test on a different thread.
CefPostTask(TID_UI,
new DictionaryTask(value, binary_data, sizeof(binary_data)-1));
WaitForUIThread();
}
// Test dictionary value nested detachment
TEST(ValuesTest, DictionaryDetachment) {
CefRefPtr<CefDictionaryValue> value = CefDictionaryValue::Create();
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
EXPECT_FALSE(value->IsReadOnly());
CefRefPtr<CefDictionaryValue> dictionary_value = CefDictionaryValue::Create();
CefRefPtr<CefDictionaryValue> dictionary_value2 =
CefDictionaryValue::Create();
CefRefPtr<CefDictionaryValue> dictionary_value3 =
CefDictionaryValue::Create();
dictionary_value2->SetDictionary(kDictionaryKey, dictionary_value3);
EXPECT_FALSE(dictionary_value3->IsValid());
dictionary_value->SetDictionary(kDictionaryKey, dictionary_value2);
EXPECT_FALSE(dictionary_value2->IsValid());
value->SetDictionary(kDictionaryKey, dictionary_value);
EXPECT_FALSE(dictionary_value->IsValid());
dictionary_value = value->GetDictionary(kDictionaryKey);
EXPECT_TRUE(dictionary_value.get());
EXPECT_TRUE(dictionary_value->IsValid());
dictionary_value2 = dictionary_value->GetDictionary(kDictionaryKey);
EXPECT_TRUE(dictionary_value2.get());
EXPECT_TRUE(dictionary_value2->IsValid());
dictionary_value3 = dictionary_value2->GetDictionary(kDictionaryKey);
EXPECT_TRUE(dictionary_value3.get());
EXPECT_TRUE(dictionary_value3->IsValid());
EXPECT_TRUE(value->Remove(kDictionaryKey));
EXPECT_FALSE(dictionary_value->IsValid());
EXPECT_FALSE(dictionary_value2->IsValid());
EXPECT_FALSE(dictionary_value3->IsValid());
}
// Test list value access.
TEST(ValuesTest, ListAccess) {
CefRefPtr<CefListValue> value = CefListValue::Create();
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
EXPECT_FALSE(value->IsReadOnly());
char binary_data[] = "This is my test data";
// Test on this thread.
TestList(value, binary_data, sizeof(binary_data)-1);
}
// Test list value access on a different thread.
TEST(ValuesTest, ListAccessOtherThread) {
CefRefPtr<CefListValue> value = CefListValue::Create();
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
EXPECT_FALSE(value->IsReadOnly());
char binary_data[] = "This is my test data";
// Test on a different thread.
CefPostTask(TID_UI, new ListTask(value, binary_data, sizeof(binary_data)-1));
WaitForUIThread();
}
// Test list value nested detachment
TEST(ValuesTest, ListDetachment) {
CefRefPtr<CefListValue> value = CefListValue::Create();
EXPECT_TRUE(value.get());
EXPECT_TRUE(value->IsValid());
EXPECT_FALSE(value->IsOwned());
EXPECT_FALSE(value->IsReadOnly());
CefRefPtr<CefListValue> list_value = CefListValue::Create();
CefRefPtr<CefListValue> list_value2 = CefListValue::Create();
CefRefPtr<CefListValue> list_value3 = CefListValue::Create();
list_value2->SetList(0, list_value3);
EXPECT_FALSE(list_value3->IsValid());
list_value->SetList(0, list_value2);
EXPECT_FALSE(list_value2->IsValid());
value->SetList(0, list_value);
EXPECT_FALSE(list_value->IsValid());
list_value = value->GetList(0);
EXPECT_TRUE(list_value.get());
EXPECT_TRUE(list_value->IsValid());
list_value2 = list_value->GetList(0);
EXPECT_TRUE(list_value2.get());
EXPECT_TRUE(list_value2->IsValid());
list_value3 = list_value2->GetList(0);
EXPECT_TRUE(list_value3.get());
EXPECT_TRUE(list_value3->IsValid());
EXPECT_TRUE(value->Remove(0));
EXPECT_FALSE(list_value->IsValid());
EXPECT_FALSE(list_value2->IsValid());
EXPECT_FALSE(list_value3->IsValid());
}

View File

@@ -1,642 +0,0 @@
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_stream.h"
#include "include/cef_xml_reader.h"
#include "include/wrapper/cef_xml_object.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
char g_test_xml[] =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
"<?my_instruction my_value?>\n"
"<!DOCTYPE my_document SYSTEM \"example.dtd\" [\n"
" <!ENTITY EA \"EA Value\">\n"
" <!ENTITY EB \"EB Value\">\n"
"]>\n"
"<ns:obj xmlns:ns=\"http://www.example.org/ns\">\n"
" <ns:objA>value A</ns:objA>\n"
" <!-- my comment -->\n"
" <ns:objB>\n"
" <ns:objB_1>value B1</ns:objB_1>\n"
" <ns:objB_2><![CDATA[some <br/> data]]></ns:objB_2>\n"
" <ns:objB_3>&EB;</ns:objB_3>\n"
" <ns:objB_4><b>this is</b> mixed content &EA;</ns:objB_4>\n"
" </ns:objB>\n"
" <ns:objC ns:attr1=\"value C1\" ns:attr2=\"value C2\"/><ns:objD>"
"</ns:objD>\n"
"</ns:obj>\n";
} // namespace
// Test XML reading
TEST(XmlReaderTest, Read) {
// Create the stream reader.
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(g_test_xml, sizeof(g_test_xml) - 1));
ASSERT_TRUE(stream.get() != NULL);
// Create the XML reader.
CefRefPtr<CefXmlReader> reader(
CefXmlReader::Create(stream, XML_ENCODING_NONE,
"http://www.example.org/example.xml"));
ASSERT_TRUE(reader.get() != NULL);
// Move to the processing instruction node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 0);
ASSERT_EQ(reader->GetType(), XML_NODE_PROCESSING_INSTRUCTION);
ASSERT_EQ(reader->GetLocalName(), "my_instruction");
ASSERT_EQ(reader->GetQualifiedName(), "my_instruction");
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), "my_value");
// Move to the DOCTYPE node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 0);
ASSERT_EQ(reader->GetType(), XML_NODE_DOCUMENT_TYPE);
ASSERT_EQ(reader->GetLocalName(), "my_document");
ASSERT_EQ(reader->GetQualifiedName(), "my_document");
ASSERT_FALSE(reader->HasValue());
// Move to ns:obj element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 0);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "obj");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:obj");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_TRUE(reader->HasAttributes());
ASSERT_EQ(reader->GetAttributeCount(), (size_t)1);
ASSERT_EQ(reader->GetAttribute(0), "http://www.example.org/ns");
ASSERT_EQ(reader->GetAttribute("xmlns:ns"), "http://www.example.org/ns");
ASSERT_EQ(reader->GetAttribute("ns", "http://www.w3.org/2000/xmlns/"),
"http://www.example.org/ns");
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objA element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objA");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objA");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the ns:objA value node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
ASSERT_EQ(reader->GetLocalName(), "#text");
ASSERT_EQ(reader->GetQualifiedName(), "#text");
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), "value A");
// Move to the ns:objA element ending node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "objA");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objA");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the comment node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_COMMENT);
ASSERT_EQ(reader->GetLocalName(), "#comment");
ASSERT_EQ(reader->GetQualifiedName(), "#comment");
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), " my comment ");
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objB element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objB");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objB_1 element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objB_1");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_1");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the ns:objB_1 value node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 3);
ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), "value B1");
// Move to the ns:objB_1 element ending node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "objB_1");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_1");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objB_2 element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objB_2");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_2");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the ns:objB_2 value node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 3);
ASSERT_EQ(reader->GetType(), XML_NODE_CDATA);
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), "some <br/> data");
// Move to the ns:objB_2 element ending node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "objB_2");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_2");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objB_3 element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objB_3");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_3");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the EB entity reference node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 3);
ASSERT_EQ(reader->GetType(), XML_NODE_ENTITY_REFERENCE);
ASSERT_EQ(reader->GetLocalName(), "EB");
ASSERT_EQ(reader->GetQualifiedName(), "EB");
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), "EB Value");
// Move to the ns:objB_3 element ending node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "objB_3");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_3");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objB_4 element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objB_4");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_4");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
ASSERT_EQ(reader->GetInnerXml(), "<b>this is</b> mixed content &EA;");
ASSERT_EQ(reader->GetOuterXml(),
"<ns:objB_4 xmlns:ns=\"http://www.example.org/ns\">"
"<b>this is</b> mixed content &EA;</ns:objB_4>");
// Move to the <b> element node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 3);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "b");
ASSERT_EQ(reader->GetQualifiedName(), "b");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the text node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 4);
ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
ASSERT_EQ(reader->GetLocalName(), "#text");
ASSERT_EQ(reader->GetQualifiedName(), "#text");
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), "this is");
// Move to the </b> element node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 3);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "b");
ASSERT_EQ(reader->GetQualifiedName(), "b");
// Move to the text node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 3);
ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
ASSERT_EQ(reader->GetLocalName(), "#text");
ASSERT_EQ(reader->GetQualifiedName(), "#text");
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), " mixed content ");
// Move to the EA entity reference node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 3);
ASSERT_EQ(reader->GetType(), XML_NODE_ENTITY_REFERENCE);
ASSERT_EQ(reader->GetLocalName(), "EA");
ASSERT_EQ(reader->GetQualifiedName(), "EA");
ASSERT_TRUE(reader->HasValue());
ASSERT_EQ(reader->GetValue(), "EA Value");
// Move to the ns:objB_4 element ending node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "objB_4");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_4");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objB element ending node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "objB");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objB");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to the ns:objC element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objC");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objC");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_TRUE(reader->IsEmptyElement());
ASSERT_TRUE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
ASSERT_EQ(reader->GetAttributeCount(), (size_t)2);
ASSERT_EQ(reader->GetAttribute(0), "value C1");
ASSERT_EQ(reader->GetAttribute("ns:attr1"), "value C1");
ASSERT_EQ(reader->GetAttribute("attr1", "http://www.example.org/ns"),
"value C1");
ASSERT_EQ(reader->GetAttribute(1), "value C2");
ASSERT_EQ(reader->GetAttribute("ns:attr2"), "value C2");
ASSERT_EQ(reader->GetAttribute("attr2", "http://www.example.org/ns"),
"value C2");
// Move to the ns:attr1 attribute.
ASSERT_TRUE(reader->MoveToFirstAttribute());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
ASSERT_EQ(reader->GetLocalName(), "attr1");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_TRUE(reader->HasValue());
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_EQ(reader->GetValue(), "value C1");
// Move to the ns:attr2 attribute.
ASSERT_TRUE(reader->MoveToNextAttribute());
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
ASSERT_EQ(reader->GetLocalName(), "attr2");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:attr2");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_TRUE(reader->HasValue());
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_EQ(reader->GetValue(), "value C2");
// No more attributes.
ASSERT_FALSE(reader->MoveToNextAttribute());
// Return to the ns:objC element start node.
ASSERT_TRUE(reader->MoveToCarryingElement());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetQualifiedName(), "ns:objC");
// Move to the ns:attr1 attribute.
ASSERT_TRUE(reader->MoveToAttribute(0));
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
ASSERT_EQ(reader->GetLocalName(), "attr1");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_TRUE(reader->HasValue());
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_EQ(reader->GetValue(), "value C1");
// Return to the ns:objC element start node.
ASSERT_TRUE(reader->MoveToCarryingElement());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetQualifiedName(), "ns:objC");
// Move to the ns:attr2 attribute.
ASSERT_TRUE(reader->MoveToAttribute("ns:attr2"));
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
ASSERT_EQ(reader->GetLocalName(), "attr2");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:attr2");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_TRUE(reader->HasValue());
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_EQ(reader->GetValue(), "value C2");
// Move to the ns:attr1 attribute without returning to the ns:objC element.
ASSERT_TRUE(reader->MoveToAttribute("attr1", "http://www.example.org/ns"));
ASSERT_EQ(reader->GetDepth(), 2);
ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
ASSERT_EQ(reader->GetLocalName(), "attr1");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_TRUE(reader->HasValue());
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_EQ(reader->GetValue(), "value C1");
// Move to the ns:objD element start node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
ASSERT_EQ(reader->GetLocalName(), "objD");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objD");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the ns:objD element end node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 1);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "objD");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:objD");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_FALSE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Move to the whitespace node without returning to the ns:objC element.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);
// Move to ns:obj element ending node.
ASSERT_TRUE(reader->MoveToNextNode());
ASSERT_EQ(reader->GetDepth(), 0);
ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
ASSERT_EQ(reader->GetLocalName(), "obj");
ASSERT_EQ(reader->GetPrefix(), "ns");
ASSERT_EQ(reader->GetQualifiedName(), "ns:obj");
ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
ASSERT_FALSE(reader->IsEmptyElement());
ASSERT_TRUE(reader->HasAttributes());
ASSERT_FALSE(reader->HasValue());
// Strangely, the end node will report if the starting node has attributes
// but will not provide access to them.
ASSERT_TRUE(reader->HasAttributes());
ASSERT_EQ(reader->GetAttributeCount(), (size_t)0);
// And we're done.
ASSERT_FALSE(reader->MoveToNextNode());
ASSERT_TRUE(reader->Close());
}
// Test XML read error handling.
TEST(XmlReaderTest, ReadError) {
char test_str[] =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
"<!ATTRIBUTE foo bar>\n";
// Create the stream reader.
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(test_str, sizeof(test_str) - 1));
ASSERT_TRUE(stream.get() != NULL);
// Create the XML reader.
CefRefPtr<CefXmlReader> reader(
CefXmlReader::Create(stream, XML_ENCODING_NONE,
"http://www.example.org/example.xml"));
ASSERT_TRUE(reader.get() != NULL);
// Move to the processing instruction node and generate parser error.
ASSERT_FALSE(reader->MoveToNextNode());
ASSERT_TRUE(reader->HasError());
}
// Test XmlObject load behavior.
TEST(XmlReaderTest, ObjectLoad) {
// Create the stream reader.
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(g_test_xml, sizeof(g_test_xml) - 1));
ASSERT_TRUE(stream.get() != NULL);
// Create the XML reader.
CefRefPtr<CefXmlObject> object(new CefXmlObject("object"));
ASSERT_TRUE(object->Load(stream, XML_ENCODING_NONE,
"http://www.example.org/example.xml", NULL));
ASSERT_FALSE(object->HasAttributes());
ASSERT_TRUE(object->HasChildren());
ASSERT_EQ(object->GetChildCount(), (size_t)1);
CefRefPtr<CefXmlObject> obj(object->FindChild("ns:obj"));
ASSERT_TRUE(obj.get());
ASSERT_TRUE(obj->HasChildren());
ASSERT_EQ(obj->GetChildCount(), (size_t)4);
CefRefPtr<CefXmlObject> obj_child(obj->FindChild("ns:objC"));
ASSERT_TRUE(obj_child.get());
ASSERT_EQ(obj_child->GetName(), "ns:objC");
ASSERT_FALSE(obj_child->HasChildren());
ASSERT_FALSE(obj_child->HasValue());
ASSERT_TRUE(obj_child->HasAttributes());
CefXmlObject::ObjectVector obj_children;
ASSERT_EQ(obj->GetChildren(obj_children), (size_t)4);
ASSERT_EQ(obj_children.size(), (size_t)4);
CefXmlObject::ObjectVector::const_iterator it = obj_children.begin();
for (int ct = 0; it != obj_children.end(); ++it, ++ct) {
obj_child = *it;
ASSERT_TRUE(obj_child.get());
if (ct == 0) {
// ns:objA
ASSERT_EQ(obj_child->GetName(), "ns:objA");
ASSERT_FALSE(obj_child->HasChildren());
ASSERT_TRUE(obj_child->HasValue());
ASSERT_FALSE(obj_child->HasAttributes());
ASSERT_EQ(obj_child->GetValue(), "value A");
} else if (ct == 1) {
// ns:objB
ASSERT_EQ(obj_child->GetName(), "ns:objB");
ASSERT_TRUE(obj_child->HasChildren());
ASSERT_FALSE(obj_child->HasValue());
ASSERT_FALSE(obj_child->HasAttributes());
ASSERT_EQ(obj_child->GetChildCount(), (size_t)4);
obj_child = obj_child->FindChild("ns:objB_4");
ASSERT_TRUE(obj_child.get());
ASSERT_TRUE(obj_child->HasValue());
ASSERT_EQ(obj_child->GetValue(),
"<b>this is</b> mixed content EA Value");
} else if (ct == 2) {
// ns:objC
ASSERT_EQ(obj_child->GetName(), "ns:objC");
ASSERT_FALSE(obj_child->HasChildren());
ASSERT_FALSE(obj_child->HasValue());
ASSERT_TRUE(obj_child->HasAttributes());
CefXmlObject::AttributeMap attribs;
ASSERT_EQ(obj_child->GetAttributes(attribs), (size_t)2);
ASSERT_EQ(attribs.size(), (size_t)2);
ASSERT_EQ(attribs["ns:attr1"], "value C1");
ASSERT_EQ(attribs["ns:attr2"], "value C2");
ASSERT_EQ(obj_child->GetAttributeCount(), (size_t)2);
ASSERT_TRUE(obj_child->HasAttribute("ns:attr1"));
ASSERT_EQ(obj_child->GetAttributeValue("ns:attr1"), "value C1");
ASSERT_TRUE(obj_child->HasAttribute("ns:attr2"));
ASSERT_EQ(obj_child->GetAttributeValue("ns:attr2"), "value C2");
} else if (ct == 3) {
// ns:objD
ASSERT_EQ(obj_child->GetName(), "ns:objD");
ASSERT_FALSE(obj_child->HasChildren());
ASSERT_FALSE(obj_child->HasValue());
ASSERT_FALSE(obj_child->HasAttributes());
}
}
}
// Test XmlObject load error handling behavior.
TEST(XmlReaderTest, ObjectLoadError) {
// Test start/end tag mismatch error.
{
char error_xml[] = "<obj>\n<foo>\n</obj>\n</foo>";
// Create the stream reader.
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(error_xml, sizeof(error_xml) - 1));
ASSERT_TRUE(stream.get() != NULL);
CefString error_str;
// Create the XML reader.
CefRefPtr<CefXmlObject> object(new CefXmlObject("object"));
ASSERT_FALSE(object->Load(stream, XML_ENCODING_NONE,
"http://www.example.org/example.xml", &error_str));
ASSERT_EQ(error_str,
"Opening and ending tag mismatch: foo line 2 and obj, line 3");
}
// Test value following child error.
{
char error_xml[] = "<obj>\n<foo>\n</foo>disallowed value\n</obj>";
// Create the stream reader.
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(error_xml, sizeof(error_xml) - 1));
ASSERT_TRUE(stream.get() != NULL);
CefString error_str;
// Create the XML reader.
CefRefPtr<CefXmlObject> object(new CefXmlObject("object"));
ASSERT_FALSE(object->Load(stream, XML_ENCODING_NONE,
"http://www.example.org/example.xml", &error_str));
ASSERT_EQ(error_str,
"Value following child element, line 4");
}
}

View File

@@ -1,253 +0,0 @@
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef_stream.h"
#include "include/cef_zip_reader.h"
#include "include/wrapper/cef_zip_archive.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
unsigned char g_test_zip[] = {
0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x67, 0x7f,
0x57, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61,
0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x50, 0x4b, 0x03, 0x04, 0x0a,
0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x7f, 0x57, 0x3d, 0xf8, 0x47, 0x0c,
0xc6, 0x13, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00,
0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76,
0x65, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x2e, 0x74, 0x78, 0x74,
0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, 0x66, 0x20,
0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x2e, 0x50, 0x4b, 0x03, 0x04, 0x0a,
0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x7f, 0x57, 0x3d, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00,
0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76,
0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x2f, 0x50,
0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x7f, 0x57,
0x3d, 0x43, 0xe3, 0x11, 0x5f, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00,
0x00, 0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72,
0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72,
0x20, 0x31, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x61, 0x2e, 0x74,
0x78, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f,
0x66, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x41, 0x2e, 0x50, 0x4b,
0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x7f, 0x57, 0x3d,
0x80, 0xb0, 0x3c, 0x74, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63,
0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20,
0x31, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x62, 0x2e, 0x74, 0x78,
0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, 0x66,
0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x42, 0x2e, 0x50, 0x4b, 0x03,
0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x7f, 0x57, 0x3d, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20,
0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68,
0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31,
0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x61, 0x2f, 0x50,
0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x7f, 0x57,
0x3d, 0x15, 0xed, 0x04, 0x2c, 0x15, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00,
0x00, 0x2c, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72,
0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72,
0x20, 0x31, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x61,
0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x61, 0x31, 0x2e, 0x74, 0x78,
0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, 0x66,
0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x41, 0x31, 0x2e, 0x50, 0x4b,
0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x7f, 0x57, 0x3d,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x16, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63,
0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20,
0x32, 0x2f, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x80, 0x57, 0x3d, 0x1a, 0x5d, 0x57, 0x5d, 0x14, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74,
0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c,
0x64, 0x65, 0x72, 0x20, 0x32, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x32,
0x61, 0x2e, 0x74, 0x78, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
0x73, 0x20, 0x6f, 0x66, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x32, 0x41,
0x2e, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00,
0x00, 0x67, 0x7f, 0x57, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74,
0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f,
0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00,
0x70, 0x7f, 0x57, 0x3d, 0xf8, 0x47, 0x0c, 0xc6, 0x13, 0x00, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x74, 0x65,
0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66,
0x69, 0x6c, 0x65, 0x20, 0x31, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b, 0x01,
0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x7f, 0x57,
0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0x00, 0x00, 0x00, 0x73, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f,
0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64,
0x65, 0x72, 0x20, 0x31, 0x2f, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x7f, 0x57, 0x3d, 0x43, 0xe3, 0x11,
0x5f, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa7,
0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68,
0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31,
0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x61, 0x2e, 0x74, 0x78, 0x74,
0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00,
0x78, 0x7f, 0x57, 0x3d, 0x80, 0xb0, 0x3c, 0x74, 0x14, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x00, 0x74, 0x65,
0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66,
0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x2f, 0x66, 0x69, 0x6c, 0x65,
0x20, 0x31, 0x62, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b, 0x01, 0x02, 0x14,
0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x7f, 0x57, 0x3d, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,
0x00, 0x4d, 0x01, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72,
0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72,
0x20, 0x31, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x61,
0x2f, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00,
0x00, 0x7c, 0x7f, 0x57, 0x3d, 0x15, 0xed, 0x04, 0x2c, 0x15, 0x00, 0x00,
0x00, 0x15, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x8b, 0x01, 0x00, 0x00, 0x74,
0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f,
0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x2f, 0x66, 0x6f, 0x6c,
0x64, 0x65, 0x72, 0x20, 0x31, 0x61, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20,
0x31, 0x61, 0x31, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b, 0x01, 0x02, 0x14,
0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x7f, 0x57, 0x3d, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,
0x00, 0xea, 0x01, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72,
0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72,
0x20, 0x32, 0x2f, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02, 0x80, 0x57, 0x3d, 0x1a, 0x5d, 0x57, 0x5d, 0x14,
0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x1e, 0x02, 0x00,
0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76,
0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x32, 0x2f, 0x66,
0x69, 0x6c, 0x65, 0x20, 0x32, 0x61, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b,
0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x09, 0x00, 0x9d, 0x02,
0x00, 0x00, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00
};
} // namespace
// Test Zip reading.
TEST(ZipReaderTest, Read) {
// Create the stream reader.
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(g_test_zip, sizeof(g_test_zip) - 1));
ASSERT_TRUE(stream.get() != NULL);
// Create the Zip reader.
CefRefPtr<CefZipReader> reader(CefZipReader::Create(stream));
ASSERT_TRUE(reader.get() != NULL);
char buff[25];
// Walk through the archive contents.
ASSERT_TRUE(reader->MoveToFirstFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/");
ASSERT_EQ(reader->GetFileSize(), 0);
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/file 1.txt");
ASSERT_EQ(reader->GetFileSize(), 19);
ASSERT_TRUE(reader->OpenFile(""));
ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 19);
ASSERT_TRUE(!strncmp(buff, "Contents of file 1.", 19));
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/");
ASSERT_EQ(reader->GetFileSize(), 0);
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/file 1a.txt");
ASSERT_EQ(reader->GetFileSize(), 20);
ASSERT_TRUE(reader->OpenFile(""));
ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20);
ASSERT_TRUE(reader->CloseFile());
ASSERT_TRUE(!strncmp(buff, "Contents of file 1A.", 20));
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/file 1b.txt");
ASSERT_EQ(reader->GetFileSize(), 20);
ASSERT_TRUE(reader->OpenFile(""));
ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20);
ASSERT_TRUE(reader->CloseFile());
ASSERT_TRUE(!strncmp(buff, "Contents of file 1B.", 20));
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/folder 1a/");
ASSERT_EQ(reader->GetFileSize(), 0);
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(),
"test_archive/folder 1/folder 1a/file 1a1.txt");
ASSERT_EQ(reader->GetFileSize(), 21);
ASSERT_TRUE(reader->OpenFile(""));
ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 21);
ASSERT_TRUE(reader->CloseFile());
ASSERT_TRUE(!strncmp(buff, "Contents of file 1A1.", 21));
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/folder 2/");
ASSERT_EQ(reader->GetFileSize(), 0);
ASSERT_TRUE(reader->MoveToNextFile());
ASSERT_EQ(reader->GetFileName(), "test_archive/folder 2/file 2a.txt");
ASSERT_EQ(reader->GetFileSize(), 20);
ASSERT_TRUE(reader->OpenFile(""));
ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20);
ASSERT_TRUE(reader->CloseFile());
ASSERT_TRUE(!strncmp(buff, "Contents of file 2A.", 20));
ASSERT_FALSE(reader->MoveToNextFile());
// Try seeking a particular file
ASSERT_TRUE(reader->MoveToFile("TEST_ARCHIVE/FOLDER 1/FILE 1B.TXT", false));
ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/file 1b.txt");
ASSERT_EQ(reader->GetFileSize(), 20);
ASSERT_TRUE(reader->OpenFile(""));
ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20);
ASSERT_TRUE(reader->CloseFile());
ASSERT_TRUE(!strncmp(buff, "Contents of file 1B.", 20));
ASSERT_TRUE(reader->MoveToFile("test_archive/folder 1/file 1b.txt", true));
ASSERT_FALSE(reader->MoveToFile("test_archive/folder 1/FILE 1B.txt", true));
ASSERT_TRUE(reader->Close());
}
// Test CefZipArchive object.
TEST(ZipReaderTest, ReadArchive) {
// Create the stream reader.
CefRefPtr<CefStreamReader> stream(
CefStreamReader::CreateForData(g_test_zip, sizeof(g_test_zip) - 1));
ASSERT_TRUE(stream.get() != NULL);
// Create the Zip archive object.
CefRefPtr<CefZipArchive> archive(new CefZipArchive());
ASSERT_EQ(archive->Load(stream, false), (size_t)5);
ASSERT_TRUE(archive->HasFile("test_archive/file 1.txt"));
ASSERT_TRUE(archive->HasFile("test_archive/folder 1/file 1a.txt"));
ASSERT_TRUE(archive->HasFile("test_archive/FOLDER 1/file 1b.txt"));
ASSERT_TRUE(archive->HasFile("test_archive/folder 1/folder 1a/file 1a1.txt"));
ASSERT_TRUE(archive->HasFile("test_archive/folder 2/file 2a.txt"));
// Test content retrieval.
CefRefPtr<CefZipArchive::File> file;
file = archive->GetFile("test_archive/folder 2/file 2a.txt");
ASSERT_TRUE(file.get());
ASSERT_EQ(file->GetDataSize(), (size_t)20);
ASSERT_TRUE(!strncmp(reinterpret_cast<const char*>(file->GetData()),
"Contents of file 2A.", 20));
// Test stream reading.
CefRefPtr<CefStreamReader> reader(file->GetStreamReader());
ASSERT_TRUE(reader.get());
char buff[8];
ASSERT_EQ(reader->Read(buff, 1, 8), (size_t)8);
ASSERT_TRUE(!strncmp(buff, "Contents", 8));
ASSERT_EQ(reader->Read(buff, 1, 8), (size_t)8);
ASSERT_TRUE(!strncmp(buff, " of file", 8));
ASSERT_EQ(reader->Read(buff, 1, 8), (size_t)4);
ASSERT_TRUE(!strncmp(buff, " 2A.", 4));
ASSERT_TRUE(reader->Eof());
}