Delete PPAPI testing code Bug: 40511450 Change-Id: Ia9dde260b1dfe9d9e2273cb5e5326ebac4ce7bac Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/6670296 Reviewed-by: Fabian Sommer <fabiansommer@chromium.org> Commit-Queue: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/main@{#1478595} NOKEYCHECK=True GitOrigin-RevId: 6420f71a85eb194385f757036ab2c84d0ff831cc
diff --git a/BUILD.gn b/BUILD.gn index c2a4ff3..8239f6d 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -19,319 +19,6 @@ # shipped for Chrome on Windows. assert(!(is_win && is_official_build)) -# Test files shared between several targets below. -# -# TODO(brettw) it seems like it should be possible to factor this in a source -# set that is shared in such a way that these only need to be referenced once. -test_common_source_files = [ - "lib/gl/gles2/gl2ext_ppapi.c", - "lib/gl/gles2/gl2ext_ppapi.h", - "lib/gl/gles2/gles2.c", - "tests/all_c_includes.h", - "tests/all_cpp_includes.h", - "tests/arch_dependent_sizes_32.h", - "tests/arch_dependent_sizes_64.h", - "tests/pp_thread.h", - "tests/test_audio.cc", - "tests/test_audio.h", - "tests/test_audio_config.cc", - "tests/test_audio_config.h", - "tests/test_case.cc", - "tests/test_case.h", - "tests/test_console.cc", - "tests/test_console.h", - "tests/test_core.cc", - "tests/test_core.h", - "tests/test_cursor_control.cc", - "tests/test_cursor_control.h", - "tests/test_empty.cc", - "tests/test_empty.h", - "tests/test_file_io.cc", - "tests/test_file_io.h", - "tests/test_file_ref.cc", - "tests/test_file_ref.h", - "tests/test_file_system.cc", - "tests/test_file_system.h", - "tests/test_fullscreen.cc", - "tests/test_fullscreen.h", - "tests/test_graphics_2d.cc", - "tests/test_graphics_2d.h", - "tests/test_graphics_3d.cc", - "tests/test_graphics_3d.h", - "tests/test_host_resolver.cc", - "tests/test_host_resolver.h", - "tests/test_host_resolver_crash.cc", - "tests/test_host_resolver_crash.h", - "tests/test_host_resolver_private.cc", - "tests/test_host_resolver_private.h", - "tests/test_host_resolver_private_disallowed.cc", - "tests/test_host_resolver_private_disallowed.h", - "tests/test_image_data.cc", - "tests/test_image_data.h", - "tests/test_ime_input_event.cc", - "tests/test_ime_input_event.h", - "tests/test_input_event.cc", - "tests/test_input_event.h", - "tests/test_media_stream_audio_track.cc", - "tests/test_media_stream_audio_track.h", - "tests/test_media_stream_video_track.cc", - "tests/test_media_stream_video_track.h", - "tests/test_memory.cc", - "tests/test_memory.h", - "tests/test_message_handler.cc", - "tests/test_message_handler.h", - "tests/test_message_loop.cc", - "tests/test_message_loop.h", - "tests/test_mouse_cursor.cc", - "tests/test_mouse_cursor.h", - "tests/test_mouse_lock.cc", - "tests/test_mouse_lock.h", - "tests/test_net_address.cc", - "tests/test_net_address.h", - "tests/test_net_address_private_untrusted.cc", - "tests/test_net_address_private_untrusted.h", - "tests/test_network_monitor.cc", - "tests/test_network_monitor.h", - "tests/test_network_proxy.cc", - "tests/test_network_proxy.h", - "tests/test_paint_aggregator.cc", - "tests/test_paint_aggregator.h", - "tests/test_post_message.cc", - "tests/test_post_message.h", - "tests/test_printing.cc", - "tests/test_printing.h", - "tests/test_tcp_server_socket_private.cc", - "tests/test_tcp_server_socket_private.h", - "tests/test_tcp_socket.cc", - "tests/test_tcp_socket.h", - "tests/test_tcp_socket_private.cc", - "tests/test_tcp_socket_private.h", - "tests/test_tcp_socket_private_crash.cc", - "tests/test_tcp_socket_private_crash.h", - "tests/test_test_internals.cc", - "tests/test_test_internals.h", - "tests/test_trace_event.cc", - "tests/test_trace_event.h", - "tests/test_udp_socket.cc", - "tests/test_udp_socket.h", - "tests/test_udp_socket_private.cc", - "tests/test_udp_socket_private.h", - "tests/test_uma.cc", - "tests/test_uma.h", - "tests/test_url_loader.cc", - "tests/test_url_loader.h", - "tests/test_url_request.cc", - "tests/test_url_request.h", - "tests/test_utils.h", - "tests/test_utils.cc", - "tests/test_var.cc", - "tests/test_var.h", - "tests/test_var_resource.cc", - "tests/test_var_resource.h", - "tests/test_video_decoder.cc", - "tests/test_video_decoder.h", - "tests/test_video_encoder.cc", - "tests/test_video_encoder.h", - "tests/test_view.cc", - "tests/test_view.h", - "tests/test_websocket.cc", - "tests/test_websocket.h", - "tests/testing_instance.cc", - "tests/testing_instance.h", - - # Compile-time tests - "tests/test_c_includes.c", - "tests/test_cpp_includes.cc", - "tests/test_struct_sizes.c", -] - -copy("copy_test_files") { - sources = [ - # Keep "test_case.html.mock-http-headers" with "test_case.html" - # and "corb_eligible_resource.json.mock-http-headers" with - # "corb_eligible_resource.json". - "tests/corb_eligible_resource.json", - "tests/corb_eligible_resource.json.mock-http-headers", - "tests/test_case.html", - "tests/test_case.html.mock-http-headers", - "tests/test_page.css", - "tests/test_page.css.mock-http-headers", - ] - outputs = [ "$root_out_dir/{{source_file_part}}" ] -} - -copy("copy_test_files2") { - sources = [ "tests/test_url_loader_data/hello.txt" ] - outputs = [ "$root_out_dir/test_url_loader_data/{{source_file_part}}" ] -} - -source_set("ppapi_tests_sources") { - sources = test_common_source_files - sources += [ - "tests/test_browser_font.cc", - "tests/test_browser_font.h", - "tests/test_buffer.cc", - "tests/test_buffer.h", - "tests/test_char_set.cc", - "tests/test_char_set.h", - "tests/test_crypto.cc", - "tests/test_crypto.h", - "tests/test_file_chooser.cc", - "tests/test_file_chooser.h", - "tests/test_net_address_private.cc", - "tests/test_net_address_private.h", - "tests/test_tcp_socket_private_trusted.cc", - "tests/test_tcp_socket_private_trusted.h", - "tests/test_url_util.cc", - "tests/test_url_util.h", - "tests/test_video_decoder_dev.cc", - "tests/test_video_decoder_dev.h", - "tests/test_x509_certificate_private.cc", - "tests/test_x509_certificate_private.h", - - # Deprecated test cases. - "tests/test_instance_deprecated.cc", - "tests/test_instance_deprecated.h", - "tests/test_var_deprecated.cc", - "tests/test_var_deprecated.h", - ] - - configs += [ - "//build/config:precompiled_headers", - "//v8:external_startup_data", - ] - - defines = [ "GL_GLEXT_PROTOTYPES" ] - include_dirs = [ "lib/gl/include" ] - - deps = [ - ":copy_test_files", - ":copy_test_files2", - "//ppapi/cpp", - "//ppapi/shared_impl", - ] -} - -if (is_mac) { - ppapi_tests_target_type = "mac_plugin_bundle" -} else { - ppapi_tests_target_type = "shared_library" -} -target(ppapi_tests_target_type, "ppapi_tests") { - deps = [ ":ppapi_tests_sources" ] -} - -source_set("blink_deprecated_test_plugin_sources") { - sources = [ "tests/blink_deprecated_test_plugin.cc" ] - - deps = [ - "//base", - "//ppapi/cpp", - "//ppapi/shared_impl", - ] -} - -if (!is_mac) { - loadable_module("blink_deprecated_test_plugin") { - deps = [ ":blink_deprecated_test_plugin_sources" ] - } -} else { - mac_plugin_bundle("blink_deprecated_test_plugin") { - deps = [ ":blink_deprecated_test_plugin_sources" ] - } -} - -source_set("blink_test_plugin_sources") { - sources = [ "tests/blink_test_plugin.cc" ] - - deps = [ - "//base", - "//ppapi/cpp", - "//ppapi/shared_impl", - ] -} - -if (!is_mac) { - loadable_module("blink_test_plugin") { - deps = [ ":blink_test_plugin_sources" ] - } -} else { - mac_plugin_bundle("blink_test_plugin") { - deps = [ ":blink_test_plugin_sources" ] - } -} - -test("ppapi_unittests") { - sources = [ - "host/resource_message_filter_unittest.cc", - "proxy/device_enumeration_resource_helper_unittest.cc", - "proxy/file_chooser_resource_unittest.cc", - "proxy/file_system_resource_unittest.cc", - "proxy/interface_list_unittest.cc", - "proxy/mock_resource.cc", - "proxy/mock_resource.h", - "proxy/nacl_message_scanner_unittest.cc", - "proxy/plugin_dispatcher_unittest.cc", - "proxy/plugin_resource_tracker_unittest.cc", - "proxy/plugin_var_tracker_unittest.cc", - "proxy/ppapi_command_buffer_proxy_unittest.cc", - "proxy/ppb_var_unittest.cc", - "proxy/ppp_instance_private_proxy_unittest.cc", - "proxy/ppp_instance_proxy_unittest.cc", - "proxy/ppp_messaging_proxy_unittest.cc", - "proxy/printing_resource_unittest.cc", - "proxy/raw_var_data_unittest.cc", - "proxy/serialized_var_unittest.cc", - "proxy/tracked_callback_unittest.cc", - "proxy/video_decoder_resource_unittest.cc", - "proxy/video_encoder_resource_unittest.cc", - "proxy/websocket_resource_unittest.cc", - "shared_impl/media_stream_audio_track_shared_unittest.cc", - "shared_impl/media_stream_buffer_manager_unittest.cc", - "shared_impl/media_stream_video_track_shared_unittest.cc", - "shared_impl/proxy_lock_unittest.cc", - "shared_impl/resource_tracker_unittest.cc", - "shared_impl/thread_aware_callback_unittest.cc", - "shared_impl/time_conversion_unittest.cc", - "shared_impl/var_tracker_unittest.cc", - ] - - deps = [ - "//base/test:test_support", - "//gpu/ipc/common:command_buffer_traits", - "//ipc", - "//ipc:run_all_unittests", - "//ipc:test_support", - "//media:shared_memory_support", - "//ppapi/host", - "//ppapi/proxy", - "//ppapi/proxy:test_support", - "//ppapi/shared_impl", - "//ppapi/shared_impl:test_support", - "//skia", - "//testing/gmock", - "//testing/gtest", - "//ui/surface", - ] -} - -test("ppapi_perftests") { - sources = [ - "proxy/ppapi_perftests.cc", - "proxy/ppp_messaging_proxy_perftest.cc", - ] - - deps = [ - "//base/test:test_support", - "//mojo/core/embedder", - "//ppapi/proxy", - "//ppapi/proxy:test_support", - "//ppapi/shared_impl", - "//ppapi/shared_impl:test_support", - "//testing/gtest", - ] -} - executable("pepper_hash_for_uma") { sources = [ "tools/pepper_hash_for_uma.cc" ] @@ -350,51 +37,3 @@ ] deps = [ "//ppapi/cpp" ] } - -if (enable_nacl) { - import("//ppapi/native_client/nacl_test_data.gni") - - if (is_nacl) { - nacl_test_data("ppapi_nacl_tests") { - include_dirs = [ "lib/gl/include" ] - sources = test_common_source_files - - sources += [ - "tests/test_nacl_irt_stack_alignment.cc", - "tests/test_nacl_irt_stack_alignment.h", - "tests/test_tcp_server_socket_private_disallowed.cc", - "tests/test_tcp_server_socket_private_disallowed.h", - "tests/test_tcp_socket_private_disallowed.cc", - "tests/test_tcp_socket_private_disallowed.h", - "tests/test_udp_socket_private_disallowed.cc", - "tests/test_udp_socket_private_disallowed.h", - ] - - defines = [ - "GL_GLEXT_PROTOTYPES", - "PPAPI_TEST_IMPLEMENTATION", - ] - deps = [ - "//ppapi/cpp", - "//ppapi/native_client/src/untrusted/irt_stub:ppapi_stub_lib", - ] - if (current_cpu == "pnacl") { - pretranslate_pexe = true - } - } - } - - group("ppapi_nacl_tests_all") { - data_deps = [ - ":copy_test_files", - ":ppapi_nacl_tests(//build/toolchain/nacl:clang_newlib_${nacl_target_cpu})", - ":ppapi_nacl_tests(//build/toolchain/nacl:newlib_pnacl)", - ] - - if (target_cpu != "mipsel" && !is_mac && !is_win) { - data_deps += [ - ":ppapi_nacl_tests(//build/toolchain/nacl:glibc_${nacl_target_cpu})", - ] - } - } -}
diff --git a/host/resource_message_filter_unittest.cc b/host/resource_message_filter_unittest.cc deleted file mode 100644 index ad3e09d..0000000 --- a/host/resource_message_filter_unittest.cc +++ /dev/null
@@ -1,229 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/run_loop.h" -#include "base/synchronization/waitable_event.h" -#include "base/task/sequenced_task_runner.h" -#include "base/task/single_thread_task_runner.h" -#include "base/test/task_environment.h" -#include "base/threading/thread.h" -#include "ipc/ipc_message.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/host/host_message_context.h" -#include "ppapi/host/resource_host.h" -#include "ppapi/host/resource_message_filter.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { -namespace host { -namespace { - -base::WaitableEvent g_handler_completion( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED); - -enum TestMessageTypes { - MSG1_TYPE = 1, - MSG2_TYPE, - MSG3_TYPE, - REPLY_MSG1_TYPE, - REPLY_MSG2_TYPE, - REPLY_MSG3_TYPE, -}; - -// Dummy resource host which simply stores a copy of messages it handles. -// |SendReply| is overridden to store a copy of the outgoing message and the -// message loop on which it was sent. -class MyResourceHost : public ResourceHost { - public: - // Messages of type |msg_type| will be handled (simply by replying with a - // message of type |reply_msg_type|). - MyResourceHost(PpapiHost* host, - PP_Instance instance, - PP_Resource resource, - uint32_t msg_type, - uint32_t reply_msg_type) - : ResourceHost(host, instance, resource), - msg_type_(msg_type), - reply_msg_type_(reply_msg_type), - last_reply_task_runner_(nullptr) {} - - const IPC::Message& last_handled_msg() const { return last_handled_msg_; } - const IPC::Message& last_reply_msg() const { return last_reply_msg_; } - scoped_refptr<base::SingleThreadTaskRunner> last_reply_task_runner() const { - return last_reply_task_runner_; - } - - void AddMessageFilter(scoped_refptr<ResourceMessageFilter> filter) { - AddFilter(filter); - } - - int32_t OnResourceMessageReceived(const IPC::Message& msg, - HostMessageContext* context) override { - last_handled_msg_ = msg; - if (msg.type() == msg_type_) { - context->reply_msg = IPC::Message(0, reply_msg_type_, - IPC::Message::PRIORITY_NORMAL); - return PP_OK; - } - return PP_ERROR_FAILED; - } - - void SendReply(const ReplyMessageContext& context, - const IPC::Message& msg) override { - last_reply_msg_ = msg; - last_reply_task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); - g_handler_completion.Signal(); - } - - private: - uint32_t msg_type_; - uint32_t reply_msg_type_; - - IPC::Message last_handled_msg_; - IPC::Message last_reply_msg_; - scoped_refptr<base::SingleThreadTaskRunner> last_reply_task_runner_; -}; - -// Dummy message filter which simply stores a copy of messages it handles. -// The message loop on which the message is handled is also stored for checking -// later. -class MyResourceFilter : public ResourceMessageFilter { - public: - // Messages of type |msg_type| will be handled (simply by replying with a - // message of type |reply_msg_type|). |io_thread| is the thread on which - // replies should be sent. |bg_thread| is the thread on which the message - // should be handled. - MyResourceFilter(const base::Thread& io_thread, - const base::Thread& bg_thread, - uint32_t msg_type, - uint32_t reply_msg_type) - : ResourceMessageFilter(io_thread.task_runner()), - task_runner_(bg_thread.task_runner()), - msg_type_(msg_type), - reply_msg_type_(reply_msg_type) {} - - const IPC::Message& last_handled_msg() const { return last_handled_msg_; } - scoped_refptr<base::SingleThreadTaskRunner> last_task_runner() const { - return last_task_runner_; - } - - scoped_refptr<base::SequencedTaskRunner> OverrideTaskRunnerForMessage( - const IPC::Message& msg) override { - if (msg.type() == msg_type_) - return task_runner_; - return nullptr; - } - - int32_t OnResourceMessageReceived( - const IPC::Message& msg, - HostMessageContext* context) override { - last_handled_msg_ = msg; - last_task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); - if (msg.type() == msg_type_) { - context->reply_msg = IPC::Message(0, reply_msg_type_, - IPC::Message::PRIORITY_NORMAL); - return PP_OK; - } - return PP_ERROR_FAILED; - } - - private: - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - uint32_t msg_type_; - uint32_t reply_msg_type_; - - IPC::Message last_handled_msg_; - scoped_refptr<base::SingleThreadTaskRunner> last_task_runner_; -}; - -} // namespace - -class ResourceMessageFilterTest : public testing::Test { - public: - void TestHandleMessageImpl() { - base::Thread io_thread("test_io_thread"); - ASSERT_TRUE(io_thread.Start()); - - base::Thread bg_thread1("test_background_thread1"); - ASSERT_TRUE(bg_thread1.Start()); - scoped_refptr<MyResourceFilter> filter1 = - new MyResourceFilter(io_thread, bg_thread1, MSG1_TYPE, REPLY_MSG1_TYPE); - - base::Thread bg_thread2("test_background_thread2"); - ASSERT_TRUE(bg_thread2.Start()); - scoped_refptr<MyResourceFilter> filter2 = - new MyResourceFilter(io_thread, bg_thread2, MSG2_TYPE, REPLY_MSG2_TYPE); - - PP_Instance instance = 12345; - PP_Resource resource = 67890; - MyResourceHost host(nullptr, instance, resource, MSG3_TYPE, - REPLY_MSG3_TYPE); - host.AddMessageFilter(filter1); - host.AddMessageFilter(filter2); - - proxy::ResourceMessageCallParams params(resource, 1); - params.set_has_callback(); - HostMessageContext context(params); - IPC::Message message1(0, MSG1_TYPE, IPC::Message::PRIORITY_NORMAL); - IPC::Message message2(0, MSG2_TYPE, IPC::Message::PRIORITY_NORMAL); - IPC::Message message3(0, MSG3_TYPE, IPC::Message::PRIORITY_NORMAL); - - // Message 1 handled by the first filter. - host.HandleMessage(message1, &context); - g_handler_completion.Wait(); - EXPECT_EQ(filter1->last_handled_msg().type(), message1.type()); - EXPECT_EQ(filter1->last_task_runner(), bg_thread1.task_runner()); - EXPECT_EQ(host.last_reply_msg().type(), - static_cast<uint32_t>(REPLY_MSG1_TYPE)); - EXPECT_EQ(host.last_reply_task_runner(), io_thread.task_runner()); - g_handler_completion.Reset(); - - // Message 2 handled by the second filter. - host.HandleMessage(message2, &context); - g_handler_completion.Wait(); - EXPECT_EQ(filter2->last_handled_msg().type(), message2.type()); - EXPECT_EQ(filter2->last_task_runner(), bg_thread2.task_runner()); - EXPECT_EQ(host.last_reply_msg().type(), - static_cast<uint32_t>(REPLY_MSG2_TYPE)); - EXPECT_EQ(host.last_reply_task_runner(), io_thread.task_runner()); - g_handler_completion.Reset(); - - // Message 3 handled by the resource host. - host.HandleMessage(message3, &context); - EXPECT_EQ(host.last_handled_msg().type(), message3.type()); - EXPECT_EQ(host.last_reply_msg().type(), - static_cast<uint32_t>(REPLY_MSG3_TYPE)); - - io_thread.Stop(); - bg_thread1.Stop(); - bg_thread2.Stop(); - } -}; - -// Test that messages are filtered correctly and handlers are run on the correct -// threads. -TEST_F(ResourceMessageFilterTest, TestHandleMessage) { - // ResourceMessageFilter instances need to be created on a thread with message - // loop. Therefore, we create a message loop and run the testing logic as a - // task on it. - base::test::SingleThreadTaskEnvironment task_environment; - - // It should be safe to use base::Unretained() because the object won't be - // destroyed before the task is run. - task_environment.GetMainThreadTaskRunner()->PostTask( - FROM_HERE, - base::BindOnce(&ResourceMessageFilterTest::TestHandleMessageImpl, - base::Unretained(this))); - - base::RunLoop().RunUntilIdle(); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/BUILD.gn b/proxy/BUILD.gn index fc97758..f83a896 100644 --- a/proxy/BUILD.gn +++ b/proxy/BUILD.gn
@@ -325,26 +325,3 @@ deps += [ "//skia" ] } } - -static_library("test_support") { - testonly = true - - sources = [ - "ppapi_proxy_test.cc", - "ppapi_proxy_test.h", - "resource_message_test_sink.cc", - "resource_message_test_sink.h", - ] - - public_deps = [ ":proxy" ] - deps = [ - "//base/test:test_support", - "//ipc", - "//ipc:test_support", - "//ppapi/proxy", - "//ppapi/shared_impl", - "//ppapi/shared_impl:test_support", - "//testing/gmock", - "//testing/gtest", - ] -}
diff --git a/proxy/device_enumeration_resource_helper_unittest.cc b/proxy/device_enumeration_resource_helper_unittest.cc deleted file mode 100644 index baacf74..0000000 --- a/proxy/device_enumeration_resource_helper_unittest.cc +++ /dev/null
@@ -1,416 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include <stddef.h> -#include <stdint.h> - -#include "base/compiler_specific.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/proxy/connection.h" -#include "ppapi/proxy/device_enumeration_resource_helper.h" -#include "ppapi/proxy/plugin_message_filter.h" -#include "ppapi/proxy/plugin_resource.h" -#include "ppapi/proxy/plugin_resource_tracker.h" -#include "ppapi/proxy/plugin_var_tracker.h" -#include "ppapi/proxy/ppapi_message_utils.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/ppb_device_ref_shared.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/thunk/enter.h" -#include "ppapi/thunk/ppb_device_ref_api.h" -#include "ppapi/thunk/thunk.h" - -namespace ppapi { -namespace proxy { - -namespace { - -typedef PluginProxyTest DeviceEnumerationResourceHelperTest; - -Connection GetConnection(PluginProxyTestHarness* harness) { - CHECK(harness->GetGlobals()->IsPluginGlobals()); - - return Connection( - static_cast<PluginGlobals*>(harness->GetGlobals())->GetBrowserSender(), - harness->plugin_dispatcher(), 0); -} - -bool CompareDeviceRef(PluginVarTracker* var_tracker, - PP_Resource resource, - const DeviceRefData& expected) { - thunk::EnterResourceNoLock<thunk::PPB_DeviceRef_API> enter(resource, true); - if (enter.failed()) - return false; - - if (expected.type != enter.object()->GetType()) - return false; - - PP_Var name_pp_var = enter.object()->GetName(); - bool result = false; - do { - Var* name_var = var_tracker->GetVar(name_pp_var); - if (!name_var) - break; - StringVar* name_string_var = name_var->AsStringVar(); - if (!name_string_var) - break; - if (expected.name != name_string_var->value()) - break; - - result = true; - } while (false); - var_tracker->ReleaseVar(name_pp_var); - return result; -} - -class TestResource : public PluginResource { - public: - TestResource(Connection connection, PP_Instance instance) - : PluginResource(connection, instance), - device_enumeration_(this) { - } - - TestResource(const TestResource&) = delete; - TestResource& operator=(const TestResource&) = delete; - - ~TestResource() override {} - - void OnReplyReceived(const ResourceMessageReplyParams& params, - const IPC::Message& msg) override { - if (!device_enumeration_.HandleReply(params, msg)) - PluginResource::OnReplyReceived(params, msg); - } - - DeviceEnumerationResourceHelper& device_enumeration() { - return device_enumeration_; - } - - private: - DeviceEnumerationResourceHelper device_enumeration_; -}; - -class TestCallback { - public: - TestCallback() : called_(false), result_(PP_ERROR_FAILED) { - } - - TestCallback(const TestCallback&) = delete; - TestCallback& operator=(const TestCallback&) = delete; - - ~TestCallback() { - CHECK(called_); - } - - PP_CompletionCallback MakeCompletionCallback() { - return PP_MakeCompletionCallback(&CompletionCallbackBody, this); - } - - bool called() const { return called_; } - int32_t result() const { return result_; } - - private: - static void CompletionCallbackBody(void* user_data, int32_t result) { - TestCallback* callback = static_cast<TestCallback*>(user_data); - - CHECK(!callback->called_); - callback->called_ = true; - callback->result_ = result; - } - - bool called_; - int32_t result_; -}; - -class TestArrayOutput { - public: - explicit TestArrayOutput(PluginResourceTracker* resource_tracker) - : data_(NULL), - count_(0), - resource_tracker_(resource_tracker) { - } - - TestArrayOutput(const TestArrayOutput&) = delete; - TestArrayOutput& operator=(const TestArrayOutput&) = delete; - - ~TestArrayOutput() { - if (count_ > 0) { - for (size_t i = 0; i < count_; ++i) - resource_tracker_->ReleaseResource(data_[i]); - delete [] data_; - } - } - - PP_ArrayOutput MakeArrayOutput() { - PP_ArrayOutput array_output = { &GetDataBuffer, this }; - return array_output; - } - - const PP_Resource* data() const { return data_; } - uint32_t count() const { return count_; } - - private: - static void* GetDataBuffer(void* user_data, - uint32_t element_count, - uint32_t element_size) { - CHECK_EQ(element_size, sizeof(PP_Resource)); - - TestArrayOutput* output = static_cast<TestArrayOutput*>(user_data); - CHECK(!output->data_); - - output->count_ = element_count; - if (element_count > 0) - output->data_ = new PP_Resource[element_count]; - else - output->data_ = NULL; - - return output->data_; - } - - PP_Resource* data_; - uint32_t count_; - PluginResourceTracker* resource_tracker_; -}; - -class TestMonitorDeviceChange { - public: - explicit TestMonitorDeviceChange(PluginVarTracker* var_tracker) - : called_(false), - same_as_expected_(false), - var_tracker_(var_tracker) { - } - - TestMonitorDeviceChange(const TestMonitorDeviceChange&) = delete; - TestMonitorDeviceChange& operator=(const TestMonitorDeviceChange&) = delete; - - ~TestMonitorDeviceChange() {} - - void SetExpectedResult(const std::vector<DeviceRefData>& expected) { - called_ = false; - same_as_expected_ = false; - expected_ = expected; - } - - bool called() const { return called_; } - - bool same_as_expected() const { return same_as_expected_; } - - static void MonitorDeviceChangeCallback(void* user_data, - uint32_t device_count, - const PP_Resource devices[]) { - ProxyAutoLock lock; - TestMonitorDeviceChange* helper = - static_cast<TestMonitorDeviceChange*>(user_data); - CHECK(!helper->called_); - - helper->called_ = true; - helper->same_as_expected_ = false; - if (device_count != helper->expected_.size()) - return; - for (size_t i = 0; i < device_count; ++i) { - if (!CompareDeviceRef(helper->var_tracker_, devices[i], - helper->expected_[i])) { - return; - } - } - helper->same_as_expected_ = true; - } - - private: - bool called_; - bool same_as_expected_; - std::vector<DeviceRefData> expected_; - PluginVarTracker* var_tracker_; -}; - -} // namespace - -TEST_F(DeviceEnumerationResourceHelperTest, EnumerateDevices) { - ProxyAutoLock lock; - - scoped_refptr<TestResource> resource( - new TestResource(GetConnection(this), pp_instance())); - DeviceEnumerationResourceHelper& device_enumeration = - resource->device_enumeration(); - - TestArrayOutput output(&resource_tracker()); - TestCallback callback; - scoped_refptr<TrackedCallback> tracked_callback( - new TrackedCallback(resource.get(), callback.MakeCompletionCallback())); - int32_t result = device_enumeration.EnumerateDevices(output.MakeArrayOutput(), - tracked_callback); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - // Should have sent an EnumerateDevices message. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_DeviceEnumeration_EnumerateDevices::ID, ¶ms, &msg)); - - // Synthesize a response. - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(PP_OK); - std::vector<DeviceRefData> data; - DeviceRefData data_item; - data_item.type = PP_DEVICETYPE_DEV_AUDIOCAPTURE; - data_item.name = "name_1"; - data_item.id = "id_1"; - data.push_back(data_item); - data_item.type = PP_DEVICETYPE_DEV_VIDEOCAPTURE; - data_item.name = "name_2"; - data_item.id = "id_2"; - data.push_back(data_item); - - { - ProxyAutoUnlock unlock; - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_DeviceEnumeration_EnumerateDevicesReply(data)); - } - EXPECT_TRUE(callback.called()); - EXPECT_EQ(PP_OK, callback.result()); - EXPECT_EQ(2U, output.count()); - for (size_t i = 0; i < output.count(); ++i) - EXPECT_TRUE(CompareDeviceRef(&var_tracker(), output.data()[i], data[i])); -} - -TEST_F(DeviceEnumerationResourceHelperTest, MonitorDeviceChange) { - ProxyAutoLock lock; - - scoped_refptr<TestResource> resource( - new TestResource(GetConnection(this), pp_instance())); - DeviceEnumerationResourceHelper& device_enumeration = - resource->device_enumeration(); - - TestMonitorDeviceChange helper(&var_tracker()); - - int32_t result = device_enumeration.MonitorDeviceChange( - &TestMonitorDeviceChange::MonitorDeviceChangeCallback, &helper); - ASSERT_EQ(PP_OK, result); - - // Should have sent a MonitorDeviceChange message. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_DeviceEnumeration_MonitorDeviceChange::ID, ¶ms, &msg)); - sink().ClearMessages(); - - uint32_t callback_id = 0; - ASSERT_TRUE(UnpackMessage<PpapiHostMsg_DeviceEnumeration_MonitorDeviceChange>( - msg, &callback_id)); - - ResourceMessageReplyParams reply_params(params.pp_resource(), 0); - reply_params.set_result(PP_OK); - std::vector<DeviceRefData> data; - - helper.SetExpectedResult(data); - - { - ProxyAutoUnlock unlock; - // Synthesize a response with no device. - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_DeviceEnumeration_NotifyDeviceChange( - callback_id, data)); - } - EXPECT_TRUE(helper.called() && helper.same_as_expected()); - - DeviceRefData data_item; - data_item.type = PP_DEVICETYPE_DEV_AUDIOCAPTURE; - data_item.name = "name_1"; - data_item.id = "id_1"; - data.push_back(data_item); - data_item.type = PP_DEVICETYPE_DEV_VIDEOCAPTURE; - data_item.name = "name_2"; - data_item.id = "id_2"; - data.push_back(data_item); - - helper.SetExpectedResult(data); - - { - ProxyAutoUnlock unlock; - // Synthesize a response with some devices. - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_DeviceEnumeration_NotifyDeviceChange( - callback_id, data)); - } - EXPECT_TRUE(helper.called() && helper.same_as_expected()); - - TestMonitorDeviceChange helper2(&var_tracker()); - - result = device_enumeration.MonitorDeviceChange( - &TestMonitorDeviceChange::MonitorDeviceChangeCallback, &helper2); - ASSERT_EQ(PP_OK, result); - - // Should have sent another MonitorDeviceChange message. - ResourceMessageCallParams params2; - IPC::Message msg2; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_DeviceEnumeration_MonitorDeviceChange::ID, ¶ms2, &msg2)); - sink().ClearMessages(); - - uint32_t callback_id2 = 0; - ASSERT_TRUE(UnpackMessage<PpapiHostMsg_DeviceEnumeration_MonitorDeviceChange>( - msg2, &callback_id2)); - - helper.SetExpectedResult(data); - helper2.SetExpectedResult(data); - { - ProxyAutoUnlock unlock; - // |helper2| should receive the result while |helper| shouldn't. - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_DeviceEnumeration_NotifyDeviceChange( - callback_id2, data)); - } - EXPECT_TRUE(helper2.called() && helper2.same_as_expected()); - EXPECT_FALSE(helper.called()); - - helper.SetExpectedResult(data); - helper2.SetExpectedResult(data); - { - ProxyAutoUnlock unlock; - // Even if a message with |callback_id| arrives. |helper| shouldn't receive - // the result. - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_DeviceEnumeration_NotifyDeviceChange( - callback_id, data)); - } - EXPECT_FALSE(helper2.called()); - EXPECT_FALSE(helper.called()); - - result = device_enumeration.MonitorDeviceChange(NULL, NULL); - ASSERT_EQ(PP_OK, result); - - // Should have sent a StopMonitoringDeviceChange message. - ResourceMessageCallParams params3; - IPC::Message msg3; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_DeviceEnumeration_StopMonitoringDeviceChange::ID, - ¶ms3, &msg3)); - sink().ClearMessages(); - - helper2.SetExpectedResult(data); - { - ProxyAutoUnlock unlock; - // |helper2| shouldn't receive any result any more. - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_DeviceEnumeration_NotifyDeviceChange( - callback_id2, data)); - } - EXPECT_FALSE(helper2.called()); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/file_chooser_resource_unittest.cc b/proxy/file_chooser_resource_unittest.cc deleted file mode 100644 index 306d4ef..0000000 --- a/proxy/file_chooser_resource_unittest.cc +++ /dev/null
@@ -1,154 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include <stddef.h> -#include <stdint.h> - -#include "ppapi/c/dev/ppb_file_chooser_dev.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_file_ref.h" -#include "ppapi/proxy/file_chooser_resource.h" -#include "ppapi/proxy/locking_resource_releaser.h" -#include "ppapi/proxy/plugin_message_filter.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/scoped_pp_var.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/thunk/thunk.h" - -namespace ppapi { -namespace proxy { - -namespace { - -typedef PluginProxyTest FileChooserResourceTest; - -void* GetFileRefDataBuffer(void* user_data, - uint32_t element_count, - uint32_t element_size) { - EXPECT_TRUE(element_size == sizeof(PP_Resource)); - std::vector<PP_Resource>* output = - static_cast<std::vector<PP_Resource>*>(user_data); - output->resize(element_count); - if (element_count > 0) - return &(*output)[0]; - return NULL; -} - -void DoNothingCallback(void* user_data, int32_t result) { -} - -// Calls PopulateAcceptTypes and verifies that the resulting array contains -// the given values. The values may be NULL if there aren't expected to be -// that many results. -bool CheckParseAcceptType(const std::string& input, - const char* expected1, - const char* expected2) { - std::vector<std::string> output; - FileChooserResource::PopulateAcceptTypes(input, &output); - - const size_t kCount = 2; - const char* expected[kCount] = { expected1, expected2 }; - - for (size_t i = 0; i < kCount; i++) { - if (!expected[i]) - return i == output.size(); - if (output.size() <= i) - return false; - if (output[i] != expected[i]) - return false; - } - - return output.size() == kCount; -} - -} // namespace - -// Does a full test of Show() and reply functionality in the plugin side using -// the public C interfaces. -TEST_F(FileChooserResourceTest, Show) { - const PPB_FileChooser_Dev_0_6* chooser_iface = - thunk::GetPPB_FileChooser_Dev_0_6_Thunk(); - LockingResourceReleaser res( - chooser_iface->Create(pp_instance(), PP_FILECHOOSERMODE_OPEN, - PP_MakeUndefined())); - - std::vector<PP_Resource> dest; - PP_ArrayOutput output; - output.GetDataBuffer = &GetFileRefDataBuffer; - output.user_data = &dest; - - int32_t result = chooser_iface->Show( - res.get(), output, PP_MakeCompletionCallback(&DoNothingCallback, NULL)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - // Should have sent a "show" message. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_FileChooser_Show::ID, ¶ms, &msg)); - - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(PP_OK); - - // Synthesize a response with one file ref in it. Note that it must have a - // pending_host_resource_id set. Since there isn't actually a host, this can - // be whatever we want. - std::vector<FileRefCreateInfo> create_info_array; - FileRefCreateInfo create_info; - create_info.file_system_type = PP_FILESYSTEMTYPE_EXTERNAL; - create_info.display_name = "bar"; - create_info.browser_pending_host_resource_id = 12; - create_info.renderer_pending_host_resource_id = 15; - create_info_array.push_back(create_info); - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, PpapiPluginMsg_FileChooser_ShowReply(create_info_array)); - - // Should have populated our vector. - ASSERT_EQ(1u, dest.size()); - LockingResourceReleaser dest_deletor(dest[0]); // Ensure it's cleaned up. - - const PPB_FileRef_1_0* file_ref_iface = thunk::GetPPB_FileRef_1_0_Thunk(); - EXPECT_EQ(PP_FILESYSTEMTYPE_EXTERNAL, - file_ref_iface->GetFileSystemType(dest[0])); - - PP_Var name_var(file_ref_iface->GetName(dest[0])); - { - ProxyAutoLock lock; - ScopedPPVar release_name_var(ScopedPPVar::PassRef(), name_var); - EXPECT_VAR_IS_STRING("bar", name_var); - } - PP_Var path_var(file_ref_iface->GetPath(dest[0])); - { - ProxyAutoLock lock; - ScopedPPVar release_path_var(ScopedPPVar::PassRef(), path_var); - EXPECT_EQ(PP_VARTYPE_UNDEFINED, path_var.type); - } -} - -TEST_F(FileChooserResourceTest, PopulateAcceptTypes) { - EXPECT_TRUE(CheckParseAcceptType(std::string(), NULL, NULL)); - EXPECT_TRUE(CheckParseAcceptType("/", NULL, NULL)); - EXPECT_TRUE(CheckParseAcceptType(".", NULL, NULL)); - EXPECT_TRUE(CheckParseAcceptType(",, , ", NULL, NULL)); - - EXPECT_TRUE(CheckParseAcceptType("app/txt", "app/txt", NULL)); - EXPECT_TRUE(CheckParseAcceptType("app/txt,app/pdf", "app/txt", "app/pdf")); - EXPECT_TRUE(CheckParseAcceptType(" app/txt , app/pdf ", - "app/txt", "app/pdf")); - - // No dot or slash ones should be skipped. - EXPECT_TRUE(CheckParseAcceptType("foo", NULL, NULL)); - EXPECT_TRUE(CheckParseAcceptType("foo,.txt", ".txt", NULL)); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/file_system_resource_unittest.cc b/proxy/file_system_resource_unittest.cc deleted file mode 100644 index c085931..0000000 --- a/proxy/file_system_resource_unittest.cc +++ /dev/null
@@ -1,371 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "base/functional/bind.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/c/ppb_file_ref.h" -#include "ppapi/c/ppb_file_system.h" -#include "ppapi/proxy/file_system_resource.h" -#include "ppapi/proxy/locking_resource_releaser.h" -#include "ppapi/proxy/plugin_message_filter.h" -#include "ppapi/proxy/ppapi_message_utils.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/scoped_pp_var.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/thunk/enter.h" -#include "ppapi/thunk/ppb_file_system_api.h" -#include "ppapi/thunk/thunk.h" - -using ppapi::proxy::ResourceMessageTestSink; -using ppapi::thunk::EnterResource; -using ppapi::thunk::PPB_FileSystem_API; - -namespace ppapi { -namespace proxy { - -namespace { - -const int64_t kExpectedFileSystemSize = 100; -const int64_t kQuotaRequestAmount1 = 10; -const int64_t kQuotaRequestAmount2 = 20; - -class MockCompletionCallback { - public: - MockCompletionCallback() : called_(false) {} - - bool called() { return called_; } - int32_t result() { return result_; } - - static void Callback(void* user_data, int32_t result) { - MockCompletionCallback* that = - reinterpret_cast<MockCompletionCallback*>(user_data); - that->called_ = true; - that->result_ = result; - } - - private: - bool called_; - int32_t result_; -}; - -class MockRequestQuotaCallback { - public: - MockRequestQuotaCallback() : called_(false) {} - - bool called() { return called_; } - int64_t result() { return result_; } - - void Reset() { called_ = false; } - - void Callback(int64_t result) { - ASSERT_FALSE(called_); - called_ = true; - result_ = result; - } - - private: - bool called_; - int64_t result_; -}; - -class FileSystemResourceTest : public PluginProxyTest { - public: - const PPB_FileSystem_1_0* file_system_iface; - const PPB_FileRef_1_1* file_ref_iface; - const PPB_FileIO_1_1* file_io_iface; - - FileSystemResourceTest() - : file_system_iface(thunk::GetPPB_FileSystem_1_0_Thunk()), - file_ref_iface(thunk::GetPPB_FileRef_1_1_Thunk()), - file_io_iface(thunk::GetPPB_FileIO_1_1_Thunk()) { - } - - void SendReply(const ResourceMessageCallParams& params, - int32_t result, - const IPC::Message& nested_message) { - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(result); - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, nested_message); - } - - void SendOpenReply(const ResourceMessageCallParams& params, int32_t result) { - SendReply(params, result, PpapiPluginMsg_FileSystem_OpenReply()); - } - - // Opens the given file system. - void OpenFileSystem(PP_Resource file_system) { - MockCompletionCallback cb; - int32_t result = file_system_iface->Open( - file_system, - kExpectedFileSystemSize, - PP_MakeCompletionCallback(&MockCompletionCallback::Callback, &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - // Should have sent two new "open" messages to the browser and renderer. - ResourceMessageTestSink::ResourceCallVector open_messages = - sink().GetAllResourceCallsMatching(PpapiHostMsg_FileSystem_Open::ID); - ASSERT_EQ(2U, open_messages.size()); - sink().ClearMessages(); - - // The resource is expecting two replies. - SendOpenReply(open_messages[0].first, PP_OK); - SendOpenReply(open_messages[1].first, PP_OK); - - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_OK, cb.result()); - } - - // Opens the given file in the given file system. Since there is no host, - // the file handle will be invalid. - void OpenFile(PP_Resource file_io, - PP_Resource file_ref, - PP_Resource file_system) { - MockCompletionCallback cb; - int32_t result = file_io_iface->Open( - file_io, - file_ref, - PP_FILEOPENFLAG_WRITE, - PP_MakeCompletionCallback(&MockCompletionCallback::Callback, &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - // Should have sent an "open" message. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_FileIO_Open::ID, ¶ms, &msg)); - sink().ClearMessages(); - - // Send a success reply. - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(PP_OK); - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_FileIO_OpenReply(file_system, - 0 /* max_written_offset */)); - } -}; - -} // namespace - -// Test that Open fails if either host returns failure. The other tests exercise -// the case where both hosts return PP_OK. -TEST_F(FileSystemResourceTest, OpenFailure) { - // Fail if the first reply doesn't return PP_OK. - { - LockingResourceReleaser file_system( - file_system_iface->Create(pp_instance(), - PP_FILESYSTEMTYPE_LOCALTEMPORARY)); - - MockCompletionCallback cb; - int32_t result = file_system_iface->Open( - file_system.get(), - kExpectedFileSystemSize, - PP_MakeCompletionCallback(&MockCompletionCallback::Callback, &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - ResourceMessageTestSink::ResourceCallVector open_messages = - sink().GetAllResourceCallsMatching(PpapiHostMsg_FileSystem_Open::ID); - ASSERT_EQ(2U, open_messages.size()); - sink().ClearMessages(); - - SendOpenReply(open_messages[0].first, PP_ERROR_FAILED); - SendOpenReply(open_messages[1].first, PP_OK); - - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - } - // Fail if the second reply doesn't return PP_OK. - { - LockingResourceReleaser file_system( - file_system_iface->Create(pp_instance(), - PP_FILESYSTEMTYPE_LOCALTEMPORARY)); - - MockCompletionCallback cb; - int32_t result = file_system_iface->Open( - file_system.get(), - kExpectedFileSystemSize, - PP_MakeCompletionCallback(&MockCompletionCallback::Callback, &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - ResourceMessageTestSink::ResourceCallVector open_messages = - sink().GetAllResourceCallsMatching(PpapiHostMsg_FileSystem_Open::ID); - ASSERT_EQ(2U, open_messages.size()); - sink().ClearMessages(); - - SendOpenReply(open_messages[0].first, PP_OK); - SendOpenReply(open_messages[1].first, PP_ERROR_FAILED); - - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - } -} - -TEST_F(FileSystemResourceTest, RequestQuota) { - LockingResourceReleaser file_system( - file_system_iface->Create(pp_instance(), - PP_FILESYSTEMTYPE_LOCALTEMPORARY)); - - OpenFileSystem(file_system.get()); - - // Create and open two files in the file system. FileIOResource calls - // FileSystemResource::OpenQuotaFile on success. - LockingResourceReleaser file_ref1( - file_ref_iface->Create(file_system.get(), "/file1")); - LockingResourceReleaser file_io1(file_io_iface->Create(pp_instance())); - OpenFile(file_io1.get(), file_ref1.get(), file_system.get()); - LockingResourceReleaser file_ref2( - file_ref_iface->Create(file_system.get(), "/file2")); - LockingResourceReleaser file_io2(file_io_iface->Create(pp_instance())); - OpenFile(file_io2.get(), file_ref2.get(), file_system.get()); - - EnterResource<PPB_FileSystem_API> enter(file_system.get(), true); - ASSERT_FALSE(enter.failed()); - PPB_FileSystem_API* file_system_api = enter.object(); - - MockRequestQuotaCallback cb1; - int64_t result = file_system_api->RequestQuota( - kQuotaRequestAmount1, base::BindOnce(&MockRequestQuotaCallback::Callback, - base::Unretained(&cb1))); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - // Should have sent a "reserve quota" message, with the amount of the request - // and a map of all currently open files to their max written offsets. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_FileSystem_ReserveQuota::ID, ¶ms, &msg)); - sink().ClearMessages(); - - int64_t amount = 0; - FileGrowthMap file_growths; - ASSERT_TRUE(UnpackMessage<PpapiHostMsg_FileSystem_ReserveQuota>( - msg, &amount, &file_growths)); - ASSERT_EQ(kQuotaRequestAmount1, amount); - ASSERT_EQ(2U, file_growths.size()); - ASSERT_EQ(0, file_growths[file_io1.get()].max_written_offset); - ASSERT_EQ(0, file_growths[file_io2.get()].max_written_offset); - - // Make another request while the "reserve quota" message is pending. - MockRequestQuotaCallback cb2; - result = file_system_api->RequestQuota( - kQuotaRequestAmount2, base::BindOnce(&MockRequestQuotaCallback::Callback, - base::Unretained(&cb2))); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - // No new "reserve quota" message should be sent while one is pending. - ASSERT_FALSE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_FileSystem_ReserveQuota::ID, ¶ms, &msg)); - { - ProxyAutoUnlock unlock_to_prevent_deadlock; - // Reply with quota reservation amount sufficient to cover both requests. - // Both callbacks should be called with the requests granted. - SendReply(params, - PP_OK, - PpapiPluginMsg_FileSystem_ReserveQuotaReply( - kQuotaRequestAmount1 + kQuotaRequestAmount2, - FileGrowthMapToFileSizeMapForTesting(file_growths))); - } - ASSERT_TRUE(cb1.called()); - ASSERT_EQ(kQuotaRequestAmount1, cb1.result()); - ASSERT_TRUE(cb2.called()); - ASSERT_EQ(kQuotaRequestAmount2, cb2.result()); - cb1.Reset(); - cb2.Reset(); - - // All requests should fail when insufficient quota is returned to satisfy - // the first request. - result = file_system_api->RequestQuota( - kQuotaRequestAmount1, base::BindOnce(&MockRequestQuotaCallback::Callback, - base::Unretained(&cb1))); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = file_system_api->RequestQuota( - kQuotaRequestAmount2, base::BindOnce(&MockRequestQuotaCallback::Callback, - base::Unretained(&cb2))); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_FileSystem_ReserveQuota::ID, ¶ms, &msg)); - sink().ClearMessages(); - { - ProxyAutoUnlock unlock_to_prevent_deadlock; - // Reply with quota reservation amount insufficient to cover the first - // request. - SendReply(params, - PP_OK, - PpapiPluginMsg_FileSystem_ReserveQuotaReply( - kQuotaRequestAmount1 - 1, - FileGrowthMapToFileSizeMapForTesting(file_growths))); - } - ASSERT_TRUE(cb1.called()); - ASSERT_EQ(0, cb1.result()); - ASSERT_TRUE(cb2.called()); - ASSERT_EQ(0, cb2.result()); - cb1.Reset(); - cb2.Reset(); - - // A new request should be made if the quota reservation is enough to satisfy - // at least one request. - result = file_system_api->RequestQuota( - kQuotaRequestAmount1, base::BindOnce(&MockRequestQuotaCallback::Callback, - base::Unretained(&cb1))); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = file_system_api->RequestQuota( - kQuotaRequestAmount2, base::BindOnce(&MockRequestQuotaCallback::Callback, - base::Unretained(&cb2))); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_FileSystem_ReserveQuota::ID, ¶ms, &msg)); - sink().ClearMessages(); - { - ProxyAutoUnlock unlock_to_prevent_deadlock; - // Reply with quota reservation amount sufficient only to cover the first - // request. - SendReply(params, - PP_OK, - PpapiPluginMsg_FileSystem_ReserveQuotaReply( - kQuotaRequestAmount1, - FileGrowthMapToFileSizeMapForTesting(file_growths))); - } - ASSERT_TRUE(cb1.called()); - ASSERT_EQ(kQuotaRequestAmount1, cb1.result()); - ASSERT_FALSE(cb2.called()); - - // Another request message should have been sent. - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_FileSystem_ReserveQuota::ID, ¶ms, &msg)); - sink().ClearMessages(); - { - ProxyAutoUnlock unlock_to_prevent_deadlock; - // Reply with quota reservation amount sufficient to cover the second - // request and some extra. - SendReply(params, - PP_OK, - PpapiPluginMsg_FileSystem_ReserveQuotaReply( - kQuotaRequestAmount1 + kQuotaRequestAmount2, - FileGrowthMapToFileSizeMapForTesting(file_growths))); - } - - ASSERT_TRUE(cb2.called()); - ASSERT_EQ(kQuotaRequestAmount2, cb2.result()); - cb1.Reset(); - cb2.Reset(); - - // There is kQuotaRequestAmount1 of quota left, and a request for it should - // succeed immediately. - result = file_system_api->RequestQuota( - kQuotaRequestAmount1, base::BindOnce(&MockRequestQuotaCallback::Callback, - base::Unretained(&cb1))); - ASSERT_EQ(kQuotaRequestAmount1, result); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/interface_list_unittest.cc b/proxy/interface_list_unittest.cc deleted file mode 100644 index 230c354..0000000 --- a/proxy/interface_list_unittest.cc +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/interface_list.h" -#include "base/hash/hash.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/proxy/ppapi_proxy_test.h" - -namespace ppapi { -namespace proxy { - -class InterfaceListTest : public PluginProxyTest { - public: - // Wrapper function so we can use the private InterfaceList::AddPPB. - void AddPPB(InterfaceList* list, - const char* iface_name, void* iface_addr, Permission perm) { - list->AddPPB(iface_name, iface_addr, perm); - } - - // Wrapper function so we can use the private - // InterfaceList::HashInterfaceName. - int HashInterfaceName(const std::string& name) { - return InterfaceList::HashInterfaceName(name); - } -}; - -// Tests looking up a stable interface. -TEST_F(InterfaceListTest, Stable) { - InterfaceList list; - ASSERT_TRUE(list.GetInterfaceForPPB(PPB_CORE_INTERFACE_1_0) != NULL); - ASSERT_TRUE(list.GetInterfaceForPPB("FakeUnknownInterface") == NULL); -} - -// Tests that dev channel restrictions work properly. -TEST_F(InterfaceListTest, DevChannel) { - InterfaceList list; - // "Dev channel" interface. - static const char* dev_channel_iface_name = "TestDevChannelInterface"; - void* dev_channel_iface_addr = (void*)0xdeadbeef; - // "Dev" interface - static const char* dev_iface_name = "TestDevInterface"; - void* dev_iface_addr = (void*)0xcafefade; - - AddPPB(&list, dev_channel_iface_name, dev_channel_iface_addr, - PERMISSION_DEV_CHANNEL); - AddPPB(&list, dev_iface_name, dev_iface_addr, PERMISSION_DEV); - - InterfaceList::SetProcessGlobalPermissions( - PpapiPermissions(PERMISSION_NONE)); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_channel_iface_name) == NULL); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_iface_name) == NULL); - - InterfaceList::SetProcessGlobalPermissions( - PpapiPermissions(PERMISSION_DEV_CHANNEL)); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_channel_iface_name) == - dev_channel_iface_addr); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_iface_name) == NULL); - - InterfaceList::SetProcessGlobalPermissions( - PpapiPermissions(PERMISSION_DEV)); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_channel_iface_name) == NULL); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_iface_name) == dev_iface_addr); - - InterfaceList::SetProcessGlobalPermissions( - PpapiPermissions(PERMISSION_DEV | PERMISSION_DEV_CHANNEL)); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_channel_iface_name) == - dev_channel_iface_addr); - ASSERT_TRUE(list.GetInterfaceForPPB(dev_iface_name) == dev_iface_addr); -} - -// Test that the hash function provided by base::Hash is unchanged. This is so -// that we will generate correct values when logging interface use to UMA. -TEST_F(InterfaceListTest, InterfaceHash) { - EXPECT_EQ(612625164, HashInterfaceName("PPB_InputEvent;1.0")); - EXPECT_EQ(79708274, HashInterfaceName("PPB_TCPSocket;1.1")); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/nacl_message_scanner_unittest.cc b/proxy/nacl_message_scanner_unittest.cc deleted file mode 100644 index fc3566e..0000000 --- a/proxy/nacl_message_scanner_unittest.cc +++ /dev/null
@@ -1,270 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "ipc/ipc_message.h" -#include "ppapi/proxy/nacl_message_scanner.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/serialized_handle.h" -#include "ppapi/shared_impl/host_resource.h" - -namespace ppapi { -namespace proxy { - -namespace { -const PP_Resource kInvalidResource = 0; -const PP_Resource kFileSystem = 1; -const PP_Resource kFileIO = 2; -const int64_t kQuotaReservationAmount = 100; -} - -class NaClMessageScannerTest : public PluginProxyTest { - public: - NaClMessageScannerTest() {} - - NaClMessageScanner::FileSystem* FindFileSystem( - const NaClMessageScanner& scanner, - PP_Resource file_system) { - NaClMessageScanner::FileSystemMap::const_iterator it = - scanner.file_systems_.find(file_system); - return (it != scanner.file_systems_.end()) ? it->second : NULL; - } - - NaClMessageScanner::FileIO* FindFileIO( - const NaClMessageScanner& scanner, - PP_Resource file_io) { - NaClMessageScanner::FileIOMap::const_iterator it = - scanner.files_.find(file_io); - return (it != scanner.files_.end()) ? it->second : NULL; - } - - void OpenQuotaFile(NaClMessageScanner* scanner, - PP_Resource file_io, - PP_Resource file_system) { - std::vector<SerializedHandle> unused_handles; - ResourceMessageReplyParams fio_reply_params(file_io, 0); - std::unique_ptr<IPC::Message> new_msg_ptr; - scanner->ScanMessage( - PpapiPluginMsg_ResourceReply( - fio_reply_params, - PpapiPluginMsg_FileIO_OpenReply(file_system, 0)), - PpapiPluginMsg_ResourceReply::ID, - &unused_handles, - &new_msg_ptr); - EXPECT_FALSE(new_msg_ptr); - } -}; - -TEST_F(NaClMessageScannerTest, FileOpenClose) { - NaClMessageScanner test; - std::vector<SerializedHandle> unused_handles; - ResourceMessageCallParams fio_call_params(kFileIO, 0); - ResourceMessageCallParams fs_call_params(kFileSystem, 0); - ResourceMessageReplyParams fio_reply_params(kFileIO, 0); - ResourceMessageReplyParams fs_reply_params(kFileSystem, 0); - std::unique_ptr<IPC::Message> new_msg_ptr; - - EXPECT_EQ(NULL, FindFileSystem(test, kFileSystem)); - EXPECT_EQ(NULL, FindFileIO(test, kFileIO)); - - // Open a file, not in a quota file system. - test.ScanMessage( - PpapiPluginMsg_ResourceReply( - fio_reply_params, - PpapiPluginMsg_FileIO_OpenReply(kInvalidResource, 0)), - PpapiPluginMsg_ResourceReply::ID, - &unused_handles, - &new_msg_ptr); - EXPECT_FALSE(new_msg_ptr); - EXPECT_FALSE(FindFileSystem(test, kFileSystem)); - EXPECT_FALSE(FindFileIO(test, kFileIO)); - - // Open a file in a quota file system; info objects for it and its file system - // should be created. - OpenQuotaFile(&test, kFileIO, kFileSystem); - NaClMessageScanner::FileSystem* fs = FindFileSystem(test, kFileSystem); - NaClMessageScanner::FileIO* fio = FindFileIO(test, kFileIO); - EXPECT_TRUE(fs); - EXPECT_EQ(0, fs->reserved_quota()); - EXPECT_TRUE(fio); - EXPECT_EQ(0, fio->max_written_offset()); - - const int64_t kNewFileSize = 10; - fio->SetMaxWrittenOffset(kNewFileSize); - - // We should not be able to under-report max_written_offset when closing. - test.ScanUntrustedMessage( - PpapiHostMsg_ResourceCall( - fio_call_params, - PpapiHostMsg_FileIO_Close(FileGrowth(0, 0))), - &new_msg_ptr); - EXPECT_TRUE(new_msg_ptr); - ResourceMessageCallParams call_params; - IPC::Message nested_msg; - FileGrowth file_growth; - EXPECT_TRUE(UnpackMessage<PpapiHostMsg_ResourceCall>( - *new_msg_ptr, &call_params, &nested_msg) && - UnpackMessage<PpapiHostMsg_FileIO_Close>( - nested_msg, &file_growth)); - new_msg_ptr.reset(); - EXPECT_EQ(kNewFileSize, file_growth.max_written_offset); - EXPECT_FALSE(FindFileIO(test, kFileIO)); - - // Reopen the file. - OpenQuotaFile(&test, kFileIO, kFileSystem); - fio = FindFileIO(test, kFileIO); - fio->SetMaxWrittenOffset(kNewFileSize); - - // Close with correct max_written_offset. - test.ScanUntrustedMessage( - PpapiHostMsg_ResourceCall( - fio_call_params, - PpapiHostMsg_FileIO_Close(FileGrowth(kNewFileSize, 0))), - &new_msg_ptr); - EXPECT_FALSE(new_msg_ptr); - EXPECT_FALSE(FindFileIO(test, kFileIO)); - - // Destroy file system. - test.ScanUntrustedMessage( - PpapiHostMsg_ResourceCall( - fs_call_params, - PpapiHostMsg_ResourceDestroyed(kFileSystem)), - &new_msg_ptr); - EXPECT_FALSE(FindFileSystem(test, kFileSystem)); -} - -TEST_F(NaClMessageScannerTest, QuotaAuditing) { - NaClMessageScanner test; - std::vector<SerializedHandle> unused_handles; - ResourceMessageCallParams fio_call_params(kFileIO, 0); - ResourceMessageCallParams fs_call_params(kFileSystem, 0); - ResourceMessageReplyParams fio_reply_params(kFileIO, 0); - ResourceMessageReplyParams fs_reply_params(kFileSystem, 0); - std::unique_ptr<IPC::Message> new_msg_ptr; - - OpenQuotaFile(&test, kFileIO, kFileSystem); - NaClMessageScanner::FileSystem* fs = FindFileSystem(test, kFileSystem); - NaClMessageScanner::FileIO* fio = FindFileIO(test, kFileIO); - EXPECT_TRUE(fs); - EXPECT_EQ(0, fs->reserved_quota()); - EXPECT_TRUE(fio); - EXPECT_EQ(0, fio->max_written_offset()); - - // Without reserving quota, we should not be able to grow the file. - EXPECT_FALSE(fio->Grow(1)); - EXPECT_EQ(0, fs->reserved_quota()); - EXPECT_EQ(0, fio->max_written_offset()); - - // Receive reserved quota, and updated file sizes. - const int64_t kNewFileSize = 10; - FileSizeMap file_sizes; - file_sizes[kFileIO] = kNewFileSize; - test.ScanMessage( - PpapiPluginMsg_ResourceReply( - fs_reply_params, - PpapiPluginMsg_FileSystem_ReserveQuotaReply( - kQuotaReservationAmount, - file_sizes)), - PpapiPluginMsg_ResourceReply::ID, - &unused_handles, - &new_msg_ptr); - EXPECT_FALSE(new_msg_ptr); - EXPECT_EQ(kQuotaReservationAmount, fs->reserved_quota()); - EXPECT_EQ(kNewFileSize, fio->max_written_offset()); - - // We should be able to grow the file within quota. - EXPECT_TRUE(fio->Grow(1)); - EXPECT_EQ(kQuotaReservationAmount - 1, fs->reserved_quota()); - EXPECT_EQ(kNewFileSize + 1, fio->max_written_offset()); - - // We should not be able to grow the file over quota. - EXPECT_FALSE(fio->Grow(kQuotaReservationAmount)); - EXPECT_EQ(kQuotaReservationAmount - 1, fs->reserved_quota()); - EXPECT_EQ(kNewFileSize + 1, fio->max_written_offset()); - - // Plugin should not under-report max written offsets when reserving quota. - file_sizes[kFileIO] = 0; // should be kNewFileSize + 1. - test.ScanUntrustedMessage( - PpapiHostMsg_ResourceCall( - fio_call_params, - PpapiHostMsg_FileSystem_ReserveQuota( - kQuotaReservationAmount, - FileSizeMapToFileGrowthMapForTesting(file_sizes))), - &new_msg_ptr); - EXPECT_TRUE(new_msg_ptr); - ResourceMessageCallParams call_params; - IPC::Message nested_msg; - int64_t amount = 0; - FileGrowthMap new_file_growths; - EXPECT_TRUE(UnpackMessage<PpapiHostMsg_ResourceCall>( - *new_msg_ptr, &call_params, &nested_msg) && - UnpackMessage<PpapiHostMsg_FileSystem_ReserveQuota>( - nested_msg, &amount, &new_file_growths)); - new_msg_ptr.reset(); - EXPECT_EQ(kQuotaReservationAmount, amount); - EXPECT_EQ(kNewFileSize + 1, new_file_growths[kFileIO].max_written_offset); -} - -TEST_F(NaClMessageScannerTest, SetLength) { - NaClMessageScanner test; - std::vector<SerializedHandle> unused_handles; - ResourceMessageCallParams fio_call_params(kFileIO, 0); - ResourceMessageCallParams fs_call_params(kFileSystem, 0); - ResourceMessageReplyParams fio_reply_params(kFileIO, 0); - ResourceMessageReplyParams fs_reply_params(kFileSystem, 0); - std::unique_ptr<IPC::Message> new_msg_ptr; - - OpenQuotaFile(&test, kFileIO, kFileSystem); - NaClMessageScanner::FileSystem* fs = FindFileSystem(test, kFileSystem); - NaClMessageScanner::FileIO* fio = FindFileIO(test, kFileIO); - - // Receive reserved quota, and updated file sizes. - const int64_t kNewFileSize = 10; - FileSizeMap file_sizes; - file_sizes[kFileIO] = 0; - test.ScanMessage( - PpapiPluginMsg_ResourceReply( - fs_reply_params, - PpapiPluginMsg_FileSystem_ReserveQuotaReply( - kQuotaReservationAmount, - file_sizes)), - PpapiPluginMsg_ResourceReply::ID, - &unused_handles, - &new_msg_ptr); - - // We should be able to SetLength within quota. - test.ScanUntrustedMessage( - PpapiHostMsg_ResourceCall( - fio_call_params, - PpapiHostMsg_FileIO_SetLength(kNewFileSize)), - &new_msg_ptr); - EXPECT_FALSE(new_msg_ptr); - EXPECT_EQ(kQuotaReservationAmount - kNewFileSize, fs->reserved_quota()); - EXPECT_EQ(kNewFileSize, fio->max_written_offset()); - - // We shouldn't be able to SetLength beyond quota. The message should be - // rewritten to fail with length == -1. - test.ScanUntrustedMessage( - PpapiHostMsg_ResourceCall( - fio_call_params, - PpapiHostMsg_FileIO_SetLength(kQuotaReservationAmount + 1)), - &new_msg_ptr); - EXPECT_TRUE(new_msg_ptr); - ResourceMessageCallParams call_params; - IPC::Message nested_msg; - int64_t length = 0; - EXPECT_TRUE(UnpackMessage<PpapiHostMsg_ResourceCall>( - *new_msg_ptr, &call_params, &nested_msg) && - UnpackMessage<PpapiHostMsg_FileIO_SetLength>( - nested_msg, &length)); - new_msg_ptr.reset(); - EXPECT_EQ(-1, length); - EXPECT_EQ(kQuotaReservationAmount - kNewFileSize, fs->reserved_quota()); - EXPECT_EQ(kNewFileSize, fio->max_written_offset()); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/plugin_dispatcher_unittest.cc b/proxy/plugin_dispatcher_unittest.cc deleted file mode 100644 index 22f796b..0000000 --- a/proxy/plugin_dispatcher_unittest.cc +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ipc/ipc_message_utils.h" -#include "ppapi/c/ppb_audio.h" -#include "ppapi/c/ppp_instance.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" - -namespace ppapi { -namespace proxy { - -namespace { - -bool received_create = false; - -// Implement PPB_Audio since it's a relatively simple PPB interface and -// includes bidirectional communication. -PP_Resource Create(PP_Instance instance, PP_Resource config, - PPB_Audio_Callback audio_callback, void* user_data) { - received_create = true; - return 0; -} -PP_Bool IsAudio(PP_Resource resource) { - return PP_FALSE; -} -PP_Resource GetCurrentConfig(PP_Resource audio) { - return 0; -} -PP_Bool StartPlayback(PP_Resource audio) { - return PP_FALSE; -} -PP_Bool StopPlayback(PP_Resource audio) { - return PP_FALSE; -} - -PPB_Audio dummy_audio_interface = { - &Create, - &IsAudio, - &GetCurrentConfig, - &StartPlayback, - &StopPlayback -}; - -PPP_Instance dummy_ppp_instance_interface = {}; - -} // namespace - -class PluginDispatcherTest : public PluginProxyTest { - public: - PluginDispatcherTest() {} - - bool HasTargetProxy(ApiID id) { - return !!plugin_dispatcher()->proxies_[id].get(); - } -}; - -TEST_F(PluginDispatcherTest, SupportsInterface) { - RegisterTestInterface(PPB_AUDIO_INTERFACE, &dummy_audio_interface); - RegisterTestInterface(PPP_INSTANCE_INTERFACE, &dummy_ppp_instance_interface); - - // Sending a request for a random interface should fail. - EXPECT_FALSE(SupportsInterface("Random interface")); - - // Sending a request for a supported PPP interface should succeed. - EXPECT_TRUE(SupportsInterface(PPP_INSTANCE_INTERFACE)); -} - -TEST_F(PluginDispatcherTest, PPBCreation) { - // Sending a PPB message out of the blue should create a target proxy for - // that interface in the plugin. - EXPECT_FALSE(HasTargetProxy(API_ID_PPB_AUDIO)); - PpapiMsg_PPBAudio_NotifyAudioStreamCreated audio_msg( - API_ID_PPB_AUDIO, HostResource(), 0, - ppapi::proxy::SerializedHandle(ppapi::proxy::SerializedHandle::SOCKET), - ppapi::proxy::SerializedHandle( - ppapi::proxy::SerializedHandle::SHARED_MEMORY_REGION)); - plugin_dispatcher()->OnMessageReceived(audio_msg); - EXPECT_TRUE(HasTargetProxy(API_ID_PPB_AUDIO)); -} - -} // namespace proxy -} // namespace ppapi -
diff --git a/proxy/plugin_resource_tracker_unittest.cc b/proxy/plugin_resource_tracker_unittest.cc deleted file mode 100644 index d44a5ac..0000000 --- a/proxy/plugin_resource_tracker_unittest.cc +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/plugin_resource_tracker.h" - -#include "base/process/process.h" -#include "ppapi/proxy/mock_resource.h" -#include "ppapi/proxy/plugin_dispatcher.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/proxy_lock.h" - -namespace ppapi { -namespace proxy { - -namespace { - -// Object so we know when a resource has been released. -class TrackedMockResource : public MockResource { - public: - TrackedMockResource(const HostResource& serialized) - : MockResource(serialized) { - tracked_alive_count++; - } - ~TrackedMockResource() { - tracked_alive_count--; - } - - static int tracked_alive_count; -}; - -int TrackedMockResource::tracked_alive_count = 0; - -} // namespace - -class PluginResourceTrackerTest : public PluginProxyTest { - public: - PluginResourceTrackerTest() {} - ~PluginResourceTrackerTest() {} -}; - -TEST_F(PluginResourceTrackerTest, PluginResourceForHostResource) { - ProxyAutoLock lock; - - PP_Resource host_resource = 0x5678; - - HostResource serialized; - serialized.SetHostResource(pp_instance(), host_resource); - - // When we haven't added an object, the return value should be 0. - EXPECT_EQ(0, resource_tracker().PluginResourceForHostResource(serialized)); - - EXPECT_EQ(0, TrackedMockResource::tracked_alive_count); - TrackedMockResource* object = new TrackedMockResource(serialized); - EXPECT_EQ(1, TrackedMockResource::tracked_alive_count); - PP_Resource plugin_resource = object->GetReference(); - - // Now that the object has been added, the return value should be the plugin - // resource ID we already got. - EXPECT_EQ(plugin_resource, - resource_tracker().PluginResourceForHostResource(serialized)); - - // Releasing the resource should have freed it. - resource_tracker().ReleaseResource(plugin_resource); - EXPECT_EQ(0, TrackedMockResource::tracked_alive_count); - EXPECT_EQ(0, resource_tracker().PluginResourceForHostResource(serialized)); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/plugin_var_tracker_unittest.cc b/proxy/plugin_var_tracker_unittest.cc deleted file mode 100644 index f5f8cb7..0000000 --- a/proxy/plugin_var_tracker_unittest.cc +++ /dev/null
@@ -1,252 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include <tuple> - -#include "ipc/ipc_test_sink.h" -#include "ppapi/c/dev/ppp_class_deprecated.h" -#include "ppapi/proxy/plugin_var_tracker.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/proxy_object_var.h" -#include "ppapi/shared_impl/proxy_lock.h" - -namespace ppapi { -namespace proxy { - -namespace { - -PP_Var MakeObject(int32_t object_id) { - PP_Var ret; - ret.type = PP_VARTYPE_OBJECT; - ret.value.as_id = object_id; - return ret; -} - -// A Deallocate() function for PPP_Class that just increments the integer -// referenced by the pointer so we know how often Deallocate was called. -void MarkOnDeallocate(void* object) { - (*static_cast<int*>(object))++; -} - -// A class that just implements MarkOnDeallocate on destruction. -PPP_Class_Deprecated mark_on_deallocate_class = { - NULL, // HasProperty, - NULL, // HasMethod, - NULL, // GetProperty, - NULL, // GetAllPropertyNames, - NULL, // SetProperty, - NULL, // RemoveProperty, - NULL, // Call, - NULL, // Construct, - &MarkOnDeallocate -}; - -} // namespace - -class PluginVarTrackerTest : public PluginProxyTest { - public: - PluginVarTrackerTest() {} - - protected: - // Asserts that there is a unique "release object" IPC message in the test - // sink. This will return the var ID from the message or -1 if none found. - int32_t GetObjectIDForUniqueReleaseObject() { - const IPC::Message* release_msg = sink().GetUniqueMessageMatching( - PpapiHostMsg_PPBVar_ReleaseObject::ID); - if (!release_msg) - return -1; - - std::tuple<int64_t> id; - PpapiHostMsg_PPBVar_ReleaseObject::Read(release_msg, &id); - return std::get<0>(id); - } -}; - -TEST_F(PluginVarTrackerTest, GetHostObject) { - ProxyAutoLock lock; - PP_Var host_object = MakeObject(12345); - - // Round-trip through the tracker to make sure the host object comes out the - // other end. - PP_Var plugin_object = var_tracker().ReceiveObjectPassRef( - host_object, plugin_dispatcher()); - PP_Var host_object2 = var_tracker().GetHostObject(plugin_object); - EXPECT_EQ(PP_VARTYPE_OBJECT, host_object2.type); - EXPECT_EQ(host_object.value.as_id, host_object2.value.as_id); - - var_tracker().ReleaseVar(plugin_object); -} - -TEST_F(PluginVarTrackerTest, ReceiveObjectPassRef) { - ProxyAutoLock lock; - PP_Var host_object = MakeObject(12345); - - // Receive the object, we should have one ref and no messages. - PP_Var plugin_object = var_tracker().ReceiveObjectPassRef( - host_object, plugin_dispatcher()); - EXPECT_EQ(0u, sink().message_count()); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_object)); - - // Receive the same object again, we should get the same plugin ID out. - PP_Var plugin_object2 = var_tracker().ReceiveObjectPassRef( - host_object, plugin_dispatcher()); - EXPECT_EQ(plugin_object.value.as_id, plugin_object2.value.as_id); - EXPECT_EQ(2, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_object)); - - // It should have sent one message to decerment the refcount in the host. - // This is because it only maintains one host refcount for all references - // in the plugin, but the host just sent the second one. - EXPECT_EQ(host_object.value.as_id, GetObjectIDForUniqueReleaseObject()); - sink().ClearMessages(); - - // Release the object, one ref at a time. The second release should free - // the tracking data and send a release message to the browser. - var_tracker().ReleaseVar(plugin_object); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - var_tracker().ReleaseVar(plugin_object); - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(host_object.value.as_id, GetObjectIDForUniqueReleaseObject()); -} - -// Tests freeing objects that have both refcounts and "tracked with no ref". -TEST_F(PluginVarTrackerTest, FreeTrackedAndReferencedObject) { - ProxyAutoLock lock; - PP_Var host_object = MakeObject(12345); - - // Phase one: First receive via a "pass ref", then a tracked with no ref. - PP_Var plugin_var = var_tracker().ReceiveObjectPassRef( - host_object, plugin_dispatcher()); - PP_Var plugin_var2 = var_tracker().TrackObjectWithNoReference( - host_object, plugin_dispatcher()); - EXPECT_EQ(plugin_var.value.as_id, plugin_var2.value.as_id); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_var)); - EXPECT_EQ(1, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_var)); - - // Free via the refcount, this should release the object to the browser but - // maintain the tracked object. - var_tracker().ReleaseVar(plugin_var); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_var)); - EXPECT_EQ(1u, sink().message_count()); - EXPECT_EQ(host_object.value.as_id, GetObjectIDForUniqueReleaseObject()); - - // Now free via the tracked object, this should free it. - var_tracker().StopTrackingObjectWithNoReference(plugin_var); - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_var)); - - // Phase two: Receive via a tracked, then get an addref. - sink().ClearMessages(); - plugin_var = var_tracker().TrackObjectWithNoReference( - host_object, plugin_dispatcher()); - plugin_var2 = var_tracker().ReceiveObjectPassRef( - host_object, plugin_dispatcher()); - EXPECT_EQ(plugin_var.value.as_id, plugin_var2.value.as_id); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_var)); - EXPECT_EQ(1, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_var)); - - // Free via the tracked object, this should have no effect. - var_tracker().StopTrackingObjectWithNoReference(plugin_var); - EXPECT_EQ(0, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_var)); - EXPECT_EQ(0u, sink().message_count()); - - // Now free via the refcount, this should delete it. - var_tracker().ReleaseVar(plugin_var); - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_var)); - EXPECT_EQ(host_object.value.as_id, GetObjectIDForUniqueReleaseObject()); -} - -TEST_F(PluginVarTrackerTest, RecursiveTrackWithNoRef) { - ProxyAutoLock lock; - PP_Var host_object = MakeObject(12345); - - // Receive a tracked object twice. - PP_Var plugin_var = var_tracker().TrackObjectWithNoReference( - host_object, plugin_dispatcher()); - EXPECT_EQ(1, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_var)); - PP_Var plugin_var2 = var_tracker().TrackObjectWithNoReference( - host_object, plugin_dispatcher()); - EXPECT_EQ(plugin_var.value.as_id, plugin_var2.value.as_id); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_var)); - EXPECT_EQ(2, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_var)); - - // Now release those tracked items, the reference should be freed. - var_tracker().StopTrackingObjectWithNoReference(plugin_var); - EXPECT_EQ(1, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_var)); - var_tracker().StopTrackingObjectWithNoReference(plugin_var); - EXPECT_EQ(-1, - var_tracker().GetTrackedWithNoReferenceCountForObject(plugin_var)); -} - -// Tests that objects implemented by the plugin that have no references by -// the plugin get their Deallocate function called on destruction. -TEST_F(PluginVarTrackerTest, PluginObjectInstanceDeleted) { - ProxyAutoLock lock; - PP_Var host_object = MakeObject(12345); - PP_Instance pp_instance = 0x12345; - - int deallocate_called = 0; - void* user_data = &deallocate_called; - - // Make a var with one reference. - scoped_refptr<ProxyObjectVar> object( - new ProxyObjectVar(plugin_dispatcher(), host_object.value.as_id)); - PP_Var plugin_var = MakeObject(var_tracker().AddVar(object.get())); - var_tracker().PluginImplementedObjectCreated( - pp_instance, plugin_var, &mark_on_deallocate_class, user_data); - - // Release the plugin ref to the var. WebKit hasn't called destroy so - // we won't get a destroy call. - object.reset(); - var_tracker().ReleaseVar(plugin_var); - EXPECT_EQ(0, deallocate_called); - - // Synthesize an instance destuction, this should call Deallocate. - var_tracker().DidDeleteInstance(pp_instance); - EXPECT_EQ(1, deallocate_called); -} - -// Tests what happens when a plugin keeps a ref to a plugin-implemented -// object var longer than the instance. We should not call the destructor until -// the plugin releases its last ref. -TEST_F(PluginVarTrackerTest, PluginObjectLeaked) { - ProxyAutoLock lock; - PP_Var host_object = MakeObject(12345); - PP_Instance pp_instance = 0x12345; - - int deallocate_called = 0; - void* user_data = &deallocate_called; - - // Make a var with one reference. - scoped_refptr<ProxyObjectVar> object( - new ProxyObjectVar(plugin_dispatcher(), host_object.value.as_id)); - PP_Var plugin_var = MakeObject(var_tracker().AddVar(object.get())); - var_tracker().PluginImplementedObjectCreated( - pp_instance, plugin_var, &mark_on_deallocate_class, user_data); - - // Destroy the instance. This should not call deallocate since the plugin - // still has a ref. - var_tracker().DidDeleteInstance(pp_instance); - EXPECT_EQ(0, deallocate_called); - - // Release the plugin ref to the var. Since the instance is gone this should - // call deallocate. - object.reset(); - var_tracker().ReleaseVar(plugin_var); - EXPECT_EQ(1, deallocate_called); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/ppapi_command_buffer_proxy_unittest.cc b/proxy/ppapi_command_buffer_proxy_unittest.cc deleted file mode 100644 index dd4db6d..0000000 --- a/proxy/ppapi_command_buffer_proxy_unittest.cc +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/ppapi_command_buffer_proxy.h" - -#include "ipc/ipc_test_sink.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { -class PpapiCommandBufferProxyTest : public testing::Test, - public proxy::LockedSender { - public: - PpapiCommandBufferProxyTest() - : proxy_(HostResource(), - &flush_info_, - this, - gpu::Capabilities(), - gpu::GLCapabilities(), - proxy::SerializedHandle( - proxy::SerializedHandle::SHARED_MEMORY_REGION), - gpu::CommandBufferId()) {} - - ~PpapiCommandBufferProxyTest() override {} - - protected: - // We can't verify sync message behavior with this setup. - bool SendAndStayLocked(IPC::Message* msg) override { return sink_.Send(msg); } - - IPC::TestSink sink_; - proxy::InstanceData::FlushInfo flush_info_; - proxy::PpapiCommandBufferProxy proxy_; -}; - -TEST_F(PpapiCommandBufferProxyTest, OrderingBarriersAreCoalescedWithFlush) { - proxy_.OrderingBarrier(10); - proxy_.OrderingBarrier(20); - proxy_.OrderingBarrier(30); - proxy_.Flush(40); - - EXPECT_EQ(1u, sink_.message_count()); - const IPC::Message* msg = - sink_.GetFirstMessageMatching(PpapiHostMsg_PPBGraphics3D_AsyncFlush::ID); - ASSERT_TRUE(msg); - PpapiHostMsg_PPBGraphics3D_AsyncFlush::Param params; - ASSERT_TRUE(PpapiHostMsg_PPBGraphics3D_AsyncFlush::Read(msg, ¶ms)); - int32_t sent_put_offset = std::get<1>(params); - EXPECT_EQ(40, sent_put_offset); - EXPECT_FALSE(flush_info_.flush_pending); - EXPECT_EQ(40, flush_info_.put_offset); -} - -TEST_F(PpapiCommandBufferProxyTest, FlushPendingWorkFlushesOrderingBarriers) { - proxy_.OrderingBarrier(10); - proxy_.OrderingBarrier(20); - proxy_.OrderingBarrier(30); - proxy_.FlushPendingWork(); - - EXPECT_EQ(1u, sink_.message_count()); - const IPC::Message* msg = - sink_.GetFirstMessageMatching(PpapiHostMsg_PPBGraphics3D_AsyncFlush::ID); - ASSERT_TRUE(msg); - PpapiHostMsg_PPBGraphics3D_AsyncFlush::Param params; - ASSERT_TRUE(PpapiHostMsg_PPBGraphics3D_AsyncFlush::Read(msg, ¶ms)); - int32_t sent_put_offset = std::get<1>(params); - EXPECT_EQ(30, sent_put_offset); - EXPECT_FALSE(flush_info_.flush_pending); - EXPECT_EQ(30, flush_info_.put_offset); -} - -TEST_F(PpapiCommandBufferProxyTest, EnsureWorkVisibleFlushesOrderingBarriers) { - proxy_.OrderingBarrier(10); - proxy_.OrderingBarrier(20); - proxy_.OrderingBarrier(30); - proxy_.EnsureWorkVisible(); - - EXPECT_EQ(2u, sink_.message_count()); - const IPC::Message* msg = sink_.GetMessageAt(0); - ASSERT_TRUE(msg); - EXPECT_EQ(static_cast<uint32_t>(PpapiHostMsg_PPBGraphics3D_AsyncFlush::ID), - msg->type()); - PpapiHostMsg_PPBGraphics3D_AsyncFlush::Param params; - ASSERT_TRUE(PpapiHostMsg_PPBGraphics3D_AsyncFlush::Read(msg, ¶ms)); - int32_t sent_put_offset = std::get<1>(params); - EXPECT_EQ(30, sent_put_offset); - EXPECT_FALSE(flush_info_.flush_pending); - EXPECT_EQ(30, flush_info_.put_offset); - - msg = sink_.GetMessageAt(1); - ASSERT_TRUE(msg); - EXPECT_EQ( - static_cast<uint32_t>(PpapiHostMsg_PPBGraphics3D_EnsureWorkVisible::ID), - msg->type()); -} - -} // namespace ppapi
diff --git a/proxy/ppapi_proxy_test.cc b/proxy/ppapi_proxy_test.cc deleted file mode 100644 index 9a996db..0000000 --- a/proxy/ppapi_proxy_test.cc +++ /dev/null
@@ -1,593 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/ppapi_proxy_test.h" - -#include <memory> -#include <tuple> - -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/message_loop/message_pump_type.h" -#include "base/observer_list.h" -#include "base/process/process_handle.h" -#include "base/run_loop.h" -#include "base/task/single_thread_task_runner.h" -#include "ipc/ipc_sync_channel.h" -#include "ipc/message_filter.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/private/ppb_proxy_private.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppb_message_loop_proxy.h" - -namespace ppapi { -namespace proxy { - -namespace { -// HostDispatcher requires a PPB_Proxy_Private, so we always provide a fallback -// do-nothing implementation. -void PluginCrashed(PP_Module module) { - NOTREACHED(); -} - -PP_Instance GetInstanceForResource(PP_Resource resource) { - // If a test relies on this, we need to implement it. - NOTREACHED(); -} - -void SetReserveInstanceIDCallback(PP_Module module, - PP_Bool (*is_seen)(PP_Module, PP_Instance)) { - // This function gets called in HostDispatcher's constructor. We simply don't - // worry about Instance uniqueness in tests, so we can ignore the call. -} - -void AddRefModule(PP_Module module) {} -void ReleaseModule(PP_Module module) {} -PP_Bool IsInModuleDestructor(PP_Module module) { return PP_FALSE; } - -PPB_Proxy_Private ppb_proxy_private = { - &PluginCrashed, - &GetInstanceForResource, - &SetReserveInstanceIDCallback, - &AddRefModule, - &ReleaseModule, - &IsInModuleDestructor -}; - -// We allow multiple harnesses at a time to respond to 'GetInterface' calls. -// We assume that only 1 harness's GetInterface function will ever support a -// given interface name. In practice, there will either be only 1 GetInterface -// handler (for PluginProxyTest or HostProxyTest), or there will be only 2 -// GetInterface handlers (for TwoWayTest). In the latter case, one handler is -// for the PluginProxyTestHarness and should only respond for PPP interfaces, -// and the other handler is for the HostProxyTestHarness which should only -// ever respond for PPB interfaces. -base::ObserverList<ProxyTestHarnessBase>::Unchecked get_interface_handlers_; - -const void* MockGetInterface(const char* name) { - for (auto& observer : get_interface_handlers_) { - const void* interface = observer.GetInterface(name); - if (interface) - return interface; - } - if (strcmp(name, PPB_PROXY_PRIVATE_INTERFACE) == 0) - return &ppb_proxy_private; - return NULL; -} - -void SetUpRemoteHarness(ProxyTestHarnessBase* harness, - const IPC::ChannelHandle& handle, - base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event, - base::WaitableEvent* harness_set_up) { - harness->SetUpHarnessWithChannel(handle, ipc_task_runner, shutdown_event, - false); - harness_set_up->Signal(); -} - -void TearDownRemoteHarness(ProxyTestHarnessBase* harness, - base::WaitableEvent* harness_torn_down) { - harness->TearDownHarness(); - harness_torn_down->Signal(); -} - -void RunTaskOnRemoteHarness(base::OnceClosure task, - base::WaitableEvent* task_complete) { - std::move(task).Run(); - task_complete->Signal(); -} - -} // namespace - -// ProxyTestHarnessBase -------------------------------------------------------- - -ProxyTestHarnessBase::ProxyTestHarnessBase() : pp_module_(0x98765), - pp_instance_(0x12345) { - get_interface_handlers_.AddObserver(this); -} - -ProxyTestHarnessBase::~ProxyTestHarnessBase() { - get_interface_handlers_.RemoveObserver(this); -} - -const void* ProxyTestHarnessBase::GetInterface(const char* name) { - return registered_interfaces_[name]; -} - -void ProxyTestHarnessBase::RegisterTestInterface(const char* name, - const void* test_interface) { - registered_interfaces_[name] = test_interface; -} - -bool ProxyTestHarnessBase::SupportsInterface(const char* name) { - sink().ClearMessages(); - - // IPC doesn't actually write to this when we send a message manually - // not actually using IPC. - bool unused_result = false; - PpapiMsg_SupportsInterface msg(name, &unused_result); - GetDispatcher()->OnMessageReceived(msg); - - const IPC::Message* reply_msg = - sink().GetUniqueMessageMatching(IPC_REPLY_ID); - EXPECT_TRUE(reply_msg); - if (!reply_msg) - return false; - - PpapiMsg_SupportsInterface::ReplyParam reply_data; - EXPECT_TRUE(PpapiMsg_SupportsInterface::ReadReplyParam( - reply_msg, &reply_data)); - - sink().ClearMessages(); - return std::get<0>(reply_data); -} - -// PluginProxyTestHarness ------------------------------------------------------ - -PluginProxyTestHarness::PluginProxyTestHarness( - GlobalsConfiguration globals_config) - : globals_config_(globals_config) { -} - -PluginProxyTestHarness::~PluginProxyTestHarness() { -} - -PpapiGlobals* PluginProxyTestHarness::GetGlobals() { - return plugin_globals_.get(); -} - -Dispatcher* PluginProxyTestHarness::GetDispatcher() { - return plugin_dispatcher_.get(); -} - -void PluginProxyTestHarness::SetUpHarness() { - // These must be first since the dispatcher set-up uses them. - CreatePluginGlobals(nullptr /* ipc_task_runner */); - // Some of the methods called during set-up check that the lock is held. - ProxyAutoLock lock; - - resource_tracker().DidCreateInstance(pp_instance()); - - plugin_dispatcher_ = std::make_unique<PluginDispatcher>( - &MockGetInterface, PpapiPermissions(), false); - plugin_dispatcher_->InitWithTestSink(&sink()); - // The plugin proxy delegate is needed for - // |PluginProxyDelegate::GetBrowserSender| which is used - // in |ResourceCreationProxy::GetConnection| to get the channel to the - // browser. In this case we just use the |plugin_dispatcher_| as the channel - // for test purposes. - plugin_delegate_mock_.set_browser_sender(plugin_dispatcher_.get()); - PluginGlobals::Get()->SetPluginProxyDelegate(&plugin_delegate_mock_); - plugin_dispatcher_->DidCreateInstance(pp_instance()); -} - -void PluginProxyTestHarness::SetUpHarnessWithChannel( - const IPC::ChannelHandle& channel_handle, - base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event, - bool is_client) { - // These must be first since the dispatcher set-up uses them. - CreatePluginGlobals(ipc_task_runner); - // Some of the methods called during set-up check that the lock is held. - ProxyAutoLock lock; - - resource_tracker().DidCreateInstance(pp_instance()); - plugin_delegate_mock_.Init(ipc_task_runner, shutdown_event); - - plugin_dispatcher_ = std::make_unique<PluginDispatcher>( - &MockGetInterface, PpapiPermissions(), false); - plugin_dispatcher_->InitPluginWithChannel(&plugin_delegate_mock_, - base::kNullProcessId, - channel_handle, - is_client); - plugin_delegate_mock_.set_browser_sender(plugin_dispatcher_.get()); - PluginGlobals::Get()->SetPluginProxyDelegate(&plugin_delegate_mock_); - plugin_dispatcher_->DidCreateInstance(pp_instance()); -} - -void PluginProxyTestHarness::TearDownHarness() { - { - // Some of the methods called during tear-down check that the lock is held. - ProxyAutoLock lock; - - plugin_dispatcher_->DidDestroyInstance(pp_instance()); - plugin_dispatcher_.reset(); - - resource_tracker().DidDeleteInstance(pp_instance()); - } - plugin_globals_.reset(); -} - -void PluginProxyTestHarness::CreatePluginGlobals( - const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner) { - if (globals_config_ == PER_THREAD_GLOBALS) { - plugin_globals_ = std::make_unique<PluginGlobals>( - PpapiGlobals::PerThreadForTest(), ipc_task_runner); - PpapiGlobals::SetPpapiGlobalsOnThreadForTest(GetGlobals()); - } else { - plugin_globals_ = std::make_unique<PluginGlobals>(ipc_task_runner); - } -} - -base::SingleThreadTaskRunner* -PluginProxyTestHarness::PluginDelegateMock::GetIPCTaskRunner() { - return ipc_task_runner_; -} - -base::WaitableEvent* -PluginProxyTestHarness::PluginDelegateMock::GetShutdownEvent() { - return shutdown_event_; -} - -IPC::PlatformFileForTransit -PluginProxyTestHarness::PluginDelegateMock::ShareHandleWithRemote( - base::PlatformFile handle, - base::ProcessId /* remote_pid */, - bool should_close_source) { - return IPC::GetPlatformFileForTransit(handle, - should_close_source); -} - -base::UnsafeSharedMemoryRegion PluginProxyTestHarness::PluginDelegateMock:: - ShareUnsafeSharedMemoryRegionWithRemote( - const base::UnsafeSharedMemoryRegion& region, - base::ProcessId /* remote_pid */) { - return region.Duplicate(); -} - -base::ReadOnlySharedMemoryRegion PluginProxyTestHarness::PluginDelegateMock:: - ShareReadOnlySharedMemoryRegionWithRemote( - const base::ReadOnlySharedMemoryRegion& region, - base::ProcessId /* remote_pid */) { - return region.Duplicate(); -} - -std::set<PP_Instance>* -PluginProxyTestHarness::PluginDelegateMock::GetGloballySeenInstanceIDSet() { - return &instance_id_set_; -} - -uint32_t PluginProxyTestHarness::PluginDelegateMock::Register( - PluginDispatcher* plugin_dispatcher) { - return 0; -} - -void PluginProxyTestHarness::PluginDelegateMock::Unregister( - uint32_t plugin_dispatcher_id) {} - -IPC::Sender* PluginProxyTestHarness::PluginDelegateMock::GetBrowserSender() { - return browser_sender_; -} - -std::string PluginProxyTestHarness::PluginDelegateMock::GetUILanguage() { - return std::string("en-US"); -} - -void PluginProxyTestHarness::PluginDelegateMock::SetActiveURL( - const std::string& url) { -} - -PP_Resource PluginProxyTestHarness::PluginDelegateMock::CreateBrowserFont( - Connection connection, - PP_Instance instance, - const PP_BrowserFont_Trusted_Description& desc, - const Preferences& prefs) { - return 0; -} - -// PluginProxyTest ------------------------------------------------------------- - -PluginProxyTest::PluginProxyTest() : PluginProxyTestHarness(SINGLETON_GLOBALS) { -} - -PluginProxyTest::~PluginProxyTest() { -} - -void PluginProxyTest::SetUp() { - SetUpHarness(); -} - -void PluginProxyTest::TearDown() { - TearDownHarness(); -} - -// PluginProxyMultiThreadTest -------------------------------------------------- - -PluginProxyMultiThreadTest::PluginProxyMultiThreadTest() { -} - -PluginProxyMultiThreadTest::~PluginProxyMultiThreadTest() { -} - -void PluginProxyMultiThreadTest::RunTest() { - main_thread_task_runner_ = PpapiGlobals::Get()->GetMainThreadMessageLoop(); - ASSERT_EQ(main_thread_task_runner_.get(), - base::SingleThreadTaskRunner::GetCurrentDefault().get()); - nested_main_thread_message_loop_ = std::make_unique<base::RunLoop>(); - - secondary_thread_ = std::make_unique<base::DelegateSimpleThread>( - this, "PluginProxyMultiThreadTest"); - - { - ProxyAutoLock auto_lock; - - // MessageLoopResource assumes that the proxy lock has been acquired. - secondary_thread_message_loop_ = new MessageLoopResource(pp_instance()); - - ASSERT_EQ(PP_OK, - secondary_thread_message_loop_->PostWork( - PP_MakeCompletionCallback( - &PluginProxyMultiThreadTest::InternalSetUpTestOnSecondaryThread, - this), - 0)); - } - - SetUpTestOnMainThread(); - - secondary_thread_->Start(); - nested_main_thread_message_loop_->Run(); - secondary_thread_->Join(); - - { - ProxyAutoLock auto_lock; - - // The destruction requires a valid PpapiGlobals instance, so we should - // explicitly release it. - secondary_thread_message_loop_.reset(); - } - - secondary_thread_.reset(NULL); - nested_main_thread_message_loop_.reset(NULL); - main_thread_task_runner_.reset(); -} - -void PluginProxyMultiThreadTest::CheckOnThread(ThreadType thread_type) { - ProxyAutoLock auto_lock; - if (thread_type == MAIN_THREAD) { - ASSERT_TRUE(MessageLoopResource::GetCurrent()->is_main_thread_loop()); - } else { - ASSERT_EQ(secondary_thread_message_loop_.get(), - MessageLoopResource::GetCurrent()); - } -} - -void PluginProxyMultiThreadTest::PostQuitForMainThread() { - main_thread_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&PluginProxyMultiThreadTest::QuitNestedLoop, - base::Unretained(this))); -} - -void PluginProxyMultiThreadTest::PostQuitForSecondaryThread() { - ProxyAutoLock auto_lock; - secondary_thread_message_loop_->PostQuit(PP_TRUE); -} - -void PluginProxyMultiThreadTest::Run() { - ProxyAutoLock auto_lock; - ASSERT_EQ(PP_OK, secondary_thread_message_loop_->AttachToCurrentThread()); - ASSERT_EQ(PP_OK, secondary_thread_message_loop_->Run()); - secondary_thread_message_loop_->DetachFromThread(); -} - -void PluginProxyMultiThreadTest::QuitNestedLoop() { - nested_main_thread_message_loop_->Quit(); -} - -// static -void PluginProxyMultiThreadTest::InternalSetUpTestOnSecondaryThread( - void* user_data, - int32_t result) { - EXPECT_EQ(PP_OK, result); - PluginProxyMultiThreadTest* thiz = - static_cast<PluginProxyMultiThreadTest*>(user_data); - thiz->CheckOnThread(SECONDARY_THREAD); - thiz->SetUpTestOnSecondaryThread(); -} - -// HostProxyTestHarness -------------------------------------------------------- - -HostProxyTestHarness::HostProxyTestHarness(GlobalsConfiguration globals_config) - : globals_config_(globals_config) { -} - -HostProxyTestHarness::~HostProxyTestHarness() { -} - -PpapiGlobals* HostProxyTestHarness::GetGlobals() { - return host_globals_.get(); -} - -Dispatcher* HostProxyTestHarness::GetDispatcher() { - return host_dispatcher_.get(); -} - -void HostProxyTestHarness::SetUpHarness() { - // These must be first since the dispatcher set-up uses them. - CreateHostGlobals(); - - host_dispatcher_ = std::make_unique<HostDispatcher>( - pp_module(), &MockGetInterface, PpapiPermissions::AllPermissions()); - host_dispatcher_->InitWithTestSink(&sink()); - HostDispatcher::SetForInstance(pp_instance(), host_dispatcher_.get()); -} - -void HostProxyTestHarness::SetUpHarnessWithChannel( - const IPC::ChannelHandle& channel_handle, - base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event, - bool is_client) { - // These must be first since the dispatcher set-up uses them. - CreateHostGlobals(); - - delegate_mock_.Init(ipc_task_runner, shutdown_event); - - host_dispatcher_ = std::make_unique<HostDispatcher>( - pp_module(), &MockGetInterface, PpapiPermissions::AllPermissions()); - ppapi::Preferences preferences; - host_dispatcher_->InitHostWithChannel( - &delegate_mock_, base::kNullProcessId, channel_handle, is_client, - preferences, base::SingleThreadTaskRunner::GetCurrentDefault()); - HostDispatcher::SetForInstance(pp_instance(), host_dispatcher_.get()); -} - -void HostProxyTestHarness::TearDownHarness() { - HostDispatcher::RemoveForInstance(pp_instance()); - host_dispatcher_.reset(); - host_globals_.reset(); -} - -void HostProxyTestHarness::CreateHostGlobals() { - disable_locking_ = std::make_unique<ProxyLock::LockingDisablerForTest>(); - if (globals_config_ == PER_THREAD_GLOBALS) { - host_globals_ = - std::make_unique<TestGlobals>(PpapiGlobals::PerThreadForTest()); - PpapiGlobals::SetPpapiGlobalsOnThreadForTest(GetGlobals()); - } else { - host_globals_ = std::make_unique<TestGlobals>(); - } -} - -base::SingleThreadTaskRunner* -HostProxyTestHarness::DelegateMock::GetIPCTaskRunner() { - return ipc_task_runner_; -} - -base::WaitableEvent* HostProxyTestHarness::DelegateMock::GetShutdownEvent() { - return shutdown_event_; -} - -IPC::PlatformFileForTransit -HostProxyTestHarness::DelegateMock::ShareHandleWithRemote( - base::PlatformFile handle, - base::ProcessId /* remote_pid */, - bool should_close_source) { - return IPC::GetPlatformFileForTransit(handle, - should_close_source); -} - -base::UnsafeSharedMemoryRegion -HostProxyTestHarness::DelegateMock::ShareUnsafeSharedMemoryRegionWithRemote( - const base::UnsafeSharedMemoryRegion& region, - base::ProcessId /*remote_pid*/) { - return region.Duplicate(); -} - -base::ReadOnlySharedMemoryRegion -HostProxyTestHarness::DelegateMock::ShareReadOnlySharedMemoryRegionWithRemote( - const base::ReadOnlySharedMemoryRegion& region, - base::ProcessId /*remote_pid*/) { - return region.Duplicate(); -} - -// HostProxyTest --------------------------------------------------------------- - -HostProxyTest::HostProxyTest() : HostProxyTestHarness(SINGLETON_GLOBALS) { -} - -HostProxyTest::~HostProxyTest() { -} - -void HostProxyTest::SetUp() { - SetUpHarness(); -} - -void HostProxyTest::TearDown() { - TearDownHarness(); -} - -// TwoWayTest --------------------------------------------------------------- - -TwoWayTest::TwoWayTest(TwoWayTest::TwoWayTestMode test_mode) - : test_mode_(test_mode), - host_(ProxyTestHarnessBase::PER_THREAD_GLOBALS), - plugin_(ProxyTestHarnessBase::PER_THREAD_GLOBALS), - io_thread_("TwoWayTest_IOThread"), - plugin_thread_("TwoWayTest_PluginThread"), - remote_harness_(NULL), - local_harness_(NULL), - channel_created_(base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED), - shutdown_event_(base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED) { - if (test_mode == TEST_PPP_INTERFACE) { - remote_harness_ = &plugin_; - local_harness_ = &host_; - } else { - remote_harness_ = &host_; - local_harness_ = &plugin_; - } -} - -TwoWayTest::~TwoWayTest() { - shutdown_event_.Signal(); -} - -void TwoWayTest::SetUp() { - base::Thread::Options options; - options.message_pump_type = base::MessagePumpType::IO; - io_thread_.StartWithOptions(std::move(options)); - plugin_thread_.Start(); - - mojo::MessagePipe pipe; - base::WaitableEvent remote_harness_set_up( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED); - plugin_thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&SetUpRemoteHarness, remote_harness_, - pipe.handle0.release(), - base::RetainedRef(io_thread_.task_runner()), - &shutdown_event_, &remote_harness_set_up)); - remote_harness_set_up.Wait(); - local_harness_->SetUpHarnessWithChannel( - pipe.handle1.release(), io_thread_.task_runner().get(), &shutdown_event_, - true); // is_client -} - -void TwoWayTest::TearDown() { - base::WaitableEvent remote_harness_torn_down( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED); - plugin_thread_.task_runner()->PostTask( - FROM_HERE, base::BindOnce(&TearDownRemoteHarness, remote_harness_, - &remote_harness_torn_down)); - remote_harness_torn_down.Wait(); - - local_harness_->TearDownHarness(); - - io_thread_.Stop(); -} - -void TwoWayTest::PostTaskOnRemoteHarness(base::OnceClosure task) { - base::WaitableEvent task_complete( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED); - plugin_thread_.task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&RunTaskOnRemoteHarness, std::move(task), &task_complete)); - task_complete.Wait(); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/ppapi_proxy_test.h b/proxy/ppapi_proxy_test.h deleted file mode 100644 index c8e3508..0000000 --- a/proxy/ppapi_proxy_test.h +++ /dev/null
@@ -1,397 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_PROXY_PPAPI_PROXY_TEST_H_ -#define PPAPI_PROXY_PPAPI_PROXY_TEST_H_ - -#include <stdint.h> - -#include <map> -#include <memory> -#include <string> - -#include "base/compiler_specific.h" -#include "base/memory/scoped_refptr.h" -#include "base/synchronization/waitable_event.h" -#include "base/test/task_environment.h" -#include "base/threading/simple_thread.h" -#include "base/threading/thread.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/proxy/host_dispatcher.h" -#include "ppapi/proxy/plugin_dispatcher.h" -#include "ppapi/proxy/plugin_globals.h" -#include "ppapi/proxy/plugin_proxy_delegate.h" -#include "ppapi/proxy/plugin_resource_tracker.h" -#include "ppapi/proxy/plugin_var_tracker.h" -#include "ppapi/proxy/resource_message_test_sink.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/test_globals.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { -class RunLoop; -class SingleThreadTaskRunner; -} - -namespace ppapi { -namespace proxy { - -class MessageLoopResource; - -// Base class for plugin and host test harnesses. Tests will not use this -// directly. Instead, use the PluginProxyTest, HostProxyTest, or TwoWayTest. -class ProxyTestHarnessBase { - public: - enum GlobalsConfiguration { - PER_THREAD_GLOBALS, - SINGLETON_GLOBALS - }; - - ProxyTestHarnessBase(); - virtual ~ProxyTestHarnessBase(); - - PP_Module pp_module() const { return pp_module_; } - PP_Instance pp_instance() const { return pp_instance_; } - ResourceMessageTestSink& sink() { return sink_; } - - virtual PpapiGlobals* GetGlobals() = 0; - // Returns either the plugin or host dispatcher, depending on the test. - virtual Dispatcher* GetDispatcher() = 0; - - // Set up the harness using an IPC::TestSink to capture messages. - virtual void SetUpHarness() = 0; - - // Set up the harness using a real IPC channel. - virtual void SetUpHarnessWithChannel( - const IPC::ChannelHandle& channel_handle, - base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event, - bool is_client) = 0; - - virtual void TearDownHarness() = 0; - - // Implementation of GetInterface for the dispatcher. This will - // return NULL for all interfaces unless one is registered by calling - // RegisterTestInterface(); - const void* GetInterface(const char* name); - - // Allows the test to specify an interface implementation for a given - // interface name. This will be returned when any of the proxy logic - // requests a local interface. - void RegisterTestInterface(const char* name, const void* test_interface); - - // Sends a "supports interface" message to the current dispatcher and returns - // true if it's supported. This is just for the convenience of tests. - bool SupportsInterface(const char* name); - - private: - // Destination for IPC messages sent by the test. - ResourceMessageTestSink sink_; - - // The module and instance ID associated with the plugin dispatcher. - PP_Module pp_module_; - PP_Instance pp_instance_; - - // Stores the data for GetInterface/RegisterTestInterface. - std::map<std::string, const void*> registered_interfaces_; -}; - -// Test harness for the plugin side of the proxy. -class PluginProxyTestHarness : public ProxyTestHarnessBase { - public: - explicit PluginProxyTestHarness(GlobalsConfiguration globals_config); - virtual ~PluginProxyTestHarness(); - - PluginDispatcher* plugin_dispatcher() { return plugin_dispatcher_.get(); } - PluginResourceTracker& resource_tracker() { - return *plugin_globals_->plugin_resource_tracker(); - } - PluginVarTracker& var_tracker() { - return *plugin_globals_->plugin_var_tracker(); - } - - // ProxyTestHarnessBase implementation. - virtual PpapiGlobals* GetGlobals(); - virtual Dispatcher* GetDispatcher(); - virtual void SetUpHarness(); - virtual void SetUpHarnessWithChannel( - const IPC::ChannelHandle& channel_handle, - base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event, - bool is_client); - virtual void TearDownHarness(); - - class PluginDelegateMock : public PluginDispatcher::PluginDelegate, - public PluginProxyDelegate { - public: - PluginDelegateMock() : ipc_task_runner_(NULL), shutdown_event_() {} - - PluginDelegateMock(const PluginDelegateMock&) = delete; - PluginDelegateMock& operator=(const PluginDelegateMock&) = delete; - - ~PluginDelegateMock() override {} - - void Init(base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event) { - ipc_task_runner_ = ipc_task_runner; - shutdown_event_ = shutdown_event; - } - - void set_browser_sender(IPC::Sender* browser_sender) { - browser_sender_ = browser_sender; - } - - // ProxyChannel::Delegate implementation. - base::SingleThreadTaskRunner* GetIPCTaskRunner() override; - base::WaitableEvent* GetShutdownEvent() override; - IPC::PlatformFileForTransit ShareHandleWithRemote( - base::PlatformFile handle, - base::ProcessId remote_pid, - bool should_close_source) override; - base::UnsafeSharedMemoryRegion ShareUnsafeSharedMemoryRegionWithRemote( - const base::UnsafeSharedMemoryRegion& region, - base::ProcessId remote_pid) override; - base::ReadOnlySharedMemoryRegion ShareReadOnlySharedMemoryRegionWithRemote( - const base::ReadOnlySharedMemoryRegion& region, - base::ProcessId remote_pid) override; - - // PluginDispatcher::PluginDelegate implementation. - std::set<PP_Instance>* GetGloballySeenInstanceIDSet() override; - uint32_t Register(PluginDispatcher* plugin_dispatcher) override; - void Unregister(uint32_t plugin_dispatcher_id) override; - - // PluginProxyDelegate implementation. - IPC::Sender* GetBrowserSender() override; - std::string GetUILanguage() override; - void SetActiveURL(const std::string& url) override; - PP_Resource CreateBrowserFont( - Connection connection, - PP_Instance instance, - const PP_BrowserFont_Trusted_Description& desc, - const Preferences& prefs) override; - - private: - base::SingleThreadTaskRunner* ipc_task_runner_; // Weak - base::WaitableEvent* shutdown_event_; // Weak - std::set<PP_Instance> instance_id_set_; - IPC::Sender* browser_sender_; - }; - - private: - void CreatePluginGlobals( - const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner); - - GlobalsConfiguration globals_config_; - std::unique_ptr<PluginGlobals> plugin_globals_; - - std::unique_ptr<PluginDispatcher> plugin_dispatcher_; - PluginDelegateMock plugin_delegate_mock_; -}; - -class PluginProxyTest : public PluginProxyTestHarness, public testing::Test { - public: - PluginProxyTest(); - virtual ~PluginProxyTest(); - - // testing::Test implementation. - virtual void SetUp(); - virtual void TearDown(); - private: - base::test::SingleThreadTaskEnvironment task_environment_; -}; - -// This class provides support for multi-thread testing. A secondary thread is -// created with a Pepper message loop. -// Subclasses need to implement the two SetUpTestOn*Thread() methods to do the -// actual testing work; and call both PostQuitFor*Thread() when testing is -// done. -class PluginProxyMultiThreadTest - : public PluginProxyTest, - public base::DelegateSimpleThread::Delegate { - public: - PluginProxyMultiThreadTest(); - ~PluginProxyMultiThreadTest() override; - - // Called before the secondary thread is started, but after all the member - // variables, including |secondary_thread_| and - // |secondary_thread_message_loop_|, are initialized. - virtual void SetUpTestOnMainThread() = 0; - - virtual void SetUpTestOnSecondaryThread() = 0; - - // TEST_F() should call this method. - void RunTest(); - - enum ThreadType { - MAIN_THREAD, - SECONDARY_THREAD - }; - void CheckOnThread(ThreadType thread_type); - - // These can be called on any thread. - void PostQuitForMainThread(); - void PostQuitForSecondaryThread(); - - protected: - scoped_refptr<MessageLoopResource> secondary_thread_message_loop_; - scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; - - private: - // base::DelegateSimpleThread::Delegate implementation. - void Run() override; - - void QuitNestedLoop(); - - static void InternalSetUpTestOnSecondaryThread(void* user_data, - int32_t result); - - std::unique_ptr<base::DelegateSimpleThread> secondary_thread_; - std::unique_ptr<base::RunLoop> nested_main_thread_message_loop_; -}; - -class HostProxyTestHarness : public ProxyTestHarnessBase { - public: - explicit HostProxyTestHarness(GlobalsConfiguration globals_config); - virtual ~HostProxyTestHarness(); - - HostDispatcher* host_dispatcher() { return host_dispatcher_.get(); } - ResourceTracker& resource_tracker() { - return *host_globals_->GetResourceTracker(); - } - VarTracker& var_tracker() { - return *host_globals_->GetVarTracker(); - } - - // ProxyTestBase implementation. - virtual PpapiGlobals* GetGlobals(); - virtual Dispatcher* GetDispatcher(); - virtual void SetUpHarness(); - virtual void SetUpHarnessWithChannel( - const IPC::ChannelHandle& channel_handle, - base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event, - bool is_client); - virtual void TearDownHarness(); - - class DelegateMock : public ProxyChannel::Delegate { - public: - DelegateMock() : ipc_task_runner_(NULL), shutdown_event_(NULL) {} - - DelegateMock(const DelegateMock&) = delete; - DelegateMock& operator=(const DelegateMock&) = delete; - - ~DelegateMock() override {} - - void Init(base::SingleThreadTaskRunner* ipc_task_runner, - base::WaitableEvent* shutdown_event) { - ipc_task_runner_ = ipc_task_runner; - shutdown_event_ = shutdown_event; - } - - // ProxyChannel::Delegate implementation. - base::SingleThreadTaskRunner* GetIPCTaskRunner() override; - base::WaitableEvent* GetShutdownEvent() override; - IPC::PlatformFileForTransit ShareHandleWithRemote( - base::PlatformFile handle, - base::ProcessId remote_pid, - bool should_close_source) override; - base::UnsafeSharedMemoryRegion ShareUnsafeSharedMemoryRegionWithRemote( - const base::UnsafeSharedMemoryRegion& region, - base::ProcessId remote_pid) override; - base::ReadOnlySharedMemoryRegion ShareReadOnlySharedMemoryRegionWithRemote( - const base::ReadOnlySharedMemoryRegion& region, - base::ProcessId remote_pid) override; - - private: - base::SingleThreadTaskRunner* ipc_task_runner_; // Weak - base::WaitableEvent* shutdown_event_; // Weak - }; - - private: - void CreateHostGlobals(); - - GlobalsConfiguration globals_config_; - std::unique_ptr<ppapi::TestGlobals> host_globals_; - std::unique_ptr<HostDispatcher> host_dispatcher_; - // The host side of the real proxy doesn't lock, so this disables locking for - // the thread the host side of the test runs on. - std::unique_ptr<ProxyLock::LockingDisablerForTest> disable_locking_; - DelegateMock delegate_mock_; -}; - -class HostProxyTest : public HostProxyTestHarness, public testing::Test { - public: - HostProxyTest(); - virtual ~HostProxyTest(); - - // testing::Test implementation. - virtual void SetUp(); - virtual void TearDown(); - private: - base::test::SingleThreadTaskEnvironment task_environment_; -}; - -// Use this base class to test both sides of a proxy. -class TwoWayTest : public testing::Test { - public: - enum TwoWayTestMode { - TEST_PPP_INTERFACE, - TEST_PPB_INTERFACE - }; - TwoWayTest(TwoWayTestMode test_mode); - virtual ~TwoWayTest(); - - HostProxyTestHarness& host() { return host_; } - PluginProxyTestHarness& plugin() { return plugin_; } - PP_Module pp_module() const { return host_.pp_module(); } - PP_Instance pp_instance() const { return host_.pp_instance(); } - TwoWayTestMode test_mode() { return test_mode_; } - - // testing::Test implementation. - virtual void SetUp(); - virtual void TearDown(); - - protected: - // Post a task to the thread where the remote harness lives. This - // is typically used to test the state of the var tracker on the plugin - // thread. This runs the task synchronously for convenience. - void PostTaskOnRemoteHarness(base::OnceClosure task); - - private: - TwoWayTestMode test_mode_; - HostProxyTestHarness host_; - PluginProxyTestHarness plugin_; - // In order to use sync IPC, we need to have an IO thread. - base::Thread io_thread_; - // The plugin side of the proxy runs on its own thread. - base::Thread plugin_thread_; - // The message loop for the main (host) thread. - base::test::SingleThreadTaskEnvironment task_environment_; - - // Aliases for the host and plugin harnesses; if we're testing a PPP - // interface, remote_harness will point to plugin_, and local_harness - // will point to host_. This makes it convenient when we're starting and - // stopping the harnesses. - ProxyTestHarnessBase* remote_harness_; - ProxyTestHarnessBase* local_harness_; - - base::WaitableEvent channel_created_; - base::WaitableEvent shutdown_event_; -}; - -// Used during Gtests when you have a PP_Var that you want to EXPECT is equal -// to a certain constant string value: -// -// EXPECT_VAR_IS_STRING("foo", my_var); -#define EXPECT_VAR_IS_STRING(str, var) { \ - StringVar* sv = StringVar::FromPPVar(var); \ - EXPECT_TRUE(sv); \ - if (sv) \ - EXPECT_EQ(str, sv->value()); \ -} - -} // namespace proxy -} // namespace ppapi - -#endif // PPAPI_PROXY_PPAPI_PROXY_TEST_H_
diff --git a/proxy/ppb_var_unittest.cc b/proxy/ppb_var_unittest.cc deleted file mode 100644 index 9b1642d..0000000 --- a/proxy/ppb_var_unittest.cc +++ /dev/null
@@ -1,249 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include <stddef.h> -#include <stdint.h> - -#include <string> -#include <vector> - -#include "base/strings/string_number_conversions.h" -#include "base/threading/platform_thread.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/ppb_var_shared.h" - -namespace { -std::string VarToString(const PP_Var& var, const PPB_Var* ppb_var) { - uint32_t len = 0; - const char* utf8 = ppb_var->VarToUtf8(var, &len); - return std::string(utf8, len); -} -const size_t kNumStrings = 100; -const size_t kNumThreads = 20; -const int kRefsToAdd = 20; -} // namespace - -namespace ppapi { -namespace proxy { - -class PPB_VarTest : public PluginProxyTest { - public: - PPB_VarTest() - : test_strings_(kNumStrings), vars_(kNumStrings), - ppb_var_(ppapi::PPB_Var_Shared::GetVarInterface1_2()) { - // Set the value of test_strings_[i] to "i". - for (size_t i = 0; i < kNumStrings; ++i) - test_strings_[i] = base::NumberToString(i); - } - protected: - std::vector<std::string> test_strings_; - std::vector<PP_Var> vars_; - const PPB_Var* ppb_var_; -}; - -// Test basic String operations. -TEST_F(PPB_VarTest, Strings) { - for (size_t i = 0; i < kNumStrings; ++i) { - vars_[i] = ppb_var_->VarFromUtf8( - test_strings_[i].c_str(), - static_cast<uint32_t>(test_strings_[i].length())); - EXPECT_EQ(test_strings_[i], VarToString(vars_[i], ppb_var_)); - } - // At this point, they should each have a ref count of 1. Add some more. - for (int ref = 0; ref < kRefsToAdd; ++ref) { - for (size_t i = 0; i < kNumStrings; ++i) { - ppb_var_->AddRef(vars_[i]); - // Make sure the string is still there with the right value. - EXPECT_EQ(test_strings_[i], VarToString(vars_[i], ppb_var_)); - } - } - for (int ref = 0; ref < kRefsToAdd; ++ref) { - for (size_t i = 0; i < kNumStrings; ++i) { - ppb_var_->Release(vars_[i]); - // Make sure the string is still there with the right value. - EXPECT_EQ(test_strings_[i], VarToString(vars_[i], ppb_var_)); - } - } - // Now remove the ref counts for each string and make sure they are gone. - for (size_t i = 0; i < kNumStrings; ++i) { - ppb_var_->Release(vars_[i]); - uint32_t len = 10; - const char* utf8 = ppb_var_->VarToUtf8(vars_[i], &len); - EXPECT_EQ(NULL, utf8); - EXPECT_EQ(0u, len); - } -} - -// PPB_VarTest.Threads tests string operations accessed by multiple threads. -namespace { -// These three delegate classes which precede the test are for use with -// PlatformThread. The test goes roughly like this: -// 1) Spawn kNumThreads 'CreateVar' threads, giving each a roughly equal subset -// of test_strings_ to 'create'. Each 'CreateVar' thread also converts its -// set of vars back in to strings so that the main test thread can verify -// their values were correctly converted. -// 2) Spawn kNumThreads 'ChangeRefVar' threads. Each of these threads will -// incremement & decrement the reference count of ALL vars kRefsToAdd times. -// Finally, each thread adds 1 ref count. This leaves each var with a ref- -// count of |kNumThreads + 1|. The main test thread removes a ref, leaving -// each var with a ref-count of |kNumThreads|. -// 3) Spawn kNumThreads 'RemoveVar' threads. Each of these threads releases each -// var once. Once all the threads have finished, there should be no vars -// left. -class CreateVarThreadDelegate : public base::PlatformThread::Delegate { - public: - // |strings_in|, |vars|, and |strings_out| are arrays, and size is their size. - // For each |strings_in[i]|, we will set |vars[i]| using that value. Then we - // read the var back out to |strings_out[i]|. - CreateVarThreadDelegate(const std::string* strings_in, - PP_Var* vars_out, - std::string* strings_out, - size_t size) - : strings_in_(strings_in), - vars_out_(vars_out), - strings_out_(strings_out), - size_(size) {} - virtual ~CreateVarThreadDelegate() {} - virtual void ThreadMain() { - const PPB_Var* ppb_var = ppapi::PPB_Var_Shared::GetVarInterface1_2(); - for (size_t i = 0; i < size_; ++i) { - vars_out_[i] = ppb_var->VarFromUtf8( - strings_in_[i].c_str(), - static_cast<uint32_t>(strings_in_[i].length())); - strings_out_[i] = VarToString(vars_out_[i], ppb_var); - } - } - private: - const std::string* strings_in_; - PP_Var* vars_out_; - std::string* strings_out_; - size_t size_; -}; - -// A thread that will increment and decrement the reference count of every var -// multiple times. -class ChangeRefVarThreadDelegate : public base::PlatformThread::Delegate { - public: - ChangeRefVarThreadDelegate(const std::vector<PP_Var>& vars) : vars_(vars) { - } - virtual ~ChangeRefVarThreadDelegate() {} - virtual void ThreadMain() { - const PPB_Var* ppb_var = ppapi::PPB_Var_Shared::GetVarInterface1_2(); - // Increment and decrement the reference count for each var kRefsToAdd - // times. Note that we always AddRef once before doing the matching Release, - // to ensure that we never accidentally release the last reference. - for (int ref = 0; ref < kRefsToAdd; ++ref) { - for (size_t i = 0; i < kNumStrings; ++i) { - ppb_var->AddRef(vars_[i]); - ppb_var->Release(vars_[i]); - } - } - // Now add 1 ref to each Var. The net result is that all Vars will have a - // ref-count of (kNumThreads + 1) after this. That will allow us to have all - // threads release all vars later. - for (size_t i = 0; i < kNumStrings; ++i) { - ppb_var->AddRef(vars_[i]); - } - } - private: - std::vector<PP_Var> vars_; -}; - -// A thread that will decrement the reference count of every var once. -class RemoveRefVarThreadDelegate : public base::PlatformThread::Delegate { - public: - RemoveRefVarThreadDelegate(const std::vector<PP_Var>& vars) : vars_(vars) { - } - virtual ~RemoveRefVarThreadDelegate() {} - virtual void ThreadMain() { - const PPB_Var* ppb_var = ppapi::PPB_Var_Shared::GetVarInterface1_2(); - for (size_t i = 0; i < kNumStrings; ++i) { - ppb_var->Release(vars_[i]); - } - } - private: - std::vector<PP_Var> vars_; -}; - -} // namespace - -TEST_F(PPB_VarTest, Threads) { - std::vector<base::PlatformThreadHandle> create_var_threads(kNumThreads); - std::vector<CreateVarThreadDelegate> create_var_delegates; - // The strings that the threads will re-extract from Vars (so we can check - // that they match the original strings). - std::vector<std::string> strings_out(kNumStrings); - size_t strings_per_thread = kNumStrings/kNumThreads; - // Give each thread an equal slice of strings to turn in to vars. (Except the - // last thread may get fewer if kNumStrings is not evenly divisible by - // kNumThreads). - for (size_t slice_start= 0; slice_start < kNumStrings; - slice_start += strings_per_thread) { - create_var_delegates.push_back(CreateVarThreadDelegate( - &test_strings_[slice_start], &vars_[slice_start], - &strings_out[slice_start], - std::min(strings_per_thread, kNumStrings - slice_start))); - } - // Now run then join all the threads. - for (size_t i = 0; i < kNumThreads; ++i) - base::PlatformThread::Create(0, &create_var_delegates[i], - &create_var_threads[i]); - for (size_t i = 0; i < kNumThreads; ++i) - base::PlatformThread::Join(create_var_threads[i]); - // Now check that the strings have the expected values. - EXPECT_EQ(test_strings_, strings_out); - - // Tinker with the reference counts in a multithreaded way. - std::vector<base::PlatformThreadHandle> change_ref_var_threads(kNumThreads); - std::vector<ChangeRefVarThreadDelegate> change_ref_var_delegates; - for (size_t i = 0; i < kNumThreads; ++i) - change_ref_var_delegates.push_back(ChangeRefVarThreadDelegate(vars_)); - for (size_t i = 0; i < kNumThreads; ++i) { - base::PlatformThread::Create(0, &change_ref_var_delegates[i], - &change_ref_var_threads[i]); - } - for (size_t i = 0; i < kNumThreads; ++i) - base::PlatformThread::Join(change_ref_var_threads[i]); - - // Now each var has a refcount of (kNumThreads + 1). Let's decrement each var - // once so that every 'RemoveRef' thread (spawned below) owns 1 reference, and - // when the last one removes a ref, the Var will be deleted. - for (size_t i = 0; i < kNumStrings; ++i) { - ppb_var_->Release(vars_[i]); - } - - // Check that all vars are still valid and have the values we expect. - for (size_t i = 0; i < kNumStrings; ++i) - EXPECT_EQ(test_strings_[i], VarToString(vars_[i], ppb_var_)); - - // Remove the last reference counts for all vars. - std::vector<base::PlatformThreadHandle> remove_ref_var_threads(kNumThreads); - std::vector<RemoveRefVarThreadDelegate> remove_ref_var_delegates; - for (size_t i = 0; i < kNumThreads; ++i) - remove_ref_var_delegates.push_back(RemoveRefVarThreadDelegate(vars_)); - for (size_t i = 0; i < kNumThreads; ++i) { - base::PlatformThread::Create(0, &remove_ref_var_delegates[i], - &remove_ref_var_threads[i]); - } - for (size_t i = 0; i < kNumThreads; ++i) - base::PlatformThread::Join(remove_ref_var_threads[i]); - - // All the vars should no longer represent valid strings. - for (size_t i = 0; i < kNumStrings; ++i) { - uint32_t len = 10; - const char* utf8 = ppb_var_->VarToUtf8(vars_[i], &len); - EXPECT_EQ(NULL, utf8); - EXPECT_EQ(0u, len); - } -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/ppp_instance_private_proxy_unittest.cc b/proxy/ppp_instance_private_proxy_unittest.cc deleted file mode 100644 index 8c84456..0000000 --- a/proxy/ppp_instance_private_proxy_unittest.cc +++ /dev/null
@@ -1,216 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "base/functional/bind.h" -#include "base/test/test_timeouts.h" -#include "base/time/time.h" -#include "ppapi/c/dev/ppb_var_deprecated.h" -#include "ppapi/c/dev/ppp_class_deprecated.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/ppp_instance.h" -#include "ppapi/c/private/ppp_instance_private.h" -#include "ppapi/proxy/host_dispatcher.h" -#include "ppapi/proxy/interface_list.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/ppapi_permissions.h" -#include "ppapi/shared_impl/ppb_var_shared.h" -#include "ppapi/shared_impl/var.h" - -namespace ppapi { - -// A fake version of V8ObjectVar for testing. -class V8ObjectVar : public ppapi::Var { - public: - V8ObjectVar(const PPP_Class_Deprecated* ppp_class, void* ppp_class_data) - : ppp_class_(ppp_class), ppp_class_data_(ppp_class_data) {} - ~V8ObjectVar() override { ppp_class_->Deallocate(ppp_class_data_); } - - // Var overrides. - V8ObjectVar* AsV8ObjectVar() override { return this; } - PP_VarType GetType() const override { return PP_VARTYPE_OBJECT; } - - private: - const PPP_Class_Deprecated* ppp_class_; - void* ppp_class_data_; -}; - -namespace proxy { - -namespace { -const PP_Instance kInstance = 0xdeadbeef; - -PP_Var GetPPVarNoAddRef(Var* var) { - PP_Var var_to_return = var->GetPPVar(); - PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(var_to_return); - return var_to_return; -} - -PluginDispatcher* plugin_dispatcher = NULL; -// Return the plugin-side proxy for PPB_Var_Deprecated. -const PPB_Var_Deprecated* plugin_var_deprecated_if() { - // The test code must set the plugin dispatcher. - CHECK(plugin_dispatcher); - // Grab the plugin-side proxy for PPB_Var_Deprecated (for CreateObject). - return static_cast<const PPB_Var_Deprecated*>( - plugin_dispatcher->GetBrowserInterface( - PPB_VAR_DEPRECATED_INTERFACE)); -} - -// Mock PPP_Instance_Private. -PP_Var instance_obj; -PP_Var GetInstanceObject(PP_Instance /*instance*/) { - // The 1 ref we got from CreateObject will be passed to the host. We want to - // have a ref of our own. - printf("GetInstanceObject called\n"); - plugin_var_deprecated_if()->AddRef(instance_obj); - return instance_obj; -} - -PPP_Instance_Private ppp_instance_private_mock = { - &GetInstanceObject -}; - -// We need to pass in a |PPP_Class_Deprecated| to -// |PPB_Var_Deprecated->CreateObject| for a mock |Deallocate| method. -void Deallocate(void* object) { -} - -const PPP_Class_Deprecated ppp_class_deprecated_mock = { - NULL, // HasProperty - NULL, // HasMethod - NULL, // GetProperty - NULL, // GetAllPropertyNames - NULL, // SetProperty - NULL, // RemoveProperty - NULL, // Call - NULL, // Construct - &Deallocate -}; - - -// We need to mock PPP_Instance, so that we can create and destroy the pretend -// instance that PPP_Instance_Private uses. -PP_Bool DidCreate(PP_Instance /*instance*/, uint32_t /*argc*/, - const char* /*argn*/[], const char* /*argv*/[]) { - // Create an object var. This should exercise the typical path for creating - // instance objects. - instance_obj = - plugin_var_deprecated_if()->CreateObject(kInstance, - &ppp_class_deprecated_mock, - NULL); - return PP_TRUE; -} - -void DidDestroy(PP_Instance /*instance*/) { - // Decrement the reference count for our instance object. It should be - // deleted. - plugin_var_deprecated_if()->Release(instance_obj); -} - -PPP_Instance_1_0 ppp_instance_mock = { &DidCreate, &DidDestroy }; - -// Mock PPB_Var_Deprecated, so that we can emulate creating an Object Var. -PP_Var CreateObject(PP_Instance /*instance*/, - const PPP_Class_Deprecated* ppp_class, - void* ppp_class_data) { - V8ObjectVar* obj_var = new V8ObjectVar(ppp_class, ppp_class_data); - return obj_var->GetPPVar(); -} - -const PPB_Var_Deprecated ppb_var_deprecated_mock = { - PPB_Var_Shared::GetVarInterface1_0()->AddRef, - PPB_Var_Shared::GetVarInterface1_0()->Release, - PPB_Var_Shared::GetVarInterface1_0()->VarFromUtf8, - PPB_Var_Shared::GetVarInterface1_0()->VarToUtf8, - NULL, // HasProperty - NULL, // HasMethod - NULL, // GetProperty - NULL, // EnumerateProperties - NULL, // SetProperty - NULL, // RemoveProperty - NULL, // Call - NULL, // Construct - NULL, // IsInstanceOf - &CreateObject -}; - -class PPP_Instance_Private_ProxyTest : public TwoWayTest { - public: - PPP_Instance_Private_ProxyTest() - : TwoWayTest(TwoWayTest::TEST_PPP_INTERFACE) { - plugin().RegisterTestInterface(PPP_INSTANCE_PRIVATE_INTERFACE, - &ppp_instance_private_mock); - plugin().RegisterTestInterface(PPP_INSTANCE_INTERFACE_1_0, - &ppp_instance_mock); - host().RegisterTestInterface(PPB_VAR_DEPRECATED_INTERFACE, - &ppb_var_deprecated_mock); - } -}; - -} // namespace - -TEST_F(PPP_Instance_Private_ProxyTest, PPPInstancePrivate) { - // This test controls its own instance; we can't use the one that - // PluginProxyTestHarness provides. - ASSERT_NE(kInstance, pp_instance()); - HostDispatcher::SetForInstance(kInstance, host().host_dispatcher()); - - // Requires dev interfaces. - InterfaceList::SetProcessGlobalPermissions( - PpapiPermissions::AllPermissions()); - - // This file-local global is used by the PPP_Instance mock above in order to - // access PPB_Var_Deprecated. - plugin_dispatcher = plugin().plugin_dispatcher(); - - // Grab the host-side proxy for PPP_Instance and PPP_Instance_Private. - const PPP_Instance_Private* ppp_instance_private = - static_cast<const PPP_Instance_Private*>( - host().host_dispatcher()->GetProxiedInterface( - PPP_INSTANCE_PRIVATE_INTERFACE)); - const PPP_Instance_1_1* ppp_instance = static_cast<const PPP_Instance_1_1*>( - host().host_dispatcher()->GetProxiedInterface( - PPP_INSTANCE_INTERFACE_1_1)); - - // Initialize an Instance, so that the plugin-side machinery will work - // properly. - EXPECT_EQ(PP_TRUE, ppp_instance->DidCreate(kInstance, 0, NULL, NULL)); - - // Check the plugin-side reference count. - EXPECT_EQ(1, plugin().var_tracker().GetRefCountForObject(instance_obj)); - // Check the host-side var exists with the expected id and has 1 refcount (the - // refcount on behalf of the plugin). - int32_t expected_host_id = - plugin().var_tracker().GetHostObject(instance_obj).value.as_id; - Var* host_var = host().var_tracker().GetVar(expected_host_id); - ASSERT_TRUE(host_var); - EXPECT_EQ( - 1, - host().var_tracker().GetRefCountForObject(GetPPVarNoAddRef(host_var))); - - // Call from the browser side to get the instance object. - PP_Var host_pp_var = ppp_instance_private->GetInstanceObject(kInstance); - EXPECT_EQ(instance_obj.type, host_pp_var.type); - EXPECT_EQ(host_pp_var.value.as_id, expected_host_id); - EXPECT_EQ(1, plugin().var_tracker().GetRefCountForObject(instance_obj)); - // A reference is passed to the browser, which we consume here. - host().var_tracker().ReleaseVar(host_pp_var); - EXPECT_EQ(1, host().var_tracker().GetRefCountForObject(host_pp_var)); - - // The plugin is going away; generally, so will all references to its instance - // object. - host().var_tracker().ReleaseVar(host_pp_var); - // Destroy the instance. DidDestroy above decrements the reference count for - // instance_obj, so it should also be destroyed. - ppp_instance->DidDestroy(kInstance); - EXPECT_EQ(-1, plugin().var_tracker().GetRefCountForObject(instance_obj)); - EXPECT_EQ(-1, host().var_tracker().GetRefCountForObject(host_pp_var)); -} - -} // namespace proxy -} // namespace ppapi -
diff --git a/proxy/ppp_instance_proxy_unittest.cc b/proxy/ppp_instance_proxy_unittest.cc deleted file mode 100644 index 15a2fd0..0000000 --- a/proxy/ppp_instance_proxy_unittest.cc +++ /dev/null
@@ -1,204 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include <stddef.h> -#include <stdint.h> - -#include "base/synchronization/waitable_event.h" -#include "ipc/ipc_message_utils.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/ppb_fullscreen.h" -#include "ppapi/c/ppb_url_loader.h" -#include "ppapi/c/ppp_instance.h" -#include "ppapi/proxy/locking_resource_releaser.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/ppb_view_shared.h" - -namespace ppapi { -namespace proxy { - -namespace { - -// This is an ad-hoc mock of PPP_Instance using global variables. Eventually, -// generalize making PPAPI interface mocks by using IDL or macro/template magic. -PP_Instance received_instance; -uint32_t received_argc; -std::vector<std::string> received_argn; -std::vector<std::string> received_argv; -PP_Bool bool_to_return; -PP_Bool DidCreate(PP_Instance instance, uint32_t argc, const char* argn[], - const char* argv[]) { - received_instance = instance; - received_argc = argc; - received_argn.clear(); - received_argn.insert(received_argn.begin(), argn, argn + argc); - received_argv.clear(); - received_argv.insert(received_argv.begin(), argv, argv + argc); - return bool_to_return; -} - -void DidDestroy(PP_Instance instance) { - received_instance = instance; -} - -PP_Rect received_position; -PP_Rect received_clip; -// DidChangeView is asynchronous. We wait until the call has completed before -// proceeding on to the next test. -base::WaitableEvent did_change_view_called( - base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED); -void DidChangeView(PP_Instance instance, const PP_Rect* position, - const PP_Rect* clip) { - received_instance = instance; - received_position = *position; - received_clip = *clip; - did_change_view_called.Signal(); -} - -PP_Bool received_has_focus; -base::WaitableEvent did_change_focus_called( - base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED); -void DidChangeFocus(PP_Instance instance, PP_Bool has_focus) { - received_instance = instance; - received_has_focus = has_focus; - did_change_focus_called.Signal(); -} - -PP_Bool HandleDocumentLoad(PP_Instance instance, PP_Resource url_loader) { - // This one requires use of the PPB_URLLoader proxy and PPB_Core, plus a - // resource tracker for the url_loader resource. - // TODO(dmichael): Mock those out and test this function. - NOTREACHED(); -} - -// Clear all the 'received' values for our mock. Call this before you expect -// one of the functions to be invoked. TODO(dmichael): It would be better to -// have a flag also for each function, so we know the right one got called. -void ResetReceived() { - received_instance = 0; - received_argc = 0; - received_argn.clear(); - received_argv.clear(); - memset(&received_position, 0, sizeof(received_position)); - memset(&received_clip, 0, sizeof(received_clip)); - received_has_focus = PP_FALSE; -} - -PPP_Instance_1_0 ppp_instance_1_0 = { - &DidCreate, - &DidDestroy, - &DidChangeView, - &DidChangeFocus, - &HandleDocumentLoad -}; - -// PPP_Instance_Proxy::DidChangeView relies on PPB_Fullscreen being -// available with a valid implementation of IsFullScreen, so we mock it. -PP_Bool IsFullscreen(PP_Instance instance) { - return PP_FALSE; -} -PPB_Fullscreen ppb_fullscreen = { &IsFullscreen }; - -} // namespace - -class PPP_Instance_ProxyTest : public TwoWayTest { - public: - PPP_Instance_ProxyTest() - : TwoWayTest(TwoWayTest::TEST_PPP_INTERFACE) { - } -}; - -TEST_F(PPP_Instance_ProxyTest, PPPInstance1_0) { - plugin().RegisterTestInterface(PPP_INSTANCE_INTERFACE_1_0, &ppp_instance_1_0); - host().RegisterTestInterface(PPB_FULLSCREEN_INTERFACE, - &ppb_fullscreen); - - // Grab the host-side proxy for the interface. The browser only speaks 1.1, - // while the proxy ensures support for the 1.0 version on the plugin side. - const PPP_Instance_1_1* ppp_instance = static_cast<const PPP_Instance_1_1*>( - host().host_dispatcher()->GetProxiedInterface( - PPP_INSTANCE_INTERFACE_1_1)); - - // Call each function in turn, make sure we get the expected values and - // returns. - // - // We don't test DidDestroy, because it has the side-effect of removing the - // PP_Instance from the PluginDispatcher, which will cause a failure later - // when the test is torn down. - PP_Instance expected_instance = pp_instance(); - std::vector<std::string> expected_argn, expected_argv; - expected_argn.push_back("Hello"); - expected_argn.push_back("world."); - expected_argv.push_back("elloHay"); - expected_argv.push_back("orldway."); - std::vector<const char*> argn_to_pass, argv_to_pass; - CHECK(expected_argn.size() == expected_argv.size()); - for (size_t i = 0; i < expected_argn.size(); ++i) { - argn_to_pass.push_back(expected_argn[i].c_str()); - argv_to_pass.push_back(expected_argv[i].c_str()); - } - uint32_t expected_argc = static_cast<uint32_t>(expected_argn.size()); - bool_to_return = PP_TRUE; - ResetReceived(); - // Tell the host resource tracker about the instance. - host().resource_tracker().DidCreateInstance(expected_instance); - EXPECT_EQ(bool_to_return, ppp_instance->DidCreate(expected_instance, - expected_argc, - &argn_to_pass[0], - &argv_to_pass[0])); - EXPECT_EQ(received_instance, expected_instance); - EXPECT_EQ(received_argc, expected_argc); - EXPECT_EQ(received_argn, expected_argn); - EXPECT_EQ(received_argv, expected_argv); - - PP_Rect expected_position = { {1, 2}, {3, 4} }; - PP_Rect expected_clip = { {5, 6}, {7, 8} }; - ViewData data; - data.rect = expected_position; - data.is_fullscreen = false; - data.is_page_visible = true; - data.clip_rect = expected_clip; - data.device_scale = 1.0f; - ResetReceived(); - LockingResourceReleaser view_resource( - (new PPB_View_Shared(OBJECT_IS_IMPL, - expected_instance, data))->GetReference()); - ppp_instance->DidChangeView(expected_instance, view_resource.get()); - did_change_view_called.Wait(); - EXPECT_EQ(received_instance, expected_instance); - EXPECT_EQ(received_position.point.x, expected_position.point.x); - EXPECT_EQ(received_position.point.y, expected_position.point.y); - EXPECT_EQ(received_position.size.width, expected_position.size.width); - EXPECT_EQ(received_position.size.height, expected_position.size.height); - EXPECT_EQ(received_clip.point.x, expected_clip.point.x); - EXPECT_EQ(received_clip.point.y, expected_clip.point.y); - EXPECT_EQ(received_clip.size.width, expected_clip.size.width); - EXPECT_EQ(received_clip.size.height, expected_clip.size.height); - - PP_Bool expected_has_focus = PP_TRUE; - ResetReceived(); - ppp_instance->DidChangeFocus(expected_instance, expected_has_focus); - did_change_focus_called.Wait(); - EXPECT_EQ(received_instance, expected_instance); - EXPECT_EQ(received_has_focus, expected_has_focus); - - // TODO(dmichael): Need to mock out a resource Tracker to be able to test - // HandleResourceLoad. It also requires - // PPB_Core.AddRefResource and for PPB_URLLoader to be - // registered. - - host().resource_tracker().DidDeleteInstance(expected_instance); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/ppp_messaging_proxy_unittest.cc b/proxy/ppp_messaging_proxy_unittest.cc deleted file mode 100644 index 003d2c9..0000000 --- a/proxy/ppp_messaging_proxy_unittest.cc +++ /dev/null
@@ -1,145 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <cstring> - -#include "base/functional/bind.h" -#include "base/synchronization/waitable_event.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/ppp_messaging.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/serialized_var.h" -#include "ppapi/shared_impl/api_id.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/var.h" - -namespace ppapi { -namespace proxy { - -namespace { - -// This is an ad-hoc mock of PPP_Messaging using global variables. Eventually, -// generalize making PPAPI interface mocks by using IDL or macro/template magic. -PP_Instance g_received_instance; -PP_Var g_received_var; -base::WaitableEvent handle_message_called( - base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED); - -void HandleMessage(PP_Instance instance, PP_Var message_data) { - g_received_instance = instance; - g_received_var = message_data; - handle_message_called.Signal(); -} - -// Clear all the 'received' values for our mock. Call this before you expect -// one of the functions to be invoked. -void ResetReceived() { - g_received_instance = 0; - g_received_var.type = PP_VARTYPE_UNDEFINED; - g_received_var.value.as_id = 0; -} - -PPP_Messaging ppp_messaging_mock = { - &HandleMessage -}; - -// CallHandleMessage does the host-side work to cause HandleMessage to be called -// in the plugin side. -void CallHandleMessage(Dispatcher* dispatcher, - PP_Instance instance, - PP_Var message) { - dispatcher->Send(new PpapiMsg_PPPMessaging_HandleMessage( - API_ID_PPP_MESSAGING, - instance, - SerializedVarSendInputShmem(dispatcher, message, instance))); -} - -class PPP_Messaging_ProxyTest : public TwoWayTest { - public: - PPP_Messaging_ProxyTest() - : TwoWayTest(TwoWayTest::TEST_PPP_INTERFACE) { - plugin().RegisterTestInterface(PPP_MESSAGING_INTERFACE, - &ppp_messaging_mock); - } -}; - -void CompareAndReleaseStringVar(PluginProxyTestHarness* plugin_harness, - PP_Var received_var, - const std::string& test_string) { - ProxyAutoLock lock; - Var* received_string = plugin_harness->var_tracker().GetVar(received_var); - ASSERT_TRUE(received_string); - ASSERT_TRUE(received_string->AsStringVar()); - EXPECT_EQ(test_string, received_string->AsStringVar()->value()); - // Now release the var, and the string should go away (because the ref - // count should be one). - plugin_harness->var_tracker().ReleaseVar(received_var); - EXPECT_FALSE(StringVar::FromPPVar(received_var)); -} - -} // namespace - -TEST_F(PPP_Messaging_ProxyTest, SendMessages) { - PP_Instance expected_instance = pp_instance(); - PP_Var expected_var = PP_MakeUndefined(); - ResetReceived(); - Dispatcher* host_dispatcher = host().GetDispatcher(); - CallHandleMessage(host_dispatcher, expected_instance, expected_var); - handle_message_called.Wait(); - EXPECT_EQ(expected_instance, g_received_instance); - EXPECT_EQ(expected_var.type, g_received_var.type); - - expected_var = PP_MakeNull(); - ResetReceived(); - CallHandleMessage(host_dispatcher, expected_instance, expected_var); - handle_message_called.Wait(); - EXPECT_EQ(expected_instance, g_received_instance); - EXPECT_EQ(expected_var.type, g_received_var.type); - - expected_var = PP_MakeBool(PP_TRUE); - ResetReceived(); - CallHandleMessage(host_dispatcher, expected_instance, expected_var); - handle_message_called.Wait(); - EXPECT_EQ(expected_instance, g_received_instance); - EXPECT_EQ(expected_var.type, g_received_var.type); - EXPECT_EQ(expected_var.value.as_bool, g_received_var.value.as_bool); - - expected_var = PP_MakeInt32(12345); - ResetReceived(); - CallHandleMessage(host_dispatcher, expected_instance, expected_var); - handle_message_called.Wait(); - EXPECT_EQ(expected_instance, g_received_instance); - EXPECT_EQ(expected_var.type, g_received_var.type); - EXPECT_EQ(expected_var.value.as_int, g_received_var.value.as_int); - - expected_var = PP_MakeDouble(3.1415); - ResetReceived(); - CallHandleMessage(host_dispatcher, expected_instance, expected_var); - handle_message_called.Wait(); - EXPECT_EQ(expected_instance, g_received_instance); - EXPECT_EQ(expected_var.type, g_received_var.type); - EXPECT_EQ(expected_var.value.as_double, g_received_var.value.as_double); - - const std::string kTestString("Hello world!"); - expected_var = StringVar::StringToPPVar(kTestString); - ResetReceived(); - CallHandleMessage(host_dispatcher, expected_instance, expected_var); - // Now release the var, and the string should go away (because the ref - // count should be one). - host().var_tracker().ReleaseVar(expected_var); - EXPECT_FALSE(StringVar::FromPPVar(expected_var)); - - handle_message_called.Wait(); - EXPECT_EQ(expected_instance, g_received_instance); - EXPECT_EQ(expected_var.type, g_received_var.type); - PostTaskOnRemoteHarness(base::BindOnce(CompareAndReleaseStringVar, &plugin(), - g_received_var, kTestString)); -} - -} // namespace proxy -} // namespace ppapi -
diff --git a/proxy/printing_resource_unittest.cc b/proxy/printing_resource_unittest.cc deleted file mode 100644 index f4da093..0000000 --- a/proxy/printing_resource_unittest.cc +++ /dev/null
@@ -1,102 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include <cstring> - -#include "ppapi/c/dev/ppb_printing_dev.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/proxy/locking_resource_releaser.h" -#include "ppapi/proxy/plugin_message_filter.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/printing_resource.h" -#include "ppapi/thunk/thunk.h" - -namespace ppapi { -namespace proxy { - -namespace { - -typedef PluginProxyTest PrintingResourceTest; - -bool g_callback_called; -int32_t g_callback_result; - -void Callback(void* user_data, int32_t result) { - g_callback_called = true; - g_callback_result = result; -} - -bool PP_SizeEqual(const PP_Size& lhs, const PP_Size& rhs) { - return lhs.width == rhs.width && lhs.height == rhs.height; -} - -bool PP_RectEqual(const PP_Rect& lhs, const PP_Rect& rhs) { - return lhs.point.x == rhs.point.x && - lhs.point.y == rhs.point.y && - PP_SizeEqual(lhs.size, rhs.size); -} - -} // namespace - -// Does a full test of GetDefaultPrintSettings() and reply functionality in the -// plugin side using the public C interfaces. -TEST_F(PrintingResourceTest, GetDefaultPrintSettings) { - g_callback_called = false; - - const PPB_Printing_Dev_0_7* printing_iface = - thunk::GetPPB_Printing_Dev_0_7_Thunk(); - LockingResourceReleaser res(printing_iface->Create(pp_instance())); - - PP_PrintSettings_Dev output_settings; - - int32_t result = printing_iface->GetDefaultPrintSettings( - res.get(), &output_settings, PP_MakeCompletionCallback(&Callback, NULL)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - // Should have sent a "GetDefaultPrintSettings" message. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_Printing_GetDefaultPrintSettings::ID, ¶ms, &msg)); - - // Synthesize a response with some random print settings. - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(PP_OK); - - PP_PrintSettings_Dev reply_settings = {{{0, 0}, {500, 515}}, - {{25, 35}, {300, 720}}, - {600, 700}, - 200, - PP_PRINTORIENTATION_NORMAL, - PP_PRINTSCALINGOPTION_NONE, - PP_FALSE, - PP_PRINTOUTPUTFORMAT_PDF}; - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_Printing_GetDefaultPrintSettingsReply( - reply_settings)); - - EXPECT_TRUE(PP_RectEqual(reply_settings.printable_area, - output_settings.printable_area)); - EXPECT_TRUE(PP_RectEqual(reply_settings.content_area, - output_settings.content_area)); - EXPECT_TRUE(PP_SizeEqual(reply_settings.paper_size, - output_settings.paper_size)); - EXPECT_EQ(reply_settings.dpi, output_settings.dpi); - EXPECT_EQ(reply_settings.orientation, output_settings.orientation); - EXPECT_EQ(reply_settings.print_scaling_option, - output_settings.print_scaling_option); - EXPECT_EQ(reply_settings.grayscale, output_settings.grayscale); - EXPECT_EQ(reply_settings.format, output_settings.format); - - EXPECT_EQ(g_callback_result, PP_OK); - EXPECT_EQ(g_callback_called, true); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/raw_var_data_unittest.cc b/proxy/raw_var_data_unittest.cc deleted file mode 100644 index e0b7d01..0000000 --- a/proxy/raw_var_data_unittest.cc +++ /dev/null
@@ -1,211 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/raw_var_data.h" - -#include <stddef.h> -#include <stdint.h> - -#include <memory> - -#include "base/functional/bind.h" -#include "base/memory/ref_counted.h" -#include "base/test/task_environment.h" -#include "base/values.h" -#include "ipc/ipc_message.h" -#include "ppapi/c/pp_bool.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/shared_impl/array_var.h" -#include "ppapi/shared_impl/dictionary_var.h" -#include "ppapi/shared_impl/ppapi_globals.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/resource_var.h" -#include "ppapi/shared_impl/scoped_pp_var.h" -#include "ppapi/shared_impl/test_globals.h" -#include "ppapi/shared_impl/test_utils.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/shared_impl/var_tracker.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { -namespace proxy { - -namespace { - -void DefaultHandleWriter(base::Pickle* m, const SerializedHandle& handle) { - IPC::ParamTraits<SerializedHandle>::Write(m, handle); -} - -class RawVarDataTest : public testing::Test { - public: - RawVarDataTest() {} - ~RawVarDataTest() {} - - // testing::Test implementation. - virtual void SetUp() { - ProxyLock::Acquire(); - } - virtual void TearDown() { - ASSERT_TRUE(PpapiGlobals::Get()->GetVarTracker()->GetLiveVars().empty()); - ProxyLock::Release(); - } - - private: - base::test::SingleThreadTaskEnvironment - task_environment_; // Required to receive callbacks. - TestGlobals globals_; -}; - -bool WriteAndRead(const PP_Var& var, PP_Var* result) { - PP_Instance dummy_instance = 1234; - std::unique_ptr<RawVarDataGraph> expected_data( - RawVarDataGraph::Create(var, dummy_instance)); - if (!expected_data) - return false; - IPC::Message m; - expected_data->Write(&m, base::BindRepeating(&DefaultHandleWriter)); - base::PickleIterator iter(m); - std::unique_ptr<RawVarDataGraph> actual_data( - RawVarDataGraph::Read(&m, &iter)); - *result = actual_data->CreatePPVar(dummy_instance); - return true; -} - -// Assumes a ref for var. -bool WriteReadAndCompare(const PP_Var& var) { - ScopedPPVar expected(ScopedPPVar::PassRef(), var); - PP_Var result; - bool success = WriteAndRead(expected.get(), &result); - if (!success) - return false; - ScopedPPVar actual(ScopedPPVar::PassRef(), result); - return TestEqual(expected.get(), actual.get(), true); -} - -} // namespace - -TEST_F(RawVarDataTest, SimpleTest) { - EXPECT_TRUE(WriteReadAndCompare(PP_MakeUndefined())); - EXPECT_TRUE(WriteReadAndCompare(PP_MakeNull())); - EXPECT_TRUE(WriteReadAndCompare(PP_MakeInt32(100))); - EXPECT_TRUE(WriteReadAndCompare(PP_MakeBool(PP_TRUE))); - EXPECT_TRUE(WriteReadAndCompare(PP_MakeDouble(53.75))); - PP_Var object; - object.type = PP_VARTYPE_OBJECT; - object.value.as_id = 10; - EXPECT_TRUE(WriteReadAndCompare(object)); -} - -TEST_F(RawVarDataTest, StringTest) { - EXPECT_TRUE(WriteReadAndCompare(StringVar::StringToPPVar(""))); - EXPECT_TRUE(WriteReadAndCompare(StringVar::StringToPPVar("hello world!"))); -} - -TEST_F(RawVarDataTest, ArrayBufferTest) { - std::string data = "hello world!"; - PP_Var var = PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar( - static_cast<uint32_t>(data.size()), data.data()); - EXPECT_TRUE(WriteReadAndCompare(var)); - var = PpapiGlobals::Get()->GetVarTracker()->MakeArrayBufferPPVar( - 0, static_cast<void*>(NULL)); - EXPECT_TRUE(WriteReadAndCompare(var)); - // TODO(raymes): add tests for shmem type array buffers. -} - -TEST_F(RawVarDataTest, DictionaryArrayTest) { - // Empty array. - scoped_refptr<ArrayVar> array(new ArrayVar); - ScopedPPVar release_array(ScopedPPVar::PassRef(), array->GetPPVar()); - EXPECT_TRUE(WriteReadAndCompare(array->GetPPVar())); - - size_t index = 0; - - // Array with primitives. - array->Set(static_cast<uint32_t>(index++), PP_MakeUndefined()); - array->Set(static_cast<uint32_t>(index++), PP_MakeNull()); - array->Set(static_cast<uint32_t>(index++), PP_MakeInt32(100)); - array->Set(static_cast<uint32_t>(index++), PP_MakeBool(PP_FALSE)); - array->Set(static_cast<uint32_t>(index++), PP_MakeDouble(0.123)); - EXPECT_TRUE(WriteReadAndCompare(array->GetPPVar())); - - // Array with 2 references to the same string. - ScopedPPVar release_string( - ScopedPPVar::PassRef(), StringVar::StringToPPVar("abc")); - array->Set(static_cast<uint32_t>(index++), release_string.get()); - array->Set(static_cast<uint32_t>(index++), release_string.get()); - EXPECT_TRUE(WriteReadAndCompare(array->GetPPVar())); - - // Array with nested array that references the same string. - scoped_refptr<ArrayVar> array2(new ArrayVar); - ScopedPPVar release_array2(ScopedPPVar::PassRef(), array2->GetPPVar()); - array2->Set(0, release_string.get()); - array->Set(static_cast<uint32_t>(index++), release_array2.get()); - EXPECT_TRUE(WriteReadAndCompare(array->GetPPVar())); - - // Empty dictionary. - scoped_refptr<DictionaryVar> dictionary(new DictionaryVar); - ScopedPPVar release_dictionary(ScopedPPVar::PassRef(), - dictionary->GetPPVar()); - EXPECT_TRUE(WriteReadAndCompare(dictionary->GetPPVar())); - - // Dictionary with primitives. - dictionary->SetWithStringKey("1", PP_MakeUndefined()); - dictionary->SetWithStringKey("2", PP_MakeNull()); - dictionary->SetWithStringKey("3", PP_MakeInt32(-100)); - dictionary->SetWithStringKey("4", PP_MakeBool(PP_TRUE)); - dictionary->SetWithStringKey("5", PP_MakeDouble(-103.52)); - EXPECT_TRUE(WriteReadAndCompare(dictionary->GetPPVar())); - - // Dictionary with 2 references to the same string. - dictionary->SetWithStringKey("6", release_string.get()); - dictionary->SetWithStringKey("7", release_string.get()); - EXPECT_TRUE(WriteReadAndCompare(dictionary->GetPPVar())); - - // Dictionary with nested dictionary that references the same string. - scoped_refptr<DictionaryVar> dictionary2(new DictionaryVar); - ScopedPPVar release_dictionary2(ScopedPPVar::PassRef(), - dictionary2->GetPPVar()); - dictionary2->SetWithStringKey("abc", release_string.get()); - dictionary->SetWithStringKey("8", release_dictionary2.get()); - EXPECT_TRUE(WriteReadAndCompare(dictionary->GetPPVar())); - - // Array with dictionary. - array->Set(static_cast<uint32_t>(index++), release_dictionary.get()); - EXPECT_TRUE(WriteReadAndCompare(array->GetPPVar())); - - // Array with dictionary with array. - array2->Set(0, PP_MakeInt32(100)); - dictionary->SetWithStringKey("9", release_array2.get()); - EXPECT_TRUE(WriteReadAndCompare(array->GetPPVar())); - - // Array <-> dictionary cycle. - dictionary->SetWithStringKey("10", release_array.get()); - PP_Var result; - ASSERT_FALSE(WriteAndRead(release_dictionary.get(), &result)); - // Break the cycle. - // TODO(raymes): We need some better machinery for releasing vars with - // cycles. Remove the code below once we have that. - dictionary->DeleteWithStringKey("10"); - - // Array with self references. - array->Set(static_cast<uint32_t>(index), release_array.get()); - ASSERT_FALSE(WriteAndRead(release_array.get(), &result)); - // Break the self reference. - array->Set(static_cast<uint32_t>(index), PP_MakeUndefined()); -} - -TEST_F(RawVarDataTest, ResourceTest) { - // TODO(mgiuca): This test passes trivially, since GetVarTracker() returns a - // TestVarTracker which returns a null PP_Var. - ScopedPPVar resource( - ScopedPPVar::PassRef(), - PpapiGlobals::Get()->GetVarTracker()->MakeResourcePPVar(34)); - EXPECT_TRUE(WriteReadAndCompare(resource.get())); - - // TODO(mgiuca): Test a host resource with an IPC::Message. It is currently a - // checkfail to deserialize such a resource. -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/resource_message_test_sink.cc b/proxy/resource_message_test_sink.cc deleted file mode 100644 index 8e5ab06..0000000 --- a/proxy/resource_message_test_sink.cc +++ /dev/null
@@ -1,159 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/resource_message_test_sink.h" - -#include <stddef.h> - -#include <tuple> - -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/resource_message_params.h" - -namespace ppapi { -namespace proxy { - -namespace { - -// Backend for GetAllResource[Calls|Replies]Matching. -template <class WrapperMessage, class Params> -std::vector<std::pair<Params, IPC::Message>> GetAllResourceMessagesMatching( - const ResourceMessageTestSink& sink, - uint32_t id) { - std::vector<std::pair<Params, IPC::Message> > result; - for (size_t i = 0; i < sink.message_count(); i++) { - const IPC::Message* msg = sink.GetMessageAt(i); - if (msg->type() == WrapperMessage::ID) { - typename WrapperMessage::Param params; - WrapperMessage::Read(msg, ¶ms); - Params cur_params = std::get<0>(params); - IPC::Message cur_msg = std::get<1>(params); - if (cur_msg.type() == id) { - result.push_back(std::make_pair(cur_params, cur_msg)); - } - } - } - return result; -} - -} // namespace - -ResourceMessageTestSink::ResourceMessageTestSink() { -} - -ResourceMessageTestSink::~ResourceMessageTestSink() { -} - -bool ResourceMessageTestSink::Send(IPC::Message* msg) { - int message_id = 0; - std::unique_ptr<IPC::MessageReplyDeserializer> reply_deserializer; - if (msg->is_sync()) { - reply_deserializer = - static_cast<IPC::SyncMessage*>(msg)->TakeReplyDeserializer(); - message_id = IPC::SyncMessage::GetMessageId(*msg); - } - bool result = IPC::TestSink::Send(msg); // Deletes |msg|. - if (sync_reply_msg_.get()) { - // |sync_reply_msg_| should always be a reply to the pending sync message. - DCHECK(IPC::SyncMessage::IsMessageReplyTo(*sync_reply_msg_.get(), - message_id)); - reply_deserializer->SerializeOutputParameters(*sync_reply_msg_.get()); - sync_reply_msg_.reset(NULL); - } - return result; -} - -void ResourceMessageTestSink::SetSyncReplyMessage(IPC::Message* reply_msg) { - DCHECK(!sync_reply_msg_.get()); - sync_reply_msg_.reset(reply_msg); -} - -bool ResourceMessageTestSink::GetFirstResourceCallMatching( - uint32_t id, - ResourceMessageCallParams* params, - IPC::Message* nested_msg) const { - ResourceCallVector matching_messages = - GetAllResourceMessagesMatching<PpapiHostMsg_ResourceCall, - ResourceMessageCallParams>(*this, id); - if (matching_messages.empty()) - return false; - - *params = matching_messages[0].first; - *nested_msg = matching_messages[0].second; - return true; -} - -bool ResourceMessageTestSink::GetFirstResourceReplyMatching( - uint32_t id, - ResourceMessageReplyParams* params, - IPC::Message* nested_msg) { - ResourceReplyVector matching_messages = - GetAllResourceMessagesMatching<PpapiPluginMsg_ResourceReply, - ResourceMessageReplyParams>(*this, id); - if (matching_messages.empty()) - return false; - - *params = matching_messages[0].first; - *nested_msg = matching_messages[0].second; - return true; -} - -ResourceMessageTestSink::ResourceCallVector -ResourceMessageTestSink::GetAllResourceCallsMatching(uint32_t id) { - return GetAllResourceMessagesMatching<PpapiHostMsg_ResourceCall, - ResourceMessageCallParams>(*this, id); -} - -ResourceMessageTestSink::ResourceReplyVector -ResourceMessageTestSink::GetAllResourceRepliesMatching(uint32_t id) { - return GetAllResourceMessagesMatching<PpapiPluginMsg_ResourceReply, - ResourceMessageReplyParams>(*this, id); -} - -ResourceSyncCallHandler::ResourceSyncCallHandler( - ResourceMessageTestSink* test_sink, - uint32_t incoming_type, - int32_t result, - const IPC::Message& reply_msg) - : test_sink_(test_sink), - incoming_type_(incoming_type), - result_(result), - reply_msg_(reply_msg) {} - -ResourceSyncCallHandler::~ResourceSyncCallHandler() { -} - -bool ResourceSyncCallHandler::OnMessageReceived(const IPC::Message& msg) { - if (msg.type() != PpapiHostMsg_ResourceSyncCall::ID) - return false; - PpapiHostMsg_ResourceSyncCall::Schema::SendParam send_params; - bool success = PpapiHostMsg_ResourceSyncCall::ReadSendParam( - &msg, &send_params); - DCHECK(success); - ResourceMessageCallParams call_params = std::get<0>(send_params); - IPC::Message call_msg = std::get<1>(send_params); - if (call_msg.type() != incoming_type_) - return false; - IPC::Message* wrapper_reply_msg = IPC::SyncMessage::GenerateReply(&msg); - ResourceMessageReplyParams reply_params(call_params.pp_resource(), - call_params.sequence()); - reply_params.set_result(result_); - if (serialized_handle_) - reply_params.AppendHandle(std::move(*serialized_handle_)); - PpapiHostMsg_ResourceSyncCall::WriteReplyParams( - wrapper_reply_msg, reply_params, reply_msg_); - test_sink_->SetSyncReplyMessage(wrapper_reply_msg); - - // Stash a copy of the message for inspection later. - last_handled_msg_ = call_msg; - return true; -} - -void ResourceSyncCallHandler::set_serialized_handle( - std::unique_ptr<SerializedHandle> serialized_handle) { - serialized_handle_ = std::move(serialized_handle); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/resource_message_test_sink.h b/proxy/resource_message_test_sink.h deleted file mode 100644 index 114b777..0000000 --- a/proxy/resource_message_test_sink.h +++ /dev/null
@@ -1,106 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_PROXY_RESOURCE_MESSAGE_TEST_SINK_H_ -#define PPAPI_PROXY_RESOURCE_MESSAGE_TEST_SINK_H_ - -#include "ipc/ipc_listener.h" -#include "ipc/ipc_test_sink.h" -#include "ppapi/c/pp_stdint.h" - -namespace ppapi { -namespace proxy { - -class ResourceMessageCallParams; -class ResourceMessageReplyParams; -class SerializedHandle; - -// Extends IPC::TestSink to add extra capabilities for searching for and -// decoding resource messages. -class ResourceMessageTestSink : public IPC::TestSink { - public: - ResourceMessageTestSink(); - ~ResourceMessageTestSink() override; - - // IPC::TestSink. - // Overridden to handle sync messages. - bool Send(IPC::Message* msg) override; - - // Sets the reply message that will be returned to the next sync message sent. - // This test sink owns any reply messages passed into this method. - void SetSyncReplyMessage(IPC::Message* reply_msg); - - // Searches the queue for the first resource call message with a nested - // message matching the given ID. On success, returns true and populates the - // given params and nested message. - bool GetFirstResourceCallMatching(uint32_t id, - ResourceMessageCallParams* params, - IPC::Message* nested_msg) const; - - // Like GetFirstResourceCallMatching except for replies. - bool GetFirstResourceReplyMatching(uint32_t id, - ResourceMessageReplyParams* params, - IPC::Message* nested_msg); - - // Searches the queue for all resource call messages with a nested message - // matching the given ID. - typedef std::pair<ResourceMessageCallParams, IPC::Message> ResourceCall; - typedef std::vector<ResourceCall> ResourceCallVector; - ResourceCallVector GetAllResourceCallsMatching(uint32_t id); - - // Like GetAllResourceCallsMatching except for replies. - typedef std::pair<ResourceMessageReplyParams, IPC::Message> ResourceReply; - typedef std::vector<ResourceReply> ResourceReplyVector; - ResourceReplyVector GetAllResourceRepliesMatching(uint32_t id); - - private: - std::unique_ptr<IPC::Message> sync_reply_msg_; -}; - -// This is a message handler which generates reply messages for synchronous -// resource calls. This allows unit testing of the plugin side of resources -// which send sync messages. If you want to reply to a sync message type named -// |PpapiHostMsg_X_Y| with |PpapiPluginMsg_X_YReply| then usage would be as -// follows (from within |PluginProxyTest|s): -// -// PpapiHostMsg_X_YReply my_reply; -// ResourceSyncCallHandler handler(&sink(), -// PpapiHostMsg_X_Y::ID, -// PP_OK, -// my_reply); -// sink().AddFilter(&handler); -// // Do stuff to send a sync message ... -// // You can check handler.last_handled_msg() to ensure the correct message was -// // handled. -// sink().RemoveFilter(&handler); -class ResourceSyncCallHandler : public IPC::Listener { - public: - ResourceSyncCallHandler(ResourceMessageTestSink* test_sink, - uint32_t incoming_type, - int32_t result, - const IPC::Message& reply_msg); - ~ResourceSyncCallHandler() override; - - // IPC::Listener. - bool OnMessageReceived(const IPC::Message& message) override; - - IPC::Message last_handled_msg() { return last_handled_msg_; } - - // Sets a handle to be appended to the ReplyParams. - void set_serialized_handle( - std::unique_ptr<SerializedHandle> serialized_handle); - - private: - ResourceMessageTestSink* test_sink_; - uint32_t incoming_type_; - int32_t result_; - std::unique_ptr<SerializedHandle> serialized_handle_; - IPC::Message reply_msg_; - IPC::Message last_handled_msg_; -}; - -} // namespace proxy -} // namespace ppapi - -#endif // PPAPI_PROXY_RESOURCE_MESSAGE_TEST_SINK_H_
diff --git a/proxy/serialized_var_unittest.cc b/proxy/serialized_var_unittest.cc deleted file mode 100644 index 74c46b7..0000000 --- a/proxy/serialized_var_unittest.cc +++ /dev/null
@@ -1,393 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include <stdint.h> - -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/proxy_object_var.h" -#include "ppapi/proxy/serialized_var.h" -#include "ppapi/shared_impl/proxy_lock.h" - -namespace ppapi { -namespace proxy { - -namespace { - -PP_Var MakeObjectVar(int64_t object_id) { - PP_Var ret; - ret.type = PP_VARTYPE_OBJECT; - ret.value.as_id = object_id; - return ret; -} - -class SerializedVarTest : public PluginProxyTest { - public: - SerializedVarTest() {} -}; - -} // namespace - -// Tests output arguments in the plugin. This is when the host calls into the -// plugin and the plugin returns something via an out param, like an exception. -TEST_F(SerializedVarTest, PluginSerializedVarInOutParam) { - ProxyAutoLock lock; - PP_Var host_object = MakeObjectVar(0x31337); - - PP_Var plugin_object; - { - // Receive the object param, we should be tracking it with no refcount, and - // no messages sent. - SerializedVarTestConstructor input(host_object); - SerializedVarReceiveInput receive_input(input); - plugin_object = receive_input.Get(plugin_dispatcher()); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0u, sink().message_count()); - - SerializedVar sv; - { - // The "OutParam" does its work in its destructor, it will write the - // information to the SerializedVar we passed in the constructor. - SerializedVarOutParam out_param(&sv); - // An out-param needs to pass a reference to the caller, so it's the - // responsibility of the plugin to bump the ref-count on an input - // parameter. - var_tracker().AddRefVar(plugin_object); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - // We should have informed the host that a reference was taken. - EXPECT_EQ(1u, sink().message_count()); - *out_param.OutParam(plugin_dispatcher()) = plugin_object; - } - - // The object should have transformed the plugin object back to the host - // object ID. Nothing in the var tracker should have changed yet, and no - // messages should have been sent. - SerializedVarTestReader reader(sv); - EXPECT_EQ(host_object.value.as_id, reader.GetVar().value.as_id); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(1u, sink().message_count()); - } - - // The out param should have done an "end receive caller owned" on the plugin - // var serialization rules, which should have released the "track-with-no- - // reference" count in the var tracker as well as the 1 reference we passed - // back to the host, so the object should no longer be in the tracker. The - // reference we added has been removed, so another message should be sent to - // the host to tell it we're done with the object. - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(2u, sink().message_count()); -} - -// Tests output strings in the plugin. This is when the host calls into the -// plugin with a string and the plugin returns it via an out param. -TEST_F(SerializedVarTest, PluginSerializedStringVarInOutParam) { - ProxyAutoLock lock; - PP_Var plugin_string; - const std::string kTestString("elite"); - { - // Receive the string param. We should track it with 1 refcount. - SerializedVarTestConstructor input(kTestString); - SerializedVarReceiveInput receive_input(input); - plugin_string = receive_input.Get(plugin_dispatcher()); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_string)); - EXPECT_EQ(0u, sink().message_count()); - - SerializedVar sv; - { - // The "OutParam" does its work in its destructor, it will write the - // information to the SerializedVar we passed in the constructor. - SerializedVarOutParam out_param(&sv); - // An out-param needs to pass a reference to the caller, so it's the - // responsibility of the plugin to bump the ref-count of an input - // parameter. - var_tracker().AddRefVar(plugin_string); - EXPECT_EQ(2, var_tracker().GetRefCountForObject(plugin_string)); - EXPECT_EQ(0u, sink().message_count()); - *out_param.OutParam(plugin_dispatcher()) = plugin_string; - } - - // The SerializedVar should have set the string value internally. Nothing in - // the var tracker should have changed yet, and no messages should have been - // sent. - SerializedVarTestReader reader(sv); - //EXPECT_EQ(kTestString, *reader.GetTrackerStringPtr()); - EXPECT_EQ(2, var_tracker().GetRefCountForObject(plugin_string)); - EXPECT_EQ(0u, sink().message_count()); - } - // The reference the string had initially should be gone, and the reference we - // passed to the host should also be gone, so the string should be removed. - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_string)); - EXPECT_EQ(0u, sink().message_count()); -} - -// Tests receiving an argument and passing it back to the browser as an output -// parameter. -TEST_F(SerializedVarTest, PluginSerializedVarOutParam) { - ProxyAutoLock lock; - PP_Var host_object = MakeObjectVar(0x31337); - - // Start tracking this object in the plugin. - PP_Var plugin_object = var_tracker().ReceiveObjectPassRef( - host_object, plugin_dispatcher()); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - - { - SerializedVar sv; - { - // The "OutParam" does its work in its destructor, it will write the - // information to the SerializedVar we passed in the constructor. - SerializedVarOutParam out_param(&sv); - *out_param.OutParam(plugin_dispatcher()) = plugin_object; - } - - // The object should have transformed the plugin object back to the host - // object ID. Nothing in the var tracker should have changed yet, and no - // messages should have been sent. - SerializedVarTestReader reader(sv); - EXPECT_EQ(host_object.value.as_id, reader.GetVar().value.as_id); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0u, sink().message_count()); - } - - // The out param should have done an "end send pass ref" on the plugin - // var serialization rules, which should have in turn released the reference - // in the var tracker. Since we only had one reference, this should have sent - // a release to the browser. - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(1u, sink().message_count()); - - // We don't bother validating that message since it's nontrivial and the - // PluginVarTracker test has cases that cover that this message is correct. -} - -// Tests the case that the plugin receives the same var twice as an input -// parameter (not passing ownership). -TEST_F(SerializedVarTest, PluginReceiveInput) { - ProxyAutoLock lock; - PP_Var host_object = MakeObjectVar(0x31337); - - PP_Var plugin_object; - { - // Receive the first param, we should be tracking it with no refcount, and - // no messages sent. - SerializedVarTestConstructor input1(host_object); - SerializedVarReceiveInput receive_input(input1); - plugin_object = receive_input.Get(plugin_dispatcher()); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0u, sink().message_count()); - - // Receive the second param, it should be resolved to the same plugin - // object and there should still be no refcount. - SerializedVarTestConstructor input2(host_object); - SerializedVarReceiveInput receive_input2(input2); - PP_Var plugin_object2 = receive_input2.Get(plugin_dispatcher()); - EXPECT_EQ(plugin_object.value.as_id, plugin_object2.value.as_id); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0u, sink().message_count()); - - // Take a reference to the object, as if the plugin was using it, and then - // release it, we should still be tracking the object since the - // ReceiveInputs keep the "track_with_no_reference_count" alive until - // they're destroyed. - var_tracker().AddRefVar(plugin_object); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - var_tracker().ReleaseVar(plugin_object); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(2u, sink().message_count()); - } - - // Since we didn't keep any refs to the objects, it should have freed the - // object. - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_object)); -} - -// Tests the case that the plugin receives the same vars twice as an input -// parameter (not passing ownership) within a vector. -TEST_F(SerializedVarTest, PluginVectorReceiveInput) { - ProxyAutoLock lock; - PP_Var host_object = MakeObjectVar(0x31337); - - std::vector<PP_Var> plugin_objects; - std::vector<PP_Var> plugin_objects2; - { - // Receive the params. The object should be tracked with no refcount and - // no messages sent. The string should is plugin-side only and should have - // a reference-count of 1. - std::vector<SerializedVar> input1; - input1.push_back(SerializedVarTestConstructor(host_object)); - input1.push_back(SerializedVarTestConstructor("elite")); - SerializedVarVectorReceiveInput receive_input(input1); - uint32_t array_size = 0; - PP_Var* plugin_objects_array = - receive_input.Get(plugin_dispatcher(), &array_size); - plugin_objects.insert(plugin_objects.begin(), plugin_objects_array, - plugin_objects_array + array_size); - ASSERT_EQ(2u, array_size); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_objects[0])); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_objects[1])); - EXPECT_EQ(0u, sink().message_count()); - - // Receive the second param, it should be resolved to the same plugin - // object and there should still be no refcount. - std::vector<SerializedVar> input2; - input2.push_back(SerializedVarTestConstructor(host_object)); - input2.push_back(SerializedVarTestConstructor("elite")); - SerializedVarVectorReceiveInput receive_input2(input2); - uint32_t array_size2 = 0; - PP_Var* plugin_objects_array2 = - receive_input2.Get(plugin_dispatcher(), &array_size2); - plugin_objects2.insert(plugin_objects2.begin(), plugin_objects_array2, - plugin_objects_array2 + array_size2); - ASSERT_EQ(2u, array_size2); - EXPECT_EQ(plugin_objects[0].value.as_id, plugin_objects2[0].value.as_id); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_objects[0])); - // Strings get re-created with a new ID. We don't try to reuse strings in - // the tracker, so the string should get a new ID. - EXPECT_NE(plugin_objects[1].value.as_id, plugin_objects2[1].value.as_id); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_objects2[1])); - EXPECT_EQ(0u, sink().message_count()); - - // Take a reference to the object, as if the plugin was using it, and then - // release it, we should still be tracking the object since the - // ReceiveInputs keep the "track_with_no_reference_count" alive until - // they're destroyed. - var_tracker().AddRefVar(plugin_objects[0]); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_objects[0])); - var_tracker().ReleaseVar(plugin_objects[0]); - EXPECT_EQ(0, var_tracker().GetRefCountForObject(plugin_objects[0])); - EXPECT_EQ(2u, sink().message_count()); - - // Take a reference to a string and then release it. Make sure no messages - // are sent. - uint32_t old_message_count = static_cast<uint32_t>(sink().message_count()); - var_tracker().AddRefVar(plugin_objects[1]); - EXPECT_EQ(2, var_tracker().GetRefCountForObject(plugin_objects[1])); - var_tracker().ReleaseVar(plugin_objects[1]); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_objects[1])); - EXPECT_EQ(old_message_count, sink().message_count()); - } - - // Since we didn't keep any refs to the objects or strings, so they should - // have been freed. - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_objects[0])); - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_objects[1])); - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_objects2[1])); -} - -// Tests the browser sending a String var as a return value to make sure we -// ref-count the host side properly. -typedef HostProxyTest HostSerializedVarTest; -TEST_F(HostSerializedVarTest, PluginReceiveStringReturn) { - { - PP_Var string_var = StringVar::StringToPPVar("Hello"); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(string_var)); - GetDispatcher()->serialization_rules()->BeginSendPassRef(string_var); - GetDispatcher()->serialization_rules()->EndSendPassRef(string_var); - // It should be gone, so we should get -1 to indicate that. - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(string_var)); - } - - { - // Note this is as little weird; we're testing the behavior of the host- - // side of the proxy, but we use ProxyObjectVar, because this unit test - // doesn't have access to stuff in content/renderer/pepper. The ref-counting - // behavior should be the same, however. All we're really testing - // is the code in ppapi/proxy (HostVarSerializationRules). - scoped_refptr<Var> obj_var = new ProxyObjectVar(NULL, 1234); - PP_Var obj_pp_var = obj_var->GetPPVar(); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(obj_pp_var)); - GetDispatcher()->serialization_rules()->BeginSendPassRef(obj_pp_var); - GetDispatcher()->serialization_rules()->EndSendPassRef(obj_pp_var); - // The host side for object vars always keeps 1 ref on behalf of the plugin. - // See HostVarSerializationRules and PluginVarSerializationRules for an - // explanation. - EXPECT_EQ(1, var_tracker().GetRefCountForObject(obj_pp_var)); - var_tracker().ReleaseVar(obj_pp_var); - } -} - -// Tests the plugin receiving a var as a return value from the browser -// two different times (passing ownership). -TEST_F(SerializedVarTest, PluginReceiveReturn) { - ProxyAutoLock lock; - PP_Var host_object = MakeObjectVar(0x31337); - - PP_Var plugin_object; - { - // Receive the first param, we should be tracking it with a refcount of 1. - SerializedVarTestConstructor input1(host_object); - ReceiveSerializedVarReturnValue receive_input(input1); - plugin_object = receive_input.Return(plugin_dispatcher()); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0u, sink().message_count()); - - // Receive the second param, it should be resolved to the same plugin - // object and there should be a plugin refcount of 2. There should have - // been an IPC message sent that released the duplicated ref in the browser - // (so both of our refs are represented by one in the browser). - SerializedVarTestConstructor input2(host_object); - ReceiveSerializedVarReturnValue receive_input2(input2); - PP_Var plugin_object2 = receive_input2.Return(plugin_dispatcher()); - EXPECT_EQ(plugin_object.value.as_id, plugin_object2.value.as_id); - EXPECT_EQ(2, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(1u, sink().message_count()); - } - - // The ReceiveSerializedVarReturnValue destructor shouldn't have affected - // the refcount or sent any messages. - EXPECT_EQ(2, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(1u, sink().message_count()); - - // Manually release one refcount, it shouldn't have sent any more messages. - var_tracker().ReleaseVar(plugin_object); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(1u, sink().message_count()); - - // Manually release the last refcount, it should have freed it and sent a - // release message to the browser. - var_tracker().ReleaseVar(plugin_object); - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(2u, sink().message_count()); -} - -// Returns a value from the browser to the plugin, then return that one ref -// back to the browser. -TEST_F(SerializedVarTest, PluginReturnValue) { - ProxyAutoLock lock; - PP_Var host_object = MakeObjectVar(0x31337); - - PP_Var plugin_object; - { - // Receive the param in the plugin. - SerializedVarTestConstructor input1(host_object); - ReceiveSerializedVarReturnValue receive_input(input1); - plugin_object = receive_input.Return(plugin_dispatcher()); - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(0u, sink().message_count()); - } - - { - // Now return to the browser. - SerializedVar output; - SerializedVarReturnValue return_output(&output); - return_output.Return(plugin_dispatcher(), plugin_object); - - // The ref in the plugin should be alive until the ReturnValue goes out of - // scope, since the release needs to be after the browser processes the - // message. - EXPECT_EQ(1, var_tracker().GetRefCountForObject(plugin_object)); - } - - // When the ReturnValue object goes out of scope, it should have sent a - // release message to the browser. - EXPECT_EQ(-1, var_tracker().GetRefCountForObject(plugin_object)); - EXPECT_EQ(1u, sink().message_count()); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/tracked_callback_unittest.cc b/proxy/tracked_callback_unittest.cc deleted file mode 100644 index 706c18a..0000000 --- a/proxy/tracked_callback_unittest.cc +++ /dev/null
@@ -1,471 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "base/functional/bind.h" -#include "base/location.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/synchronization/waitable_event.h" -#include "base/task/single_thread_task_runner.h" -#include "base/threading/simple_thread.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/ppb_message_loop_proxy.h" -#include "ppapi/shared_impl/callback_tracker.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/resource.h" -#include "ppapi/shared_impl/resource_tracker.h" -#include "ppapi/shared_impl/scoped_pp_resource.h" -#include "ppapi/shared_impl/test_globals.h" -#include "ppapi/shared_impl/tracked_callback.h" -#include "testing/gtest/include/gtest/gtest.h" - -// Note, this file tests TrackedCallback which lives in ppapi/shared_impl. -// Unfortunately, we need the test to live in ppapi/proxy so that it can use -// the thread support there. -namespace ppapi { -namespace proxy { - -namespace { - -class CallbackThread : public base::SimpleThread { - public: - explicit CallbackThread(PP_Instance instance) - : SimpleThread("CallbackThread"), instance_(instance) {} - ~CallbackThread() override {} - - // base::SimpleThread overrides. - void BeforeStart() override { - ProxyAutoLock acquire; - // Create the message loop here, after PpapiGlobals has been created. - message_loop_ = new MessageLoopResource(instance_); - } - void BeforeJoin() override { - ProxyAutoLock acquire; - message_loop()->PostQuit(PP_TRUE); - message_loop_ = nullptr; - } - void Run() override { - ProxyAutoLock acquire; - // Make a local copy of message_loop_ for this thread so we can interact - // with it even after the main thread releases it. - scoped_refptr<MessageLoopResource> message_loop(message_loop_); - message_loop->AttachToCurrentThread(); - // Note, run releases the lock to run events. - base::RunLoop().Run(); - message_loop->DetachFromThread(); - } - - MessageLoopResource* message_loop() { return message_loop_.get(); } - - private: - PP_Instance instance_; - scoped_refptr<MessageLoopResource> message_loop_; -}; - -class TrackedCallbackTest : public PluginProxyTest { - public: - TrackedCallbackTest() : thread_(pp_instance()) {} - CallbackThread& thread() { return thread_; } - - private: - // PluginProxyTest overrides. - void SetUp() override { - PluginProxyTest::SetUp(); - thread_.Start(); - } - void TearDown() override { - thread_.Join(); - PluginProxyTest::TearDown(); - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - } - CallbackThread thread_; -}; - -// All valid results (PP_OK, PP_ERROR_...) are nonpositive. -const int32_t kInitializedResultValue = 1; -const int32_t kOverrideResultValue = 2; - -struct CallbackRunInfo { - explicit CallbackRunInfo(base::ThreadChecker* thread_checker) - : run_count_(0), - result_(kInitializedResultValue), - completion_task_run_count_(0), - completion_task_result_(kInitializedResultValue), - thread_checker_(thread_checker), - callback_did_run_event_( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED) {} - void CallbackDidRun(int32_t result) { - CHECK(thread_checker_->CalledOnValidThread()); - if (!run_count_) - result_ = result; - ++run_count_; - callback_did_run_event_.Signal(); - } - void CompletionTaskDidRun(int32_t result) { - CHECK(thread_checker_->CalledOnValidThread()); - if (!completion_task_run_count_) - completion_task_result_ = result; - ++completion_task_run_count_; - } - void WaitUntilCompleted() { callback_did_run_event_.Wait(); } - unsigned run_count() { return run_count_; } - int32_t result() { return result_; } - unsigned completion_task_run_count() { return completion_task_run_count_; } - int32_t completion_task_result() { return completion_task_result_; } - private: - unsigned run_count_; - int32_t result_; - unsigned completion_task_run_count_; - int32_t completion_task_result_; - // Weak; owned by the creator of CallbackRunInfo. - base::ThreadChecker* thread_checker_; - - base::WaitableEvent callback_did_run_event_; -}; - -void TestCallback(void* user_data, int32_t result) { - CallbackRunInfo* info = static_cast<CallbackRunInfo*>(user_data); - info->CallbackDidRun(result); -} - -// CallbackShutdownTest -------------------------------------------------------- - -class CallbackShutdownTest : public TrackedCallbackTest { - public: - CallbackShutdownTest() : info_did_run_(&thread_checker_), - info_did_abort_(&thread_checker_), - info_didnt_run_(&thread_checker_) {} - - // Cases: - // (1) A callback which is run (so shouldn't be aborted on shutdown). - // (2) A callback which is aborted (so shouldn't be aborted on shutdown). - // (3) A callback which isn't run (so should be aborted on shutdown). - CallbackRunInfo& info_did_run() { return info_did_run_; } // (1) - CallbackRunInfo& info_did_abort() { return info_did_abort_; } // (2) - CallbackRunInfo& info_didnt_run() { return info_didnt_run_; } // (3) - - private: - base::ThreadChecker thread_checker_; - CallbackRunInfo info_did_run_; - CallbackRunInfo info_did_abort_; - CallbackRunInfo info_didnt_run_; -}; - -} // namespace - -// Tests that callbacks are properly aborted on module shutdown. -TEST_F(CallbackShutdownTest, DISABLED_AbortOnShutdown) { - ProxyAutoLock lock; - scoped_refptr<Resource> resource( - new Resource(OBJECT_IS_PROXY, pp_instance())); - - // Set up case (1) (see above). - EXPECT_EQ(0U, info_did_run().run_count()); - // TODO(dmichael): Test this on a background thread? - scoped_refptr<TrackedCallback> callback_did_run = new TrackedCallback( - resource.get(), - PP_MakeCompletionCallback(&TestCallback, &info_did_run())); - EXPECT_EQ(0U, info_did_run().run_count()); - callback_did_run->Run(PP_OK); - EXPECT_EQ(1U, info_did_run().run_count()); - EXPECT_EQ(PP_OK, info_did_run().result()); - - // Set up case (2). - EXPECT_EQ(0U, info_did_abort().run_count()); - scoped_refptr<TrackedCallback> callback_did_abort = new TrackedCallback( - resource.get(), - PP_MakeCompletionCallback(&TestCallback, &info_did_abort())); - EXPECT_EQ(0U, info_did_abort().run_count()); - callback_did_abort->Abort(); - EXPECT_EQ(1U, info_did_abort().run_count()); - EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort().result()); - - // Set up case (3). - EXPECT_EQ(0U, info_didnt_run().run_count()); - scoped_refptr<TrackedCallback> callback_didnt_run = new TrackedCallback( - resource.get(), - PP_MakeCompletionCallback(&TestCallback, &info_didnt_run())); - EXPECT_EQ(0U, info_didnt_run().run_count()); - - GetGlobals()->GetCallbackTrackerForInstance(pp_instance())->AbortAll(); - - // Check case (1). - EXPECT_EQ(1U, info_did_run().run_count()); - - // Check case (2). - EXPECT_EQ(1U, info_did_abort().run_count()); - - // Check case (3). - EXPECT_EQ(1U, info_didnt_run().run_count()); - EXPECT_EQ(PP_ERROR_ABORTED, info_didnt_run().result()); -} - -// CallbackResourceTest -------------------------------------------------------- - -namespace { - -class CallbackResourceTest : public TrackedCallbackTest { - public: - CallbackResourceTest() {} -}; - -class CallbackMockResource : public Resource { - public: - static scoped_refptr<CallbackMockResource> Create(PP_Instance instance) { - ProxyAutoLock acquire; - return scoped_refptr<CallbackMockResource>( - new CallbackMockResource(instance)); - } - ~CallbackMockResource() {} - - // Take a reference to this resource, which will add it to the tracker. - void TakeRef() { - ProxyAutoLock acquire; - ScopedPPResource temp_resource(ScopedPPResource::PassRef(), GetReference()); - EXPECT_NE(0, temp_resource.get()); - reference_holder_ = temp_resource; - } - // Release it, removing it from the tracker. - void ReleaseRef() { - ProxyAutoLock acquire; - reference_holder_ = 0; - } - - // Create the test callbacks on a background thread, so that we can verify - // they are run on the same thread where they were created. - void CreateCallbacksOnLoop(MessageLoopResource* loop_resource) { - ProxyAutoLock acquire; - // |thread_checker_| will bind to the background thread. - thread_checker_.DetachFromThread(); - loop_resource->task_runner()->PostTask( - FROM_HERE, RunWhileLocked(base::BindOnce( - &CallbackMockResource::CreateCallbacks, this))); - } - - int32_t CompletionTask(CallbackRunInfo* info, int32_t result) { - // The completion task must run on the thread where the callback was - // created, and must hold the proxy lock. - CHECK(thread_checker_.CalledOnValidThread()); - ProxyLock::AssertAcquired(); - - // We should run before the callback. - CHECK_EQ(0U, info->run_count()); - info->CompletionTaskDidRun(result); - return kOverrideResultValue; - } - - void CheckInitialState() { - callbacks_created_event_.Wait(); - EXPECT_EQ(0U, info_did_run_.run_count()); - EXPECT_EQ(0U, info_did_run_.completion_task_run_count()); - - EXPECT_EQ(0U, info_did_run_with_completion_task_.run_count()); - EXPECT_EQ(0U, - info_did_run_with_completion_task_.completion_task_run_count()); - - EXPECT_EQ(0U, info_did_abort_.run_count()); - EXPECT_EQ(0U, info_did_abort_.completion_task_run_count()); - - EXPECT_EQ(0U, info_didnt_run_.run_count()); - EXPECT_EQ(0U, info_didnt_run_.completion_task_run_count()); - } - - void RunCallbacks() { - callback_did_run_->Run(PP_OK); - callback_did_run_with_completion_task_->Run(PP_OK); - callback_did_abort_->Abort(); - info_did_run_.WaitUntilCompleted(); - info_did_run_with_completion_task_.WaitUntilCompleted(); - info_did_abort_.WaitUntilCompleted(); - } - - void CheckIntermediateState() { - EXPECT_EQ(1U, info_did_run_.run_count()); - EXPECT_EQ(PP_OK, info_did_run_.result()); - EXPECT_EQ(0U, info_did_run_.completion_task_run_count()); - - EXPECT_EQ(1U, info_did_run_with_completion_task_.run_count()); - // completion task should override the result. - EXPECT_EQ(kOverrideResultValue, - info_did_run_with_completion_task_.result()); - EXPECT_EQ(1U, - info_did_run_with_completion_task_.completion_task_run_count()); - EXPECT_EQ(PP_OK, - info_did_run_with_completion_task_.completion_task_result()); - - EXPECT_EQ(1U, info_did_abort_.run_count()); - // completion task shouldn't override an abort. - EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort_.result()); - EXPECT_EQ(1U, info_did_abort_.completion_task_run_count()); - EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort_.completion_task_result()); - - EXPECT_EQ(0U, info_didnt_run_.completion_task_run_count()); - EXPECT_EQ(0U, info_didnt_run_.run_count()); - } - - void CheckFinalState() { - info_didnt_run_.WaitUntilCompleted(); - EXPECT_EQ(1U, info_did_run_with_completion_task_.run_count()); - EXPECT_EQ(kOverrideResultValue, - info_did_run_with_completion_task_.result()); - callback_did_run_with_completion_task_ = nullptr; - EXPECT_EQ(1U, info_did_run_.run_count()); - EXPECT_EQ(PP_OK, info_did_run_.result()); - callback_did_run_ = nullptr; - EXPECT_EQ(1U, info_did_abort_.run_count()); - EXPECT_EQ(PP_ERROR_ABORTED, info_did_abort_.result()); - callback_did_abort_ = nullptr; - EXPECT_EQ(1U, info_didnt_run_.run_count()); - EXPECT_EQ(PP_ERROR_ABORTED, info_didnt_run_.result()); - callback_didnt_run_ = nullptr; - } - - private: - explicit CallbackMockResource(PP_Instance instance) - : Resource(OBJECT_IS_PROXY, instance), - info_did_run_(&thread_checker_), - info_did_run_with_completion_task_(&thread_checker_), - info_did_abort_(&thread_checker_), - info_didnt_run_(&thread_checker_), - callbacks_created_event_( - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED) {} - void CreateCallbacks() { - // Bind thread_checker_ to the thread where we create the callbacks. - // Later, when the callback runs, it will check that it was invoked on this - // same thread. - CHECK(thread_checker_.CalledOnValidThread()); - - callback_did_run_ = new TrackedCallback( - this, PP_MakeCompletionCallback(&TestCallback, &info_did_run_)); - - // In order to test that the completion task can override the callback - // result, we need to test callbacks with and without a completion task. - callback_did_run_with_completion_task_ = new TrackedCallback( - this, - PP_MakeCompletionCallback(&TestCallback, - &info_did_run_with_completion_task_)); - callback_did_run_with_completion_task_->set_completion_task( - base::BindOnce(&CallbackMockResource::CompletionTask, this, - &info_did_run_with_completion_task_)); - - callback_did_abort_ = new TrackedCallback( - this, PP_MakeCompletionCallback(&TestCallback, &info_did_abort_)); - callback_did_abort_->set_completion_task(base::BindOnce( - &CallbackMockResource::CompletionTask, this, &info_did_abort_)); - - callback_didnt_run_ = new TrackedCallback( - this, PP_MakeCompletionCallback(&TestCallback, &info_didnt_run_)); - callback_didnt_run_->set_completion_task(base::BindOnce( - &CallbackMockResource::CompletionTask, this, &info_didnt_run_)); - - callbacks_created_event_.Signal(); - } - - // Used to verify that the callback runs on the same thread where it is - // created. - base::ThreadChecker thread_checker_; - - scoped_refptr<TrackedCallback> callback_did_run_; - CallbackRunInfo info_did_run_; - - scoped_refptr<TrackedCallback> callback_did_run_with_completion_task_; - CallbackRunInfo info_did_run_with_completion_task_; - - scoped_refptr<TrackedCallback> callback_did_abort_; - CallbackRunInfo info_did_abort_; - - scoped_refptr<TrackedCallback> callback_didnt_run_; - CallbackRunInfo info_didnt_run_; - - base::WaitableEvent callbacks_created_event_; - - ScopedPPResource reference_holder_; -}; - -} // namespace - -// Test that callbacks get aborted on the last resource unref. -TEST_F(CallbackResourceTest, DISABLED_AbortOnNoRef) { - // Test several things: Unref-ing a resource (to zero refs) with callbacks - // which (1) have been run, (2) have been aborted, (3) haven't been completed. - // Check that the uncompleted one gets aborted, and that the others don't get - // called again. - scoped_refptr<CallbackMockResource> resource_1( - CallbackMockResource::Create(pp_instance())); - resource_1->CreateCallbacksOnLoop(thread().message_loop()); - resource_1->CheckInitialState(); - resource_1->RunCallbacks(); - resource_1->TakeRef(); - resource_1->CheckIntermediateState(); - - // Also do the same for a second resource, and make sure that unref-ing the - // first resource doesn't much up the second resource. - scoped_refptr<CallbackMockResource> resource_2( - CallbackMockResource::Create(pp_instance())); - resource_2->CreateCallbacksOnLoop(thread().message_loop()); - resource_2->CheckInitialState(); - resource_2->RunCallbacks(); - resource_2->TakeRef(); - resource_2->CheckIntermediateState(); - - // Double-check that resource #1 is still okay. - resource_1->CheckIntermediateState(); - - // Kill resource #1, spin the message loop to run posted calls, and check that - // things are in the expected states. - resource_1->ReleaseRef(); - - resource_1->CheckFinalState(); - resource_2->CheckIntermediateState(); - - // Kill resource #2. - resource_2->ReleaseRef(); - - resource_1->CheckFinalState(); - resource_2->CheckFinalState(); - - { - ProxyAutoLock lock; - resource_1 = nullptr; - resource_2 = nullptr; - } -} - -// Test that "resurrecting" a resource (getting a new ID for a |Resource|) -// doesn't resurrect callbacks. -TEST_F(CallbackResourceTest, DISABLED_Resurrection) { - scoped_refptr<CallbackMockResource> resource( - CallbackMockResource::Create(pp_instance())); - resource->CreateCallbacksOnLoop(thread().message_loop()); - resource->CheckInitialState(); - resource->RunCallbacks(); - resource->TakeRef(); - resource->CheckIntermediateState(); - - // Unref it and check that things are in the expected states. - resource->ReleaseRef(); - resource->CheckFinalState(); - - // "Resurrect" it and check that the callbacks are still dead. - resource->TakeRef(); - resource->CheckFinalState(); - - // Unref it again and do the same. - resource->ReleaseRef(); - resource->CheckFinalState(); - { - ProxyAutoLock lock; - resource = nullptr; - } -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/video_decoder_resource_unittest.cc b/proxy/video_decoder_resource_unittest.cc deleted file mode 100644 index 187f7f5..0000000 --- a/proxy/video_decoder_resource_unittest.cc +++ /dev/null
@@ -1,583 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <GLES2/gl2.h> -#include <stddef.h> -#include <stdint.h> - -#include "base/memory/unsafe_shared_memory_region.h" -#include "build/build_config.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_video_decoder.h" -#include "ppapi/proxy/locking_resource_releaser.h" -#include "ppapi/proxy/plugin_message_filter.h" -#include "ppapi/proxy/ppapi_message_utils.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/ppb_graphics_3d_proxy.h" -#include "ppapi/proxy/video_decoder_constants.h" -#include "ppapi/proxy/video_decoder_resource.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/thunk/thunk.h" - -using ppapi::proxy::ResourceMessageTestSink; - -namespace ppapi { -namespace proxy { - -namespace { - -const PP_Resource kGraphics3D = 7; -const uint32_t kShmSize = 256; -const size_t kDecodeBufferSize = 16; -const uint32_t kDecodeId = 5; - -class MockCompletionCallback { - public: - MockCompletionCallback() : called_(false) {} - - bool called() { return called_; } - int32_t result() { return result_; } - - void Reset() { called_ = false; } - - static void Callback(void* user_data, int32_t result) { - MockCompletionCallback* that = - reinterpret_cast<MockCompletionCallback*>(user_data); - that->called_ = true; - that->result_ = result; - } - - private: - bool called_; - int32_t result_; -}; - -class VideoDecoderResourceTest : public PluginProxyTest { - public: - VideoDecoderResourceTest() - : decoder_iface_(thunk::GetPPB_VideoDecoder_1_1_Thunk()) {} - - const PPB_VideoDecoder_1_1* decoder_iface() const { return decoder_iface_; } - - void SendReply(const ResourceMessageCallParams& params, - int32_t result, - const IPC::Message& nested_message) { - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(result); - PluginMessageFilter::DispatchResourceReplyForTest(reply_params, - nested_message); - } - - PP_Resource CreateDecoder() { - PP_Resource result = decoder_iface()->Create(pp_instance()); - if (result) { - ProxyAutoLock lock; - ppapi::Resource* resource = - GetGlobals()->GetResourceTracker()->GetResource(result); - proxy::VideoDecoderResource* decoder = - static_cast<proxy::VideoDecoderResource*>(resource); - decoder->SetForTest(); - } - - return result; - } - - PP_Resource CreateGraphics3d() { - ProxyAutoLock lock; - - HostResource host_resource; - host_resource.SetHostResource(pp_instance(), kGraphics3D); - scoped_refptr<ppapi::proxy::Graphics3D> graphics_3d( - new ppapi::proxy::Graphics3D(host_resource, gfx::Size(640, 480))); - - return graphics_3d->GetReference(); - } - - PP_Resource CreateAndInitializeDecoder() { - PP_Resource decoder = CreateDecoder(); - LockingResourceReleaser graphics3d(CreateGraphics3d()); - MockCompletionCallback cb; - int32_t result = decoder_iface()->Initialize( - decoder, - graphics3d.get(), - PP_VIDEOPROFILE_H264MAIN, - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - if (result != PP_OK_COMPLETIONPENDING) - return 0; - ResourceMessageCallParams params; - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoDecoder_Initialize::ID, ¶ms, &msg)) - return 0; - sink().ClearMessages(); - SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_InitializeReply()); - return decoder; - } - - int32_t CallDecode(PP_Resource pp_decoder, - MockCompletionCallback* cb, - const PpapiHostMsg_VideoDecoder_GetShm* expected_shm_msg) { - // Set up a handler in case the resource sends a sync message to create - // shared memory. - PpapiPluginMsg_VideoDecoder_GetShmReply shm_msg_reply(kShmSize); - ResourceSyncCallHandler shm_msg_handler( - &sink(), PpapiHostMsg_VideoDecoder_GetShm::ID, PP_OK, shm_msg_reply); - sink().AddFilter(&shm_msg_handler); - - if (expected_shm_msg) { - auto region = base::UnsafeSharedMemoryRegion::Create(kShmSize); - auto serialized_handle = std::make_unique<SerializedHandle>( - base::UnsafeSharedMemoryRegion::TakeHandleForSerialization( - std::move(region))); - shm_msg_handler.set_serialized_handle(std::move(serialized_handle)); - } - - memset(decode_buffer_, 0x55, kDecodeBufferSize); - int32_t result = - decoder_iface()->Decode(pp_decoder, - kDecodeId, - kDecodeBufferSize, - decode_buffer_, - PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - - if (expected_shm_msg) { - uint32_t shm_id, shm_size, expected_shm_id, expected_shm_size; - UnpackMessage<PpapiHostMsg_VideoDecoder_GetShm>( - *expected_shm_msg, &expected_shm_id, &expected_shm_size); - if (shm_msg_handler.last_handled_msg().type() == 0 || - !UnpackMessage<PpapiHostMsg_VideoDecoder_GetShm>( - shm_msg_handler.last_handled_msg(), &shm_id, &shm_size) || - shm_id != expected_shm_id || - shm_size != expected_shm_size) { - // Signal that the expected shm message wasn't sent by failing. - result = PP_ERROR_FAILED; - } - } - - sink().RemoveFilter(&shm_msg_handler); - return result; - } - - int32_t CallGetPicture(PP_Resource pp_decoder, - PP_VideoPicture* picture, - MockCompletionCallback* cb) { - int32_t result = - decoder_iface()->GetPicture(pp_decoder, - picture, - PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - return result; - } - - void CallRecyclePicture(PP_Resource pp_decoder, - const PP_VideoPicture& picture) { - decoder_iface()->RecyclePicture(pp_decoder, &picture); - } - - int32_t CallFlush(PP_Resource pp_decoder, MockCompletionCallback* cb) { - int32_t result = - decoder_iface()->Flush(pp_decoder, - PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - return result; - } - - int32_t CallReset(PP_Resource pp_decoder, MockCompletionCallback* cb) { - int32_t result = - decoder_iface()->Reset(pp_decoder, - PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - return result; - } - - void SendDecodeReply(const ResourceMessageCallParams& params, - uint32_t shm_id) { - SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_DecodeReply(shm_id)); - } - - void SendSharedImageReady(const ResourceMessageCallParams& params, - uint32_t decode_count, - const gpu::Mailbox& mailbox) { - PP_Rect visible_rect = PP_MakeRectFromXYWH(0, 0, 640, 480); - SendReply(params, PP_OK, - PpapiPluginMsg_VideoDecoder_SharedImageReady( - decode_count, mailbox, visible_rect.size, visible_rect)); - } - - void SendFlushReply(const ResourceMessageCallParams& params) { - SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_FlushReply()); - } - - void SendResetReply(const ResourceMessageCallParams& params) { - SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_ResetReply()); - } - - void SendNotifyError(const ResourceMessageCallParams& params, int32_t error) { - SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_NotifyError(error)); - } - - bool CheckDecodeMsg(ResourceMessageCallParams* params, - uint32_t* shm_id, - uint32_t* size, - int32_t* decode_id) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoDecoder_Decode::ID, params, &msg)) - return false; - sink().ClearMessages(); - return UnpackMessage<PpapiHostMsg_VideoDecoder_Decode>( - msg, shm_id, size, decode_id); - } - - bool CheckRecycleSharedImageMsg(ResourceMessageCallParams* params, - gpu::Mailbox& mailbox) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoDecoder_RecycleSharedImage::ID, params, &msg)) { - return false; - } - sink().ClearMessages(); - return UnpackMessage<PpapiHostMsg_VideoDecoder_RecycleSharedImage>( - msg, &mailbox); - } - - bool CheckFlushMsg(ResourceMessageCallParams* params) { - return CheckMsg(params, PpapiHostMsg_VideoDecoder_Flush::ID); - } - - bool CheckResetMsg(ResourceMessageCallParams* params) { - return CheckMsg(params, PpapiHostMsg_VideoDecoder_Reset::ID); - } - - void ClearCallbacks(PP_Resource pp_decoder) { - ResourceMessageCallParams params; - MockCompletionCallback cb; - - // Reset to abort Decode and GetPicture callbacks. - CallReset(pp_decoder, &cb); - // Initialize params so we can reply to the Reset. - CheckResetMsg(¶ms); - // Run the Reset callback. - SendResetReply(params); - } - - private: - bool CheckMsg(ResourceMessageCallParams* params, int id) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching(id, params, &msg)) - return false; - sink().ClearMessages(); - return true; - } - - const PPB_VideoDecoder_1_1* decoder_iface_; - - char decode_buffer_[kDecodeBufferSize]; -}; - -} // namespace - -TEST_F(VideoDecoderResourceTest, Initialize) { - // Initialize with 0 graphics3d_context should fail. - { - LockingResourceReleaser decoder(CreateDecoder()); - MockCompletionCallback cb; - int32_t result = decoder_iface()->Initialize( - decoder.get(), - 0 /* invalid 3d graphics */, - PP_VIDEOPROFILE_H264MAIN, - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_ERROR_BADRESOURCE, result); - } - // Initialize with bad profile value should fail. - { - LockingResourceReleaser decoder(CreateDecoder()); - MockCompletionCallback cb; - int32_t result = decoder_iface()->Initialize( - decoder.get(), - 1 /* non-zero resource */, - static_cast<PP_VideoProfile>(-1), - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - } - // Initialize with valid graphics3d_context and profile should succeed. - { - LockingResourceReleaser decoder(CreateDecoder()); - LockingResourceReleaser graphics3d(CreateGraphics3d()); - MockCompletionCallback cb; - int32_t result = decoder_iface()->Initialize( - decoder.get(), - graphics3d.get(), - PP_VIDEOPROFILE_H264MAIN, - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - ASSERT_TRUE(decoder_iface()->IsVideoDecoder(decoder.get())); - - // Another attempt while pending should fail. - result = decoder_iface()->Initialize( - decoder.get(), - graphics3d.get(), - PP_VIDEOPROFILE_H264MAIN, - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_ERROR_INPROGRESS, result); - - // Check for host message and send a reply to complete initialization. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoDecoder_Initialize::ID, ¶ms, &msg)); - sink().ClearMessages(); - SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_InitializeReply()); - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_OK, cb.result()); - } -} - -TEST_F(VideoDecoderResourceTest, Uninitialized) { - // Operations on uninitialized decoders should fail. - LockingResourceReleaser decoder(CreateDecoder()); - MockCompletionCallback uncalled_cb; - - ASSERT_EQ(PP_ERROR_FAILED, CallDecode(decoder.get(), &uncalled_cb, NULL)); - ASSERT_FALSE(uncalled_cb.called()); - - ASSERT_EQ(PP_ERROR_FAILED, CallGetPicture(decoder.get(), NULL, &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - - ASSERT_EQ(PP_ERROR_FAILED, CallFlush(decoder.get(), &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - - ASSERT_EQ(PP_ERROR_FAILED, CallReset(decoder.get(), &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); -} - -// TODO(bbudge) Fix sync message testing on Windows 64 bit builds. The reply -// message for GetShm isn't received, causing Decode to fail. -// http://crbug.com/379260 -#if !BUILDFLAG(IS_WIN) || !defined(ARCH_CPU_64_BITS) -TEST_F(VideoDecoderResourceTest, DecodeAndGetPicture) { - LockingResourceReleaser decoder(CreateAndInitializeDecoder()); - ResourceMessageCallParams params, params2; - MockCompletionCallback decode_cb, get_picture_cb, uncalled_cb; - - uint32_t shm_id; - uint32_t decode_size; - int32_t decode_id; - // Call Decode until we have the maximum pending, minus one. - for (uint32_t i = 0; i < kMaximumPendingDecodes - 1; i++) { - PpapiHostMsg_VideoDecoder_GetShm shm_msg(i, kDecodeBufferSize); - ASSERT_EQ(PP_OK, CallDecode(decoder.get(), &uncalled_cb, &shm_msg)); - ASSERT_FALSE(uncalled_cb.called()); - CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id); - ASSERT_EQ(i, shm_id); - ASSERT_EQ(kDecodeBufferSize, decode_size); - // The resource generates uids internally, starting at 1. - int32_t uid = i + 1; - ASSERT_EQ(uid, decode_id); - } - // Once we've allocated the maximum number of buffers, we must wait. - PpapiHostMsg_VideoDecoder_GetShm shm_msg(7U, kDecodeBufferSize); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallDecode(decoder.get(), &decode_cb, &shm_msg)); - CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id); - ASSERT_EQ(7U, shm_id); - ASSERT_EQ(kDecodeBufferSize, decode_size); - - // Calling Decode when another Decode is pending should fail. - ASSERT_EQ(PP_ERROR_INPROGRESS, CallDecode(decoder.get(), &uncalled_cb, NULL)); - ASSERT_FALSE(uncalled_cb.called()); - // Free up the first decode buffer. - SendDecodeReply(params, 0U); - // The decoder should run the pending callback. - ASSERT_TRUE(decode_cb.called()); - ASSERT_EQ(PP_OK, decode_cb.result()); - decode_cb.Reset(); - - // Now try to get a picture. No picture ready message has been received yet. - PP_VideoPicture picture; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetPicture(decoder.get(), &picture, &get_picture_cb)); - ASSERT_FALSE(get_picture_cb.called()); - // Calling GetPicture when another GetPicture is pending should fail. - ASSERT_EQ(PP_ERROR_INPROGRESS, - CallGetPicture(decoder.get(), &picture, &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - - const auto mailbox1 = gpu::Mailbox::Generate(); - // Send a shared image ready message for Decode call 1. The GetPicture - // callback should complete. - SendSharedImageReady(params, 1U, mailbox1); - - ASSERT_TRUE(get_picture_cb.called()); - ASSERT_EQ(PP_OK, get_picture_cb.result()); - ASSERT_EQ(kDecodeId, picture.decode_id); - get_picture_cb.Reset(); - - // Send a shared image ready message for Decode call 2. Since there is no - // pending GetPicture call, the picture should be queued. - const auto mailbox2 = gpu::Mailbox::Generate(); - SendSharedImageReady(params, 2U, mailbox2); - - // The next GetPicture should return synchronously. - ASSERT_EQ(PP_OK, CallGetPicture(decoder.get(), &picture, &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - ASSERT_EQ(kDecodeId, picture.decode_id); -} -#endif // !BUILDFLAG(IS_WIN) || !defined(ARCH_CPU_64_BITS) - -// TODO(bbudge) Fix sync message testing on Windows 64 bit builds. The reply -// message for GetShm isn't received, causing Decode to fail. -// http://crbug.com/379260 -#if !BUILDFLAG(IS_WIN) || !defined(ARCH_CPU_64_BITS) -TEST_F(VideoDecoderResourceTest, RecyclePicture) { - LockingResourceReleaser decoder(CreateAndInitializeDecoder()); - ResourceMessageCallParams params; - MockCompletionCallback decode_cb, get_picture_cb, uncalled_cb; - - // Get to a state where we have a picture to recycle. - PpapiHostMsg_VideoDecoder_GetShm shm_msg(0U, kDecodeBufferSize); - ASSERT_EQ(PP_OK, CallDecode(decoder.get(), &decode_cb, &shm_msg)); - uint32_t shm_id; - uint32_t decode_size; - int32_t decode_id; - CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id); - SendDecodeReply(params, 0U); - - // Call GetPicture and send 'picture ready' message to get a picture to - // recycle. - PP_VideoPicture picture; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetPicture(decoder.get(), &picture, &get_picture_cb)); - - const auto mailbox = gpu::Mailbox::Generate(); - SendSharedImageReady(params, 0U, mailbox); - - CallRecyclePicture(decoder.get(), picture); - gpu::Mailbox recycle_mailbox; - ASSERT_TRUE(CheckRecycleSharedImageMsg(¶ms, recycle_mailbox)); - ASSERT_EQ(mailbox, recycle_mailbox); - - ClearCallbacks(decoder.get()); -} -#endif // !BUILDFLAG(IS_WIN) || !defined(ARCH_CPU_64_BITS) - -TEST_F(VideoDecoderResourceTest, Flush) { - LockingResourceReleaser decoder(CreateAndInitializeDecoder()); - ResourceMessageCallParams params, params2; - MockCompletionCallback flush_cb, get_picture_cb, uncalled_cb, decode_cb; - - // Get to a state where we have a picture to recycle. - PpapiHostMsg_VideoDecoder_GetShm shm_msg(0U, kDecodeBufferSize); - ASSERT_EQ(PP_OK, CallDecode(decoder.get(), &decode_cb, &shm_msg)); - uint32_t shm_id; - uint32_t decode_size; - int32_t decode_id; - CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id); - SendDecodeReply(params, 0U); - - gpu::Mailbox mailbox = gpu::Mailbox::Generate(); - SendSharedImageReady(params, 0U, mailbox); - - PP_VideoPicture picture; - ASSERT_EQ(PP_OK, CallGetPicture(decoder.get(), &picture, &get_picture_cb)); - - ASSERT_EQ(PP_OK_COMPLETIONPENDING, CallFlush(decoder.get(), &flush_cb)); - ASSERT_FALSE(flush_cb.called()); - ASSERT_TRUE(CheckFlushMsg(¶ms)); - - ASSERT_EQ(PP_ERROR_FAILED, CallDecode(decoder.get(), &uncalled_cb, NULL)); - ASSERT_FALSE(uncalled_cb.called()); - - // Plugin can call GetPicture while Flush is pending. - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetPicture(decoder.get(), NULL, &get_picture_cb)); - ASSERT_FALSE(get_picture_cb.called()); - - ASSERT_EQ(PP_ERROR_INPROGRESS, CallFlush(decoder.get(), &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - - ASSERT_EQ(PP_ERROR_FAILED, CallReset(decoder.get(), &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - - // Plugin can call RecyclePicture while Flush is pending. - CallRecyclePicture(decoder.get(), picture); - - gpu::Mailbox recycle_mailbox; - ASSERT_TRUE(CheckRecycleSharedImageMsg(¶ms2, recycle_mailbox)); - ASSERT_EQ(mailbox, recycle_mailbox); - - SendFlushReply(params); - // Any pending GetPicture call is aborted. - ASSERT_TRUE(get_picture_cb.called()); - ASSERT_EQ(PP_ERROR_ABORTED, get_picture_cb.result()); - ASSERT_TRUE(flush_cb.called()); - ASSERT_EQ(PP_OK, flush_cb.result()); -} - -// TODO(bbudge) Test Reset when we can run the message loop to get aborted -// callbacks to run. - -// TODO(bbudge) Fix sync message testing on Windows 64 bit builds. The reply -// message for GetShm isn't received, causing Decode to fail. -// http://crbug.com/379260 -#if !BUILDFLAG(IS_WIN) || !defined(ARCH_CPU_64_BITS) -TEST_F(VideoDecoderResourceTest, NotifyError) { - LockingResourceReleaser decoder(CreateAndInitializeDecoder()); - ResourceMessageCallParams params; - MockCompletionCallback decode_cb, get_picture_cb, uncalled_cb; - - // Call Decode and GetPicture to have some pending requests. - PpapiHostMsg_VideoDecoder_GetShm shm_msg(0U, kDecodeBufferSize); - ASSERT_EQ(PP_OK, CallDecode(decoder.get(), &decode_cb, &shm_msg)); - ASSERT_FALSE(decode_cb.called()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetPicture(decoder.get(), NULL, &get_picture_cb)); - ASSERT_FALSE(get_picture_cb.called()); - - // Send the decoder resource an unsolicited notify error message. We first - // need to initialize 'params' so the message is routed to the decoder. - uint32_t shm_id; - uint32_t decode_size; - int32_t decode_id; - CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id); - SendNotifyError(params, PP_ERROR_RESOURCE_FAILED); - - // Any pending message should be run with the reported error. - ASSERT_TRUE(get_picture_cb.called()); - ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, get_picture_cb.result()); - - // All further calls return the reported error. - ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, - CallDecode(decoder.get(), &uncalled_cb, NULL)); - ASSERT_FALSE(uncalled_cb.called()); - ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, - CallGetPicture(decoder.get(), NULL, &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, CallFlush(decoder.get(), &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, CallReset(decoder.get(), &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); -} -#endif // !BUILDFLAG(IS_WIN) || !defined(ARCH_CPU_64_BITS) - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/video_encoder_resource_unittest.cc b/proxy/video_encoder_resource_unittest.cc deleted file mode 100644 index 85fe0e1..0000000 --- a/proxy/video_encoder_resource_unittest.cc +++ /dev/null
@@ -1,1159 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/proxy/video_encoder_resource.h" - -#include <stdint.h> - -#include <memory> -#include <utility> -#include <vector> - -#include "base/memory/unsafe_shared_memory_region.h" -#include "base/process/process.h" -#include "base/synchronization/waitable_event.h" -#include "ppapi/c/pp_codecs.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_video_encoder.h" -#include "ppapi/c/ppb_video_frame.h" -#include "ppapi/proxy/locking_resource_releaser.h" -#include "ppapi/proxy/plugin_message_filter.h" -#include "ppapi/proxy/ppapi_message_utils.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/shared_impl/media_stream_buffer.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/thunk/thunk.h" - -using ppapi::proxy::ResourceMessageTestSink; - -namespace ppapi { -namespace proxy { - -namespace { - -class MockCompletionCallback { - public: - MockCompletionCallback() - : called_(false), - call_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED) {} - - bool called() { return called_; } - int32_t result() { return result_; } - - void WaitUntilCalled() { call_event_.Wait(); } - - void Reset() { - called_ = false; - call_event_.Reset(); - } - - static void Callback(void* user_data, int32_t result) { - MockCompletionCallback* that = - reinterpret_cast<MockCompletionCallback*>(user_data); - that->call_event_.Signal(); - that->called_ = true; - that->result_ = result; - } - - private: - bool called_; - int32_t result_; - base::WaitableEvent call_event_; -}; - -class VideoEncoderResourceTest : public PluginProxyTest, - public MediaStreamBufferManager::Delegate { - public: - VideoEncoderResourceTest() - : encoder_iface_(thunk::GetPPB_VideoEncoder_0_2_Thunk()), - encoder_iface_0_1_(thunk::GetPPB_VideoEncoder_0_1_Thunk()), - video_frames_manager_(this) {} - ~VideoEncoderResourceTest() override {} - - const PPB_VideoEncoder_0_2* encoder_iface() const { return encoder_iface_; } - const PPB_VideoEncoder_0_1* encoder_iface_0_1() const { - return encoder_iface_0_1_; - } - - const uint32_t kBitstreamBufferSize = 4000; - const uint32_t kBitstreamBufferCount = 5; - const uint32_t kVideoFrameCount = 3; - const uint32_t kBitrate = 200000; - - const PP_Size kFrameSize = PP_MakeSize(640, 480); - - void SendReply(const ResourceMessageCallParams& params, - int32_t result, - const IPC::Message& nested_message) { - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(result); - PluginMessageFilter::DispatchResourceReplyForTest(reply_params, - nested_message); - } - - void SendReplyWithHandle(const ResourceMessageCallParams& params, - int32_t result, - const IPC::Message& nested_message, - SerializedHandle handle) { - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(result); - reply_params.AppendHandle(std::move(handle)); - PluginMessageFilter::DispatchResourceReplyForTest(reply_params, - nested_message); - } - - void SendReplyWithHandles(const ResourceMessageCallParams& params, - int32_t result, - const IPC::Message& nested_message, - std::vector<SerializedHandle> handles) { - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(result); - for (auto& handle : handles) - reply_params.AppendHandle(std::move(handle)); - PluginMessageFilter::DispatchResourceReplyForTest(reply_params, - nested_message); - } - - PP_Resource CreateEncoder() { - PP_Resource result = encoder_iface()->Create(pp_instance()); - return result; - } - - void CreateBitstreamSharedMemory(uint32_t buffer_size, uint32_t nb_buffers) { - shared_memory_bitstreams_.clear(); - for (uint32_t i = 0; i < nb_buffers; ++i) { - base::UnsafeSharedMemoryRegion region = - base::UnsafeSharedMemoryRegion::Create(buffer_size); - ASSERT_TRUE(region.IsValid()); - shared_memory_bitstreams_.push_back(std::move(region)); - } - } - - void CreateVideoFramesSharedMemory(uint32_t frame_length, - uint32_t frame_count) { - uint32_t buffer_length = - frame_length + sizeof(ppapi::MediaStreamBuffer::Video); - base::UnsafeSharedMemoryRegion shared_memory_frames = - base::UnsafeSharedMemoryRegion::Create(buffer_length * frame_count); - ASSERT_TRUE(shared_memory_frames.IsValid()); - ASSERT_TRUE(video_frames_manager_.SetBuffers( - frame_count, buffer_length, std::move(shared_memory_frames), true)); - for (int32_t i = 0; i < video_frames_manager_.number_of_buffers(); ++i) { - ppapi::MediaStreamBuffer::Video* buffer = - &(video_frames_manager_.GetBufferPointer(i)->video); - buffer->header.size = buffer_length; - buffer->header.type = ppapi::MediaStreamBuffer::TYPE_VIDEO; - buffer->format = PP_VIDEOFRAME_FORMAT_I420; - buffer->size = kFrameSize; - buffer->data_size = frame_length; - } - } - - PP_Resource CreateAndInitializeEncoder() { - PP_Resource encoder = CreateEncoder(); - PP_Size size = kFrameSize; - MockCompletionCallback cb; - int32_t result = encoder_iface()->Initialize( - encoder, PP_VIDEOFRAME_FORMAT_I420, &size, PP_VIDEOPROFILE_H264MAIN, - kBitrate, PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - if (result != PP_OK_COMPLETIONPENDING) - return 0; - ResourceMessageCallParams params; - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoEncoder_Initialize::ID, ¶ms, &msg)) - return 0; - sink().ClearMessages(); - - SendInitializeReply(params, PP_OK, kVideoFrameCount, kFrameSize); - CreateBitstreamSharedMemory(kBitstreamBufferSize, kBitstreamBufferCount); - SendBitstreamBuffers(params, kBitstreamBufferSize); - - if (!cb.called() || cb.result() != PP_OK) - return 0; - - return encoder; - } - - int32_t CallGetFramesRequired(PP_Resource pp_encoder) { - return encoder_iface()->GetFramesRequired(pp_encoder); - } - - int32_t CallGetFrameCodedSize(PP_Resource pp_encoder, PP_Size* coded_size) { - return encoder_iface()->GetFrameCodedSize(pp_encoder, coded_size); - } - - int32_t CallGetVideoFrame(PP_Resource pp_encoder, - PP_Resource* video_frame, - MockCompletionCallback* cb) { - return encoder_iface()->GetVideoFrame( - pp_encoder, video_frame, PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - } - - int32_t CallFirstGetVideoFrame(PP_Resource pp_encoder, - PP_Resource* video_frame, - MockCompletionCallback* cb) { - int32_t result = encoder_iface()->GetVideoFrame( - pp_encoder, video_frame, PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - if (result != PP_OK_COMPLETIONPENDING) - return result; - - ResourceMessageCallParams params; - CheckGetVideoFramesMsg(¶ms); - - uint32_t frame_length = kFrameSize.width * kFrameSize.height * 2; - CreateVideoFramesSharedMemory(frame_length, kVideoFrameCount); - SendGetVideoFramesReply(params, kVideoFrameCount, frame_length, kFrameSize); - - return result; - } - - int32_t CallEncode(PP_Resource pp_encoder, - PP_Resource video_frame, - PP_Bool force_keyframe, - MockCompletionCallback* cb) { - return encoder_iface()->Encode(pp_encoder, video_frame, force_keyframe, - PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - } - - int32_t CallCompleteEncode(PP_Resource pp_encoder, - PP_Resource video_frame, - PP_Bool force_keyframe, - MockCompletionCallback* cb) { - int32_t result = - encoder_iface()->Encode(pp_encoder, video_frame, force_keyframe, - PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, cb)); - if (result != PP_OK_COMPLETIONPENDING) - return result; - - ResourceMessageCallParams params; - uint32_t frame_id; - bool forced_keyframe; - if (!CheckEncodeMsg(¶ms, &frame_id, &forced_keyframe)) - return PP_ERROR_FAILED; - - SendEncodeReply(params, frame_id); - - return result; - } - - int32_t CallGetBitstreamBuffer(PP_Resource pp_encoder, - PP_BitstreamBuffer* bitstream_buffer, - MockCompletionCallback* cb) { - return encoder_iface()->GetBitstreamBuffer( - pp_encoder, bitstream_buffer, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - cb)); - } - - void CallRecycleBitstreamBuffer(PP_Resource pp_encoder, - const PP_BitstreamBuffer& buffer) { - encoder_iface()->RecycleBitstreamBuffer(pp_encoder, &buffer); - } - - void CallRequestEncodingParametersChange(PP_Resource pp_encoder, - uint32_t bitrate, - uint32_t framerate) { - encoder_iface()->RequestEncodingParametersChange(pp_encoder, bitrate, - framerate); - } - - void CallClose(PP_Resource pp_encoder) { - encoder_iface()->Close(pp_encoder); - } - - void SendGetSupportedProfilesReply( - const ResourceMessageCallParams& params, - const std::vector<PP_VideoProfileDescription>& profiles) { - SendReply(params, PP_OK, - PpapiPluginMsg_VideoEncoder_GetSupportedProfilesReply(profiles)); - } - - void SendInitializeReply(const ResourceMessageCallParams& params, - int32_t success, - uint32_t input_frame_count, - const PP_Size& input_coded_size) { - SendReply(params, success, PpapiPluginMsg_VideoEncoder_InitializeReply( - input_frame_count, input_coded_size)); - } - - void SendBitstreamBuffers(const ResourceMessageCallParams& params, - uint32_t buffer_length) { - std::vector<SerializedHandle> handles; - for (const auto& mem : shared_memory_bitstreams_) { - ASSERT_EQ(mem.GetSize(), buffer_length); - base::UnsafeSharedMemoryRegion region = mem.Duplicate(); - ASSERT_TRUE(region.IsValid()); - handles.push_back(SerializedHandle(std::move(region))); - } - SendReplyWithHandles( - params, PP_OK, - PpapiPluginMsg_VideoEncoder_BitstreamBuffers(buffer_length), - std::move(handles)); - } - - void SendGetVideoFramesReply(const ResourceMessageCallParams& params, - uint32_t frame_count, - uint32_t frame_length, - const PP_Size& size) { - base::UnsafeSharedMemoryRegion region = - video_frames_manager_.region().Duplicate(); - ASSERT_TRUE(region.IsValid()); - SendReplyWithHandle( - params, PP_OK, - PpapiPluginMsg_VideoEncoder_GetVideoFramesReply( - frame_count, frame_length + sizeof(MediaStreamBuffer::Video), size), - SerializedHandle(std::move(region))); - } - - void SendEncodeReply(const ResourceMessageCallParams& params, - uint32_t frame_id) { - SendReply(params, PP_OK, PpapiPluginMsg_VideoEncoder_EncodeReply(frame_id)); - } - - void SendBitstreamBufferReady(const ResourceMessageCallParams& params, - uint32_t buffer_id, - uint32_t buffer_size, - bool keyframe) { - SendReply(params, PP_OK, - PpapiPluginMsg_VideoEncoder_BitstreamBufferReady( - buffer_id, buffer_size, PP_FromBool(keyframe))); - } - - void SendNotifyError(const ResourceMessageCallParams& params, int32_t error) { - SendReply(params, PP_OK, PpapiPluginMsg_VideoEncoder_NotifyError(error)); - } - - bool CheckGetSupportedProfilesMsg(ResourceMessageCallParams* params) { - IPC::Message msg; - return sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoEncoder_GetSupportedProfiles::ID, params, &msg); - } - - bool CheckInitializeMsg(ResourceMessageCallParams* params, - PP_VideoFrame_Format* input_format, - struct PP_Size* input_visible_size, - PP_VideoProfile* output_profile, - uint32_t* bitrate, - PP_HardwareAcceleration* acceleration) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoEncoder_Initialize::ID, params, &msg)) - return false; - sink().ClearMessages(); - return UnpackMessage<PpapiHostMsg_VideoEncoder_Initialize>( - msg, input_format, input_visible_size, output_profile, bitrate, - acceleration); - } - - bool CheckGetVideoFramesMsg(ResourceMessageCallParams* params) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoEncoder_GetVideoFrames::ID, params, &msg)) - return false; - sink().ClearMessages(); - return true; - } - - bool CheckEncodeMsg(ResourceMessageCallParams* params, - uint32_t* frame_id, - bool* keyframe) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoEncoder_Encode::ID, params, &msg)) - return false; - sink().ClearMessages(); - return UnpackMessage<PpapiHostMsg_VideoEncoder_Encode>(msg, frame_id, - keyframe); - } - - bool CheckRecycleBitstreamBufferMsg(ResourceMessageCallParams* params, - uint32_t* buffer_id) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoEncoder_RecycleBitstreamBuffer::ID, params, &msg)) - return false; - sink().ClearMessages(); - return UnpackMessage<PpapiHostMsg_VideoEncoder_RecycleBitstreamBuffer>( - msg, buffer_id); - } - - bool CheckRequestEncodingParametersChangeMsg( - ResourceMessageCallParams* params, - uint32_t* bitrate, - uint32_t* framerate) { - IPC::Message msg; - if (!sink().GetFirstResourceCallMatching( - PpapiHostMsg_VideoEncoder_RequestEncodingParametersChange::ID, - params, &msg)) - return false; - sink().ClearMessages(); - return UnpackMessage< - PpapiHostMsg_VideoEncoder_RequestEncodingParametersChange>(msg, bitrate, - framerate); - } - - bool CheckIsVideoFrame(PP_Resource video_frame) { - return thunk::GetPPB_VideoFrame_0_1_Thunk()->IsVideoFrame(video_frame); - } - - bool CheckIsVideoFrameValid(PP_Resource video_frame) { - PP_Size frame_size; - return thunk::GetPPB_VideoFrame_0_1_Thunk()->GetSize( - video_frame, &frame_size) == PP_TRUE; - } - - private: - // MediaStreamBufferManager::Delegate: - void OnNewBufferEnqueued() override {} - - const PPB_VideoEncoder_0_2* encoder_iface_; - const PPB_VideoEncoder_0_1* encoder_iface_0_1_; - - std::vector<base::UnsafeSharedMemoryRegion> shared_memory_bitstreams_; - - MediaStreamBufferManager video_frames_manager_; -}; - -void* ForwardUserData(void* user_data, - uint32_t element_count, - uint32_t element_size) { - return user_data; -} - -} // namespace - -TEST_F(VideoEncoderResourceTest, GetSupportedProfiles) { - // Verifies that GetSupportedProfiles calls into the renderer and - // the we get the right results back. - { - LockingResourceReleaser encoder(CreateEncoder()); - PP_VideoProfileDescription profiles[2]; - PP_ArrayOutput output; - output.user_data = &profiles[0]; - output.GetDataBuffer = ForwardUserData; - ResourceMessageCallParams params; - MockCompletionCallback cb; - int32_t result = encoder_iface()->GetSupportedProfiles( - encoder.get(), output, PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - ASSERT_TRUE(CheckGetSupportedProfilesMsg(¶ms)); - - std::vector<PP_VideoProfileDescription> profiles_response; - PP_VideoProfileDescription profile; - profile.profile = PP_VIDEOPROFILE_H264MAIN; - profile.max_resolution.width = 1920; - profile.max_resolution.height = 1080; - profile.max_framerate_numerator = 30; - profile.max_framerate_denominator = 1; - profile.hardware_accelerated = PP_TRUE; - profiles_response.push_back(profile); - profile.profile = PP_VIDEOPROFILE_VP8_ANY; - profile.max_resolution.width = 1920; - profile.max_resolution.height = 1080; - profile.max_framerate_numerator = 30; - profile.max_framerate_denominator = 1; - profile.hardware_accelerated = PP_FALSE; - profiles_response.push_back(profile); - - SendGetSupportedProfilesReply(params, profiles_response); - ASSERT_EQ(profiles_response.size(), static_cast<uint32_t>(cb.result())); - ASSERT_EQ(0, memcmp(&profiles[0], &profiles_response[0], sizeof(profiles))); - } -} - -TEST_F(VideoEncoderResourceTest, GetSupportedProfiles0_1) { - // Verifies that GetSupportedProfiles calls into the renderer and - // the we get the right results back. - { - LockingResourceReleaser encoder(CreateEncoder()); - PP_VideoProfileDescription_0_1 profiles[2]; - PP_ArrayOutput output; - output.user_data = &profiles[0]; - output.GetDataBuffer = ForwardUserData; - ResourceMessageCallParams params; - MockCompletionCallback cb; - int32_t result = encoder_iface_0_1()->GetSupportedProfiles( - encoder.get(), output, PP_MakeOptionalCompletionCallback( - &MockCompletionCallback::Callback, &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - ASSERT_TRUE(CheckGetSupportedProfilesMsg(¶ms)); - - std::vector<PP_VideoProfileDescription> profiles_response; - PP_VideoProfileDescription profile; - profile.profile = PP_VIDEOPROFILE_H264MAIN; - profile.max_resolution.width = 1920; - profile.max_resolution.height = 1080; - profile.max_framerate_numerator = 30; - profile.max_framerate_denominator = 1; - profile.hardware_accelerated = PP_TRUE; - profiles_response.push_back(profile); - profile.profile = PP_VIDEOPROFILE_VP8_ANY; - profile.max_resolution.width = 1920; - profile.max_resolution.height = 1080; - profile.max_framerate_numerator = 30; - profile.max_framerate_denominator = 1; - profile.hardware_accelerated = PP_FALSE; - profiles_response.push_back(profile); - - SendGetSupportedProfilesReply(params, profiles_response); - - ASSERT_EQ(profiles_response.size(), static_cast<uint32_t>(cb.result())); - - for (uint32_t i = 0; i < profiles_response.size(); i++) { - ASSERT_EQ(profiles_response[i].profile, profiles[i].profile); - ASSERT_EQ(profiles_response[i].max_resolution.width, - profiles[i].max_resolution.width); - ASSERT_EQ(profiles_response[i].max_resolution.height, - profiles[i].max_resolution.height); - ASSERT_EQ(profiles_response[i].max_framerate_numerator, - profiles[i].max_framerate_numerator); - ASSERT_EQ(profiles_response[i].max_framerate_denominator, - profiles[i].max_framerate_denominator); - if (profiles_response[i].hardware_accelerated) - ASSERT_EQ(PP_HARDWAREACCELERATION_ONLY, profiles[i].acceleration); - else - ASSERT_EQ(PP_HARDWAREACCELERATION_NONE, profiles[i].acceleration); - } - } -} - -TEST_F(VideoEncoderResourceTest, InitializeFailure) { - { - // Verify the initialize callback is called in case of failure. - LockingResourceReleaser encoder(CreateEncoder()); - ResourceMessageCallParams params; - PP_Size size = kFrameSize; - MockCompletionCallback cb; - int32_t result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_BGRA, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - PP_VideoFrame_Format input_format; - PP_Size input_visible_size; - PP_VideoProfile output_profile; - uint32_t bitrate; - PP_HardwareAcceleration acceleration; - ASSERT_TRUE(CheckInitializeMsg(¶ms, &input_format, &input_visible_size, - &output_profile, &bitrate, &acceleration)); - ASSERT_EQ(PP_VIDEOFRAME_FORMAT_BGRA, input_format); - ASSERT_EQ(size.width, input_visible_size.width); - ASSERT_EQ(size.height, input_visible_size.height); - ASSERT_EQ(kBitrate, bitrate); - ASSERT_EQ(PP_VIDEOPROFILE_H264MAIN, output_profile); - ASSERT_EQ(PP_HARDWAREACCELERATION_WITHFALLBACK, acceleration); - - SendInitializeReply(params, PP_ERROR_NOTSUPPORTED, kVideoFrameCount, - kFrameSize); - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_ERROR_NOTSUPPORTED, cb.result()); - } - { - // Verify the initialize callback is called in case of error - // notification. - LockingResourceReleaser encoder(CreateEncoder()); - ResourceMessageCallParams params; - PP_Size size = kFrameSize; - MockCompletionCallback cb; - int32_t result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_BGRA, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - PP_VideoFrame_Format input_format; - PP_Size input_visible_size; - PP_VideoProfile output_profile; - uint32_t bitrate; - PP_HardwareAcceleration acceleration; - ASSERT_TRUE(CheckInitializeMsg(¶ms, &input_format, &input_visible_size, - &output_profile, &bitrate, &acceleration)); - ASSERT_EQ(PP_VIDEOFRAME_FORMAT_BGRA, input_format); - ASSERT_EQ(kFrameSize.width, input_visible_size.width); - ASSERT_EQ(kFrameSize.height, input_visible_size.height); - ASSERT_EQ(kBitrate, bitrate); - ASSERT_EQ(PP_VIDEOPROFILE_H264MAIN, output_profile); - ASSERT_EQ(PP_HARDWAREACCELERATION_WITHFALLBACK, acceleration); - - ResourceMessageCallParams error_params(encoder.get(), 0); - SendNotifyError(error_params, PP_ERROR_FAILED); - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - } - { - // Verify that calling initialize twice fails the second time if - // we haven't received a response yet. - LockingResourceReleaser encoder(CreateEncoder()); - ResourceMessageCallParams params; - PP_Size size = kFrameSize; - MockCompletionCallback cb; - int32_t result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_BGRA, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - PP_VideoFrame_Format input_format; - PP_Size input_visible_size; - PP_VideoProfile output_profile; - uint32_t bitrate; - PP_HardwareAcceleration acceleration; - ASSERT_TRUE(CheckInitializeMsg(¶ms, &input_format, &input_visible_size, - &output_profile, &bitrate, &acceleration)); - ASSERT_EQ(PP_VIDEOFRAME_FORMAT_BGRA, input_format); - ASSERT_EQ(size.width, input_visible_size.width); - ASSERT_EQ(size.height, input_visible_size.height); - ASSERT_EQ(kBitrate, bitrate); - ASSERT_EQ(PP_VIDEOPROFILE_H264MAIN, output_profile); - ASSERT_EQ(PP_HARDWAREACCELERATION_WITHFALLBACK, acceleration); - - result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_BGRA, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_ERROR_INPROGRESS, result); - - ResourceMessageCallParams error_params(encoder.get(), 0); - SendNotifyError(error_params, PP_ERROR_FAILED); - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - } -} - -TEST_F(VideoEncoderResourceTest, InitializeSuccess) { - { - // Verify the initialize callback is called when initialization is - // successful. - LockingResourceReleaser encoder(CreateEncoder()); - ResourceMessageCallParams params; - PP_Size size = kFrameSize; - const uint32_t kBitrate = 420000; - MockCompletionCallback cb; - int32_t result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_I420, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - PP_VideoFrame_Format input_format; - PP_Size input_visible_size; - PP_VideoProfile output_profile; - uint32_t bitrate; - PP_HardwareAcceleration acceleration; - ASSERT_TRUE(CheckInitializeMsg(¶ms, &input_format, &input_visible_size, - &output_profile, &bitrate, &acceleration)); - ASSERT_EQ(PP_VIDEOFRAME_FORMAT_I420, input_format); - ASSERT_EQ(kFrameSize.width, input_visible_size.width); - ASSERT_EQ(kFrameSize.height, input_visible_size.height); - ASSERT_EQ(kBitrate, bitrate); - ASSERT_EQ(PP_VIDEOPROFILE_H264MAIN, output_profile); - ASSERT_EQ(PP_HARDWAREACCELERATION_WITHFALLBACK, acceleration); - - SendInitializeReply(params, PP_OK, kVideoFrameCount, kFrameSize); - - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_OK, cb.result()); - } - { - // Verify that calling initialize a second time, after it already - // succeeded, fails. - LockingResourceReleaser encoder(CreateEncoder()); - ResourceMessageCallParams params; - PP_Size size = kFrameSize; - const uint32_t kBitrate = 420000; - MockCompletionCallback cb; - int32_t result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_I420, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - PP_VideoFrame_Format input_format; - PP_Size input_visible_size; - PP_VideoProfile output_profile; - uint32_t bitrate; - PP_HardwareAcceleration acceleration; - ASSERT_TRUE(CheckInitializeMsg(¶ms, &input_format, &input_visible_size, - &output_profile, &bitrate, &acceleration)); - ASSERT_EQ(PP_VIDEOFRAME_FORMAT_I420, input_format); - ASSERT_EQ(kFrameSize.width, input_visible_size.width); - ASSERT_EQ(kFrameSize.height, input_visible_size.height); - ASSERT_EQ(kBitrate, bitrate); - ASSERT_EQ(PP_VIDEOPROFILE_H264MAIN, output_profile); - ASSERT_EQ(PP_HARDWAREACCELERATION_WITHFALLBACK, acceleration); - - SendInitializeReply(params, PP_OK, kVideoFrameCount, kFrameSize); - - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_OK, cb.result()); - - result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_I420, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_ERROR_FAILED, result); - } - { - // Verify the sending the bitstream buffers details makes them - // available through the API. the right values. - LockingResourceReleaser encoder(CreateEncoder()); - ResourceMessageCallParams params; - PP_Size size = kFrameSize; - const uint32_t kBitrate = 420000; - MockCompletionCallback cb; - int32_t result = encoder_iface()->Initialize( - encoder.get(), PP_VIDEOFRAME_FORMAT_I420, &size, - PP_VIDEOPROFILE_H264MAIN, kBitrate, - PP_HARDWAREACCELERATION_WITHFALLBACK, - PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback, - &cb)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - PP_VideoFrame_Format input_format; - PP_Size input_visible_size; - PP_VideoProfile output_profile; - uint32_t bitrate; - PP_HardwareAcceleration acceleration; - ASSERT_TRUE(CheckInitializeMsg(¶ms, &input_format, &input_visible_size, - &output_profile, &bitrate, &acceleration)); - ASSERT_EQ(PP_VIDEOFRAME_FORMAT_I420, input_format); - ASSERT_EQ(kFrameSize.width, input_visible_size.width); - ASSERT_EQ(kFrameSize.height, input_visible_size.height); - ASSERT_EQ(kBitrate, bitrate); - ASSERT_EQ(PP_VIDEOPROFILE_H264MAIN, output_profile); - ASSERT_EQ(PP_HARDWAREACCELERATION_WITHFALLBACK, acceleration); - - SendInitializeReply(params, PP_OK, kVideoFrameCount, kFrameSize); - - ASSERT_TRUE(cb.called()); - ASSERT_EQ(PP_OK, cb.result()); - - PP_Size coded_size; - ASSERT_EQ(PP_OK, CallGetFrameCodedSize(encoder.get(), &coded_size)); - ASSERT_EQ(kFrameSize.width, coded_size.width); - ASSERT_EQ(kFrameSize.height, coded_size.height); - ASSERT_EQ(static_cast<int32_t>(kVideoFrameCount), - CallGetFramesRequired(encoder.get())); - } -} - -TEST_F(VideoEncoderResourceTest, Uninitialized) { - // Operations on uninitialized encoders should fail. - LockingResourceReleaser encoder(CreateEncoder()); - - ASSERT_EQ(PP_ERROR_FAILED, CallGetFramesRequired(encoder.get())); - - PP_Size size; - ASSERT_EQ(PP_ERROR_FAILED, CallGetFrameCodedSize(encoder.get(), &size)); - - MockCompletionCallback uncalled_cb; - PP_Resource video_frame = 0; - ASSERT_EQ(PP_ERROR_FAILED, - CallGetVideoFrame(encoder.get(), &video_frame, &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - ASSERT_EQ(0, video_frame); - - ASSERT_EQ(PP_ERROR_FAILED, - CallEncode(encoder.get(), video_frame, PP_FALSE, &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ( - PP_ERROR_FAILED, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, &uncalled_cb)); - ASSERT_FALSE(uncalled_cb.called()); - - ResourceMessageCallParams params; - uint32_t buffer_id; - CallRecycleBitstreamBuffer(encoder.get(), bitstream_buffer); - ASSERT_FALSE(CheckRecycleBitstreamBufferMsg(¶ms, &buffer_id)); - - uint32_t bitrate, framerate; - CallRequestEncodingParametersChange(encoder.get(), 0, 0); - ASSERT_FALSE( - CheckRequestEncodingParametersChangeMsg(¶ms, &bitrate, &framerate)); -} - -TEST_F(VideoEncoderResourceTest, InitializeAndGetVideoFrame) { - // Verify that we can pull the right number of video frames before - // the proxy makes us wait. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - ResourceMessageCallParams params; - std::vector<PP_Resource> video_frames; - MockCompletionCallback get_frame_cb; - - video_frames.resize(kVideoFrameCount + 1); - - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetVideoFrame(encoder.get(), &video_frames[0], &get_frame_cb)); - ASSERT_FALSE(get_frame_cb.called()); - ASSERT_TRUE(CheckGetVideoFramesMsg(¶ms)); - - uint32_t frame_length = kFrameSize.width * kFrameSize.height * 2; - CreateVideoFramesSharedMemory(frame_length, kVideoFrameCount); - SendGetVideoFramesReply(params, kVideoFrameCount, frame_length, kFrameSize); - - for (uint32_t i = 1; i < kVideoFrameCount; ++i) { - get_frame_cb.Reset(); - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallGetVideoFrame(encoder.get(), &video_frames[i], &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - ASSERT_TRUE(CheckIsVideoFrame(video_frames[i])); - } - - get_frame_cb.Reset(); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetVideoFrame(encoder.get(), &video_frames[kVideoFrameCount], - &get_frame_cb)); - ASSERT_FALSE(get_frame_cb.called()); - - MockCompletionCallback get_frame_fail_cb; - ASSERT_EQ(PP_ERROR_INPROGRESS, - CallGetVideoFrame(encoder.get(), &video_frames[kVideoFrameCount], - &get_frame_fail_cb)); - ASSERT_FALSE(get_frame_fail_cb.called()); - - // Unblock the GetVideoFrame callback by freeing up a frame. - MockCompletionCallback encode_cb; - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallCompleteEncode(encoder.get(), video_frames[0], PP_FALSE, &encode_cb)); - ASSERT_TRUE(encode_cb.called()); - ASSERT_EQ(PP_OK, encode_cb.result()); - ASSERT_TRUE(get_frame_cb.called()); - - CallClose(encoder.get()); -} - -TEST_F(VideoEncoderResourceTest, Encode) { - // Check Encode() calls into the renderer. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - PP_Resource video_frame; - MockCompletionCallback get_frame_cb; - - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallFirstGetVideoFrame(encoder.get(), &video_frame, &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - - MockCompletionCallback encode_cb; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallEncode(encoder.get(), video_frame, PP_TRUE, &encode_cb)); - ASSERT_FALSE(encode_cb.called()); - ASSERT_FALSE(CheckIsVideoFrameValid(video_frame)); - - ResourceMessageCallParams params; - uint32_t frame_id; - bool force_frame; - ASSERT_TRUE(CheckEncodeMsg(¶ms, &frame_id, &force_frame)); - - SendEncodeReply(params, frame_id); - - ASSERT_TRUE(encode_cb.called()); - ASSERT_EQ(PP_OK, encode_cb.result()); -} - -TEST_F(VideoEncoderResourceTest, EncodeAndGetVideoFrame) { - // Check the encoding loop works well. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - ResourceMessageCallParams params; - PP_Resource video_frame; - MockCompletionCallback get_frame_cb, encode_cb; - - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallFirstGetVideoFrame(encoder.get(), &video_frame, &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - - for (uint32_t i = 1; i < 20 * kVideoFrameCount; ++i) { - encode_cb.Reset(); - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallCompleteEncode(encoder.get(), video_frame, PP_FALSE, &encode_cb)); - ASSERT_TRUE(encode_cb.called()); - ASSERT_EQ(PP_OK, encode_cb.result()); - - get_frame_cb.Reset(); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetVideoFrame(encoder.get(), &video_frame, &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - ASSERT_TRUE(CheckIsVideoFrame(video_frame)); - } - - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallCompleteEncode(encoder.get(), video_frame, PP_FALSE, &encode_cb)); - ASSERT_TRUE(encode_cb.called()); - ASSERT_EQ(PP_OK, encode_cb.result()); -} - -TEST_F(VideoEncoderResourceTest, GetBitstreamBuffer) { - { - // Verify that the GetBitstreamBuffer callback is fired whenever the - // renderer signals a buffer is available. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - MockCompletionCallback get_bitstream_buffer_cb; - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - ASSERT_FALSE(get_bitstream_buffer_cb.called()); - - ResourceMessageCallParams buffer_params(encoder.get(), 0); - SendBitstreamBufferReady(buffer_params, 0, 10, true); - - ASSERT_TRUE(get_bitstream_buffer_cb.called()); - ASSERT_EQ(PP_OK, get_bitstream_buffer_cb.result()); - ASSERT_EQ(10U, bitstream_buffer.size); - ASSERT_EQ(PP_TRUE, bitstream_buffer.key_frame); - } - { - // Verify that calling GetBitstreamBuffer a second time, while the - // first callback hasn't been fired fails. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - MockCompletionCallback get_bitstream_buffer_cb; - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - ASSERT_FALSE(get_bitstream_buffer_cb.called()); - - ASSERT_EQ(PP_ERROR_INPROGRESS, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - ASSERT_FALSE(get_bitstream_buffer_cb.called()); - - ResourceMessageCallParams buffer_params(encoder.get(), 0); - SendBitstreamBufferReady(buffer_params, 0, 10, true); - } -} - -TEST_F(VideoEncoderResourceTest, RecycleBitstreamBuffer) { - // Verify that we signal the renderer that a bitstream buffer has been - // recycled. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - MockCompletionCallback get_bitstream_buffer_cb; - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - ASSERT_FALSE(get_bitstream_buffer_cb.called()); - - ResourceMessageCallParams buffer_params(encoder.get(), 0); - SendBitstreamBufferReady(buffer_params, kBitstreamBufferCount - 1, 10, true); - - ASSERT_TRUE(get_bitstream_buffer_cb.called()); - ASSERT_EQ(PP_OK, get_bitstream_buffer_cb.result()); - - CallRecycleBitstreamBuffer(encoder.get(), bitstream_buffer); - - ResourceMessageCallParams recycle_params; - uint32_t buffer_id; - ASSERT_TRUE(CheckRecycleBitstreamBufferMsg(&recycle_params, &buffer_id)); - ASSERT_EQ(kBitstreamBufferCount - 1, buffer_id); -} - -TEST_F(VideoEncoderResourceTest, RequestEncodingParametersChange) { - // Check encoding parameter changes are correctly sent to the - // renderer. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - CallRequestEncodingParametersChange(encoder.get(), 1, 2); - ResourceMessageCallParams params; - uint32_t bitrate, framerate; - ASSERT_TRUE( - CheckRequestEncodingParametersChangeMsg(¶ms, &bitrate, &framerate)); - ASSERT_EQ(1U, bitrate); - ASSERT_EQ(2U, framerate); -} - -TEST_F(VideoEncoderResourceTest, NotifyError) { - { - // Check an error from the encoder aborts GetVideoFrame and - // GetBitstreamBuffer callbacks. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - MockCompletionCallback get_frame_cb; - PP_Resource video_frame; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetVideoFrame(encoder.get(), &video_frame, &get_frame_cb)); - ASSERT_FALSE(get_frame_cb.called()); - - MockCompletionCallback get_bitstream_buffer_cb; - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - - ResourceMessageCallParams error_params(encoder.get(), 0); - SendNotifyError(error_params, PP_ERROR_FAILED); - - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_ERROR_FAILED, get_frame_cb.result()); - ASSERT_TRUE(get_bitstream_buffer_cb.called()); - ASSERT_EQ(PP_ERROR_FAILED, get_bitstream_buffer_cb.result()); - } - { - // Check an error from the encoder aborts Encode and GetBitstreamBuffer - // callbacks. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - MockCompletionCallback get_frame_cb, encode_cb1, encode_cb2; - PP_Resource video_frame1, video_frame2; - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallFirstGetVideoFrame(encoder.get(), &video_frame1, &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - - get_frame_cb.Reset(); - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallFirstGetVideoFrame(encoder.get(), &video_frame2, &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallEncode(encoder.get(), video_frame1, PP_FALSE, &encode_cb1)); - ASSERT_FALSE(encode_cb1.called()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallEncode(encoder.get(), video_frame2, PP_FALSE, &encode_cb2)); - ASSERT_FALSE(encode_cb2.called()); - - MockCompletionCallback get_bitstream_buffer_cb; - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - - ResourceMessageCallParams error_params(encoder.get(), 0); - SendNotifyError(error_params, PP_ERROR_FAILED); - - ASSERT_TRUE(encode_cb1.called()); - ASSERT_EQ(PP_ERROR_FAILED, encode_cb1.result()); - ASSERT_TRUE(encode_cb2.called()); - ASSERT_EQ(PP_ERROR_FAILED, encode_cb2.result()); - ASSERT_TRUE(get_bitstream_buffer_cb.called()); - ASSERT_EQ(PP_ERROR_FAILED, get_bitstream_buffer_cb.result()); - } -} - -TEST_F(VideoEncoderResourceTest, Close) { - { - // Check closing the encoder aborts GetVideoFrame and - // GetBitstreamBuffer callbacks. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - MockCompletionCallback get_frame_cb; - PP_Resource video_frame; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetVideoFrame(encoder.get(), &video_frame, &get_frame_cb)); - ASSERT_FALSE(get_frame_cb.called()); - - MockCompletionCallback get_bitstream_buffer_cb; - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - - CallClose(encoder.get()); - - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_ERROR_ABORTED, get_frame_cb.result()); - ASSERT_TRUE(get_bitstream_buffer_cb.called()); - ASSERT_EQ(PP_ERROR_ABORTED, get_bitstream_buffer_cb.result()); - } - { - // Check closing the encoder aborts Encode and GetBitstreamBuffer - // callbacks. - LockingResourceReleaser encoder(CreateAndInitializeEncoder()); - - MockCompletionCallback get_frame_cb, encode_cb1, encode_cb2; - PP_Resource video_frame1, video_frame2; - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallFirstGetVideoFrame(encoder.get(), &video_frame1, &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - - get_frame_cb.Reset(); - ASSERT_EQ( - PP_OK_COMPLETIONPENDING, - CallFirstGetVideoFrame(encoder.get(), &video_frame2, &get_frame_cb)); - ASSERT_TRUE(get_frame_cb.called()); - ASSERT_EQ(PP_OK, get_frame_cb.result()); - - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallEncode(encoder.get(), video_frame1, PP_FALSE, &encode_cb1)); - ASSERT_FALSE(encode_cb1.called()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallEncode(encoder.get(), video_frame2, PP_FALSE, &encode_cb2)); - ASSERT_FALSE(encode_cb2.called()); - - MockCompletionCallback get_bitstream_buffer_cb; - PP_BitstreamBuffer bitstream_buffer; - ASSERT_EQ(PP_OK_COMPLETIONPENDING, - CallGetBitstreamBuffer(encoder.get(), &bitstream_buffer, - &get_bitstream_buffer_cb)); - - CallClose(encoder.get()); - - ASSERT_TRUE(encode_cb1.called()); - ASSERT_EQ(PP_ERROR_ABORTED, encode_cb1.result()); - ASSERT_TRUE(encode_cb2.called()); - ASSERT_EQ(PP_ERROR_ABORTED, encode_cb2.result()); - ASSERT_TRUE(get_bitstream_buffer_cb.called()); - ASSERT_EQ(PP_ERROR_ABORTED, get_bitstream_buffer_cb.result()); - - // Verify that a remaining encode response from the renderer is - // discarded. - ResourceMessageCallParams params; - uint32_t frame_id; - bool force_frame; - ASSERT_TRUE(CheckEncodeMsg(¶ms, &frame_id, &force_frame)); - SendEncodeReply(params, frame_id); - } -} - -} // namespace proxy -} // namespace ppapi
diff --git a/proxy/websocket_resource_unittest.cc b/proxy/websocket_resource_unittest.cc deleted file mode 100644 index 2a8f060..0000000 --- a/proxy/websocket_resource_unittest.cc +++ /dev/null
@@ -1,169 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include <tuple> - -#include "base/memory/ref_counted.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/ppb_websocket.h" -#include "ppapi/proxy/locking_resource_releaser.h" -#include "ppapi/proxy/plugin_message_filter.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/websocket_resource.h" -#include "ppapi/shared_impl/ppapi_globals.h" -#include "ppapi/shared_impl/ppb_var_shared.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/resource_tracker.h" -#include "ppapi/shared_impl/scoped_pp_resource.h" -#include "ppapi/shared_impl/scoped_pp_var.h" -#include "ppapi/shared_impl/tracked_callback.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/thunk/thunk.h" - -namespace ppapi { -namespace proxy { - -namespace { - -typedef PluginProxyTest WebSocketResourceTest; - -bool g_callback_called; -int32_t g_callback_result; -const PPB_Var* ppb_var_ = NULL; - -void Callback(void* user_data, int32_t result) { - g_callback_called = true; - g_callback_result = result; -} - -PP_CompletionCallback MakeCallback() { - g_callback_called = false; - g_callback_result = PP_OK; - return PP_MakeCompletionCallback(Callback, NULL); -} - -PP_Var MakeStringVar(const std::string& string) { - if (!ppb_var_) - ppb_var_ = ppapi::PPB_Var_Shared::GetVarInterface1_2(); - return ppb_var_->VarFromUtf8(string.c_str(), - static_cast<uint32_t>(string.length())); -} - -} // namespace - - -// Does a test of Connect(). -TEST_F(WebSocketResourceTest, Connect) { - const PPB_WebSocket_1_0* websocket_iface = - thunk::GetPPB_WebSocket_1_0_Thunk(); - - std::string url("ws://ws.google.com"); - std::string protocol0("x-foo"); - std::string protocol1("x-bar"); - PP_Var url_var = MakeStringVar(url); - PP_Var protocols[] = { MakeStringVar(protocol0), MakeStringVar(protocol1) }; - - LockingResourceReleaser res(websocket_iface->Create(pp_instance())); - - int32_t result = websocket_iface->Connect(res.get(), url_var, protocols, 2, - MakeCallback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - // Should be sent a "Connect" message. - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_WebSocket_Connect::ID, ¶ms, &msg)); - PpapiHostMsg_WebSocket_Connect::Schema::Param p; - PpapiHostMsg_WebSocket_Connect::Read(&msg, &p); - EXPECT_EQ(url, std::get<0>(p)); - EXPECT_EQ(protocol0, std::get<1>(p)[0]); - EXPECT_EQ(protocol1, std::get<1>(p)[1]); - - // Synthesize a response. - ResourceMessageReplyParams reply_params(params.pp_resource(), - params.sequence()); - reply_params.set_result(PP_OK); - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, PpapiPluginMsg_WebSocket_ConnectReply(url, protocol1)); - - EXPECT_EQ(PP_OK, g_callback_result); - EXPECT_EQ(true, g_callback_called); -} - -// Does a test for unsolicited replies. -TEST_F(WebSocketResourceTest, UnsolicitedReplies) { - const PPB_WebSocket_1_0* websocket_iface = - thunk::GetPPB_WebSocket_1_0_Thunk(); - - LockingResourceReleaser res(websocket_iface->Create(pp_instance())); - - // Check if BufferedAmountReply is handled. - ResourceMessageReplyParams reply_params(res.get(), 0); - reply_params.set_result(PP_OK); - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, PpapiPluginMsg_WebSocket_BufferedAmountReply(19760227u)); - - uint64_t amount = websocket_iface->GetBufferedAmount(res.get()); - EXPECT_EQ(19760227u, amount); - - // Check if StateReply is handled. - PluginMessageFilter::DispatchResourceReplyForTest( - reply_params, - PpapiPluginMsg_WebSocket_StateReply( - static_cast<int32_t>(PP_WEBSOCKETREADYSTATE_CLOSING))); - - PP_WebSocketReadyState state = websocket_iface->GetReadyState(res.get()); - EXPECT_EQ(PP_WEBSOCKETREADYSTATE_CLOSING, state); -} - -TEST_F(WebSocketResourceTest, MessageError) { - const PPB_WebSocket_1_0* websocket_iface = - thunk::GetPPB_WebSocket_1_0_Thunk(); - - std::string url("ws://ws.google.com"); - PP_Var url_var = MakeStringVar(url); - - LockingResourceReleaser res(websocket_iface->Create(pp_instance())); - - // Establish the connection virtually. - int32_t result = - websocket_iface->Connect(res.get(), url_var, NULL, 0, MakeCallback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_WebSocket_Connect::ID, ¶ms, &msg)); - - ResourceMessageReplyParams connect_reply_params(params.pp_resource(), - params.sequence()); - connect_reply_params.set_result(PP_OK); - PluginMessageFilter::DispatchResourceReplyForTest( - connect_reply_params, - PpapiPluginMsg_WebSocket_ConnectReply(url, std::string())); - - EXPECT_EQ(PP_OK, g_callback_result); - EXPECT_TRUE(g_callback_called); - - PP_Var message; - result = websocket_iface->ReceiveMessage(res.get(), &message, MakeCallback()); - EXPECT_FALSE(g_callback_called); - - // Synthesize a WebSocket_ErrorReply message. - ResourceMessageReplyParams error_reply_params(res.get(), 0); - error_reply_params.set_result(PP_OK); - PluginMessageFilter::DispatchResourceReplyForTest( - error_reply_params, PpapiPluginMsg_WebSocket_ErrorReply()); - - EXPECT_EQ(PP_ERROR_FAILED, g_callback_result); - EXPECT_TRUE(g_callback_called); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/shared_impl/BUILD.gn b/shared_impl/BUILD.gn index d6efdcc..819f5ef 100644 --- a/shared_impl/BUILD.gn +++ b/shared_impl/BUILD.gn
@@ -252,24 +252,3 @@ frameworks = [ "QuartzCore.framework" ] } } - -static_library("test_support") { - testonly = true - - sources = [ - "test_globals.cc", - "test_globals.h", - "test_utils.cc", - "test_utils.h", - ] - - public_deps = [ "//ppapi/shared_impl" ] - deps = [ - "//base/test:test_support", - "//ipc", - "//ipc:test_support", - "//ppapi/proxy", - "//testing/gmock", - "//testing/gtest", - ] -}
diff --git a/shared_impl/media_stream_audio_track_shared_unittest.cc b/shared_impl/media_stream_audio_track_shared_unittest.cc deleted file mode 100644 index f6b5d77..0000000 --- a/shared_impl/media_stream_audio_track_shared_unittest.cc +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/shared_impl/media_stream_audio_track_shared.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { - -TEST(MediaStreamAudioTrackShared, Verify) { - { - MediaStreamAudioTrackShared::Attributes attributes; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - } - - // Verify buffers - { - MediaStreamAudioTrackShared::Attributes attributes; - attributes.buffers = 0; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.buffers = 8; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.buffers = 1024; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.buffers = -1; - EXPECT_FALSE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - } - - // Verify duration - { - MediaStreamAudioTrackShared::Attributes attributes; - attributes.duration = 0; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.duration = 10; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.duration = 10000; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.duration = 123; - EXPECT_TRUE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.duration = 9; - EXPECT_FALSE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - - attributes.duration = -1; - EXPECT_FALSE(MediaStreamAudioTrackShared::VerifyAttributes(attributes)); - } -} - -} // namespace ppapi
diff --git a/shared_impl/media_stream_buffer_manager_unittest.cc b/shared_impl/media_stream_buffer_manager_unittest.cc deleted file mode 100644 index d66b28d..0000000 --- a/shared_impl/media_stream_buffer_manager_unittest.cc +++ /dev/null
@@ -1,178 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/shared_impl/media_stream_buffer_manager.h" - -#include <stdint.h> - -#include <utility> - -#include "base/memory/unsafe_shared_memory_region.h" -#include "ppapi/c/pp_errors.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -base::UnsafeSharedMemoryRegion CreateSharedMemory(int32_t buffer_size, - int32_t number_of_buffers) { - base::UnsafeSharedMemoryRegion region = - base::UnsafeSharedMemoryRegion::Create(buffer_size * number_of_buffers); - EXPECT_TRUE(region.IsValid()); - return region; -} - -} // namespace - -namespace ppapi { - -class MockDelegate : public MediaStreamBufferManager::Delegate { - public: - MockDelegate() : new_buffer_enqueue_counter_(0) {} - void OnNewBufferEnqueued() override { - new_buffer_enqueue_counter_++; - } - - int32_t new_buffer_enqueue_counter_; -}; - -TEST(MediaStreamBufferManager, General) { - { - const int32_t kNumberOfBuffers = 5; - const int32_t kBufferSize = 128; - MockDelegate delegate; - MediaStreamBufferManager manager(&delegate); - base::UnsafeSharedMemoryRegion shared_memory = - CreateSharedMemory(kBufferSize, kNumberOfBuffers); - // SetBuffers with enqueue_all_buffers = true; - EXPECT_TRUE(manager.SetBuffers(kNumberOfBuffers, kBufferSize, - std::move(shared_memory), true)); - - int8_t* memory = reinterpret_cast<int8_t*>(manager.GetBufferPointer(0)); - EXPECT_NE(static_cast<int8_t*>(NULL), memory); - - EXPECT_EQ(kNumberOfBuffers, manager.number_of_buffers()); - EXPECT_EQ(kBufferSize, manager.buffer_size()); - EXPECT_TRUE(manager.HasAvailableBuffer()); - - // Test DequeueBuffer() and GetBufferPointer() - for (int32_t i = 0; i < kNumberOfBuffers; ++i) { - EXPECT_EQ(i, manager.DequeueBuffer()); - EXPECT_EQ(reinterpret_cast<MediaStreamBuffer*>(memory + i * kBufferSize), - manager.GetBufferPointer(i)); - } - - manager.EnqueueBuffer(0); - manager.EnqueueBuffer(4); - manager.EnqueueBuffer(3); - manager.EnqueueBuffer(1); - manager.EnqueueBuffer(2); - EXPECT_EQ(5, delegate.new_buffer_enqueue_counter_); - - EXPECT_EQ(0, manager.DequeueBuffer()); - EXPECT_EQ(4, manager.DequeueBuffer()); - EXPECT_EQ(3, manager.DequeueBuffer()); - EXPECT_EQ(1, manager.DequeueBuffer()); - EXPECT_EQ(2, manager.DequeueBuffer()); - EXPECT_EQ(PP_ERROR_FAILED, manager.DequeueBuffer()); - EXPECT_EQ(PP_ERROR_FAILED, manager.DequeueBuffer()); - EXPECT_FALSE(manager.HasAvailableBuffer()); - - // Returns NULL for invalid index to GetBufferPointer() - EXPECT_EQ(NULL, manager.GetBufferPointer(-1)); - EXPECT_EQ(NULL, manager.GetBufferPointer(kNumberOfBuffers)); - - // Test crash for passing invalid index to EnqueueBuffer(). - // String arguments aren't passed to CHECK() in official builds. -#if defined(OFFICIAL_BUILD) && defined(NDEBUG) - EXPECT_DEATH(manager.EnqueueBuffer(-1), ""); - EXPECT_DEATH(manager.EnqueueBuffer(kNumberOfBuffers), ""); -#else - EXPECT_DEATH(manager.EnqueueBuffer(-1), ".*Check failed: index >= 0.*"); - EXPECT_DEATH(manager.EnqueueBuffer(kNumberOfBuffers), - ".*Check failed: index < number_of_buffers_.*"); -#endif - } - - { - const int32_t kNumberOfBuffers = 5; - const int32_t kBufferSize = 128; - MockDelegate delegate; - MediaStreamBufferManager manager(&delegate); - base::UnsafeSharedMemoryRegion shared_memory = - CreateSharedMemory(kBufferSize, kNumberOfBuffers); - // SetBuffers with enqueue_all_buffers = false; - EXPECT_TRUE(manager.SetBuffers(kNumberOfBuffers, kBufferSize, - std::move(shared_memory), false)); - - int8_t* memory = reinterpret_cast<int8_t*>(manager.GetBufferPointer(0)); - EXPECT_NE(static_cast<int8_t*>(NULL), memory); - - EXPECT_EQ(kNumberOfBuffers, manager.number_of_buffers()); - EXPECT_EQ(kBufferSize, manager.buffer_size()); - - // Test DequeueBuffer() and GetBufferPointer() - for (int32_t i = 0; i < kNumberOfBuffers; ++i) { - EXPECT_EQ(PP_ERROR_FAILED, manager.DequeueBuffer()); - EXPECT_EQ(reinterpret_cast<MediaStreamBuffer*>(memory + i * kBufferSize), - manager.GetBufferPointer(i)); - } - } -} - -TEST(MediaStreamBufferManager, ResetBuffers) { - const int32_t kNumberOfBuffers1 = 5; - const int32_t kBufferSize1 = 128; - const int32_t kNumberOfBuffers2 = 8; - const int32_t kBufferSize2 = 256; - MockDelegate delegate; - MediaStreamBufferManager manager(&delegate); - { - base::UnsafeSharedMemoryRegion shared_memory = - CreateSharedMemory(kBufferSize1, kNumberOfBuffers1); - // SetBuffers with enqueue_all_buffers = true; - EXPECT_TRUE(manager.SetBuffers(kNumberOfBuffers1, kBufferSize1, - std::move(shared_memory), true)); - - int8_t* memory = reinterpret_cast<int8_t*>(manager.GetBufferPointer(0)); - EXPECT_NE(static_cast<int8_t*>(NULL), memory); - - EXPECT_EQ(kNumberOfBuffers1, manager.number_of_buffers()); - EXPECT_EQ(kBufferSize1, manager.buffer_size()); - - // Test DequeueBuffer() and GetBufferPointer() - for (int32_t i = 0; i < kNumberOfBuffers1; ++i) { - EXPECT_EQ(i, manager.DequeueBuffer()); - EXPECT_EQ(reinterpret_cast<MediaStreamBuffer*>(memory + i * kBufferSize1), - manager.GetBufferPointer(i)); - } - } - - { - base::UnsafeSharedMemoryRegion shared_memory = - CreateSharedMemory(kBufferSize2, kNumberOfBuffers2); - // SetBuffers with enqueue_all_buffers = true; - EXPECT_TRUE(manager.SetBuffers(kNumberOfBuffers2, kBufferSize2, - std::move(shared_memory), true)); - - int8_t* memory = reinterpret_cast<int8_t*>(manager.GetBufferPointer(0)); - EXPECT_NE(static_cast<int8_t*>(NULL), memory); - - EXPECT_EQ(kNumberOfBuffers2, manager.number_of_buffers()); - EXPECT_EQ(kBufferSize2, manager.buffer_size()); - - // Test DequeueBuffer() and GetBufferPointer() - for (int32_t i = 0; i < kNumberOfBuffers2; ++i) { - EXPECT_EQ(i, manager.DequeueBuffer()); - EXPECT_EQ(reinterpret_cast<MediaStreamBuffer*>(memory + i * kBufferSize2), - manager.GetBufferPointer(i)); - } - } -} - -} // namespace ppapi
diff --git a/shared_impl/media_stream_video_track_shared_unittest.cc b/shared_impl/media_stream_video_track_shared_unittest.cc deleted file mode 100644 index 1a2fb40..0000000 --- a/shared_impl/media_stream_video_track_shared_unittest.cc +++ /dev/null
@@ -1,98 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "ppapi/shared_impl/media_stream_video_track_shared.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { - -TEST(MediaStreamVideoTrackShared, Verify) { - { - MediaStreamVideoTrackShared::Attributes attributes; - EXPECT_TRUE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - } - - // Verify buffers - { - MediaStreamVideoTrackShared::Attributes attributes; - attributes.buffers = 0; - EXPECT_TRUE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.buffers = 8; - EXPECT_TRUE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.buffers = 1024; - EXPECT_TRUE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.buffers = -1; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - } - - // Verify format - { - MediaStreamVideoTrackShared::Attributes attributes; - for (int32_t i = PP_VIDEOFRAME_FORMAT_UNKNOWN; - i <= PP_VIDEOFRAME_FORMAT_LAST; - ++i) { - attributes.format = static_cast<PP_VideoFrame_Format>(i); - EXPECT_TRUE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - } - - attributes.format = static_cast<PP_VideoFrame_Format>(-1); - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.format = - static_cast<PP_VideoFrame_Format>(PP_VIDEOFRAME_FORMAT_LAST + 1); - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - } - - // Verify width - { - MediaStreamVideoTrackShared::Attributes attributes; - attributes.width = 1024; - EXPECT_TRUE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.width = 1025; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.width = 1026; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.width = -1; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.width = -4; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.width = 4097; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - } - - // Verify height - { - MediaStreamVideoTrackShared::Attributes attributes; - attributes.height = 1024; - EXPECT_TRUE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.height = 1025; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.height = 1026; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.height = -1; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.height = -4; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - - attributes.height = 4096 + 4; - EXPECT_FALSE(MediaStreamVideoTrackShared::VerifyAttributes(attributes)); - } - -} - -} // namespace ppapi
diff --git a/shared_impl/proxy_lock_unittest.cc b/shared_impl/proxy_lock_unittest.cc deleted file mode 100644 index abb8618..0000000 --- a/shared_impl/proxy_lock_unittest.cc +++ /dev/null
@@ -1,186 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <string> - -#include "base/compiler_specific.h" -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/memory/ref_counted.h" -#include "base/test/task_environment.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/test_globals.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { - -namespace { - -bool expect_to_be_locked = false; -void CheckLockState() { - if (expect_to_be_locked) { - ProxyLock::AssertAcquired(); - } else { - // If we expect to be unlocked, try to lock. We rely on the checking inside - // base::Lock that prevents recursive locking. - ProxyAutoLock lock; - } -} - -int called_num = 0; - -class CheckLockStateInDestructor - : public base::RefCounted<CheckLockStateInDestructor> { - public: - CheckLockStateInDestructor() {} - - CheckLockStateInDestructor(const CheckLockStateInDestructor&) = delete; - CheckLockStateInDestructor& operator=(const CheckLockStateInDestructor&) = - delete; - - void Method() { ++called_num; } - - private: - friend class base::RefCounted<CheckLockStateInDestructor>; - ~CheckLockStateInDestructor() { CheckLockState(); } -}; - -void TestCallback_0() { - CheckLockState(); - ++called_num; -} - -void TestCallback_1(int p1) { - CheckLockState(); - ++called_num; -} - -void TestCallback_2(int p1, const std::string& p2) { - CheckLockState(); - ++called_num; -} - -struct Param {}; -void TestCallback_3(int p1, const std::string& p2, Param p3) { - CheckLockState(); - ++called_num; -} - -} // namespace - -class PpapiProxyLockTest : public testing::Test { - base::test::SingleThreadTaskEnvironment - task_environment_; // Required to receive callbacks. -}; - -TEST_F(PpapiProxyLockTest, Locking) { - TestGlobals globals; - expect_to_be_locked = true; - - base::OnceCallback<void()> cb0; - { - ProxyAutoLock lock; - cb0 = RunWhileLocked(base::BindOnce(TestCallback_0)); - } - std::move(cb0).Run(); - ASSERT_EQ(1, called_num); - called_num = 0; - - { - ProxyAutoLock lock; - cb0 = RunWhileLocked(base::BindOnce(TestCallback_1, 123)); - } - std::move(cb0).Run(); - ASSERT_EQ(1, called_num); - called_num = 0; - - { - ProxyAutoLock lock; - scoped_refptr<CheckLockStateInDestructor> object = - new CheckLockStateInDestructor(); - cb0 = RunWhileLocked( - base::BindOnce(&CheckLockStateInDestructor::Method, object)); - // Note after this scope, the Callback owns the only reference. - } - std::move(cb0).Run(); - ASSERT_EQ(1, called_num); - called_num = 0; - - base::OnceCallback<void(int)> cb1; - { - ProxyAutoLock lock; - cb1 = RunWhileLocked(base::BindOnce(TestCallback_1)); - } - std::move(cb1).Run(123); - ASSERT_EQ(1, called_num); - called_num = 0; - - base::OnceCallback<void(int, const std::string&)> cb2; - { - ProxyAutoLock lock; - cb2 = RunWhileLocked(base::BindOnce(TestCallback_2)); - } - std::move(cb2).Run(123, std::string("yo")); - ASSERT_EQ(1, called_num); - called_num = 0; - - base::OnceCallback<void(int, const std::string&, Param)> cb3; - { - ProxyAutoLock lock; - cb3 = RunWhileLocked(base::BindOnce(TestCallback_3)); - } - std::move(cb3).Run(123, std::string("yo"), Param()); - ASSERT_EQ(1, called_num); - called_num = 0; - - base::OnceCallback<void(const std::string&)> cb1_string; - { - ProxyAutoLock lock; - cb1_string = RunWhileLocked(base::BindOnce(TestCallback_2, 123)); - } - std::move(cb1_string).Run(std::string("yo")); - ASSERT_EQ(1, called_num); - called_num = 0; - - { - ProxyAutoLock lock; - cb0 = - RunWhileLocked(base::BindOnce(TestCallback_2, 123, std::string("yo"))); - } - std::move(cb0).Run(); - ASSERT_EQ(1, called_num); - called_num = 0; -} - -TEST_F(PpapiProxyLockTest, Unlocking) { - TestGlobals globals; - expect_to_be_locked = false; - // These calls should all try to _unlock_, so we must be locked before - // entering them. - ProxyAutoLock auto_lock; - - { - CallWhileUnlocked(TestCallback_0); - ASSERT_EQ(1, called_num); - called_num = 0; - } - { - CallWhileUnlocked(TestCallback_1, 123); - ASSERT_EQ(1, called_num); - called_num = 0; - } - { - CallWhileUnlocked(TestCallback_2, 123, std::string("yo")); - ASSERT_EQ(1, called_num); - called_num = 0; - } - { - base::OnceCallback<void()> callback(base::BindOnce(TestCallback_0)); - CallWhileUnlocked(std::move(callback)); - ASSERT_EQ(1, called_num); - called_num = 0; - } -} - -} // namespace ppapi
diff --git a/shared_impl/resource_tracker_unittest.cc b/shared_impl/resource_tracker_unittest.cc deleted file mode 100644 index 316fabb..0000000 --- a/shared_impl/resource_tracker_unittest.cc +++ /dev/null
@@ -1,124 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "testing/gtest/include/gtest/gtest.h" - -#include "base/compiler_specific.h" -#include "base/test/task_environment.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/resource.h" -#include "ppapi/shared_impl/resource_tracker.h" -#include "ppapi/shared_impl/test_globals.h" - -namespace ppapi { - -namespace { - -int mock_resource_alive_count = 0; -int last_plugin_ref_was_deleted_count = 0; -int instance_was_deleted_count = 0; - -class MyMockResource : public Resource { - public: - MyMockResource(PP_Instance instance) : Resource(OBJECT_IS_IMPL, instance) { - mock_resource_alive_count++; - } - ~MyMockResource() override { mock_resource_alive_count--; } - - void LastPluginRefWasDeleted() override { - last_plugin_ref_was_deleted_count++; - } - void InstanceWasDeleted() override { instance_was_deleted_count++; } -}; - -} // namespace - -class ResourceTrackerTest : public testing::Test { - public: - ResourceTrackerTest() {} - - // Test implementation. - void SetUp() override { - ASSERT_EQ(0, mock_resource_alive_count); - last_plugin_ref_was_deleted_count = 0; - instance_was_deleted_count = 0; - } - void TearDown() override {} - - ResourceTracker& resource_tracker() { return *globals_.GetResourceTracker(); } - - private: - base::test::SingleThreadTaskEnvironment - task_environment_; // Required to receive callbacks. - TestGlobals globals_; -}; - -// Test that LastPluginRefWasDeleted is called when the last plugin ref was -// deleted but the object lives on. -TEST_F(ResourceTrackerTest, LastPluginRef) { - PP_Instance instance = 0x1234567; - ProxyAutoLock lock; - resource_tracker().DidCreateInstance(instance); - - scoped_refptr<MyMockResource> resource(new MyMockResource(instance)); - PP_Resource pp_resource = resource->GetReference(); - EXPECT_TRUE(resource_tracker().GetResource(pp_resource)); - - // Releasing it should keep the object (because we have a ref) but fire the - // "last plugin ref" message. - resource_tracker().ReleaseResource(pp_resource); - EXPECT_EQ(1, last_plugin_ref_was_deleted_count); - EXPECT_EQ(1, mock_resource_alive_count); - - resource_tracker().DidDeleteInstance(instance); - resource.reset(); - EXPECT_FALSE(resource_tracker().GetResource(pp_resource)); -} - -// Tests when the plugin is holding a ref to a resource when the instance is -// deleted. -TEST_F(ResourceTrackerTest, InstanceDeletedWithPluginRef) { - // Make a resource with one ref held by the plugin, and delete the instance. - PP_Instance instance = 0x2345678; - ProxyAutoLock lock; - resource_tracker().DidCreateInstance(instance); - MyMockResource* resource = new MyMockResource(instance); - resource->GetReference(); - EXPECT_EQ(1, mock_resource_alive_count); - resource_tracker().DidDeleteInstance(instance); - - // The resource should have been deleted, and before it was, it should have - // received a "last plugin ref was deleted" notification. - EXPECT_EQ(0, mock_resource_alive_count); - EXPECT_EQ(1, last_plugin_ref_was_deleted_count); - EXPECT_EQ(0, instance_was_deleted_count); -} - -// Test when the plugin and the internal implementation (via scoped_refptr) is -// holding a ref to a resource when the instance is deleted. -TEST_F(ResourceTrackerTest, InstanceDeletedWithBothRefed) { - // Create a new instance. - PP_Instance instance = 0x3456789; - ProxyAutoLock lock; - - // Make a resource with one ref held by the plugin and one ref held by us - // (outlives the plugin), and delete the instance. - resource_tracker().DidCreateInstance(instance); - scoped_refptr<MyMockResource> resource = new MyMockResource(instance); - resource->GetReference(); - EXPECT_EQ(1, mock_resource_alive_count); - resource_tracker().DidDeleteInstance(instance); - - // The resource should NOT have been deleted, and it should have received both - // a "last plugin ref was deleted" and a "instance was deleted" notification. - EXPECT_EQ(1, mock_resource_alive_count); - EXPECT_EQ(1, last_plugin_ref_was_deleted_count); - EXPECT_EQ(1, instance_was_deleted_count); - EXPECT_EQ(0, resource->pp_instance()); - - resource.reset(); - EXPECT_EQ(0, mock_resource_alive_count); -} - -} // namespace ppapi
diff --git a/shared_impl/test_globals.cc b/shared_impl/test_globals.cc deleted file mode 100644 index a7949b4..0000000 --- a/shared_impl/test_globals.cc +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/shared_impl/test_globals.h" - -namespace ppapi { - -TestGlobals::TestGlobals() - : ppapi::PpapiGlobals(), - resource_tracker_(ResourceTracker::THREAD_SAFE), - callback_tracker_(new CallbackTracker) {} - -TestGlobals::TestGlobals(PpapiGlobals::PerThreadForTest per_thread_for_test) - : ppapi::PpapiGlobals(per_thread_for_test), - resource_tracker_(ResourceTracker::THREAD_SAFE), - callback_tracker_(new CallbackTracker) {} - -TestGlobals::~TestGlobals() {} - -ResourceTracker* TestGlobals::GetResourceTracker() { - return &resource_tracker_; -} - -VarTracker* TestGlobals::GetVarTracker() { return &var_tracker_; } - -CallbackTracker* TestGlobals::GetCallbackTrackerForInstance( - PP_Instance instance) { - return callback_tracker_.get(); -} - -thunk::PPB_Instance_API* TestGlobals::GetInstanceAPI(PP_Instance instance) { - return NULL; -} - -thunk::ResourceCreationAPI* TestGlobals::GetResourceCreationAPI( - PP_Instance instance) { - return NULL; -} - -PP_Module TestGlobals::GetModuleForInstance(PP_Instance instance) { return 0; } - -void TestGlobals::LogWithSource(PP_Instance instance, - PP_LogLevel level, - const std::string& source, - const std::string& value) {} - -void TestGlobals::BroadcastLogWithSource(PP_Module module, - PP_LogLevel level, - const std::string& source, - const std::string& value) {} - -MessageLoopShared* TestGlobals::GetCurrentMessageLoop() { return NULL; } - -base::TaskRunner* TestGlobals::GetFileTaskRunner() { return NULL; } - -bool TestGlobals::IsHostGlobals() const { - // Pretend to be the host-side, for code that expects one or the other. - // TODO(dmichael): just make it settable which one we're pretending to be? - return true; -} - -} // namespace ppapi
diff --git a/shared_impl/test_globals.h b/shared_impl/test_globals.h deleted file mode 100644 index 82a66c9..0000000 --- a/shared_impl/test_globals.h +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_SHARED_IMPL_TEST_GLOBALS_H_ -#define PPAPI_SHARED_IMPL_TEST_GLOBALS_H_ - -#include <stdint.h> - -#include "base/compiler_specific.h" -#include "base/memory/unsafe_shared_memory_region.h" -#include "ppapi/shared_impl/callback_tracker.h" -#include "ppapi/shared_impl/ppapi_globals.h" -#include "ppapi/shared_impl/resource_tracker.h" -#include "ppapi/shared_impl/var_tracker.h" - -namespace ppapi { - -class TestVarTracker : public VarTracker { - public: - TestVarTracker() : VarTracker(THREAD_SAFE) {} - ~TestVarTracker() override {} - PP_Var MakeResourcePPVarFromMessage( - PP_Instance instance, - const IPC::Message& creation_message, - int pending_renderer_id, - int pending_browser_id) override { - return PP_MakeNull(); - } - ResourceVar* MakeResourceVar(PP_Resource pp_resource) override { - return NULL; - } - ArrayBufferVar* CreateArrayBuffer(uint32_t size_in_bytes) override { - return NULL; - } - ArrayBufferVar* CreateShmArrayBuffer( - uint32_t size_in_bytes, - base::UnsafeSharedMemoryRegion region) override { - return NULL; - } - void DidDeleteInstance(PP_Instance instance) override {} - int TrackSharedMemoryRegion(PP_Instance instance, - base::UnsafeSharedMemoryRegion region, - uint32_t size_in_bytes) override { - return -1; - } - bool StopTrackingSharedMemoryRegion(int id, - PP_Instance instance, - base::UnsafeSharedMemoryRegion* region, - uint32_t* size_in_bytes) override { - return false; - } -}; - -// Implementation of PpapiGlobals for tests that don't need either the host- or -// plugin-specific implementations. -class TestGlobals : public PpapiGlobals { - public: - TestGlobals(); - explicit TestGlobals(PpapiGlobals::PerThreadForTest); - - TestGlobals(const TestGlobals&) = delete; - TestGlobals& operator=(const TestGlobals&) = delete; - - ~TestGlobals() override; - - // PpapiGlobals implementation. - ResourceTracker* GetResourceTracker() override; - VarTracker* GetVarTracker() override; - CallbackTracker* GetCallbackTrackerForInstance(PP_Instance instance) override; - thunk::PPB_Instance_API* GetInstanceAPI(PP_Instance instance) override; - thunk::ResourceCreationAPI* GetResourceCreationAPI( - PP_Instance instance) override; - PP_Module GetModuleForInstance(PP_Instance instance) override; - void LogWithSource(PP_Instance instance, - PP_LogLevel level, - const std::string& source, - const std::string& value) override; - void BroadcastLogWithSource(PP_Module module, - PP_LogLevel level, - const std::string& source, - const std::string& value) override; - MessageLoopShared* GetCurrentMessageLoop() override; - base::TaskRunner* GetFileTaskRunner() override; - - // PpapiGlobals overrides: - bool IsHostGlobals() const override; - - private: - ResourceTracker resource_tracker_; - TestVarTracker var_tracker_; - scoped_refptr<CallbackTracker> callback_tracker_; -}; - -} // namespace ppapi - -#endif // PPAPI_SHARED_IMPL_TEST_GLOBALS_H_
diff --git a/shared_impl/test_utils.cc b/shared_impl/test_utils.cc deleted file mode 100644 index fa99eeb..0000000 --- a/shared_impl/test_utils.cc +++ /dev/null
@@ -1,225 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/shared_impl/test_utils.h" - -#include <stddef.h> -#include <stdint.h> - -#include <cmath> -#include <unordered_map> - -#include "base/logging.h" -#include "base/notreached.h" -#include "base/strings/string_util.h" -#include "ipc/ipc_message.h" -#include "ppapi/shared_impl/array_var.h" -#include "ppapi/shared_impl/dictionary_var.h" -#include "ppapi/shared_impl/resource_var.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/shared_impl/var_tracker.h" - -namespace ppapi { - -namespace { - -// When two vars x and y are found to be equal, an entry is inserted into -// |visited_map| with (x.value.as_id, y.value.as_id). This allows reference -// cycles to be avoided. It also allows us to associate nodes in |expected| with -// nodes in |actual| and check whether the graphs have equivalent topology. -bool Equals(const PP_Var& expected, - const PP_Var& actual, - bool test_string_references, - std::unordered_map<int64_t, int64_t>* visited_map) { - if (expected.type != actual.type) { - LOG(ERROR) << "expected type: " << expected.type - << " actual type: " << actual.type; - return false; - } - if (VarTracker::IsVarTypeRefcounted(expected.type)) { - std::unordered_map<int64_t, int64_t>::iterator it = - visited_map->find(expected.value.as_id); - if (it != visited_map->end()) { - if (it->second != actual.value.as_id) { - LOG(ERROR) << "expected id: " << it->second - << " actual id: " << actual.value.as_id; - return false; - } else { - return true; - } - } else { - if (expected.type != PP_VARTYPE_STRING || test_string_references) - (*visited_map)[expected.value.as_id] = actual.value.as_id; - } - } - switch (expected.type) { - case PP_VARTYPE_UNDEFINED: - return true; - case PP_VARTYPE_NULL: - return true; - case PP_VARTYPE_BOOL: - if (expected.value.as_bool != actual.value.as_bool) { - LOG(ERROR) << "expected: " << expected.value.as_bool - << " actual: " << actual.value.as_bool; - return false; - } - return true; - case PP_VARTYPE_INT32: - if (expected.value.as_int != actual.value.as_int) { - LOG(ERROR) << "expected: " << expected.value.as_int - << " actual: " << actual.value.as_int; - return false; - } - return true; - case PP_VARTYPE_DOUBLE: - if (fabs(expected.value.as_double - actual.value.as_double) > 1.0e-4) { - LOG(ERROR) << "expected: " << expected.value.as_double - << " actual: " << actual.value.as_double; - return false; - } - return true; - case PP_VARTYPE_OBJECT: - if (expected.value.as_id != actual.value.as_id) { - LOG(ERROR) << "expected: " << expected.value.as_id - << " actual: " << actual.value.as_id; - return false; - } - return true; - case PP_VARTYPE_STRING: { - StringVar* expected_var = StringVar::FromPPVar(expected); - StringVar* actual_var = StringVar::FromPPVar(actual); - DCHECK(expected_var && actual_var); - if (expected_var->value() != actual_var->value()) { - LOG(ERROR) << "expected: " << expected_var->value() - << " actual: " << actual_var->value(); - return false; - } - return true; - } - case PP_VARTYPE_ARRAY_BUFFER: { - ArrayBufferVar* expected_var = ArrayBufferVar::FromPPVar(expected); - ArrayBufferVar* actual_var = ArrayBufferVar::FromPPVar(actual); - DCHECK(expected_var && actual_var); - if (expected_var->ByteLength() != actual_var->ByteLength()) { - LOG(ERROR) << "expected: " << expected_var->ByteLength() - << " actual: " << actual_var->ByteLength(); - return false; - } - if (memcmp(expected_var->Map(), - actual_var->Map(), - expected_var->ByteLength()) != 0) { - LOG(ERROR) << "expected array buffer does not match actual."; - return false; - } - return true; - } - case PP_VARTYPE_ARRAY: { - ArrayVar* expected_var = ArrayVar::FromPPVar(expected); - ArrayVar* actual_var = ArrayVar::FromPPVar(actual); - DCHECK(expected_var && actual_var); - if (expected_var->elements().size() != actual_var->elements().size()) { - LOG(ERROR) << "expected: " << expected_var->elements().size() - << " actual: " << actual_var->elements().size(); - return false; - } - for (size_t i = 0; i < expected_var->elements().size(); ++i) { - if (!Equals(expected_var->elements()[i].get(), - actual_var->elements()[i].get(), - test_string_references, - visited_map)) { - return false; - } - } - return true; - } - case PP_VARTYPE_DICTIONARY: { - DictionaryVar* expected_var = DictionaryVar::FromPPVar(expected); - DictionaryVar* actual_var = DictionaryVar::FromPPVar(actual); - DCHECK(expected_var && actual_var); - if (expected_var->key_value_map().size() != - actual_var->key_value_map().size()) { - LOG(ERROR) << "expected: " << expected_var->key_value_map().size() - << " actual: " << actual_var->key_value_map().size(); - return false; - } - DictionaryVar::KeyValueMap::const_iterator expected_iter = - expected_var->key_value_map().begin(); - DictionaryVar::KeyValueMap::const_iterator actual_iter = - actual_var->key_value_map().begin(); - for (; expected_iter != expected_var->key_value_map().end(); - ++expected_iter, ++actual_iter) { - if (expected_iter->first != actual_iter->first) { - LOG(ERROR) << "expected: " << expected_iter->first - << " actual: " << actual_iter->first; - return false; - } - if (!Equals(expected_iter->second.get(), - actual_iter->second.get(), - test_string_references, - visited_map)) { - return false; - } - } - return true; - } - case PP_VARTYPE_RESOURCE: { - ResourceVar* expected_var = ResourceVar::FromPPVar(expected); - ResourceVar* actual_var = ResourceVar::FromPPVar(actual); - DCHECK(expected_var && actual_var); - if (expected_var->GetPPResource() != actual_var->GetPPResource()) { - LOG(ERROR) << "expected: " << expected_var->GetPPResource() - << " actual: " << actual_var->GetPPResource(); - return false; - } - - const IPC::Message* actual_message = actual_var->GetCreationMessage(); - const IPC::Message* expected_message = expected_var->GetCreationMessage(); - if (expected_message->size() != actual_message->size()) { - LOG(ERROR) << "expected creation message size: " - << expected_message->size() - << " actual: " << actual_message->size(); - return false; - } - - // Set the upper 24 bits of actual creation_message flags to the same as - // expected. This is an unpredictable reference number that changes - // between serialization/deserialization, and we do not want it to cause - // the comparison to fail. - IPC::Message local_actual_message(*actual_message); - local_actual_message.SetHeaderValues( - actual_message->routing_id(), - actual_message->type(), - (expected_message->flags() & 0xffffff00) | - (actual_message->flags() & 0xff)); - if (memcmp(expected_message->data(), - local_actual_message.data(), - expected_message->size()) != 0) { - LOG(ERROR) << "expected creation message does not match actual."; - return false; - } - return true; - } - } - NOTREACHED(); -} - -} // namespace - -bool TestEqual(const PP_Var& expected, - const PP_Var& actual, - bool test_string_references) { - std::unordered_map<int64_t, int64_t> visited_map; - return Equals(expected, actual, test_string_references, &visited_map); -} - -std::string StripTestPrefixes(const std::string& test_name) { - const char kDisabledPrefix[] = "DISABLED_"; - if (base::StartsWith(test_name, kDisabledPrefix, - base::CompareCase::SENSITIVE)) { - return test_name.substr(sizeof(kDisabledPrefix) - 1); - } - return test_name; -} - -} // namespace ppapi
diff --git a/shared_impl/test_utils.h b/shared_impl/test_utils.h deleted file mode 100644 index 57b674f..0000000 --- a/shared_impl/test_utils.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_SHARED_IMPL_TEST_UTILS_H_ -#define PPAPI_SHARED_IMPL_TEST_UTILS_H_ - -#include <string> - -#include "ppapi/c/pp_var.h" - -namespace ppapi { - -// Compares two vars for equality. This is a deep comparison (the entire graph -// is traversed recursively). The function guarantees that the topology of the -// two PP_Var graphs being compared is identical, including graphs with cycles. -// If |test_string_references| is set to true, then incoming references to -// string vars in the two graphs must be isomorphic. Otherwise only the content -// of the strings is tested for equality. -bool TestEqual(const PP_Var& expected, - const PP_Var& actual, - bool test_string_references); - -std::string StripTestPrefixes(const std::string& test_name); - -} // namespace ppapi - -#endif // PPAPI_SHARED_IMPL_TEST_UTILS_H_
diff --git a/shared_impl/thread_aware_callback_unittest.cc b/shared_impl/thread_aware_callback_unittest.cc deleted file mode 100644 index 162cbc9..0000000 --- a/shared_impl/thread_aware_callback_unittest.cc +++ /dev/null
@@ -1,203 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/shared_impl/thread_aware_callback.h" - -#include <memory> - -#include "base/check.h" -#include "base/compiler_specific.h" -#include "base/functional/bind.h" -#include "base/functional/callback_helpers.h" -#include "base/location.h" -#include "base/task/single_thread_task_runner.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { - -namespace { - -class TestParameter { - public: - TestParameter() : value_(0) {} - - int value_; -}; - -int called_num = 0; - -void TestCallback_0() { ++called_num; } - -void TestCallback_1(int p1) { ++called_num; } - -void TestCallback_2(int p1, const double* p2) { ++called_num; } - -void TestCallback_3(int p1, const double* p2, bool* p3) { ++called_num; } - -void TestCallback_4(int p1, const double* p2, bool* p3, TestParameter p4) { - ++called_num; -} - -void TestCallback_5(int p1, - const double* p2, - bool* p3, - TestParameter p4, - const TestParameter& p5) { - ++called_num; -} - -typedef proxy::PluginProxyTest ThreadAwareCallbackTest; - -// Test that a callback created on the main thread will run on the main thread, -// even when requested from a different thread. -class ThreadAwareCallbackMultiThreadTest - : public proxy::PluginProxyMultiThreadTest { - public: - ThreadAwareCallbackMultiThreadTest() : main_thread_callback_called_(false) {} - ~ThreadAwareCallbackMultiThreadTest() override { - CHECK(main_thread_callback_called_); - } - - // proxy::PluginProxyMultiThreadTest implementation. - void SetUpTestOnMainThread() override { - ProxyAutoLock auto_lock; - - main_thread_callback_.reset( - ThreadAwareCallback<CallbackFunc>::Create(&MainThreadCallbackBody)); - } - - void SetUpTestOnSecondaryThread() override { - { - ProxyAutoLock auto_lock; - main_thread_callback_->RunOnTargetThread(this); - } - - PostQuitForSecondaryThread(); - PostQuitForMainThread(); - } - - private: - typedef void (*CallbackFunc)(ThreadAwareCallbackMultiThreadTest*); - - static void MainThreadCallbackBody(ThreadAwareCallbackMultiThreadTest* thiz) { - thiz->CheckOnThread(MAIN_THREAD); - thiz->main_thread_callback_called_ = true; - - { - ProxyAutoLock auto_lock; - // We have to destroy it prior to the PluginGlobals instance held by the - // base class. Otherwise it has a ref to Pepper message loop for the main - // thread and the PluginGlobals destructor will complain. - thiz->main_thread_callback_.reset(NULL); - } - } - - std::unique_ptr<ThreadAwareCallback<CallbackFunc>> main_thread_callback_; - bool main_thread_callback_called_; -}; - -// Test that when a ThreadAwareCallback instance is destroyed, pending tasks to -// run the callback will be ignored. -class ThreadAwareCallbackAbortTest : public proxy::PluginProxyMultiThreadTest { - public: - ThreadAwareCallbackAbortTest() {} - ~ThreadAwareCallbackAbortTest() override {} - - // proxy::PluginProxyMultiThreadTest implementation. - void SetUpTestOnMainThread() override { - ProxyAutoLock auto_lock; - - main_thread_callback_.reset( - ThreadAwareCallback<CallbackFunc>::Create(&MainThreadCallbackBody)); - } - - void SetUpTestOnSecondaryThread() override { - { - ProxyAutoLock auto_lock; - main_thread_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&ThreadAwareCallbackAbortTest::DeleteCallback, - base::Unretained(this))); - // |main_thread_callback_| is still valid, even if DeleteCallback() can be - // called before this following statement. That is because |auto_lock| is - // still held by this method, which prevents DeleteCallback() from - // deleting the callback. - main_thread_callback_->RunOnTargetThread(this); - } - - PostQuitForSecondaryThread(); - PostQuitForMainThread(); - } - - private: - typedef void (*CallbackFunc)(ThreadAwareCallbackAbortTest*); - - static void MainThreadCallbackBody(ThreadAwareCallbackAbortTest* thiz) { - // The callback should not be called. - ASSERT_TRUE(false); - } - - void DeleteCallback() { - ProxyAutoLock auto_lock; - main_thread_callback_.reset(NULL); - } - - std::unique_ptr<ThreadAwareCallback<CallbackFunc>> main_thread_callback_; -}; - -} // namespace - -TEST_F(ThreadAwareCallbackTest, Basics) { - // ThreadAwareCallback should only be used when the proxy lock has been - // acquired. - ProxyAutoLock auto_lock; - - double double_arg = 0.0; - bool bool_arg = false; - TestParameter object_arg; - - // Exercise all the template code. - called_num = 0; - typedef void (*FuncType_0)(); - std::unique_ptr<ThreadAwareCallback<FuncType_0>> callback_0( - ThreadAwareCallback<FuncType_0>::Create(TestCallback_0)); - callback_0->RunOnTargetThread(); - - typedef void (*FuncType_1)(int); - std::unique_ptr<ThreadAwareCallback<FuncType_1>> callback_1( - ThreadAwareCallback<FuncType_1>::Create(TestCallback_1)); - callback_1->RunOnTargetThread(1); - - typedef void (*FuncType_2)(int, const double*); - std::unique_ptr<ThreadAwareCallback<FuncType_2>> callback_2( - ThreadAwareCallback<FuncType_2>::Create(TestCallback_2)); - callback_2->RunOnTargetThread(1, &double_arg); - - typedef void (*FuncType_3)(int, const double*, bool*); - std::unique_ptr<ThreadAwareCallback<FuncType_3>> callback_3( - ThreadAwareCallback<FuncType_3>::Create(TestCallback_3)); - callback_3->RunOnTargetThread(1, &double_arg, &bool_arg); - - typedef void (*FuncType_4)(int, const double*, bool*, TestParameter); - std::unique_ptr<ThreadAwareCallback<FuncType_4>> callback_4( - ThreadAwareCallback<FuncType_4>::Create(TestCallback_4)); - callback_4->RunOnTargetThread(1, &double_arg, &bool_arg, object_arg); - - typedef void (*FuncType_5)( - int, const double*, bool*, TestParameter, const TestParameter&); - std::unique_ptr<ThreadAwareCallback<FuncType_5>> callback_5( - ThreadAwareCallback<FuncType_5>::Create(TestCallback_5)); - callback_5->RunOnTargetThread( - 1, &double_arg, &bool_arg, object_arg, object_arg); - - EXPECT_EQ(6, called_num); -} - -TEST_F(ThreadAwareCallbackMultiThreadTest, RunOnTargetThread) { RunTest(); } - -TEST_F(ThreadAwareCallbackAbortTest, NotRunIfAborted) { RunTest(); } - -} // namespace ppapi
diff --git a/shared_impl/time_conversion_unittest.cc b/shared_impl/time_conversion_unittest.cc deleted file mode 100644 index 86d887f..0000000 --- a/shared_impl/time_conversion_unittest.cc +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <math.h> -#include <stdlib.h> - -#include "base/time/time.h" -#include "ppapi/shared_impl/time_conversion.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ppapi { - -// Slop we'll allow in two Time "internal values" to consider them equal. -// Double conversion can introduce rounding errors. The internal values are in -// microseconds, so an error here is very small. -static const int kTimeInternalValueSlop = 2; - -// Same as above in double-precision seconds units. -static const double kTimeSecondsSlop = - static_cast<double>(kTimeInternalValueSlop) / - base::Time::kMicrosecondsPerSecond; - -TEST(TimeConversion, Time) { - // Should be able to round-trip. - base::Time now = base::Time::Now(); - base::Time converted = ppapi::PPTimeToTime(TimeToPPTime(now)); - EXPECT_GE(kTimeInternalValueSlop, - abs(static_cast<int>((converted - now).ToInternalValue()))); - - // Units should be in seconds. - base::Time one_second_from_now = now + base::Seconds(1); - double converted_one_second_from_now = - ppapi::TimeToPPTime(one_second_from_now) - ppapi::TimeToPPTime(now); - EXPECT_GE(kTimeSecondsSlop, fabs(converted_one_second_from_now - 1)); -} - -TEST(TimeConversion, EpochTime) { - // Should be able to round-trip from epoch time. - base::Time epoch = base::Time::UnixEpoch(); - base::Time converted = ppapi::PPTimeToTime(TimeToPPTime(epoch)); - EXPECT_GE(kTimeInternalValueSlop, - abs(static_cast<int>((converted - epoch).ToInternalValue()))); - - // Units should be in seconds. - base::Time one_second_from_epoch = epoch + base::Seconds(1); - double converted_one_second_from_epoch = - ppapi::TimeToPPTime(one_second_from_epoch) - ppapi::TimeToPPTime(epoch); - EXPECT_GE(kTimeSecondsSlop, fabs(converted_one_second_from_epoch - 1)); - - // Epoch time should be equal to a PP_Time of 0.0. - EXPECT_GE(kTimeSecondsSlop, fabs(ppapi::TimeToPPTime(epoch) - 0.0)); - EXPECT_GE(kTimeInternalValueSlop, - abs(static_cast<int>( - (ppapi::PPTimeToTime(0.0) - epoch).ToInternalValue()))); -} - -} // namespace ppapi
diff --git a/shared_impl/var_tracker_unittest.cc b/shared_impl/var_tracker_unittest.cc deleted file mode 100644 index 2a4d194..0000000 --- a/shared_impl/var_tracker_unittest.cc +++ /dev/null
@@ -1,154 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "testing/gtest/include/gtest/gtest.h" - -#include "base/compiler_specific.h" -#include "base/test/task_environment.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/test_globals.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/shared_impl/var_tracker.h" - -namespace ppapi { - -namespace { - -int mock_var_alive_count = 0; - -class MockStringVar : public StringVar { - public: - MockStringVar(const std::string& str) : StringVar(str) { - mock_var_alive_count++; - } - ~MockStringVar() override { mock_var_alive_count--; } - bool HasValidVarID() { return GetExistingVarID() != 0; } -}; - -class MockObjectVar : public Var { - public: - MockObjectVar() : Var() { mock_var_alive_count++; } - ~MockObjectVar() override { mock_var_alive_count--; } - PP_VarType GetType() const override { return PP_VARTYPE_OBJECT; } - bool HasValidVarID() { return GetExistingVarID() != 0; } -}; - -} // namespace - -class VarTrackerTest : public testing::Test { - public: - VarTrackerTest() {} - - // Test implementation. - void SetUp() override { - ASSERT_EQ(0, mock_var_alive_count); - } - void TearDown() override {} - - VarTracker& var_tracker() { return *globals_.GetVarTracker(); } - - private: - base::test::SingleThreadTaskEnvironment - task_environment_; // Required to receive callbacks. - TestGlobals globals_; -}; - -// Test that ResetVarID is called when the last PP_Var ref was deleted but the -// object lives on. -TEST_F(VarTrackerTest, LastResourceRef) { - ProxyAutoLock lock; - scoped_refptr<MockStringVar> var(new MockStringVar(std::string("xyz"))); - PP_Var pp_var = var->GetPPVar(); - EXPECT_TRUE(var->HasValidVarID()); - EXPECT_TRUE(var_tracker().GetVar(var->GetExistingVarID())); - - // Releasing it should keep the object (because we have a ref) but reset the - // var_id_. - EXPECT_TRUE(var_tracker().ReleaseVar(pp_var)); - EXPECT_FALSE(var->HasValidVarID()); - EXPECT_EQ(1, mock_var_alive_count); - - var.reset(); - EXPECT_EQ(0, mock_var_alive_count); -} - -TEST_F(VarTrackerTest, GetPluginRefAgain) { - ProxyAutoLock lock; - scoped_refptr<MockStringVar> var(new MockStringVar(std::string("xyz"))); - PP_Var pp_var = var->GetPPVar(); - EXPECT_TRUE(var_tracker().ReleaseVar(pp_var)); - EXPECT_FALSE(var->HasValidVarID()); - EXPECT_EQ(1, mock_var_alive_count); - - // Obtaining PP_Var ref again, and add ref from VarTracker. - pp_var = var->GetPPVar(); - EXPECT_TRUE(var->HasValidVarID()); - EXPECT_TRUE(var_tracker().GetVar(var->GetExistingVarID())); - scoped_refptr<MockStringVar> another_var = - static_cast<MockStringVar*>(var_tracker().GetVar(pp_var)); - EXPECT_EQ(1, mock_var_alive_count); - - // Releasing it again. - EXPECT_TRUE(var_tracker().ReleaseVar(pp_var)); - EXPECT_FALSE(var->HasValidVarID()); - EXPECT_EQ(1, mock_var_alive_count); - - var.reset(); - EXPECT_FALSE(var_tracker().GetVar(pp_var)); - EXPECT_EQ(1, mock_var_alive_count); - another_var.reset(); - EXPECT_FALSE(var_tracker().GetVar(pp_var)); - EXPECT_EQ(0, mock_var_alive_count); -} - -// Tests when the plugin is holding a ref to a PP_Var when the instance is -// owned only by VarTracker. -TEST_F(VarTrackerTest, PluginRefWithoutVarRef) { - ProxyAutoLock lock; - // Make a PP_Var with one ref held by the plugin, and release the reference. - scoped_refptr<MockStringVar> var(new MockStringVar(std::string("zzz"))); - PP_Var pp_var = var->GetPPVar(); - EXPECT_EQ(1, mock_var_alive_count); - var.reset(); - EXPECT_EQ(1, mock_var_alive_count); - - // The var is owned only by VarTracker. PP_Var must be still valid. - EXPECT_TRUE(var_tracker().GetVar(pp_var)); - - var_tracker().ReleaseVar(pp_var); - EXPECT_EQ(0, mock_var_alive_count); - EXPECT_FALSE(var_tracker().GetVar(pp_var)); -} - -// Tests on Var having type of PP_VARTYPE_OBJECT. -TEST_F(VarTrackerTest, ObjectRef) { - ProxyAutoLock lock; - scoped_refptr<MockObjectVar> var(new MockObjectVar()); - PP_Var pp_var = var->GetPPVar(); - EXPECT_TRUE(var_tracker().ReleaseVar(pp_var)); - EXPECT_FALSE(var->HasValidVarID()); - EXPECT_EQ(1, mock_var_alive_count); - - // Obtaining PP_Var ref again, and add ref from VarTracker. - pp_var = var->GetPPVar(); - EXPECT_TRUE(var->HasValidVarID()); - EXPECT_TRUE(var_tracker().GetVar(var->GetExistingVarID())); - scoped_refptr<MockObjectVar> another_var = - static_cast<MockObjectVar*>(var_tracker().GetVar(pp_var)); - EXPECT_EQ(1, mock_var_alive_count); - - // Releasing all references, then only VarTracker own the instance. - var.reset(); - EXPECT_TRUE(var_tracker().GetVar(pp_var)); - EXPECT_EQ(1, mock_var_alive_count); - another_var.reset(); - EXPECT_TRUE(var_tracker().GetVar(pp_var)); - EXPECT_EQ(1, mock_var_alive_count); - - // Releasing plugin reference. - EXPECT_TRUE(var_tracker().ReleaseVar(pp_var)); - EXPECT_EQ(0, mock_var_alive_count); -} - -} // namespace ppapi
diff --git a/tests/DEPS b/tests/DEPS deleted file mode 100644 index 1a9836b..0000000 --- a/tests/DEPS +++ /dev/null
@@ -1,37 +0,0 @@ -# ppapi/tests should not be dependent on other parts of chromium; it should stay -# browser-neutral as much as possible. -include_rules = [ - "-base", - "-build", - "-ipc", - "-uncode", - "-testing", - "-ppapi", - "+ppapi/c", - "+ppapi/cpp", - "+ppapi/lib", - "+ppapi/tests", - "+ppapi/utility", - - # Test to confirm whether PPB_Audio_Shared works properly in NaCl needs to - # call nacl_irt_ppapihook internally to emulate some erroneous situation. - "+native_client/src/untrusted/irt/irt.h", - "+ppapi/native_client/src/untrusted/irt_stub/thread_creator.h", -] -# checkdeps.py shouldn't check include paths for files in clang, which aren't -# part of the chrome build. -skip_child_includes = [ - "clang", -] -specific_include_rules = { - # The Blink test plugins use //base. - "blink_(deprecated_)?test_plugin\.cc": [ - "+base", - ], - - # extensions/packaged_app/test_packaged_app.cc uses kMaxDescriptorsPerMessage - # defined in ipc/ipc_message_attachment_set.h. - "test_packaged_app\.cc": [ - "+ipc/ipc_message_attachment_set.h", - ] -}
diff --git a/tests/OWNERS b/tests/OWNERS deleted file mode 100644 index 17525ab..0000000 --- a/tests/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -per-file blink_test_plugin.cc=dcheng@chromium.org -per-file blink_deprecated_test_plugin.cc=dcheng@chromium.org
diff --git a/tests/all_c_includes.h b/tests/all_c_includes.h deleted file mode 100644 index 8eedff1..0000000 --- a/tests/all_c_includes.h +++ /dev/null
@@ -1,114 +0,0 @@ -/* Copyright 2012 The Chromium Authors - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - * - * This test simply includes all the C headers to ensure they compile with a C - * compiler. If it compiles, it passes. - */ -#ifndef PPAPI_TESTS_ALL_C_INCLUDES_H_ -#define PPAPI_TESTS_ALL_C_INCLUDES_H_ - -#include "ppapi/c/dev/deprecated_bool.h" -#include "ppapi/c/dev/pp_cursor_type_dev.h" -#include "ppapi/c/dev/pp_video_dev.h" -#include "ppapi/c/dev/ppb_buffer_dev.h" -#include "ppapi/c/dev/ppb_char_set_dev.h" -#include "ppapi/c/dev/ppb_crypto_dev.h" -#include "ppapi/c/dev/ppb_cursor_control_dev.h" -#include "ppapi/c/dev/ppb_device_ref_dev.h" -#include "ppapi/c/dev/ppb_file_chooser_dev.h" -#include "ppapi/c/dev/ppb_ime_input_event_dev.h" -#include "ppapi/c/dev/ppb_memory_dev.h" -#include "ppapi/c/dev/ppb_printing_dev.h" -#include "ppapi/c/dev/ppb_text_input_dev.h" -#include "ppapi/c/dev/ppb_trace_event_dev.h" -#include "ppapi/c/dev/ppb_url_util_dev.h" -#include "ppapi/c/dev/ppb_var_deprecated.h" -#include "ppapi/c/dev/ppb_video_decoder_dev.h" -#include "ppapi/c/dev/ppb_view_dev.h" -#include "ppapi/c/dev/ppp_class_deprecated.h" -#include "ppapi/c/dev/ppp_printing_dev.h" -#include "ppapi/c/dev/ppp_text_input_dev.h" -#include "ppapi/c/dev/ppp_video_decoder_dev.h" -#include "ppapi/c/pp_bool.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/pp_file_info.h" -#include "ppapi/c/pp_graphics_3d.h" -#include "ppapi/c/pp_input_event.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_macros.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_size.h" -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/pp_time.h" -#include "ppapi/c/pp_touch_point.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb.h" -#include "ppapi/c/ppb_audio.h" -#include "ppapi/c/ppb_audio_buffer.h" -#include "ppapi/c/ppb_audio_config.h" -#include "ppapi/c/ppb_console.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/c/ppb_file_ref.h" -#include "ppapi/c/ppb_file_system.h" -#include "ppapi/c/ppb_fullscreen.h" -#include "ppapi/c/ppb_gamepad.h" -#include "ppapi/c/ppb_graphics_2d.h" -#include "ppapi/c/ppb_graphics_3d.h" -#include "ppapi/c/ppb_host_resolver.h" -#include "ppapi/c/ppb_image_data.h" -#include "ppapi/c/ppb_input_event.h" -#include "ppapi/c/ppb_instance.h" -#include "ppapi/c/ppb_media_stream_audio_track.h" -#include "ppapi/c/ppb_media_stream_video_track.h" -#include "ppapi/c/ppb_messaging.h" -#include "ppapi/c/ppb_mouse_lock.h" -#include "ppapi/c/ppb_net_address.h" -#include "ppapi/c/ppb_network_list.h" -#include "ppapi/c/ppb_network_monitor.h" -#include "ppapi/c/ppb_network_proxy.h" -#include "ppapi/c/ppb_opengles2.h" -#include "ppapi/c/ppb_tcp_socket.h" -#include "ppapi/c/ppb_text_input_controller.h" -#include "ppapi/c/ppb_udp_socket.h" -#include "ppapi/c/ppb_url_loader.h" -#include "ppapi/c/ppb_url_request_info.h" -#include "ppapi/c/ppb_url_response_info.h" -#include "ppapi/c/ppb_var_array.h" -#include "ppapi/c/ppb_var_array_buffer.h" -#include "ppapi/c/ppb_var_dictionary.h" -#include "ppapi/c/ppb_video_frame.h" -#include "ppapi/c/ppb_vpn_provider.h" -#include "ppapi/c/ppb_websocket.h" -#include "ppapi/c/ppp.h" -#include "ppapi/c/ppp_graphics_3d.h" -#include "ppapi/c/ppp_input_event.h" -#include "ppapi/c/ppp_instance.h" -#include "ppapi/c/ppp_message_handler.h" -#include "ppapi/c/ppp_messaging.h" -#include "ppapi/c/ppp_mouse_lock.h" -#include "ppapi/c/private/pp_private_font_charset.h" -#include "ppapi/c/private/pp_video_frame_private.h" -#include "ppapi/c/private/ppb_camera_capabilities_private.h" -#include "ppapi/c/private/ppb_camera_device_private.h" -#include "ppapi/c/private/ppb_display_color_profile_private.h" -#include "ppapi/c/private/ppb_ext_crx_file_system_private.h" -#include "ppapi/c/private/ppb_file_io_private.h" -#include "ppapi/c/private/ppb_host_resolver_private.h" -#include "ppapi/c/private/ppb_instance_private.h" -#include "ppapi/c/private/ppb_net_address_private.h" -#include "ppapi/c/private/ppb_proxy_private.h" -#include "ppapi/c/private/ppb_tcp_socket_private.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/c/private/ppb_udp_socket_private.h" -#include "ppapi/c/private/ppb_uma_private.h" -#include "ppapi/c/private/ppb_x509_certificate_private.h" -#include "ppapi/c/private/ppp_instance_private.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" - -#endif /* PPAPI_TESTS_ALL_C_INCLUDES_H_ */
diff --git a/tests/all_cpp_includes.h b/tests/all_cpp_includes.h deleted file mode 100644 index 0fd6e0a..0000000 --- a/tests/all_cpp_includes.h +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// This test simply includes all the C++ headers to ensure they compile with a -// C++ compiler. If it compiles, it passes. -// -#ifndef PPAPI_TESTS_ALL_CPP_INCLUDES_H_ -#define PPAPI_TESTS_ALL_CPP_INCLUDES_H_ - -#include "ppapi/cpp/audio.h" -#include "ppapi/cpp/audio_buffer.h" -#include "ppapi/cpp/audio_config.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/core.h" -#include "ppapi/cpp/dev/buffer_dev.h" -#include "ppapi/cpp/dev/device_ref_dev.h" -#include "ppapi/cpp/dev/file_chooser_dev.h" -#include "ppapi/cpp/dev/ime_input_event_dev.h" -#include "ppapi/cpp/dev/memory_dev.h" -#include "ppapi/cpp/dev/printing_dev.h" -#include "ppapi/cpp/dev/scriptable_object_deprecated.h" -#include "ppapi/cpp/dev/text_input_dev.h" -#include "ppapi/cpp/dev/url_util_dev.h" -#include "ppapi/cpp/dev/video_decoder_dev.h" -#include "ppapi/cpp/dev/view_dev.h" -#include "ppapi/cpp/directory_entry.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/fullscreen.h" -#include "ppapi/cpp/graphics_2d.h" -#include "ppapi/cpp/graphics_3d.h" -#include "ppapi/cpp/graphics_3d_client.h" -#include "ppapi/cpp/host_resolver.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/logging.h" -#include "ppapi/cpp/media_stream_audio_track.h" -#include "ppapi/cpp/media_stream_video_track.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/module_impl.h" -#include "ppapi/cpp/mouse_lock.h" -#include "ppapi/cpp/net_address.h" -#include "ppapi/cpp/network_proxy.h" -#include "ppapi/cpp/point.h" -#include "ppapi/cpp/private/camera_capabilities_private.h" -#include "ppapi/cpp/private/camera_device_private.h" -#include "ppapi/cpp/private/instance_private.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/cpp/private/udp_socket_private.h" -#include "ppapi/cpp/private/var_private.h" -#include "ppapi/cpp/private/video_frame_private.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/cpp/resource.h" -#include "ppapi/cpp/size.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/cpp/text_input_controller.h" -#include "ppapi/cpp/touch_point.h" -#include "ppapi/cpp/udp_socket.h" -#include "ppapi/cpp/url_loader.h" -#include "ppapi/cpp/url_request_info.h" -#include "ppapi/cpp/url_response_info.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/var_array.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/cpp/var_dictionary.h" -#include "ppapi/cpp/video_frame.h" -#include "ppapi/cpp/vpn_provider.h" -#include "ppapi/cpp/websocket.h" -#include "ppapi/utility/completion_callback_factory.h" -#include "ppapi/utility/completion_callback_factory_thread_traits.h" -#include "ppapi/utility/graphics/paint_aggregator.h" -#include "ppapi/utility/graphics/paint_manager.h" -#include "ppapi/utility/threading/lock.h" -#include "ppapi/utility/threading/simple_thread.h" - -#endif // PPAPI_TESTS_ALL_CPP_INCLUDES_H_
diff --git a/tests/arch_dependent_sizes_32.h b/tests/arch_dependent_sizes_32.h deleted file mode 100644 index d033c3c..0000000 --- a/tests/arch_dependent_sizes_32.h +++ /dev/null
@@ -1,20 +0,0 @@ -/* Copyright 2012 The Chromium Authors - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - * - * This file has compile assertions for the sizes of types that are dependent - * on the architecture for which they are compiled (i.e., 32-bit vs 64-bit). - */ - -#ifndef PPAPI_TESTS_ARCH_DEPENDENT_SIZES_32_H_ -#define PPAPI_TESTS_ARCH_DEPENDENT_SIZES_32_H_ - -PP_COMPILE_ASSERT_SIZE_IN_BYTES(GLintptr, 4); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(GLsizeiptr, 4); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PP_CompletionCallback_Func, 4); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PP_URLLoaderTrusted_StatusCallback, 4); -PP_COMPILE_ASSERT_STRUCT_SIZE_IN_BYTES(PP_CompletionCallback, 12); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PPB_VideoDecoder_Dev, 32); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PPP_VideoDecoder_Dev, 16); - -#endif /* PPAPI_TESTS_ARCH_DEPENDENT_SIZES_32_H_ */
diff --git a/tests/arch_dependent_sizes_64.h b/tests/arch_dependent_sizes_64.h deleted file mode 100644 index 7df20c9..0000000 --- a/tests/arch_dependent_sizes_64.h +++ /dev/null
@@ -1,20 +0,0 @@ -/* Copyright 2012 The Chromium Authors - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - * - * This file has compile assertions for the sizes of types that are dependent - * on the architecture for which they are compiled (i.e., 32-bit vs 64-bit). - */ - -#ifndef PPAPI_TESTS_ARCH_DEPENDENT_SIZES_64_H_ -#define PPAPI_TESTS_ARCH_DEPENDENT_SIZES_64_H_ - -PP_COMPILE_ASSERT_SIZE_IN_BYTES(GLintptr, 8); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(GLsizeiptr, 8); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PP_CompletionCallback_Func, 8); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PP_URLLoaderTrusted_StatusCallback, 8); -PP_COMPILE_ASSERT_STRUCT_SIZE_IN_BYTES(PP_CompletionCallback, 24); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PPB_VideoDecoder_Dev, 64); -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PPP_VideoDecoder_Dev, 32); - -#endif /* PPAPI_TESTS_ARCH_DEPENDENT_SIZES_64_H_ */
diff --git a/tests/blink_deprecated_test_plugin.cc b/tests/blink_deprecated_test_plugin.cc deleted file mode 100644 index 828c9ab..0000000 --- a/tests/blink_deprecated_test_plugin.cc +++ /dev/null
@@ -1,437 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// A simple C++ Pepper plugin for exercising deprecated PPAPI interfaces in -// Blink layout tests. -// -// Most layout tests should prefer to use the normal Blink test plugin, with the -// MIME type application/x-blink-test-plugin. For layout tests that absolutely -// need to test deprecated synchronous scripting interfaces, this plugin can be -// instantiated using the application/x-blink-deprecated-test-plugin MIME type. -// -// The plugin exposes the following interface: -// -// Attributes: -// testwindowopen: if set, the plugin will synchronously attempt to open a -// window from DidCreateInstance, and log a message if successful. -// -// keydownscript: if set, the plugin will execute the value of the attribute as -// a script on a key down. -// -// mousedownscript: if set, the plugin will execute the value of the attribute -// as a script on a mouse button down. -// -// -// Functions: -// * plugin.normalize(): synchronously calls window.pluginCallback. -// -// * plugin.remember(value): keeps a reference on |value| in the plugin. -// -// * plugin.testCloneObject(): creates and returns another instance of the -// plugin object. -// -// * plugin.testCreateTestObject(): creates and returns a new TestObject -// instance (see below). -// -// * plugin.testExecuteScript(script): synchronously evaluates |script| and -// returns the result. -// -// * plugin.testGetProperty(property): returns the property named |property| -// from the window object. -// -// * plugin.testPassTestObject(function, object): synchronously calls the -// function named |function| on the window object, passing it |object| as a -// parameter, and returns its result. -// -// * plugin.testScriptObjectInvoke(function, value): synchronously calls the -// function named |function| on the window object, passing it |value| as a -// parameter, and returns its result. -// -// -// Properties: -// * plugin.testObject (read-only): a TestObject instance (see below). -// -// * plugin.testObjectCount (read-only): the number of TestObject instance -// created. -// -// * plugin.testGetUndefined (read-only): returns undefined. -// -// -// TestObject exposes the following interface: -// Properties: -// * object.testObject (read-only: another TestObject instance. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include <stdint.h> - -#include <map> -#include <sstream> -#include <unordered_map> -#include <utility> - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/functional/callback_helpers.h" -#include "base/strings/stringprintf.h" -#include "ppapi/cpp/dev/scriptable_object_deprecated.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/instance_private.h" -#include "ppapi/cpp/private/var_private.h" -#include "ppapi/cpp/var.h" - -namespace { - -class ScriptableBase : public pp::deprecated::ScriptableObject { - public: - explicit ScriptableBase(pp::InstancePrivate* instance) - : instance_(instance) {} - ~ScriptableBase() override {} - - // pp::deprecated::ScriptableObject overrides: - bool HasMethod(const pp::Var& name, pp::Var* exception) override { - return FindMethod(name) != methods_.end(); - } - - bool HasProperty(const pp::Var& name, pp::Var* exception) override { - return FindProperty(name) != properties_.end(); - } - - pp::Var Call(const pp::Var& method_name, - const std::vector<pp::Var>& args, - pp::Var* exception) override { - auto method = FindMethod(method_name); - if (method != methods_.end()) { - return method->second.Run(args, exception); - } - - return ScriptableObject::Call(method_name, args, exception); - } - - pp::Var GetProperty(const pp::Var& name, pp::Var* exception) override { - auto accessor = FindProperty(name); - if (accessor != properties_.end()) { - pp::Var value; - accessor->second.Run(false, &value); - return value; - } - return ScriptableObject::GetProperty(name, exception); - } - - void SetProperty(const pp::Var& name, - const pp::Var& value, - pp::Var* exception) override { - auto accessor = FindProperty(name); - if (accessor != properties_.end()) - accessor->second.Run(true, const_cast<pp::Var*>(&value)); - else - ScriptableObject::SetProperty(name, value, exception); - } - - protected: - using MethodMap = std::map< - std::string, - base::RepeatingCallback<pp::Var(const std::vector<pp::Var>&, pp::Var*)>>; - using PropertyMap = - std::map<std::string, base::RepeatingCallback<void(bool, pp::Var*)>>; - - MethodMap::iterator FindMethod(const pp::Var& name) { - if (!name.is_string()) - return methods_.end(); - return methods_.find(name.AsString()); - } - - PropertyMap::iterator FindProperty(const pp::Var& name) { - if (!name.is_string()) - return properties_.end(); - return properties_.find(name.AsString()); - } - - pp::InstancePrivate* const instance_; - MethodMap methods_; - PropertyMap properties_; -}; - -class TestObjectSO : public ScriptableBase { - public: - explicit TestObjectSO(pp::InstancePrivate* instance) - : ScriptableBase(instance) { - ++count_; - properties_.insert(std::make_pair( - "testObject", base::BindRepeating(&TestObjectSO::TestObjectAccessor, - base::Unretained(this)))); - } - ~TestObjectSO() override { - --count_; - } - - static int32_t count() { return count_; } - - private: - void TestObjectAccessor(bool set, pp::Var* var) { - if (set) - return; - if (test_object_.is_undefined()) - test_object_ = pp::VarPrivate(instance_, new TestObjectSO(instance_)); - *var = test_object_; - } - - static int32_t count_; - - pp::VarPrivate test_object_; -}; - -int32_t TestObjectSO::count_ = 0; - -class InstanceSO : public ScriptableBase { - public: - explicit InstanceSO(pp::InstancePrivate* instance) - : ScriptableBase(instance) { - methods_.insert(std::make_pair( - "normalize", - base::BindRepeating(&InstanceSO::Normalize, base::Unretained(this)))); - methods_.insert(std::make_pair( - "remember", - base::BindRepeating(&InstanceSO::Remember, base::Unretained(this)))); - methods_.insert(std::make_pair( - "testCloneObject", base::BindRepeating(&InstanceSO::TestCloneObject, - base::Unretained(this)))); - methods_.insert( - std::make_pair("testCreateTestObject", - base::BindRepeating(&InstanceSO::TestCreateTestObject, - base::Unretained(this)))); - methods_.insert(std::make_pair( - "testExecuteScript", base::BindRepeating(&InstanceSO::TestExecuteScript, - base::Unretained(this)))); - methods_.insert(std::make_pair( - "testGetProperty", base::BindRepeating(&InstanceSO::TestGetProperty, - base::Unretained(this)))); - methods_.insert( - std::make_pair("testPassTestObject", - base::BindRepeating(&InstanceSO::TestPassTestObject, - base::Unretained(this)))); - // Note: the semantics of testScriptObjectInvoke are identical to the - // semantics of testPassTestObject: call args[0] with args[1] as a - // parameter. - methods_.insert( - std::make_pair("testScriptObjectInvoke", - base::BindRepeating(&InstanceSO::TestPassTestObject, - base::Unretained(this)))); - properties_.insert(std::make_pair( - "testObject", base::BindRepeating(&InstanceSO::TestObjectAccessor, - base::Unretained(this)))); - properties_.insert( - std::make_pair("testObjectCount", - base::BindRepeating(&InstanceSO::TestObjectCountAccessor, - base::Unretained(this)))); - properties_.insert(std::make_pair( - "testGetUndefined", - base::BindRepeating(&InstanceSO::TestGetUndefinedAccessor, - base::Unretained(this)))); - } - ~InstanceSO() override = default; - - private: - // Requires no argument. - pp::Var Normalize(const std::vector<pp::Var>& args, pp::Var* exception) { - pp::VarPrivate object = instance_->GetWindowObject(); - return object.Call(pp::Var("pluginCallback"), exception); - } - - // Requires 1 argument. The argument is retained into remembered_ - pp::Var Remember(const std::vector<pp::Var>& args, pp::Var* exception) { - if (args.size() != 1) { - *exception = pp::Var("remember requires one argument"); - return pp::Var(); - } - remembered_ = args[0]; - return pp::Var(); - } - - // Requires no argument. - pp::Var TestCloneObject(const std::vector<pp::Var>& args, - pp::Var* exception) { - return pp::VarPrivate(instance_, new InstanceSO(instance_)); - } - - // Requires no argument. - pp::Var TestCreateTestObject(const std::vector<pp::Var>& args, - pp::Var* exception) { - return pp::VarPrivate(instance_, new TestObjectSO(instance_)); - } - - // Requires one argument. The argument is passed through as-is to - // pp::InstancePrivate::ExecuteScript(). - pp::Var TestExecuteScript(const std::vector<pp::Var>& args, - pp::Var* exception) { - if (args.size() != 1) { - *exception = pp::Var("testExecuteScript requires one argument"); - return pp::Var(); - } - return instance_->ExecuteScript(args[0], exception); - } - - // Requires one or more arguments. Roughly analogous to NPN_GetProperty. - // The arguments are the chain of properties to traverse, starting with the - // global context. - pp::Var TestGetProperty(const std::vector<pp::Var>& args, - pp::Var* exception) { - if (args.size() < 1) { - *exception = pp::Var("testGetProperty requires at least one argument"); - return pp::Var(); - } - pp::VarPrivate object = instance_->GetWindowObject(); - for (const auto& arg : args) { - if (!object.HasProperty(arg, exception)) - return pp::Var(); - object = object.GetProperty(arg, exception); - } - return object; - } - - // Requires 2 or more arguments. The first argument is the name of a function - // to invoke, and the second argument is a value to pass to that function. - pp::Var TestPassTestObject(const std::vector<pp::Var>& args, - pp::Var* exception) { - if (args.size() < 2) { - *exception = pp::Var("testPassTestObject requires at least 2 arguments"); - return pp::Var(); - } - pp::VarPrivate object = instance_->GetWindowObject(); - return object.Call(args[0], args[1], exception); - } - - void TestObjectAccessor(bool set, pp::Var* var) { - if (set) - return; - if (test_object_.is_undefined()) - test_object_ = pp::VarPrivate(instance_, new TestObjectSO(instance_)); - *var = test_object_; - } - - void TestObjectCountAccessor(bool set, pp::Var* var) { - if (set) - return; - *var = pp::Var(TestObjectSO::count()); - } - - void TestGetUndefinedAccessor(bool set, pp::Var* var) { - if (set) - return; - *var = pp::Var(); - } - - pp::VarPrivate test_object_; - pp::Var remembered_; -}; - -class BlinkDeprecatedTestInstance : public pp::InstancePrivate { - public: - explicit BlinkDeprecatedTestInstance(PP_Instance instance) - : pp::InstancePrivate(instance) {} - ~BlinkDeprecatedTestInstance() override { - LogMessage("%s", "Destroying"); - } - - // pp::Instance overrides - bool Init(uint32_t argc, const char* argn[], const char* argv[]) override { - for (uint32_t i = 0; i < argc; ++i) - attributes_[argn[i]] = argv[i]; - - if (HasAttribute("testwindowopen")) - return TestWindowOpen(); - - if (HasAttribute("initscript")) - ExecuteScript(attributes_["initscript"]); - - uint32_t event_classes = 0; - if (HasAttribute("keydownscript")) - event_classes |= PP_INPUTEVENT_CLASS_KEYBOARD; - if (HasAttribute("mousedownscript")) - event_classes |= PP_INPUTEVENT_CLASS_MOUSE; - RequestFilteringInputEvents(event_classes); - - return true; - } - - virtual bool HandleInputEvent(const pp::InputEvent& event) override { - switch (event.GetType()) { - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - if (HasAttribute("mousedownscript")) - ExecuteScript(attributes_["mousedownscript"]); - return true; - case PP_INPUTEVENT_TYPE_KEYDOWN: - if (HasAttribute("keydownscript")) - ExecuteScript(attributes_["keydownscript"]); - return true; - default: - return false; - } - } - - // pp::InstancePrivate overrides: - pp::Var GetInstanceObject() override { - if (instance_var_.is_undefined()) { - instance_so_ = new InstanceSO(this); - instance_var_ = pp::VarPrivate(this, instance_so_); - } - return instance_var_; - } - - void NotifyTestCompletion() { - ExecuteScript("window.testRunner.notifyDone()"); - } - - bool TestWindowOpen() { - pp::Var result = GetWindowObject().Call( - pp::Var("open"), pp::Var("about:blank"), pp::Var("_blank")); - if (result.is_object()) - LogMessage("PLUGIN: WINDOW OPEN SUCCESS"); - NotifyTestCompletion(); - return true; - } - - void LogMessage(const char* format...) { - va_list args; - va_start(args, format); - LogToConsoleWithSource(PP_LOGLEVEL_LOG, - pp::Var("Blink Deprecated Test Plugin"), - pp::Var(base::StringPrintV(format, args))); - va_end(args); - } - - private: - bool HasAttribute(const std::string& name) { - return attributes_.find(name) != attributes_.end(); - } - - std::unordered_map<std::string, std::string> attributes_; - pp::VarPrivate instance_var_; - // Owned by |instance_var_|. - InstanceSO* instance_so_; -}; - -class BlinkDeprecatedTestModule : public pp::Module { - public: - BlinkDeprecatedTestModule() {} - ~BlinkDeprecatedTestModule() override {} - - pp::Instance* CreateInstance(PP_Instance instance) override { - return new BlinkDeprecatedTestInstance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new BlinkDeprecatedTestModule(); -} - -} // namespace pp
diff --git a/tests/blink_test_plugin.cc b/tests/blink_test_plugin.cc deleted file mode 100644 index 353fa04..0000000 --- a/tests/blink_test_plugin.cc +++ /dev/null
@@ -1,189 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include <stdarg.h> -#include <stdint.h> -#include <string.h> - -#include <sstream> -#include <utility> - -#include "base/strings/stringprintf.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/graphics_2d.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" - -namespace { - -void DummyCompletionCallback(void*, int32_t) {} - -// This is a simple C++ Pepper plugin for Blink layout tests. -// -// Layout tests can instantiate this plugin by requesting the mime type -// application/x-blink-test-plugin. When possible, tests should use the -// startAfterLoadAndFinish() helper in resources/plugin.js to perform work -// after the plugin has loaded. -// -// The plugin also exposes several other features for testing convenience: -// - On first paint, the plugin posts a 'loaded' message to its owner element. -// - On subsequent paints, the plugin posts a 'painted' message instead. -// - Keyboard and mouse input events are logged to the console. -class BlinkTestInstance : public pp::Instance { - public: - explicit BlinkTestInstance(PP_Instance instance) - : pp::Instance(instance), first_paint_(true) {} - ~BlinkTestInstance() override {} - - bool Init(uint32_t argc, const char* argn[], const char* argv[]) override { - // It's hard / impossible for some layout tests to listen for a message from - // the plugin. For example, a plugin in PluginDocuments is unreachable from - // a cross-origin parent frame, since the actual plugin element is in a - // different Document. To help with this case, the plugin logs a message - // that can be captured indirectly in test expectations. - LogMessage("initializing"); - // Used by layout tests that want to inspect the args the plugin is - // instantiated with. - for (uint32_t i = 0; i < argc; ++i) { - if (!strcmp(argn[i], "logargs")) { - LogMessage("plugin args:"); - for (uint32_t j = 0; j < argc; ++j) - LogMessage(" name = %s, value = %s", argn[j], argv[j]); - } - } - return RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE | - PP_INPUTEVENT_CLASS_KEYBOARD) == PP_OK; - } - - void DidChangeView(const pp::View& view) override { - view_ = view; - device_context_ = pp::Graphics2D(this, view_.GetRect().size(), true); - if (!BindGraphics(device_context_)) - return; - - // Since we draw a static image, we only need to make a new frame when - // the device is initialized or the view size changes. - Paint(); - } - - void DidChangeFocus(bool has_focus) override { - LogMessage("DidChangeFocus(%s)", has_focus ? "true" : "false"); - } - - bool HandleInputEvent(const pp::InputEvent& event) override { - switch (event.GetType()) { - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - LogMouseEvent("Down", event); - break; - case PP_INPUTEVENT_TYPE_MOUSEUP: - LogMouseEvent("Up", event); - break; - case PP_INPUTEVENT_TYPE_KEYDOWN: - LogKeyboardEvent("Down", event); - break; - case PP_INPUTEVENT_TYPE_KEYUP: - LogKeyboardEvent("Up", event); - break; - case PP_INPUTEVENT_TYPE_MOUSEMOVE: - case PP_INPUTEVENT_TYPE_MOUSEENTER: - case PP_INPUTEVENT_TYPE_MOUSELEAVE: - case PP_INPUTEVENT_TYPE_RAWKEYDOWN: - case PP_INPUTEVENT_TYPE_CHAR: - // Just swallow these events without any logging. - return true; - default: - LogMessage("Unexpected input event with type = %d", event.GetType()); - return false; - } - return true; - } - - private: - void Paint() { - pp::ImageData image(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - view_.GetRect().size(), true); - if (image.is_null()) - return; - - // Draw blue and green checkerboard pattern to show "interesting" keyframe. - const int kSquareSizePixels = 8; - for (int y = 0; y < view_.GetRect().size().height(); ++y) { - for (int x = 0; x < view_.GetRect().size().width(); ++x) { - int x_square = x / kSquareSizePixels; - int y_square = y / kSquareSizePixels; - uint32_t color = ((x_square + y_square) % 2) ? 0xFF0000FF : 0xFF00FF00; - *image.GetAddr32(pp::Point(x, y)) = color; - } - } - - device_context_.ReplaceContents(&image); - device_context_.Flush( - pp::CompletionCallback(&DummyCompletionCallback, nullptr)); - - // TODO(dcheng): In theory, this should wait for the flush to complete - // before claiming that it's painted. In practice, this is difficult: when - // running layout tests, a frame is typically only generated at the end of - // the layout test. Sending the completion message in the callback results - // in a deadlock: the test wants to wait for the plugin to paint, but the - // plugin won't paint until the test completes. This seems to be Good - // Enough™ for now. - if (first_paint_) { - first_paint_ = false; - PostMessage(pp::Var("loaded")); - } else { - PostMessage(pp::Var("painted")); - } - } - - void LogMouseEvent(const char* type, const pp::InputEvent& event) { - pp::MouseInputEvent mouse_event(event); - pp::Point mouse_position = mouse_event.GetPosition(); - LogMessage("Mouse%s at (%d,%d)", type, mouse_position.x(), - mouse_position.y()); - } - - void LogKeyboardEvent(const char* type, const pp::InputEvent& event) { - pp::KeyboardInputEvent keyboard_event(event); - LogMessage("Key%s '%s'", type, keyboard_event.GetCode().AsString().c_str()); - } - - void LogMessage(const char* format...) { - va_list args; - va_start(args, format); - LogToConsoleWithSource(PP_LOGLEVEL_LOG, pp::Var("Blink Test Plugin"), - pp::Var(base::StringPrintV(format, args))); - va_end(args); - } - - bool first_paint_; - pp::View view_; - pp::Graphics2D device_context_; -}; - -class BlinkTestModule : public pp::Module { - public: - BlinkTestModule() {} - virtual ~BlinkTestModule() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new BlinkTestInstance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new BlinkTestModule(); -} - -} // namespace pp
diff --git a/tests/corb_eligible_resource.json b/tests/corb_eligible_resource.json deleted file mode 100644 index 8c850a5..0000000 --- a/tests/corb_eligible_resource.json +++ /dev/null
@@ -1 +0,0 @@ -{ "foo": "bar" }
diff --git a/tests/corb_eligible_resource.json.mock-http-headers b/tests/corb_eligible_resource.json.mock-http-headers deleted file mode 100644 index c09a209..0000000 --- a/tests/corb_eligible_resource.json.mock-http-headers +++ /dev/null
@@ -1,3 +0,0 @@ -HTTP/1.1 200 OK -Content-Type: text/json -X-Content-Type-Options: nosniff
diff --git a/tests/extensions/BUILD.gn b/tests/extensions/BUILD.gn deleted file mode 100644 index c2c071d..0000000 --- a/tests/extensions/BUILD.gn +++ /dev/null
@@ -1,157 +0,0 @@ -# Copyright 2015 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//components/nacl/features.gni") -import("//components/nacl/target_cpu.gni") -import("//ppapi/buildflags/buildflags.gni") -import("//ppapi/native_client/nacl_test_data.gni") - -assert(enable_ppapi) - -group("extensions") { - newlib = "//build/toolchain/nacl:clang_newlib_${nacl_target_cpu}" - pnacl = "//build/toolchain/nacl:newlib_pnacl" - data_deps = [ - ":ppapi_tests_extensions_background_keepalive($newlib)", - ":ppapi_tests_extensions_load_unload($newlib)", - ":ppapi_tests_extensions_media_galleries($newlib)", - ":ppapi_tests_extensions_multicast_permissions($newlib)", - ":ppapi_tests_extensions_no_socket_permissions($newlib)", - ":ppapi_tests_extensions_packaged_app($newlib)", - ":ppapi_tests_extensions_packaged_app($pnacl)", - ":ppapi_tests_extensions_popup($newlib)", - ":ppapi_tests_extensions_socket_permissions($newlib)", - ] -} - -if (is_nacl) { - nacl_test_data("ppapi_tests_extensions_background_keepalive") { - sources = [ "background_keepalive/background.cc" ] - deps = [ "//ppapi/cpp" ] - destination_dir = "test_data/ppapi/tests/extensions/background_keepalive" - test_files = [ - "background_keepalive/background.js", - "background_keepalive/manifest.json", - ] - } - - nacl_test_data("ppapi_tests_extensions_load_unload") { - sources = [ "load_unload/load_unload.cc" ] - deps = [ "//ppapi/cpp" ] - destination_dir = "test_data/ppapi/tests/extensions/load_unload" - test_files = [ - "load_unload/background.js", - "load_unload/ext_icon.png", - "load_unload/manifest.json", - ] - } - - nacl_test_data("ppapi_tests_extensions_media_galleries") { - sources = [ - "//ppapi/tests/test_utils.cc", - "//ppapi/tests/test_utils.h", - "media_galleries/test_galleries.cc", - ] - deps = [ "//ppapi/cpp" ] - destination_dir = "test_data/ppapi/tests/extensions/media_galleries" - test_files = [ - "media_galleries/background.js", - "media_galleries/index.html", - "media_galleries/manifest.json", - "media_galleries/test.js", - ] - } - - nacl_test_data("ppapi_tests_extensions_multicast_permissions") { - sources = [ "multicast_permissions/test_multicast_permissions.cc" ] - deps = [ "//ppapi/cpp" ] - destination_dir = "test_data/ppapi/tests/extensions/multicast_permissions" - test_files = [ - "multicast_permissions/controller.js", - "multicast_permissions/index.html", - "multicast_permissions/main.js", - "multicast_permissions/manifest.json", - ] - } - - nacl_test_data("ppapi_tests_extensions_no_socket_permissions") { - sources = [ "no_socket_permissions/test_no_socket_permissions.cc" ] - deps = [ "//ppapi/cpp" ] - destination_dir = "test_data/ppapi/tests/extensions/no_socket_permissions" - test_files = [ - "no_socket_permissions/controller.js", - "no_socket_permissions/index.html", - "no_socket_permissions/main.js", - "no_socket_permissions/manifest.json", - ] - } - - nacl_test_data("ppapi_tests_extensions_popup") { - sources = [ "popup/module.cc" ] - deps = [ "//ppapi/cpp" ] - destination_dir = "test_data/ppapi/tests/extensions/popup" - test_files = [ - "popup/background.js", - "popup/popup.html", - "popup/popup.js", - "popup/manifest.json", - ] - } - - nacl_test_data("ppapi_tests_extensions_socket_permissions") { - sources = [ "socket_permissions/test_socket_permissions.cc" ] - deps = [ "//ppapi/cpp" ] - destination_dir = "test_data/ppapi/tests/extensions/socket_permissions" - test_files = [ - "socket_permissions/controller.js", - "socket_permissions/index.html", - "socket_permissions/main.js", - "socket_permissions/manifest.json", - ] - } -} - -if (is_nacl) { - nacl_test_data("ppapi_tests_extensions_packaged_app") { - sources = [ "packaged_app/test_packaged_app.cc" ] - deps = [ "//ppapi/cpp" ] - - # This is built with an old nacl toolchain, so it shouldn't pull in - # any of chrome's "actual" code. - assert_no_deps = [ "//base" ] - - destination_dir = "test_data/ppapi/tests/extensions/packaged_app" - test_files = [ - "packaged_app/controller.js", - "packaged_app/index.html", - "packaged_app/main.js", - "packaged_app/manifest.json", - "packaged_app/test_file.txt", - "packaged_app/test_file2.txt", - ] - nmfflags = [ - # Add 16 "files" entries to make sure that open_resource can handle - # more files than IPC::MessageAttachmentSet::kMaxDescriptorsPerMessage - # which is currently 7 (also 16 is a large-but-reasonable number of - # possible DSOs for an app to have) - "-xtest_file0:test_file.txt", - "-xtest_file1:test_file2.txt", - "-xtest_file2:test_file.txt", - "-xtest_file3:test_file2.txt", - "-xtest_file4:test_file.txt", - "-xtest_file5:test_file2.txt", - "-xtest_file6:test_file.txt", - "-xtest_file7:test_file2.txt", - "-xtest_file8:test_file.txt", - "-xtest_file9:test_file2.txt", - "-xtest_file10:test_file.txt", - "-xtest_file11:test_file2.txt", - "-xtest_file12:test_file.txt", - "-xtest_file13:test_file2.txt", - "-xtest_file14:test_file.txt", - "-xtest_file15:test_file2.txt", - "-xtest_file16:test_file.txt", - ] - } -}
diff --git a/tests/extensions/background_keepalive/background.cc b/tests/extensions/background_keepalive/background.cc deleted file mode 100644 index ba2d474..0000000 --- a/tests/extensions/background_keepalive/background.cc +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include <cstdio> -#include <string> - -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/message_loop.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var.h" -#include "ppapi/utility/completion_callback_factory.h" - -class Instance : public pp::Instance { - public: - explicit Instance(PP_Instance instance) : - pp::Instance(instance), - callback_factory_(this), - delay_milliseconds_(10), - active_(true) { - DoSomething(PP_OK); - } - virtual ~Instance() {} - - virtual void HandleMessage(const pp::Var& message_var) { - std::string message_string = message_var.AsString(); - if (message_string == "be idle") { - active_ = false; - } else { - PostMessage("Unhandled control message."); - } - } - - void DoSomething(int32_t result) { - if (active_) { - pp::MessageLoop loop = pp::MessageLoop::GetCurrent(); - pp::CompletionCallback c = callback_factory_.NewCallback( - &Instance::DoSomething); - loop.PostWork(c, delay_milliseconds_); - } - } - - pp::CompletionCallbackFactory<Instance> callback_factory_; - int delay_milliseconds_; - bool active_; -}; - -class Module : public pp::Module { - public: - Module() : pp::Module() {} - virtual ~Module() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new Instance(instance); - } -}; - -namespace pp { -Module* CreateModule() { - return new ::Module(); -} -} // namespace pp -
diff --git a/tests/extensions/background_keepalive/background.js b/tests/extensions/background_keepalive/background.js deleted file mode 100644 index 16e8e95..0000000 --- a/tests/extensions/background_keepalive/background.js +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var modulesCreated = 0; - -// Indicate load success. -function moduleDidLoad(moduleNumber) { - chrome.test.sendMessage('created_module:' + moduleNumber.toString(), - handleChromeTestMessage); -} - -var handleChromeTestMessage = function (message) { - if (message == 'create_module') { - createNaClEmbed(true); - } else if (message == 'create_module_without_hack') { - createNaClEmbed(false); - } else if (message == 'destroy_module') { - destroyNaClEmbed(); - } -} - -function handleNaclMessage(messageEvent) { - console.log('handleNaclMessage: ' + messageEvent.data); -} - -function createNaClEmbed(touchEmbedHack) { - modulesCreated++; - - var embed = document.createElement('embed'); - embed.src = 'ppapi_tests_extensions_background_keepalive.nmf'; - embed.type = 'application/x-nacl'; - - var listener = document.createElement('div'); - listener.addEventListener('load', moduleDidLoad.bind(null, modulesCreated), - true); - listener.addEventListener('message', handleNaclMessage, true); - listener.appendChild(embed); - - document.body.appendChild(listener); - - if (touchEmbedHack) - console.assert(embed.lastError == 0); -} - -function destroyNaClEmbed() { - moduleDivs = document.querySelectorAll('div'); - console.assert(moduleDivs.length > 0); - document.body.removeChild(moduleDivs[0]); - - chrome.test.sendMessage('destroyed_module', handleChromeTestMessage); -} - -chrome.test.sendMessage('ready', handleChromeTestMessage);
diff --git a/tests/extensions/background_keepalive/manifest.json b/tests/extensions/background_keepalive/manifest.json deleted file mode 100644 index 28fb912..0000000 --- a/tests/extensions/background_keepalive/manifest.json +++ /dev/null
@@ -1,11 +0,0 @@ -{ - "manifest_version": 2, - "name": "background_nacl", - "version": "0", - "description": "Tests keeping background page with NaCl alive when active.", - "app": { - "background": { - "scripts": ["background.js"] - } - } -}
diff --git a/tests/extensions/load_unload/background.js b/tests/extensions/load_unload/background.js deleted file mode 100644 index 5c3e66c..0000000 --- a/tests/extensions/load_unload/background.js +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var nacl = null; - -function loadNaClModule() { - nacl = document.createElement('embed'); - nacl.addEventListener('load', onNaClModuleLoaded, true); - nacl.type = 'application/x-nacl'; - nacl.width = 0; - nacl.height = 0; - nacl.src = 'ppapi_tests_extensions_load_unload.nmf'; - document.body.appendChild(nacl); - - // Request the offsetTop property to force a relayout. As of Apr 10, 2014 - // this is needed if the module is being loaded in a background page (see - // crbug.com/350445). - nacl.offsetTop; -} - -function detachNaClModule() { - document.body.removeChild(nacl); - nacl = null; -} - -function onNaClModuleLoaded() { - chrome.test.sendMessage("nacl_module_loaded"); -} - -chrome.browserAction.onClicked.addListener(function(tab) { - if (!nacl) - loadNaClModule(); - else - detachNaClModule(); -});
diff --git a/tests/extensions/load_unload/ext_icon.png b/tests/extensions/load_unload/ext_icon.png deleted file mode 100644 index e3cdb8a..0000000 --- a/tests/extensions/load_unload/ext_icon.png +++ /dev/null Binary files differ
diff --git a/tests/extensions/load_unload/load_unload.cc b/tests/extensions/load_unload/load_unload.cc deleted file mode 100644 index e9b09f1..0000000 --- a/tests/extensions/load_unload/load_unload.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" - -namespace { - -class Module : public pp::Module { - public: - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new pp::Instance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new ::Module(); -} - -} // namespace pp
diff --git a/tests/extensions/load_unload/manifest.json b/tests/extensions/load_unload/manifest.json deleted file mode 100644 index 33d12da..0000000 --- a/tests/extensions/load_unload/manifest.json +++ /dev/null
@@ -1,14 +0,0 @@ -{ - "name": "Lazy background wait for NaCl test", - "description": "Tests that a lazy background page stays alive while a NaCl module exists in its DOM", - "version": "0", - "manifest_version": 2, - "background": { - "scripts": ["background.js"], - "persistent": false - }, - "browser_action": { - "default_icon" : "ext_icon.png", - "default_title": "Open Extensions window" - } -}
diff --git a/tests/extensions/media_galleries/background.js b/tests/extensions/media_galleries/background.js deleted file mode 100644 index 01da9fe..0000000 --- a/tests/extensions/media_galleries/background.js +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.app.runtime.onLaunched.addListener(function() { - chrome.app.window.create('index.html', {width: 500, height: 500}); -});
diff --git a/tests/extensions/media_galleries/index.html b/tests/extensions/media_galleries/index.html deleted file mode 100644 index e048ba5..0000000 --- a/tests/extensions/media_galleries/index.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>chrome.mediaGalleries</title> - <script src="test.js"></script> -</head> -<body> - <embed id="nacl_module" src="ppapi_tests_extensions_media_galleries.nmf" - type="application/x-nacl" /> -</body> -</html>
diff --git a/tests/extensions/media_galleries/manifest.json b/tests/extensions/media_galleries/manifest.json deleted file mode 100644 index e145265..0000000 --- a/tests/extensions/media_galleries/manifest.json +++ /dev/null
@@ -1,14 +0,0 @@ -{ - "manifest_version": 2, - "name": "media_galleries_nacl", - "version": "0", - "description": "Tests media galleries file system access in NaCl.", - "app": { - "background": { - "scripts": ["background.js"] - } - }, - "permissions": [ - { "mediaGalleries": [ "read", "allAutoDetected" ] } - ] -}
diff --git a/tests/extensions/media_galleries/test.js b/tests/extensions/media_galleries/test.js deleted file mode 100644 index 25e1f90..0000000 --- a/tests/extensions/media_galleries/test.js +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var filePassingModule = null; -var testFilesystem; -var gotReady = false; - -function handleMessage(message) { - if (message.data == 'ready') { - chrome.test.assertFalse(gotReady); - gotReady = true; - chrome.mediaGalleries.getMediaFileSystems( - function(filesystems) { - if (filesystems.length != 1) { - chrome.test.fail('Wrong number of media galleries: ' + - filesystems.length); - return; - } - testFilesystem = filesystems[0]; - var message = { - 'filesystem': testFilesystem, - 'fullPath': '/test.jpg', - 'testType': 'read_test' - }; - filePassingModule.postMessage(message); - }); - } else if (message.data == 'read_success'){ - var message = { - 'filesystem': testFilesystem, - 'fullPath': '/test.jpg', - 'testType': 'write_test' - }; - filePassingModule.postMessage(message); - } else if (message.data == 'write_success'){ - chrome.test.succeed(); - } else { - chrome.test.fail(message.data); - } -} - -window.onload = function() { - filePassingModule = document.getElementById('nacl_module'); - filePassingModule.addEventListener('message', handleMessage, false); -}; -
diff --git a/tests/extensions/media_galleries/test_galleries.cc b/tests/extensions/media_galleries/test_galleries.cc deleted file mode 100644 index c0bbc8b..0000000 --- a/tests/extensions/media_galleries/test_galleries.cc +++ /dev/null
@@ -1,168 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include <string> - -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/var_dictionary.h" -#include "ppapi/tests/test_utils.h" - -/// The Instance class. Receives the file through HandleMessage(), and returns -/// data to the plugin with PostMessage(). -class FilePassingInstance : public pp::Instance { - public: - /// The constructor creates the plugin-side instance. - /// @param[in] instance the handle to the browser-side plugin instance. - explicit FilePassingInstance(PP_Instance instance); - virtual ~FilePassingInstance(); - - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); - - private: - /// Handler for messages coming in from the browser via postMessage(). - /// @param[in] var_message The message posted by the browser. - virtual void HandleMessage(const pp::Var& var_message); - - /// Takes a fileEntry-dictionary message received from JavaScript and converts - /// it into a pp::FileRef. On failure, returns a null FileRef. - pp::FileRef ParseMessage(const pp::Var& var_message, std::string* test_type); - - void TestRead(pp::FileRef file_ref); - void TestWrite(pp::FileRef file_ref); -}; - -FilePassingInstance::FilePassingInstance(PP_Instance instance) - : pp::Instance(instance) {} - -FilePassingInstance::~FilePassingInstance() {} - -bool FilePassingInstance::Init(uint32_t argc, - const char* argn[], - const char* argv[]) { - PostMessage("ready"); - return true; -} - -pp::FileRef FilePassingInstance::ParseMessage(const pp::Var& var_message, - std::string* test_type) { - if (!var_message.is_dictionary()) { - PostMessage("Message was not a dictionary."); - return pp::FileRef(); - } - pp::VarDictionary var_dictionary_message(var_message); - pp::Var var_filesystem = var_dictionary_message.Get("filesystem"); - pp::Var var_fullpath = var_dictionary_message.Get("fullPath"); - pp::Var var_testtype = var_dictionary_message.Get("testType"); - - if (!var_filesystem.is_resource()) { - PostMessage("Filesystem was missing or not a resource."); - return pp::FileRef(); - } - pp::Resource resource_filesystem = var_filesystem.AsResource(); - if (!var_fullpath.is_string()) { - PostMessage("FullPath was missing or not a string."); - return pp::FileRef(); - } - std::string fullpath = var_fullpath.AsString(); - if (!var_testtype.is_string()) { - PostMessage("TestType was missing or not a string."); - return pp::FileRef(); - } - std::string name_of_test = var_testtype.AsString(); - - if (!pp::FileSystem::IsFileSystem(resource_filesystem)) { - PostMessage("Filesystem was not a file system."); - return pp::FileRef(); - } - - *test_type = name_of_test; - pp::FileSystem filesystem(resource_filesystem); - // Note: The filesystem is already open (there is no need to call Open again). - - return pp::FileRef(filesystem, fullpath.c_str()); -} - -void FilePassingInstance::HandleMessage(const pp::Var& var_message) { - // Extract the filesystem and fullPath from the message. - std::string test_type; - pp::FileRef file_ref = ParseMessage(var_message, &test_type); - if (file_ref.is_null()) - return; - - if (test_type == "read_test") { - TestRead(file_ref); - } else if (test_type == "write_test") { - TestWrite(file_ref); - } else { - PostMessage("Unknown test type"); - } -} - -void FilePassingInstance::TestRead(pp::FileRef file_ref) { - pp::FileIO file_io(pp::InstanceHandle(this)); - - { - TestCompletionCallback callback(pp_instance(), PP_REQUIRED); - callback.WaitForResult( - file_io.Open(file_ref, PP_FILEOPENFLAG_READ, callback.GetCallback())); - if (callback.result() != PP_OK) { - PostMessage("Could not open file"); - return; - } - } - { - TestCompletionCallbackWithOutput<std::vector<char> > callback(pp_instance(), - PP_REQUIRED); - callback.WaitForResult( - file_io.Read(0, 1024, callback.GetCallback())); - if (callback.result() < 0) { - PostMessage("Could not read file"); - return; - } - - if (callback.output().size() != 306) { - PostMessage("Read the wrong number of bytes"); - return; - } - } - PostMessage("read_success"); -} - -void FilePassingInstance::TestWrite(pp::FileRef file_ref) { - pp::FileIO file_io(pp::InstanceHandle(this)); - TestCompletionCallback callback(pp_instance(), PP_REQUIRED); - callback.WaitForResult( - file_io.Open(file_ref, PP_FILEOPENFLAG_WRITE, callback.GetCallback())); - if (callback.result() != PP_ERROR_NOACCESS) { - PostMessage("Opening for write should have failed"); - return; - } - PostMessage("write_success"); -} - -class FilePassingModule : public pp::Module { - public: - FilePassingModule() : pp::Module() {} - virtual ~FilePassingModule() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new FilePassingInstance(instance); - } -}; - -namespace pp { - -Module* CreateModule() { - return new FilePassingModule(); -} - -} // namespace pp
diff --git a/tests/extensions/multicast_permissions/controller.js b/tests/extensions/multicast_permissions/controller.js deleted file mode 100644 index 921ad5f..0000000 --- a/tests/extensions/multicast_permissions/controller.js +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var control_message; - -function testAll() { - var nacl_module = document.getElementById('nacl_module'); - // The plugin will start the corresponding test and post a message back - // the test is done. If the test has failed, the message is a description - // of the error; otherwise the message is empty. - nacl_module.postMessage(control_message); -} - -var onControlMessageReceived = function(message) { - control_message = message; - chrome.test.runTests([testAll]); -} - -var onPluginMessageReceived = function(message) { - if (message.data == "PASS") { - chrome.test.sendMessage("PASS", onControlMessageReceived); - } else if (message.data) { - chrome.test.fail(message.data); - } -}; - -window.onload = function() { - var nacl_module = document.getElementById('nacl_module'); - nacl_module.addEventListener("message", onPluginMessageReceived, false); -};
diff --git a/tests/extensions/multicast_permissions/index.html b/tests/extensions/multicast_permissions/index.html deleted file mode 100644 index ae65854..0000000 --- a/tests/extensions/multicast_permissions/index.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>No permissions test</title> - <script src="controller.js"></script> -</head> -<body> - <embed id="nacl_module" src="ppapi_tests_extensions_multicast_permissions.nmf" - type="application/x-nacl" /> -</body> -</html>
diff --git a/tests/extensions/multicast_permissions/main.js b/tests/extensions/multicast_permissions/main.js deleted file mode 100644 index 88db9f6..0000000 --- a/tests/extensions/multicast_permissions/main.js +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.app.runtime.onLaunched.addListener(function() { - chrome.app.window.create('index.html', {width: 500, height: 500}); -});
diff --git a/tests/extensions/multicast_permissions/manifest.json b/tests/extensions/multicast_permissions/manifest.json deleted file mode 100644 index cb9cba2..0000000 --- a/tests/extensions/multicast_permissions/manifest.json +++ /dev/null
@@ -1,18 +0,0 @@ -{ - "manifest_version": 2, - "name": "packaged_app_test", - "version": "0.1", - "description": "Packaged App test for Pepper", - "app": { - "background": { - "scripts": [ "main.js" ] - } - }, - "permissions": [{"socket": ["udp-bind", "udp-multicast-membership"]}], - "sockets": { - "udp": { - "bind": "127.0.0.1:80", - "multicastMembership": "" - } - } -}
diff --git a/tests/extensions/multicast_permissions/test_multicast_permissions.cc b/tests/extensions/multicast_permissions/test_multicast_permissions.cc deleted file mode 100644 index cbafb2e..0000000 --- a/tests/extensions/multicast_permissions/test_multicast_permissions.cc +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/cpp/udp_socket.h" -#include "ppapi/utility/completion_callback_factory.h" - -namespace { - -class MyInstance : public pp::Instance { - public: - explicit MyInstance(PP_Instance instance) - : pp::Instance(instance), udp_socket_(this), factory_(this) {} - virtual ~MyInstance() {} - - void DidBindUDPSocket(int32_t result) { - // We should be able to bind the multicast socket with permission. - if (result != PP_OK) - PostMessage(result); - else - PostMessage("PASS"); - } - - void DidSetOptionUDPSocket(int32_t result) { - // We should be able to set the multicast option with permission. - if (result != PP_OK) { - PostMessage(result); - return; - } - - PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1}}; - pp::NetAddress address(this, ipv4_address); - udp_socket_.Bind(address, - factory_.NewCallback(&MyInstance::DidBindUDPSocket)); - } - - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) { - udp_socket_.SetOption( - PP_UDPSOCKET_OPTION_MULTICAST_LOOP, pp::Var(true), - factory_.NewCallback(&MyInstance::DidSetOptionUDPSocket)); - return true; - } - - private: - pp::UDPSocket udp_socket_; - pp::CompletionCallbackFactory<MyInstance> factory_; -}; - -class MyModule : public pp::Module { - public: - MyModule() : pp::Module() {} - virtual ~MyModule() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new MyInstance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new MyModule(); -} - -} // namespace pp
diff --git a/tests/extensions/no_socket_permissions/controller.js b/tests/extensions/no_socket_permissions/controller.js deleted file mode 100644 index 921ad5f..0000000 --- a/tests/extensions/no_socket_permissions/controller.js +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var control_message; - -function testAll() { - var nacl_module = document.getElementById('nacl_module'); - // The plugin will start the corresponding test and post a message back - // the test is done. If the test has failed, the message is a description - // of the error; otherwise the message is empty. - nacl_module.postMessage(control_message); -} - -var onControlMessageReceived = function(message) { - control_message = message; - chrome.test.runTests([testAll]); -} - -var onPluginMessageReceived = function(message) { - if (message.data == "PASS") { - chrome.test.sendMessage("PASS", onControlMessageReceived); - } else if (message.data) { - chrome.test.fail(message.data); - } -}; - -window.onload = function() { - var nacl_module = document.getElementById('nacl_module'); - nacl_module.addEventListener("message", onPluginMessageReceived, false); -};
diff --git a/tests/extensions/no_socket_permissions/index.html b/tests/extensions/no_socket_permissions/index.html deleted file mode 100644 index dd2e1e6..0000000 --- a/tests/extensions/no_socket_permissions/index.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>No socket permissions test</title> - <script src="controller.js"></script> -</head> -<body> - <embed id="nacl_module" src="ppapi_tests_extensions_no_socket_permissions.nmf" - type="application/x-nacl" /> -</body> -</html>
diff --git a/tests/extensions/no_socket_permissions/main.js b/tests/extensions/no_socket_permissions/main.js deleted file mode 100644 index 88db9f6..0000000 --- a/tests/extensions/no_socket_permissions/main.js +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.app.runtime.onLaunched.addListener(function() { - chrome.app.window.create('index.html', {width: 500, height: 500}); -});
diff --git a/tests/extensions/no_socket_permissions/manifest.json b/tests/extensions/no_socket_permissions/manifest.json deleted file mode 100644 index 939cd4b..0000000 --- a/tests/extensions/no_socket_permissions/manifest.json +++ /dev/null
@@ -1,11 +0,0 @@ -{ - "manifest_version": 2, - "name": "packaged_app_test", - "version": "0.1", - "description": "Packaged App test for Pepper", - "app": { - "background": { - "scripts": [ "main.js" ] - } - } -}
diff --git a/tests/extensions/no_socket_permissions/test_no_socket_permissions.cc b/tests/extensions/no_socket_permissions/test_no_socket_permissions.cc deleted file mode 100644 index b0ea677..0000000 --- a/tests/extensions/no_socket_permissions/test_no_socket_permissions.cc +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/cpp/udp_socket.h" -#include "ppapi/utility/completion_callback_factory.h" - -namespace { - -class MyInstance : public pp::Instance { - public: - explicit MyInstance(PP_Instance instance) - : pp::Instance(instance), - tcp_socket_(this), - udp_socket_(this), - factory_(this) {} - virtual ~MyInstance() {} - - void DidBindTCPSocket(int32_t result) { - // We should not be able to bind the TCP socket without permission. - if (result == PP_OK) { - PostMessage("FAIL"); - return; - } - PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1}}; - pp::NetAddress address(this, ipv4_address); - udp_socket_.Bind(address, - factory_.NewCallback(&MyInstance::DidBindUDPSocket)); - } - - void DidBindUDPSocket(int32_t result) { - // We should not be able to bind the UDP socket without permission. - if (result == PP_OK) - PostMessage("FAIL"); - else - PostMessage("PASS"); - } - - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) { - PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1}}; - pp::NetAddress address(this, ipv4_address); - tcp_socket_.Bind(address, - factory_.NewCallback(&MyInstance::DidBindTCPSocket)); - return true; - } - - private: - pp::TCPSocket tcp_socket_; - pp::UDPSocket udp_socket_; - pp::CompletionCallbackFactory<MyInstance> factory_; -}; - -class MyModule : public pp::Module { - public: - MyModule() : pp::Module() {} - virtual ~MyModule() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new MyInstance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new MyModule(); -} - -} // namespace pp
diff --git a/tests/extensions/packaged_app/controller.js b/tests/extensions/packaged_app/controller.js deleted file mode 100644 index 3f4a96b..0000000 --- a/tests/extensions/packaged_app/controller.js +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var control_message; - -function testAll() { - var nacl_module = document.getElementById('nacl_module'); - // The plugin will start the corresponding test and post a message back - // the test is done. If the test has failed, the message is a description - // of the error; otherwise the message is empty. - nacl_module.postMessage(control_message); -} - -var onControlMessageReceived = function(message) { - control_message = message; - chrome.test.runTests([testAll]); -} - -var pass_count = 0 -var onPluginMessageReceived = function(message) { - if (message.data == "PASS") { - pass_count++; - if (pass_count == 2) - chrome.test.sendMessage("PASS", onControlMessageReceived); - } else if (message.data) { - chrome.test.fail(message.data); - } -}; - -window.onload = function() { - var nacl_module = document.getElementById('nacl_module'); - nacl_module.addEventListener("message", onPluginMessageReceived, false); -};
diff --git a/tests/extensions/packaged_app/index.html b/tests/extensions/packaged_app/index.html deleted file mode 100644 index 73b2a70..0000000 --- a/tests/extensions/packaged_app/index.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>Packaged app test</title> - <script src="controller.js"></script> -</head> -<body> - <embed id="nacl_module" src="ppapi_tests_extensions_packaged_app.nmf" - type="application/x-nacl" /> -</body> -</html>
diff --git a/tests/extensions/packaged_app/main.js b/tests/extensions/packaged_app/main.js deleted file mode 100644 index 01da9fe..0000000 --- a/tests/extensions/packaged_app/main.js +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.app.runtime.onLaunched.addListener(function() { - chrome.app.window.create('index.html', {width: 500, height: 500}); -});
diff --git a/tests/extensions/packaged_app/manifest.json b/tests/extensions/packaged_app/manifest.json deleted file mode 100644 index 939cd4b..0000000 --- a/tests/extensions/packaged_app/manifest.json +++ /dev/null
@@ -1,11 +0,0 @@ -{ - "manifest_version": 2, - "name": "packaged_app_test", - "version": "0.1", - "description": "Packaged App test for Pepper", - "app": { - "background": { - "scripts": [ "main.js" ] - } - } -}
diff --git a/tests/extensions/packaged_app/test_file.txt b/tests/extensions/packaged_app/test_file.txt deleted file mode 100644 index 8e5ffd8..0000000 --- a/tests/extensions/packaged_app/test_file.txt +++ /dev/null
@@ -1 +0,0 @@ -Example contents for open_resource test \ No newline at end of file
diff --git a/tests/extensions/packaged_app/test_file2.txt b/tests/extensions/packaged_app/test_file2.txt deleted file mode 100644 index adcf813..0000000 --- a/tests/extensions/packaged_app/test_file2.txt +++ /dev/null
@@ -1 +0,0 @@ -Example contents for open_resource test2 \ No newline at end of file
diff --git a/tests/extensions/packaged_app/test_packaged_app.cc b/tests/extensions/packaged_app/test_packaged_app.cc deleted file mode 100644 index 8862a6d..0000000 --- a/tests/extensions/packaged_app/test_packaged_app.cc +++ /dev/null
@@ -1,169 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <pthread.h> -#include <stddef.h> -#include <stdint.h> -#include <unistd.h> - -#include <sstream> -#include <string> - -#include "native_client/src/untrusted/irt/irt.h" - -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/cpp/var.h" -#include "ppapi/utility/completion_callback_factory.h" - -namespace { - -std::string g_last_error; -pp::Instance* g_instance = NULL; - -// This should be larger than or equal to -// MessageAttachmentSet::kMaxDescriptorsPerMessage in -// ipc/ipc_message_attachment_set.h. -const size_t kMaxDescriptorsPerMessage = 16; - -// Returns true if the resource file whose name is |key| exists and its content -// matches |content|. -bool LoadManifestInternal(nacl_irt_resource_open* nacl_irt_resource_open, - const std::string& key, - const std::string& content) { - int desc; - int error; - error = nacl_irt_resource_open->open_resource(key.c_str(), &desc); - if (0 != error) { - g_last_error = "Can't open file " + key; - return false; - } - - std::string str; - - char buffer[4096]; - int len; - while ((len = read(desc, buffer, sizeof(buffer) - 1)) > 0) { - // Null terminate. - buffer[len] = '\0'; - str += buffer; - } - if (close(desc)) { - g_last_error = "Close failed: file=" + key; - return false; - } - - if (str != content) { - g_last_error = "Wrong file content: file=" + key + ", expected=" + content + - ", actual=" + str; - return false; - } - - return true; -} - -// Tests if open_resource works in a packaged app. This test is similar to -// NaClBrowserTest*.IrtManifestFile, but unlike the NaCl test, this one tests -// the "fast path" in DownloadNexe() in ppb_nacl_private_impl.cc which opens -// resource files without using URLLoader. -void LoadManifest() { - if (pthread_detach(pthread_self())) { - g_last_error = "pthread_detach failed"; - return; - } - - struct nacl_irt_resource_open nacl_irt_resource_open; - if (sizeof(nacl_irt_resource_open) != - nacl_interface_query(NACL_IRT_RESOURCE_OPEN_v0_1, - &nacl_irt_resource_open, - sizeof(nacl_irt_resource_open))) { - g_last_error = "NACL_IRT_RESOURCE_OPEN_v0_1 not found"; - return; - } - - for (size_t i = 0; i <= kMaxDescriptorsPerMessage; ++i) { - std::stringstream key; - key << "test_file" << i; - std::string content = "Example contents for open_resource test" + - std::string(i % 2 ? "2" : ""); - if (!LoadManifestInternal(&nacl_irt_resource_open, key.str(), content)) - break; - // Open the same resource file again to make sure each file descriptor - // returned from open_resource has its own file offset. - if (!LoadManifestInternal(&nacl_irt_resource_open, key.str(), content)) - break; - } -} - -void PostReply(void* user_data, int32_t status) { - if (!g_last_error.empty()) - g_instance->PostMessage(g_last_error.c_str()); - else - g_instance->PostMessage("PASS"); -} - -void* RunTestsOnBackgroundThread(void* thread_id) { - LoadManifest(); - pp::Module::Get()->core()->CallOnMainThread( - 0, pp::CompletionCallback(&PostReply, NULL)); - return NULL; -} - -class MyInstance : public pp::Instance { - public: - explicit MyInstance(PP_Instance instance) - : pp::Instance(instance), socket_(this), factory_(this) { - g_instance = this; - } - virtual ~MyInstance() { } - - void DidBindSocket(int32_t result) { - // We didn't ask for socket permission in our manifest, so it should fail. - if (result == PP_ERROR_NOACCESS) - PostMessage("PASS"); - else - PostMessage(result); - } - - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) { - pthread_t thread; - // irt_open_resource() isn't allowed to be called on the main thread once - // Pepper starts, so the test must happen on a background thread. - if (pthread_create(&thread, NULL, &RunTestsOnBackgroundThread, NULL)) { - g_last_error = "pthread_create failed"; - PostReply(NULL, 0); - } - // Attempt to bind a socket. We don't have permissions, so it should fail. - PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1} }; - pp::NetAddress address(this, ipv4_address); - socket_.Bind(address, factory_.NewCallback(&MyInstance::DidBindSocket)); - return true; - } - - private: - pp::TCPSocket socket_; - pp::CompletionCallbackFactory<MyInstance> factory_; -}; - -class MyModule : public pp::Module { - public: - MyModule() : pp::Module() { } - virtual ~MyModule() { } - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new MyInstance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new MyModule(); -} - -} // namespace pp
diff --git a/tests/extensions/popup/background.js b/tests/extensions/popup/background.js deleted file mode 100644 index 4c39fab..0000000 --- a/tests/extensions/popup/background.js +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Annoying hack: the test suite modifies the event page idle timeout to be -// 1 millisecond to avoid waiting multiple seconds for the event page to be -// torn down. However, tabs.create() will not wait for the tab to be *loaded* -// before returning. The test expects that the tab will keep the event page -// alive, which it will, but only after it commits to the extension origin. -// To work around this, keep the event page alive by consistently querying until -// it's finished loading (having an outstanding extension API function like -// tabs.get() will keep the page alive in the meantime). -async function waitForTabLoaded(tab) { - state = tab.status; - while (state !== 'complete') { - await new Promise((resolve) => { - chrome.tabs.get(tab.id, (updated) => { - state = updated.status; - resolve(); - }); - }); - } -} - -chrome.runtime.onInstalled.addListener(function() { - chrome.tabs.create({url: 'popup.html'}, (tab) => { - waitForTabLoaded(tab); - }); -});
diff --git a/tests/extensions/popup/manifest.json b/tests/extensions/popup/manifest.json deleted file mode 100644 index 8ce2a76..0000000 --- a/tests/extensions/popup/manifest.json +++ /dev/null
@@ -1,10 +0,0 @@ -{ - "name": "Create popup with NaCl embed for lazy background test", - "description": "Tests that a lazy background page is shut down as soon as a popup with a NaCl module is closed", - "version": "0", - "manifest_version": 2, - "background": { - "scripts": ["background.js"], - "persistent": false - } -}
diff --git a/tests/extensions/popup/module.cc b/tests/extensions/popup/module.cc deleted file mode 100644 index e9b09f1..0000000 --- a/tests/extensions/popup/module.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" - -namespace { - -class Module : public pp::Module { - public: - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new pp::Instance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new ::Module(); -} - -} // namespace pp
diff --git a/tests/extensions/popup/popup.html b/tests/extensions/popup/popup.html deleted file mode 100644 index 5f18ca7..0000000 --- a/tests/extensions/popup/popup.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>Popup with NaCl embed App test</title> - <script src="popup.js"></script> -</head> -<body> - <embed id="nacl_module" src="ppapi_tests_extensions_popup.nmf" - type="application/x-nacl" /> -</body> -</html>
diff --git a/tests/extensions/popup/popup.js b/tests/extensions/popup/popup.js deleted file mode 100644 index aa3055d..0000000 --- a/tests/extensions/popup/popup.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -function onModuleLoaded() { - chrome.test.notifyPass(); -} - -window.onload = function() { - var nacl_module = document.getElementById('nacl_module'); - nacl_module.addEventListener('load', onModuleLoaded, false); -};
diff --git a/tests/extensions/socket_permissions/controller.js b/tests/extensions/socket_permissions/controller.js deleted file mode 100644 index 921ad5f..0000000 --- a/tests/extensions/socket_permissions/controller.js +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var control_message; - -function testAll() { - var nacl_module = document.getElementById('nacl_module'); - // The plugin will start the corresponding test and post a message back - // the test is done. If the test has failed, the message is a description - // of the error; otherwise the message is empty. - nacl_module.postMessage(control_message); -} - -var onControlMessageReceived = function(message) { - control_message = message; - chrome.test.runTests([testAll]); -} - -var onPluginMessageReceived = function(message) { - if (message.data == "PASS") { - chrome.test.sendMessage("PASS", onControlMessageReceived); - } else if (message.data) { - chrome.test.fail(message.data); - } -}; - -window.onload = function() { - var nacl_module = document.getElementById('nacl_module'); - nacl_module.addEventListener("message", onPluginMessageReceived, false); -};
diff --git a/tests/extensions/socket_permissions/index.html b/tests/extensions/socket_permissions/index.html deleted file mode 100644 index 7d4cb9c..0000000 --- a/tests/extensions/socket_permissions/index.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>Socket permissions test</title> - <script src="controller.js"></script> -</head> -<body> - <embed id="nacl_module" src="ppapi_tests_extensions_socket_permissions.nmf" - type="application/x-nacl" /> -</body> -</html>
diff --git a/tests/extensions/socket_permissions/main.js b/tests/extensions/socket_permissions/main.js deleted file mode 100644 index 88db9f6..0000000 --- a/tests/extensions/socket_permissions/main.js +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.app.runtime.onLaunched.addListener(function() { - chrome.app.window.create('index.html', {width: 500, height: 500}); -});
diff --git a/tests/extensions/socket_permissions/manifest.json b/tests/extensions/socket_permissions/manifest.json deleted file mode 100644 index 29427cd..0000000 --- a/tests/extensions/socket_permissions/manifest.json +++ /dev/null
@@ -1,20 +0,0 @@ -{ - "manifest_version": 2, - "name": "packaged_app_test", - "version": "0.1", - "description": "Packaged App test for Pepper", - "app": { - "background": { - "scripts": [ "main.js" ] - } - }, - "permissions": [{"socket": ["tcp-connect", "udp-bind"]}], - "sockets": { - "tcp": { - "connect": "127.0.0.1:80" - }, - "udp": { - "bind": "127.0.0.1:80" - } - } -}
diff --git a/tests/extensions/socket_permissions/test_socket_permissions.cc b/tests/extensions/socket_permissions/test_socket_permissions.cc deleted file mode 100644 index 7a44fdc..0000000 --- a/tests/extensions/socket_permissions/test_socket_permissions.cc +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/cpp/udp_socket.h" -#include "ppapi/utility/completion_callback_factory.h" - -namespace { - -class MyInstance : public pp::Instance { - public: - explicit MyInstance(PP_Instance instance) - : pp::Instance(instance), - tcp_socket_(this), - udp_socket_(this), - udp_multicast_socket_(this), - factory_(this) {} - virtual ~MyInstance() { } - - void DidBindTCPSocket(int32_t result) { - // We should be able to bind the TCP socket with permission. - if (result != PP_OK) { - PostMessage(result); - return; - } - PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1}}; - pp::NetAddress address(this, ipv4_address); - udp_socket_.Bind(address, - factory_.NewCallback(&MyInstance::DidBindUDPSocket)); - } - - void DidBindUDPSocket(int32_t result) { - // We should be able to bind the UDP socket with permission. - if (result != PP_OK) { - PostMessage(result); - return; - } - // Close the socket by releasing it. - udp_socket_ = pp::UDPSocket(); - udp_multicast_socket_.SetOption( - PP_UDPSOCKET_OPTION_MULTICAST_LOOP, pp::Var(true), - factory_.NewCallback(&MyInstance::DidSetOptionMulticastUDPSocket)); - } - - void DidSetOptionMulticastUDPSocket(int32_t result) { - // We should be able to set the multicast option, even without permission. - if (result != PP_OK) { - PostMessage(result); - return; - } - PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1}}; - pp::NetAddress address(this, ipv4_address); - udp_multicast_socket_.Bind( - address, factory_.NewCallback(&MyInstance::DidBindMulticastUDPSocket)); - } - - void DidBindMulticastUDPSocket(int32_t result) { - // We should NOT be able to do UDP multicast without permission. - if (result == PP_OK) - PostMessage("FAIL"); - else - PostMessage("PASS"); - } - - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) { - PP_NetAddress_IPv4 ipv4_address = {80, {127, 0, 0, 1} }; - pp::NetAddress address(this, ipv4_address); - tcp_socket_.Bind(address, - factory_.NewCallback(&MyInstance::DidBindTCPSocket)); - return true; - } - - private: - pp::TCPSocket tcp_socket_; - pp::UDPSocket udp_socket_; - pp::UDPSocket udp_multicast_socket_; - pp::CompletionCallbackFactory<MyInstance> factory_; -}; - -class MyModule : public pp::Module { - public: - MyModule() : pp::Module() { } - virtual ~MyModule() { } - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new MyInstance(instance); - } -}; - -} // namespace - -namespace pp { - -Module* CreateModule() { - return new MyModule(); -} - -} // namespace pp
diff --git a/tests/manual/delete_plugin.cc b/tests/manual/delete_plugin.cc deleted file mode 100644 index 118c036..0000000 --- a/tests/manual/delete_plugin.cc +++ /dev/null
@@ -1,78 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/pp_input_event.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/trusted/ppb_instance_trusted.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/var_private.h" - -class MyInstance : public pp::Instance { - public: - MyInstance(PP_Instance instance) : pp::Instance(instance) { - factory_.Initialize(this); - } - - virtual ~MyInstance() { - } - - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) { - return true; - } - - virtual bool HandleInputEvent(const PP_InputEvent& event) { - switch (event.type) { - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - pp::Module::Get()->core()->CallOnMainThread(100, - factory_.NewCallback(&MyInstance::SayHello)); - return true; - case PP_INPUTEVENT_TYPE_MOUSEMOVE: - return true; - case PP_INPUTEVENT_TYPE_KEYDOWN: - return true; - default: - return false; - } - } - - private: - void SayHello(int32_t) { - pp::Var code("deletePlugin()"); - /* - When scripting is removed from instance, this is the code that will do the - same thing: - const PPB_Instance_Trusted* inst = - (const PPB_Instance_Trusted*)pp::Module::Get()->GetBrowserInterface( - PPB_INSTANCE_TRUSTED_INTERFACE); - inst->ExecuteScript(pp_instance(), code.pp_var(), NULL); - */ - ExecuteScript(code); - } - - pp::CompletionCallbackFactory<MyInstance> factory_; -}; - -class MyModule : public pp::Module { - public: - MyModule() : pp::Module() {} - virtual ~MyModule() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new MyInstance(instance); - } -}; - -namespace pp { - -// Factory function for your specialization of the Module object. -Module* CreateModule() { - return new MyModule(); -} - -} // namespace pp
diff --git a/tests/manual/delete_plugin.html b/tests/manual/delete_plugin.html deleted file mode 100644 index 9437c3d..0000000 --- a/tests/manual/delete_plugin.html +++ /dev/null
@@ -1,25 +0,0 @@ -<html><head><title> -<body> -<script type="text/javascript"> -function deletePlugin() { - // Remove the plugin. - document.getElementById('foo').removeChild(document.getElementById('plugin')); - - // Forces a style recalculation which actually will delete the plugin. - // Without this, the plugin would be deleted later from a timer. If the test - // fails, this line will cause the crash. - var foo = document.getElementById('foo').offsetWidth; - - // If we get here, there's no crash so we succeeded. - document.cookie = "COMPLETION_COOKIE=PASS; path=/"; -} -</script> - This test tests deleting a the <object> synchronously from within a - script call. Neither the proxy nor the PPAPI implementation should crash in - this case. - <div id="foo"> - <object id="plugin" type="application/x-ppapi-tests" width="400" height="400" style="border:5px solid blue;"> - <param name="customtest" value="delete_plugin"> - </object> - </div> -</body>
diff --git a/tests/pp_thread.h b/tests/pp_thread.h deleted file mode 100644 index c4d6361..0000000 --- a/tests/pp_thread.h +++ /dev/null
@@ -1,129 +0,0 @@ -/* Copyright 2011 The Chromium Authors - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef PPAPI_TESTS_PP_THREAD_H_ -#define PPAPI_TESTS_PP_THREAD_H_ - -#include "ppapi/c/pp_macros.h" -#include "ppapi/tests/test_utils.h" - -#if defined(PPAPI_POSIX) -#include <pthread.h> -#elif defined(PPAPI_OS_WIN) -#include <windows.h> - -#include <process.h> -#else -#error No thread library detected. -#endif - -/** - * @file - * This file provides platform-independent wrappers around threads. This is for - * use by PPAPI wrappers and tests which need to run on multiple platforms to - * support both trusted platforms (Windows, Mac, Linux) and untrusted (Native - * Client). Apps that use PPAPI only with Native Client should generally use the - * Native Client POSIX implementation instead. - * - * TODO(dmichael): Move this file to ppapi/c and delete this comment, if we end - * up needing platform independent threads in PPAPI C or C++. This file was - * written using inline functions and PPAPI naming conventions with the intent - * of making it possible to put it in to ppapi/c. Currently, however, it's only - * used in ppapi/tests, so is not part of the published API. - */ - -typedef void (PP_ThreadFunction)(void* data); - -#if defined(PPAPI_POSIX) -typedef pthread_t PP_Thread; -#elif defined(PPAPI_OS_WIN) -struct PP_Thread { - HANDLE handle; - PP_ThreadFunction* thread_func; - void* thread_arg; -}; -#endif - -PP_INLINE bool PP_CreateThread(PP_Thread* thread, - PP_ThreadFunction function, - void* thread_arg); -PP_INLINE void PP_JoinThread(PP_Thread thread); - -#if defined(PPAPI_POSIX) -/* Because POSIX thread functions return void* and Windows thread functions do - * not, we make PPAPI thread functions have the least capability (no returns). - * This struct wraps the user data & function so that we can use the correct - * function type on POSIX platforms. - */ -struct PP_ThreadFunctionArgWrapper { - void* user_data; - PP_ThreadFunction* user_function; -}; - -PP_INLINE void* PP_POSIXThreadFunctionThunk(void* posix_thread_arg) { - PP_ThreadFunctionArgWrapper* arg_wrapper = - (PP_ThreadFunctionArgWrapper*)posix_thread_arg; - arg_wrapper->user_function(arg_wrapper->user_data); - free(posix_thread_arg); - return NULL; -} - -PP_INLINE bool PP_CreateThread(PP_Thread* thread, - PP_ThreadFunction function, - void* thread_arg) { - PP_ThreadFunctionArgWrapper* arg_wrapper = - (PP_ThreadFunctionArgWrapper*)malloc(sizeof(PP_ThreadFunctionArgWrapper)); - arg_wrapper->user_function = function; - arg_wrapper->user_data = thread_arg; - return (pthread_create(thread, - NULL, - PP_POSIXThreadFunctionThunk, - arg_wrapper) == 0); -} - -PP_INLINE void PP_JoinThread(PP_Thread thread) { - void* exit_status; - pthread_join(thread, &exit_status); -} - -#elif defined(PPAPI_OS_WIN) - -PP_INLINE unsigned __stdcall PP_WindowsThreadFunction(void* param) { - PP_Thread* thread = reinterpret_cast<PP_Thread*>(param); - thread->thread_func(thread->thread_arg); - return 0; -} - -PP_INLINE bool PP_CreateThread(PP_Thread* thread, - PP_ThreadFunction function, - void* thread_arg) { - if (!thread) - return false; - thread->thread_func = function; - thread->thread_arg = thread_arg; - uintptr_t raw_handle = ::_beginthreadex(NULL, - 0, /* Use default stack size. */ - &PP_WindowsThreadFunction, - thread, - 0, - NULL); - thread->handle = reinterpret_cast<HANDLE>(raw_handle); - return (thread->handle != NULL); -} - -PP_INLINE void PP_JoinThread(PP_Thread thread) { - ::WaitForSingleObject(thread.handle, INFINITE); - ::CloseHandle(thread.handle); -} - -#endif - - -/** - * @} - */ - -#endif /* PPAPI_TESTS_PP_THREAD_H_ */ -
diff --git a/tests/ppapi_nacl_tests_newlib.nmf b/tests/ppapi_nacl_tests_newlib.nmf deleted file mode 100644 index ffeb778..0000000 --- a/tests/ppapi_nacl_tests_newlib.nmf +++ /dev/null
@@ -1,8 +0,0 @@ -{ - "program": { - "x86-64": {"url": "ppapi_nacl_tests_newlib_x64.nexe"}, - "x86-32": {"url": "ppapi_nacl_tests_newlib_x32.nexe"}, - "arm": {"url": "ppapi_nacl_tests_newlib_arm.nexe"}, - "mips32": {"url": "ppapi_nacl_tests_newlib_mips32.nexe"} - } -}
diff --git a/tests/test_audio.cc b/tests/test_audio.cc deleted file mode 100644 index 1684fb0..0000000 --- a/tests/test_audio.cc +++ /dev/null
@@ -1,549 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_audio.h" - -#include <stddef.h> -#include <string.h> - -#include "ppapi/c/ppb_audio.h" -#include "ppapi/c/ppb_audio_config.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -#if defined(__native_client__) -#include "native_client/src/untrusted/irt/irt.h" -#include "ppapi/native_client/src/untrusted/irt_stub/thread_creator.h" -#endif - -#define ARRAYSIZE_UNSAFE(a) \ - ((sizeof(a) / sizeof(*(a))) / \ - static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) - -#if defined(__native_client__) -namespace { - -void GetNaClIrtPpapiHook(struct nacl_irt_ppapihook* hooks) { - nacl_interface_query(NACL_IRT_PPAPIHOOK_v0_1, hooks, sizeof(*hooks)); -} - -struct PP_ThreadFunctions g_thread_funcs = {}; - -void ThreadFunctionsGetter(const struct PP_ThreadFunctions* thread_funcs) { - g_thread_funcs = *thread_funcs; -} - -// In order to check if the thread_create is called, CountingThreadCreate() -// increments this variable. Callers can check if the function is actually -// called by looking at this value. -int g_num_thread_create_called = 0; -int g_num_thread_join_called = 0; - -int CountingThreadCreate(uintptr_t* tid, - void (*func)(void* thread_argument), - void* thread_argument) { - ++g_num_thread_create_called; - return g_thread_funcs.thread_create(tid, func, thread_argument); -} - -int CountingThreadJoin(uintptr_t tid) { - ++g_num_thread_join_called; - return g_thread_funcs.thread_join(tid); -} - -// Sets NULL for PP_ThreadFunctions to emulate the situation that -// ppapi_register_thread_creator() is not yet called. -void SetNullThreadFunctions() { - nacl_irt_ppapihook hooks; - GetNaClIrtPpapiHook(&hooks); - PP_ThreadFunctions thread_functions = {}; - hooks.ppapi_register_thread_creator(&thread_functions); -} - -void InjectCountingThreadFunctions() { - // First of all, we extract the system default thread functions. - // Internally, __nacl_register_thread_creator calls - // hooks.ppapi_register_thread_creator with default PP_ThreadFunctions - // instance. ThreadFunctionGetter stores it to g_thread_funcs. - nacl_irt_ppapihook hooks = { NULL, ThreadFunctionsGetter }; - __nacl_register_thread_creator(&hooks); - - // Here g_thread_funcs stores the thread functions. - // Inject the CountingThreadCreate. - PP_ThreadFunctions thread_functions = { - CountingThreadCreate, - CountingThreadJoin, - }; - GetNaClIrtPpapiHook(&hooks); - hooks.ppapi_register_thread_creator(&thread_functions); -} - -// Resets the PP_ThreadFunctions on exit from the scope. -class ScopedThreadFunctionsResetter { - public: - ScopedThreadFunctionsResetter() {} - ~ScopedThreadFunctionsResetter() { - nacl_irt_ppapihook hooks; - GetNaClIrtPpapiHook(&hooks); - __nacl_register_thread_creator(&hooks); - } -}; - -} // namespace -#endif // __native_client__ - -REGISTER_TEST_CASE(Audio); - -TestAudio::TestAudio(TestingInstance* instance) - : TestCase(instance), - audio_callback_method_(NULL), - audio_callback_event_(instance->pp_instance()), - test_done_(false), - audio_interface_(NULL), - audio_interface_1_0_(NULL), - audio_config_interface_(NULL), - core_interface_(NULL) { -} - -TestAudio::~TestAudio() { -} - -bool TestAudio::Init() { - audio_interface_ = static_cast<const PPB_Audio_1_1*>( - pp::Module::Get()->GetBrowserInterface(PPB_AUDIO_INTERFACE_1_1)); - audio_interface_1_0_ = static_cast<const PPB_Audio_1_0*>( - pp::Module::Get()->GetBrowserInterface(PPB_AUDIO_INTERFACE_1_0)); - audio_config_interface_ = static_cast<const PPB_AudioConfig*>( - pp::Module::Get()->GetBrowserInterface(PPB_AUDIO_CONFIG_INTERFACE)); - core_interface_ = static_cast<const PPB_Core*>( - pp::Module::Get()->GetBrowserInterface(PPB_CORE_INTERFACE)); - return audio_interface_ && audio_interface_1_0_ && audio_config_interface_ && - core_interface_; -} - -void TestAudio::RunTests(const std::string& filter) { - RUN_TEST(Creation, filter); - RUN_TEST(DestroyNoStop, filter); - RUN_TEST(Failures, filter); - RUN_TEST(AudioCallback1, filter); - RUN_TEST(AudioCallback2, filter); - RUN_TEST(AudioCallback3, filter); - RUN_TEST(AudioCallback4, filter); - -#if defined(__native_client__) - RUN_TEST(AudioThreadCreatorIsRequired, filter); - RUN_TEST(AudioThreadCreatorIsCalled, filter); -#endif -} - -// Test creating audio resources for all guaranteed sample rates and various -// frame counts. -std::string TestAudio::TestCreation() { - static const PP_AudioSampleRate kSampleRates[] = { - PP_AUDIOSAMPLERATE_44100, - PP_AUDIOSAMPLERATE_48000 - }; - static const uint32_t kRequestFrameCounts[] = { - PP_AUDIOMINSAMPLEFRAMECOUNT, - PP_AUDIOMAXSAMPLEFRAMECOUNT, - // Include some "okay-looking" frame counts; check their validity below. - PP_AUDIOSAMPLERATE_44100 / 100, // 10ms @ 44.1kHz - PP_AUDIOSAMPLERATE_48000 / 100, // 10ms @ 48kHz - 2 * PP_AUDIOSAMPLERATE_44100 / 100, // 20ms @ 44.1kHz - 2 * PP_AUDIOSAMPLERATE_48000 / 100, // 20ms @ 48kHz - 1024, - 2048, - 4096 - }; - PP_AudioSampleRate sample_rate = audio_config_interface_->RecommendSampleRate( - instance_->pp_instance()); - ASSERT_TRUE(sample_rate == PP_AUDIOSAMPLERATE_NONE || - sample_rate == PP_AUDIOSAMPLERATE_44100 || - sample_rate == PP_AUDIOSAMPLERATE_48000); - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kSampleRates); i++) { - sample_rate = kSampleRates[i]; - - for (size_t j = 0; j < ARRAYSIZE_UNSAFE(kRequestFrameCounts); j++) { - // Make a config, create the audio resource, and release the config. - uint32_t request_frame_count = kRequestFrameCounts[j]; - uint32_t frame_count = audio_config_interface_->RecommendSampleFrameCount( - instance_->pp_instance(), sample_rate, request_frame_count); - PP_Resource ac = audio_config_interface_->CreateStereo16Bit( - instance_->pp_instance(), sample_rate, frame_count); - ASSERT_TRUE(ac); - PP_Resource audio = audio_interface_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - ASSERT_TRUE(audio); - ASSERT_TRUE(audio_interface_->IsAudio(audio)); - - // Check that the config returned for |audio| matches what we gave it. - ac = audio_interface_->GetCurrentConfig(audio); - ASSERT_TRUE(ac); - ASSERT_TRUE(audio_config_interface_->IsAudioConfig(ac)); - ASSERT_EQ(sample_rate, audio_config_interface_->GetSampleRate(ac)); - ASSERT_EQ(frame_count, audio_config_interface_->GetSampleFrameCount(ac)); - core_interface_->ReleaseResource(ac); - ac = 0; - - // Start and stop audio playback. The documentation indicates that - // |StartPlayback()| and |StopPlayback()| may fail, but gives no - // indication as to why ... so check that they succeed. - audio_callback_method_ = &TestAudio::AudioCallbackTrivial; - ASSERT_TRUE(audio_interface_->StartPlayback(audio)); - ASSERT_TRUE(audio_interface_->StopPlayback(audio)); - audio_callback_method_ = NULL; - - core_interface_->ReleaseResource(audio); - } - } - - PASS(); -} - -// Test that releasing the resource without calling |StopPlayback()| "works". -std::string TestAudio::TestDestroyNoStop() { - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 2048); - ASSERT_TRUE(ac); - audio_callback_method_ = NULL; - PP_Resource audio = audio_interface_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - ASSERT_TRUE(audio); - ASSERT_TRUE(audio_interface_->IsAudio(audio)); - - // Start playback and release the resource. - audio_callback_method_ = &TestAudio::AudioCallbackTrivial; - ASSERT_TRUE(audio_interface_->StartPlayback(audio)); - core_interface_->ReleaseResource(audio); - audio_callback_method_ = NULL; - - PASS(); -} - -std::string TestAudio::TestFailures() { - // Test invalid parameters to |Create()|. - - // We want a valid config for some of our tests of |Create()|. - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 2048); - ASSERT_TRUE(ac); - - // Failure cases should never lead to the callback being called. - audio_callback_method_ = NULL; - - // Invalid instance -> failure. - PP_Resource audio = audio_interface_->Create( - 0, ac, AudioCallbackTrampoline, this); - ASSERT_EQ(0, audio); - - // Invalid config -> failure. - audio = audio_interface_->Create( - instance_->pp_instance(), 0, AudioCallbackTrampoline, this); - ASSERT_EQ(0, audio); - - // Null callback -> failure. - audio = audio_interface_->Create( - instance_->pp_instance(), ac, NULL, NULL); - ASSERT_EQ(0, audio); - - core_interface_->ReleaseResource(ac); - ac = 0; - - // Test the other functions with an invalid audio resource. - ASSERT_FALSE(audio_interface_->IsAudio(0)); - ASSERT_EQ(0, audio_interface_->GetCurrentConfig(0)); - ASSERT_FALSE(audio_interface_->StartPlayback(0)); - ASSERT_FALSE(audio_interface_->StopPlayback(0)); - - PASS(); -} - -// NOTE: |TestAudioCallbackN| assumes that the audio callback is called at least -// once. If the audio stream does not start up correctly or is interrupted this -// may not be the case and these tests will fail. However, in order to properly -// test the audio callbacks, we must have a configuration where audio can -// successfully play, so we assume this is the case on bots. - -// This test starts playback and verifies that: -// 1) the audio callback is actually called; -// 2) that |StopPlayback()| waits for the audio callback to finish. -std::string TestAudio::TestAudioCallback1() { - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 1024); - ASSERT_TRUE(ac); - audio_callback_method_ = NULL; - PP_Resource audio = audio_interface_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - audio_callback_event_.Reset(); - test_done_ = false; - - audio_callback_method_ = &TestAudio::AudioCallbackTest; - ASSERT_TRUE(audio_interface_->StartPlayback(audio)); - - // Wait for the audio callback to be called. - audio_callback_event_.Wait(); - ASSERT_TRUE(audio_interface_->StopPlayback(audio)); - test_done_ = true; - - // If any more audio callbacks are generated, we should crash (which is good). - audio_callback_method_ = NULL; - - core_interface_->ReleaseResource(audio); - - PASS(); -} - -// This is the same as |TestAudioCallback1()|, except that instead of calling -// |StopPlayback()|, it just releases the resource. -std::string TestAudio::TestAudioCallback2() { - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 1024); - ASSERT_TRUE(ac); - audio_callback_method_ = NULL; - PP_Resource audio = audio_interface_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - audio_callback_event_.Reset(); - test_done_ = false; - - audio_callback_method_ = &TestAudio::AudioCallbackTest; - ASSERT_TRUE(audio_interface_->StartPlayback(audio)); - - // Wait for the audio callback to be called. - audio_callback_event_.Wait(); - - core_interface_->ReleaseResource(audio); - - test_done_ = true; - - // If any more audio callbacks are generated, we should crash (which is good). - audio_callback_method_ = NULL; - - PASS(); -} - -// This is the same as |TestAudioCallback1()|, except that it attempts a second -// round of |StartPlayback| and |StopPlayback| to make sure the callback -// function still responds when using the same audio resource. -std::string TestAudio::TestAudioCallback3() { - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 1024); - ASSERT_TRUE(ac); - audio_callback_method_ = NULL; - PP_Resource audio = audio_interface_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - audio_callback_event_.Reset(); - test_done_ = false; - - audio_callback_method_ = &TestAudio::AudioCallbackTest; - ASSERT_TRUE(audio_interface_->StartPlayback(audio)); - - // Wait for the audio callback to be called. - audio_callback_event_.Wait(); - - ASSERT_TRUE(audio_interface_->StopPlayback(audio)); - - // Repeat one more |StartPlayback| & |StopPlayback| cycle, and verify again - // that the callback function was invoked. - audio_callback_event_.Reset(); - ASSERT_TRUE(audio_interface_->StartPlayback(audio)); - - // Wait for the audio callback to be called. - audio_callback_event_.Wait(); - ASSERT_TRUE(audio_interface_->StopPlayback(audio)); - test_done_ = true; - - // If any more audio callbacks are generated, we should crash (which is good). - audio_callback_method_ = NULL; - - core_interface_->ReleaseResource(audio); - - PASS(); -} - -// This is the same as |TestAudioCallback1()|, except that it uses -// PPB_Audio_1_0. -std::string TestAudio::TestAudioCallback4() { - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 1024); - ASSERT_TRUE(ac); - audio_callback_method_ = NULL; - PP_Resource audio = audio_interface_1_0_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline1_0, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - audio_callback_event_.Reset(); - test_done_ = false; - - audio_callback_method_ = &TestAudio::AudioCallbackTest; - ASSERT_TRUE(audio_interface_1_0_->StartPlayback(audio)); - - // Wait for the audio callback to be called. - audio_callback_event_.Wait(); - ASSERT_TRUE(audio_interface_1_0_->StopPlayback(audio)); - test_done_ = true; - - // If any more audio callbacks are generated, we should crash (which is good). - audio_callback_method_ = NULL; - - core_interface_->ReleaseResource(audio); - - PASS(); -} - -#if defined(__native_client__) -// Tests the behavior of the thread_create functions. -// For PPB_Audio_Shared to work properly, the user code must call -// ppapi_register_thread_creator(). This test checks the error handling for the -// case when user code doesn't call ppapi_register_thread_creator(). -std::string TestAudio::TestAudioThreadCreatorIsRequired() { - // We'll inject some thread functions in this test case. - // Reset them at the end of this case. - ScopedThreadFunctionsResetter thread_resetter; - - // Set the thread functions to NULLs to emulate the situation where - // ppapi_register_thread_creator() is not called by user code. - SetNullThreadFunctions(); - - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 1024); - ASSERT_TRUE(ac); - audio_callback_method_ = NULL; - PP_Resource audio = audio_interface_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - // StartPlayback() fails, because no thread creating function - // is available. - ASSERT_FALSE(audio_interface_->StartPlayback(audio)); - - // If any more audio callbacks are generated, - // we should crash (which is good). - audio_callback_method_ = NULL; - - core_interface_->ReleaseResource(audio); - - PASS(); -} - -// Tests whether the thread functions passed from the user code are actually -// called. -std::string TestAudio::TestAudioThreadCreatorIsCalled() { - // We'll inject some thread functions in this test case. - // Reset them at the end of this case. - ScopedThreadFunctionsResetter thread_resetter; - - // Inject the thread counting function. In the injected function, - // when called, g_num_thread_create_called is incremented. - g_num_thread_create_called = 0; - g_num_thread_join_called = 0; - InjectCountingThreadFunctions(); - - PP_Resource ac = CreateAudioConfig(PP_AUDIOSAMPLERATE_44100, 1024); - ASSERT_TRUE(ac); - audio_callback_method_ = NULL; - PP_Resource audio = audio_interface_->Create( - instance_->pp_instance(), ac, AudioCallbackTrampoline, this); - core_interface_->ReleaseResource(ac); - ac = 0; - - audio_callback_event_.Reset(); - test_done_ = false; - - audio_callback_method_ = &TestAudio::AudioCallbackTest; - ASSERT_TRUE(audio_interface_->StartPlayback(audio)); - - // Wait for the audio callback to be called. - audio_callback_event_.Wait(); - // Here, the injected thread_create is called, but thread_join is not yet. - ASSERT_EQ(1, g_num_thread_create_called); - ASSERT_EQ(0, g_num_thread_join_called); - - ASSERT_TRUE(audio_interface_->StopPlayback(audio)); - - test_done_ = true; - - // Here, the injected thread_join is called. - ASSERT_EQ(1, g_num_thread_join_called); - - // If any more audio callbacks are generated, - // we should crash (which is good). - audio_callback_method_ = NULL; - - core_interface_->ReleaseResource(audio); - - PASS(); -} -#endif - -// TODO(raymes): Test that actually playback happens correctly, etc. - -static void Crash() { - *static_cast<volatile unsigned*>(NULL) = 0xdeadbeef; -} - -// static -void TestAudio::AudioCallbackTrampoline(void* sample_buffer, - uint32_t buffer_size_in_bytes, - PP_TimeDelta latency, - void* user_data) { - TestAudio* thiz = static_cast<TestAudio*>(user_data); - - // Crash if on the main thread. - if (thiz->core_interface_->IsMainThread()) - Crash(); - - AudioCallbackMethod method = thiz->audio_callback_method_; - (thiz->*method)(sample_buffer, buffer_size_in_bytes, latency); -} - -// static -void TestAudio::AudioCallbackTrampoline1_0(void* sample_buffer, - uint32_t buffer_size_in_bytes, - void* user_data) { - AudioCallbackTrampoline(sample_buffer, buffer_size_in_bytes, 0.0, user_data); -} - -void TestAudio::AudioCallbackTrivial(void* sample_buffer, - uint32_t buffer_size_in_bytes, - PP_TimeDelta latency) { - if (latency < 0) - Crash(); - - memset(sample_buffer, 0, buffer_size_in_bytes); -} - -void TestAudio::AudioCallbackTest(void* sample_buffer, - uint32_t buffer_size_in_bytes, - PP_TimeDelta latency) { - if (test_done_ || latency < 0) - Crash(); - - memset(sample_buffer, 0, buffer_size_in_bytes); - audio_callback_event_.Signal(); -} - -PP_Resource TestAudio::CreateAudioConfig( - PP_AudioSampleRate sample_rate, - uint32_t requested_sample_frame_count) { - uint32_t frame_count = audio_config_interface_->RecommendSampleFrameCount( - instance_->pp_instance(), sample_rate, requested_sample_frame_count); - return audio_config_interface_->CreateStereo16Bit( - instance_->pp_instance(), sample_rate, frame_count); -}
diff --git a/tests/test_audio.h b/tests/test_audio.h deleted file mode 100644 index abe8416..0000000 --- a/tests/test_audio.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_AUDIO_H_ -#define PPAPI_TESTS_TEST_AUDIO_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/c/ppb_audio.h" -#include "ppapi/c/ppb_audio_config.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/tests/test_case.h" - -class TestAudio : public TestCase { - public: - explicit TestAudio(TestingInstance* instance); - ~TestAudio(); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestCreation(); - std::string TestDestroyNoStop(); - std::string TestFailures(); - std::string TestAudioCallback1(); - std::string TestAudioCallback2(); - std::string TestAudioCallback3(); - std::string TestAudioCallback4(); - -#if defined(__native_client__) - std::string TestAudioThreadCreatorIsRequired(); - std::string TestAudioThreadCreatorIsCalled(); -#endif - - // Calls |audio_callback_method_| (where |user_data| is "this"). - static void AudioCallbackTrampoline(void* sample_buffer, - uint32_t buffer_size_in_bytes, - PP_TimeDelta latency, - void* user_data); - static void AudioCallbackTrampoline1_0(void* sample_buffer, - uint32_t buffer_size_in_bytes, - void* user_data); - - typedef void (TestAudio::*AudioCallbackMethod)(void* sample_buffer, - uint32_t buffer_size_in_bytes, - PP_TimeDelta latency); - - // Method called by |AudioCallbackTrampoline()|. Set only when the callback - // can't be running (before |StartPlayback()|, after |StopPlayback()| or - // releasing the last reference to the audio resource). - AudioCallbackMethod audio_callback_method_; - - // An |AudioCallbackMethod| that just clears |sample_buffer|. - void AudioCallbackTrivial(void* sample_buffer, - uint32_t buffer_size_in_bytes, - PP_TimeDelta latency); - - // |AudioCallbackMethod| used by |TestAudioCallbackN()|. - void AudioCallbackTest(void* sample_buffer, - uint32_t buffer_size_in_bytes, - PP_TimeDelta latency); - - PP_Resource CreateAudioConfig(PP_AudioSampleRate sample_rate, - uint32_t requested_sample_frame_count); - - // Used by |TestAudioCallbackN()|. - NestedEvent audio_callback_event_; - - bool test_done_; - - // Raw C-level interfaces, set in |Init()|; do not modify them elsewhere. - const PPB_Audio_1_1* audio_interface_; - const PPB_Audio_1_0* audio_interface_1_0_; - const PPB_AudioConfig* audio_config_interface_; - const PPB_Core* core_interface_; -}; - -#endif // PPAPI_TESTS_TEST_AUDIO_H_
diff --git a/tests/test_audio_config.cc b/tests/test_audio_config.cc deleted file mode 100644 index 4923d45..0000000 --- a/tests/test_audio_config.cc +++ /dev/null
@@ -1,116 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_audio_config.h" - -#include <stddef.h> -#include <stdint.h> - -#include "ppapi/c/ppb_audio_config.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(AudioConfig); - -bool TestAudioConfig::Init() { - audio_config_interface_ = static_cast<const PPB_AudioConfig*>( - pp::Module::Get()->GetBrowserInterface(PPB_AUDIO_CONFIG_INTERFACE)); - core_interface_ = static_cast<const PPB_Core*>( - pp::Module::Get()->GetBrowserInterface(PPB_CORE_INTERFACE)); - return audio_config_interface_ && core_interface_; -} - -void TestAudioConfig::RunTests(const std::string& filter) { - RUN_TEST(RecommendSampleRate, filter); - RUN_TEST(ValidConfigs, filter); - RUN_TEST(InvalidConfigs, filter); -} - -std::string TestAudioConfig::TestRecommendSampleRate() { - // Ask PPB_AudioConfig about the recommended sample rate. - PP_AudioSampleRate sample_rate = audio_config_interface_->RecommendSampleRate( - instance_->pp_instance()); - ASSERT_TRUE(sample_rate == PP_AUDIOSAMPLERATE_NONE || - sample_rate == PP_AUDIOSAMPLERATE_44100 || - sample_rate == PP_AUDIOSAMPLERATE_48000); - - PASS(); -} - -std::string TestAudioConfig::TestValidConfigs() { - static const PP_AudioSampleRate kSampleRates[] = { - PP_AUDIOSAMPLERATE_44100, - PP_AUDIOSAMPLERATE_48000 - }; - static const uint32_t kRequestFrameCounts[] = { - PP_AUDIOMINSAMPLEFRAMECOUNT, - PP_AUDIOMAXSAMPLEFRAMECOUNT, - // Include some "okay-looking" frame counts; check their validity below. - 1024, - 2048, - 4096 - }; - - for (size_t i = 0; i < sizeof(kSampleRates)/sizeof(kSampleRates[0]); i++) { - PP_AudioSampleRate sample_rate = kSampleRates[i]; - - for (size_t j = 0; - j < sizeof(kRequestFrameCounts)/sizeof(kRequestFrameCounts[0]); - j++) { - uint32_t request_frame_count = kRequestFrameCounts[j]; - ASSERT_TRUE(request_frame_count >= PP_AUDIOMINSAMPLEFRAMECOUNT); - ASSERT_TRUE(request_frame_count <= PP_AUDIOMAXSAMPLEFRAMECOUNT); - - uint32_t frame_count = audio_config_interface_->RecommendSampleFrameCount( - instance_->pp_instance(), sample_rate, request_frame_count); - ASSERT_TRUE(frame_count >= PP_AUDIOMINSAMPLEFRAMECOUNT); - ASSERT_TRUE(frame_count <= PP_AUDIOMAXSAMPLEFRAMECOUNT); - - PP_Resource ac = audio_config_interface_->CreateStereo16Bit( - instance_->pp_instance(), sample_rate, frame_count); - ASSERT_TRUE(ac); - ASSERT_TRUE(audio_config_interface_->IsAudioConfig(ac)); - ASSERT_EQ(sample_rate, audio_config_interface_->GetSampleRate(ac)); - ASSERT_EQ(frame_count, audio_config_interface_->GetSampleFrameCount(ac)); - - core_interface_->ReleaseResource(ac); - } - } - - PASS(); -} - -std::string TestAudioConfig::TestInvalidConfigs() { - // |PP_AUDIOSAMPLERATE_NONE| is not a valid rate, so this should fail. - PP_Resource ac = audio_config_interface_->CreateStereo16Bit( - instance_->pp_instance(), - PP_AUDIOSAMPLERATE_NONE, - PP_AUDIOMINSAMPLEFRAMECOUNT); - ASSERT_EQ(0, ac); - - // Test invalid frame counts. - ASSERT_TRUE(PP_AUDIOMINSAMPLEFRAMECOUNT >= 1); - ac = audio_config_interface_->CreateStereo16Bit( - instance_->pp_instance(), - PP_AUDIOSAMPLERATE_44100, - PP_AUDIOMINSAMPLEFRAMECOUNT - 1u); - ASSERT_EQ(0, ac); - ac = audio_config_interface_->CreateStereo16Bit( - instance_->pp_instance(), - PP_AUDIOSAMPLERATE_44100, - PP_AUDIOMAXSAMPLEFRAMECOUNT + 1u); - ASSERT_EQ(0, ac); - - // Test rest of API whose failure cases are defined. - ASSERT_FALSE(audio_config_interface_->IsAudioConfig(0)); - ASSERT_EQ(PP_AUDIOSAMPLERATE_NONE, audio_config_interface_->GetSampleRate(0)); - ASSERT_EQ(0u, audio_config_interface_->GetSampleFrameCount(0)); - - PASS(); -}
diff --git a/tests/test_audio_config.h b/tests/test_audio_config.h deleted file mode 100644 index 79e0b56..0000000 --- a/tests/test_audio_config.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_AUDIO_CONFIG_H_ -#define PPAPI_TESTS_TEST_AUDIO_CONFIG_H_ - -#include <string> - -#include "ppapi/c/ppb_audio_config.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/tests/test_case.h" - -class TestAudioConfig : public TestCase { - public: - explicit TestAudioConfig(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestRecommendSampleRate(); - std::string TestValidConfigs(); - std::string TestInvalidConfigs(); - - const PPB_AudioConfig* audio_config_interface_; - const PPB_Core* core_interface_; -}; - -#endif // PPAPI_TESTS_TEST_AUDIO_CONFIG_H_
diff --git a/tests/test_browser_font.cc b/tests/test_browser_font.cc deleted file mode 100644 index 0159ade..0000000 --- a/tests/test_browser_font.cc +++ /dev/null
@@ -1,211 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_browser_font.h" - -#include <stdint.h> -#include <string.h> - -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/trusted/browser_font_trusted.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(BrowserFont); - -bool TestBrowserFont::Init() { - return true; -} - -void TestBrowserFont::RunTests(const std::string& filter) { - RUN_TEST(FontFamilies, filter); - RUN_TEST(Measure, filter); - RUN_TEST(MeasureRTL, filter); - RUN_TEST(CharPos, filter); - // This test is disabled. It doesn't currently pass. See the - // CharacterOffsetForPixel API. - //RUN_TEST(CharPosRTL, filter); - RUN_TEST(Draw, filter); -} - -// Just tests that GetFontFamilies is hooked up & returns something. -std::string TestBrowserFont::TestFontFamilies() { - // This function is only supported out-of-process. - const PPB_Testing_Private* testing_interface = GetTestingInterface(); - if (testing_interface && !testing_interface->IsOutOfProcess()) - PASS(); - - pp::Var families = pp::BrowserFont_Trusted::GetFontFamilies(instance_); - - ASSERT_TRUE(families.is_string()); - ASSERT_TRUE(!families.AsString().empty()); - PASS(); -} - -// Tests that measuring text behaves reasonably. We aren't sure if the browser -// will be doing kerning or something for the particular default font, so we -// just make a string that we're pretty sure should be more than twice as long -// as another one, and verify that condition. -std::string TestBrowserFont::TestMeasure() { - pp::BrowserFontDescription desc; - pp::BrowserFont_Trusted font(instance_, desc); - - int32_t length1 = font.MeasureText(pp::BrowserFontTextRun("WWW")); - ASSERT_TRUE(length1 > 0); - int32_t length2 = font.MeasureText(pp::BrowserFontTextRun("WWWWWWWW")); - ASSERT_TRUE(length2 >= length1 * 2); - - // Fallback font test. - int32_t length3 = font.MeasureText(pp::BrowserFontTextRun("こんにちは")); - ASSERT_TRUE(length3 > 0); - - PASS(); -} - -std::string TestBrowserFont::TestMeasureRTL() { - pp::BrowserFontDescription desc; - pp::BrowserFont_Trusted font(instance_, desc); - - // Mixed string, two chars of LTR, two of RTL, then two of LTR. - // Note this is in UTF-8 so has more than 6 bytes. - std::string mixed("AB\xd7\x94\xd7\x97ZZ"); - const int kNumChars = 6; - pp::BrowserFontTextRun run(mixed); - - // Note that since this is UTF-8, the two RTL chars are two bytes each. - int32_t len[kNumChars]; - len[0] = font.PixelOffsetForCharacter(run, 0); - len[1] = font.PixelOffsetForCharacter(run, 1); - len[2] = font.PixelOffsetForCharacter(run, 2); - len[3] = font.PixelOffsetForCharacter(run, 3); - len[4] = font.PixelOffsetForCharacter(run, 4); - len[5] = font.PixelOffsetForCharacter(run, 5); - - // First three chars should be increasing. - ASSERT_TRUE(len[0] >= 0); - ASSERT_TRUE(len[1] > len[0]); - ASSERT_TRUE(len[3] > len[1]); - ASSERT_TRUE(len[2] > len[3]); - ASSERT_TRUE(len[4] > len[2]); - ASSERT_TRUE(len[5] > len[4]); - - // Test the same sequence with force LTR. The offsets should appear in - // sequence. - pp::BrowserFontTextRun forced_run(mixed, false, true); - len[0] = font.PixelOffsetForCharacter(forced_run, 0); - len[1] = font.PixelOffsetForCharacter(forced_run, 1); - len[2] = font.PixelOffsetForCharacter(forced_run, 2); - len[3] = font.PixelOffsetForCharacter(forced_run, 3); - len[4] = font.PixelOffsetForCharacter(forced_run, 4); - len[5] = font.PixelOffsetForCharacter(forced_run, 5); - for (int i = 1; i < kNumChars; i++) - ASSERT_TRUE(len[i] > len[i - 1]); - - PASS(); -} - -// Tests that the character/pixel offset functions correctly round-trip. -std::string TestBrowserFont::TestCharPos() { - pp::BrowserFontDescription desc; - pp::BrowserFont_Trusted font(instance_, desc); - - pp::BrowserFontTextRun run("Hello, world"); - uint32_t original_char = 3; - uint32_t pixel_offset = font.PixelOffsetForCharacter(run, original_char); - ASSERT_TRUE(pixel_offset > 0); - - uint32_t computed_char = font.CharacterOffsetForPixel( - run, static_cast<int32_t>(pixel_offset)); - ASSERT_TRUE(computed_char == original_char); - - PASS(); -} - -// Tests that we can get character positions in a mixed LTR/RTL run. -std::string TestBrowserFont::TestCharPosRTL() { - pp::BrowserFontDescription desc; - pp::BrowserFont_Trusted font(instance_, desc); - - // Mixed string, two chars of LTR, two of RTL, than two of LTR. - // Note this is in UTF-8 so has more than 6 bytes. - std::string mixed("AB\xd7\x94\xd7\x97ZZ"); - - pp::BrowserFontTextRun run(mixed); - static const int kNumChars = 6; - int expected_char_sequence[kNumChars] = { 0, 1, 3, 2, 4, 5 }; - - // Check that the characters appear in the order we expect. - int pixel_width = font.MeasureText(pp::BrowserFontTextRun(mixed)); - int last_sequence = 0; // Index into expected_char_sequence. - for (int x = 0; x < pixel_width; x++) { - int cur_char = font.CharacterOffsetForPixel(run, x); - if (cur_char != expected_char_sequence[last_sequence]) { - // This pixel has a different character. It should be the next one in - // the sequence for it to be correct. - last_sequence++; - ASSERT_TRUE(last_sequence < kNumChars); - ASSERT_TRUE(cur_char == expected_char_sequence[last_sequence]); - } - } - - // Try the same string with force LTR. The characters should all appear in - // sequence. - pp::BrowserFontTextRun forced_run(mixed, false, true); - int last_forced_char = 0; // Char index into the forced sequence. - for (int x = 0; x < pixel_width; x++) { - int cur_char = font.CharacterOffsetForPixel(forced_run, x); - if (cur_char != last_forced_char) { - last_forced_char++; - ASSERT_TRUE(cur_char == last_forced_char); - } - } - - PASS(); -} - -// Tests that drawing some text produces "some" output. -std::string TestBrowserFont::TestDraw() { - pp::BrowserFontDescription desc; - desc.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE); - desc.set_size(10); - pp::BrowserFont_Trusted font(instance_, desc); - - const pp::Size kSize(30, 10); - pp::ImageData image(instance_, - PP_IMAGEDATAFORMAT_BGRA_PREMUL, // 0xAARRGGBB - kSize, - false); // init_to_zero - ASSERT_FALSE(image.is_null()); - - // Draw black text on white canvas. - memset(image.data(), 0xFF, 4 * kSize.GetArea()); - font.DrawSimpleText(&image, - "Hello", - pp::Point(0, 10), // Baseline position. - 0xFF000000, // Black text. - true); // image_data_is_opaque. - - // Expect that at least a few pixels are non-white (text). - // Due to blending, there may be rounding errors and - // checking for exact black may not be correct. - // Also expect that all pixels are opaque. - const uint32_t kRGBMask = 0x00FFFFFF; - const uint32_t kAlphaMask = 0xFF000000; - int text_pixels = 0, opaque_pixels = 0; - const uint32_t* pixels = static_cast<const uint32_t*>(image.data()); - for (int i = 0; i < kSize.GetArea(); ++i) { - if ((pixels[i] & kRGBMask) != kRGBMask) - ++text_pixels; - if ((pixels[i] & kAlphaMask) == kAlphaMask) - ++opaque_pixels; - } - ASSERT_GT(text_pixels, 0); - ASSERT_EQ(opaque_pixels, kSize.GetArea()); - PASS(); -}
diff --git a/tests/test_browser_font.h b/tests/test_browser_font.h deleted file mode 100644 index 47b7466..0000000 --- a/tests/test_browser_font.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_BROWSER_FONT_H_ -#define PPAPI_TESTS_TEST_BROWSER_FONT_H_ - -#include "ppapi/tests/test_case.h" - -class TestBrowserFont : public TestCase { - public: - TestBrowserFont(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestFontFamilies(); - std::string TestMeasure(); - std::string TestMeasureRTL(); - std::string TestCharPos(); - std::string TestCharPosRTL(); - std::string TestDraw(); -}; - -#endif // PPAPI_TESTS_TEST_BROWSER_FONT_H_
diff --git a/tests/test_buffer.cc b/tests/test_buffer.cc deleted file mode 100644 index cb3e410..0000000 --- a/tests/test_buffer.cc +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_buffer.h" - -#include <stdint.h> - -#include "ppapi/c/dev/ppb_buffer_dev.h" -#include "ppapi/cpp/dev/buffer_dev.h" -#include "ppapi/cpp/graphics_2d.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(Buffer); - -bool TestBuffer::Init() { - buffer_interface_ = static_cast<const PPB_Buffer_Dev*>( - pp::Module::Get()->GetBrowserInterface(PPB_BUFFER_DEV_INTERFACE)); - return !!buffer_interface_; -} - -void TestBuffer::RunTests(const std::string& filter) { - RUN_TEST(InvalidSize, filter); - RUN_TEST(InitToZero, filter); - RUN_TEST(IsBuffer, filter); - RUN_TEST(BasicLifeCycle, filter); -} - -std::string TestBuffer::TestInvalidSize() { - pp::Buffer_Dev zero_size(instance_, 0); - if (!zero_size.is_null()) - return "Zero size accepted"; - - PASS(); -} - -std::string TestBuffer::TestInitToZero() { - pp::Buffer_Dev buffer(instance_, 100); - if (buffer.is_null()) - return "Could not create buffer"; - - if (buffer.size() != 100) - return "Buffer size not as expected"; - - // Now check that everything is 0. - unsigned char* bytes = static_cast<unsigned char *>(buffer.data()); - for (uint32_t index = 0; index < buffer.size(); index++) { - if (bytes[index] != 0) - return "Buffer isn't entirely zero"; - } - - PASS(); -} - -std::string TestBuffer::TestIsBuffer() { - // Test that a NULL resource isn't a buffer. - pp::Resource null_resource; - if (buffer_interface_->IsBuffer(null_resource.pp_resource())) - return "Null resource was reported as a valid buffer"; - - // Make another resource type and test it. - const int w = 16, h = 16; - pp::Graphics2D device(instance_, pp::Size(w, h), true); - if (device.is_null()) - return "Couldn't create device context"; - if (buffer_interface_->IsBuffer(device.pp_resource())) - return "Device context was reported as a buffer"; - - // Make a valid buffer. - pp::Buffer_Dev buffer(instance_, 100); - if (buffer.is_null()) - return "Couldn't create buffer"; - if (!buffer_interface_->IsBuffer(buffer.pp_resource())) - return "Buffer should be identified as a buffer"; - - PASS(); -} - -std::string TestBuffer::TestBasicLifeCycle() { - enum { kBufferSize = 100 }; - - pp::Buffer_Dev *buffer = new pp::Buffer_Dev(instance_, kBufferSize); - if (buffer->is_null() || - !buffer_interface_->IsBuffer(buffer->pp_resource()) || - buffer->size() != kBufferSize) { - return "Error creating buffer (earlier test should have failed)"; - } - - // Test that the buffer got created & mapped. - if (buffer->data() == NULL) - return "Failed to Map() buffer"; - - // Test that the buffer is writeable. - char* data = static_cast<char*>(buffer->data()); - for (int i = 0; i < kBufferSize; ++i) - data[i] = 'X'; - - // Implicitly test that the copy constructor doesn't cause a double-unmap on - // delete. - pp::Buffer_Dev* copy = new pp::Buffer_Dev(*buffer); - - // Implicitly test that destroying the buffer doesn't encounter a fatal error - // in Unmap. - delete buffer; - - // Test that we can still write to copy's copy of the data. - char* copy_data = static_cast<char*>(copy->data()); - for (int i = 0; i < kBufferSize; ++i) - copy_data[i] = 'Y'; - - delete copy; - - PASS(); -}
diff --git a/tests/test_buffer.h b/tests/test_buffer.h deleted file mode 100644 index 37509b8..0000000 --- a/tests/test_buffer.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_BUFFER_H_ -#define PPAPI_TESTS_TEST_BUFFER_H_ - -#include <string> - -#include "ppapi/c/dev/ppb_buffer_dev.h" -#include "ppapi/tests/test_case.h" - -class TestBuffer : public TestCase { - public: - explicit TestBuffer(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestInvalidSize(); - std::string TestInitToZero(); - std::string TestIsBuffer(); - std::string TestBasicLifeCycle(); - - // Used by the tests that access the C API directly. - const PPB_Buffer_Dev* buffer_interface_; -}; - -#endif // PPAPI_TESTS_TEST_BUFFER_H_
diff --git a/tests/test_c_includes.c b/tests/test_c_includes.c deleted file mode 100644 index 1df001e..0000000 --- a/tests/test_c_includes.c +++ /dev/null
@@ -1,10 +0,0 @@ -/* Copyright 2010 The Chromium Authors - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - * - * This test simply includes all the C headers to ensure they compile with a - * C compiler. If it compiles, it passes. - */ - -#include "ppapi/tests/all_c_includes.h" -
diff --git a/tests/test_case.cc b/tests/test_case.cc deleted file mode 100644 index 71f3052..0000000 --- a/tests/test_case.cc +++ /dev/null
@@ -1,263 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_case.h" - -#include <stddef.h> -#include <string.h> - -#include <algorithm> -#include <sstream> - -#include "ppapi/cpp/core.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/pp_thread.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -std::string StripPrefix(const std::string& test_name) { - if (test_name.find("DISABLED_") == 0) - return test_name.substr(strlen("DISABLED_")); - return test_name; -} - -// Strip the TestCase name off and return the remainder (i.e., everything after -// '_'). If there is no '_', assume only the TestCase was provided, and return -// an empty string. -// For example: -// StripTestCase("TestCase_TestName"); -// returns -// "TestName" -// while -// StripTestCase("TestCase); -// returns -// "" -std::string StripTestCase(const std::string& full_test_name) { - size_t delim = full_test_name.find_first_of('_'); - if (delim != std::string::npos) - return full_test_name.substr(delim+1); - // In this case, our "filter" is the empty string; the full test name is the - // same as the TestCase name with which we were constructed. - // TODO(dmichael): It might be nice to be able to PP_DCHECK against the - // TestCase class name, but we'd have to plumb that name to TestCase somehow. - return std::string(); -} - -// Parse |test_filter|, which is a comma-delimited list of (possibly prefixed) -// test names and insert the un-prefixed names into |remaining_tests|, with -// the bool indicating whether the test should be run. -void ParseTestFilter(const std::string& test_filter, - std::map<std::string, bool>* remaining_tests) { - // We can't use base/strings/string_util.h::Tokenize in ppapi, so we have to - // do it ourselves. - std::istringstream filter_stream(test_filter); - std::string current_test; - while (std::getline(filter_stream, current_test, ',')) { - // |current_test| might include a prefix, like DISABLED_Foo_TestBar, so we - // we strip it off if there is one. - std::string stripped_test_name(StripPrefix(current_test)); - // Strip off the test case and use the test name as a key, because the test - // name ShouldRunTest wants to use to look up the test doesn't have the - // TestCase name. - std::string test_name_without_case(StripTestCase(stripped_test_name)); - - // If the test wasn't prefixed, it should be run. - bool should_run_test = (current_test == stripped_test_name); - PP_DCHECK(remaining_tests->count(test_name_without_case) == 0); - remaining_tests->insert( - std::make_pair(test_name_without_case, should_run_test)); - } - // There may be a trailing comma; ignore empty strings. - remaining_tests->erase(std::string()); -} - -} // namespace - -TestCase::TestCase(TestingInstance* instance) - : instance_(instance), - testing_interface_(NULL), - callback_type_(PP_REQUIRED), - have_populated_filter_tests_(false) { - // Get the testing_interface_ if it is available, so that we can do Resource - // and Var checks on shutdown (see CheckResourcesAndVars). If it is not - // available, testing_interface_ will be NULL. Some tests do not require it. - testing_interface_ = GetTestingInterface(); -} - -TestCase::~TestCase() { -} - -bool TestCase::Init() { - return true; -} - -// static -std::string TestCase::MakeFailureMessage(const char* file, - int line, - const char* cmd) { - std::ostringstream output; - output << "Failure in " << file << "(" << line << "): " << cmd; - return output.str(); -} - -#if !(defined __native_client__) -pp::VarPrivate TestCase::GetTestObject() { - if (test_object_.is_undefined()) { - pp::deprecated::ScriptableObject* so = CreateTestObject(); - if (so) { - test_object_ = pp::VarPrivate(instance_, so); // Takes ownership. - // CheckResourcesAndVars runs and looks for leaks before we've actually - // completely shut down. Ignore the instance object, since it's not a real - // leak. - IgnoreLeakedVar(test_object_.pp_var().value.as_id); - } - } - return test_object_; -} -#endif - -bool TestCase::CheckTestingInterface() { - testing_interface_ = GetTestingInterface(); - if (!testing_interface_) { - // Give a more helpful error message for the testing interface being gone - // since that needs special enabling in Chrome. - instance_->AppendError("This test needs the testing interface, which is " - "not currently available. In Chrome, use " - "--enable-pepper-testing when launching."); - return false; - } - - return true; -} - -void TestCase::HandleMessage(const pp::Var& message_data) { -} - -void TestCase::DidChangeView(const pp::View& view) { -} - -bool TestCase::HandleInputEvent(const pp::InputEvent& event) { - return false; -} - -void TestCase::IgnoreLeakedVar(int64_t id) { - ignored_leaked_vars_.insert(id); -} - -#if !(defined __native_client__) -pp::deprecated::ScriptableObject* TestCase::CreateTestObject() { - return NULL; -} -#endif - -bool TestCase::EnsureRunningOverHTTP() { - if (instance_->protocol() != "http:") { - instance_->AppendError("This test needs to be run over HTTP."); - return false; - } - - return true; -} - -bool TestCase::ShouldRunAllTests(const std::string& filter) { - // If only the TestCase is listed, we're running all the tests in RunTests. - return (StripTestCase(filter) == std::string()); -} - -bool TestCase::ShouldRunTest(const std::string& test_name, - const std::string& filter) { - if (ShouldRunAllTests(filter)) - return true; - - // Lazily initialize our "filter_tests_" map. - if (!have_populated_filter_tests_) { - ParseTestFilter(filter, &filter_tests_); - remaining_tests_ = filter_tests_; - have_populated_filter_tests_ = true; - } - std::map<std::string, bool>::iterator iter = filter_tests_.find(test_name); - if (iter == filter_tests_.end()) { - // The test name wasn't listed in the filter. Don't run it, but store it - // so TestingInstance::ExecuteTests can report an error later. - skipped_tests_.insert(test_name); - return false; - } - remaining_tests_.erase(test_name); - return iter->second; -} - -PP_TimeTicks TestCase::NowInTimeTicks() { - return pp::Module::Get()->core()->GetTimeTicks(); -} - -std::string TestCase::CheckResourcesAndVars(std::string errors) { - if (!errors.empty()) - return errors; - - if (testing_interface_) { - // TODO(dmichael): Fix tests that leak resources and enable the following: - /* - uint32_t leaked_resources = - testing_interface_->GetLiveObjectsForInstance(instance_->pp_instance()); - if (leaked_resources) { - std::ostringstream output; - output << "FAILED: Test leaked " << leaked_resources << " resources.\n"; - errors += output.str(); - } - */ - const int kVarsToPrint = 100; - PP_Var vars[kVarsToPrint]; - int found_vars = testing_interface_->GetLiveVars(vars, kVarsToPrint); - // This will undercount if we are told to ignore a Var which is then *not* - // leaked. Worst case, we just won't print the little "Test leaked" message, - // but we'll still print any non-ignored leaked vars we found. - int leaked_vars = - found_vars - static_cast<int>(ignored_leaked_vars_.size()); - if (leaked_vars > 0) { - std::ostringstream output; - output << "Test leaked " << leaked_vars << " vars (printing at most " - << kVarsToPrint <<"):<p>"; - errors += output.str(); - } - for (int i = 0; i < std::min(found_vars, kVarsToPrint); ++i) { - pp::Var leaked_var(pp::PASS_REF, vars[i]); - if (ignored_leaked_vars_.count(leaked_var.pp_var().value.as_id) == 0) - errors += leaked_var.DebugString() + "<p>"; - } - } - return errors; -} - -// static -void TestCase::QuitMainMessageLoop(PP_Instance instance) { - PP_Instance* heap_instance = new PP_Instance(instance); - pp::CompletionCallback callback(&DoQuitMainMessageLoop, heap_instance); - pp::Module::Get()->core()->CallOnMainThread(0, callback); -} - -// static -void TestCase::DoQuitMainMessageLoop(void* pp_instance, int32_t result) { - PP_Instance* instance = static_cast<PP_Instance*>(pp_instance); - GetTestingInterface()->QuitMessageLoop(*instance); - delete instance; -} - -void TestCase::RunOnThreadInternal( - void (*thread_func)(void*), - void* thread_param, - const PPB_Testing_Private* testing_interface) { - PP_Thread thread; - PP_CreateThread(&thread, thread_func, thread_param); - // Run a message loop so pepper calls can be dispatched. The background - // thread will set result_ and make us Quit when it's done. - testing_interface->RunMessageLoop(instance_->pp_instance()); - PP_JoinThread(thread); -}
diff --git a/tests/test_case.h b/tests/test_case.h deleted file mode 100644 index 43c30e9..0000000 --- a/tests/test_case.h +++ /dev/null
@@ -1,745 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_CASE_H_ -#define PPAPI_TESTS_TEST_CASE_H_ - -#include <stdint.h> - -#include <cmath> -#include <limits> -#include <map> -#include <set> -#include <sstream> -#include <string> - -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_time.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/message_loop.h" -#include "ppapi/cpp/view.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -#if (defined __native_client__) -#include "ppapi/cpp/var.h" -#else -#include "ppapi/cpp/private/var_private.h" -#endif - -class TestingInstance; - -namespace pp { -namespace deprecated { -class ScriptableObject; -} -} - -// Individual classes of tests derive from this generic test case. -class TestCase { - public: - explicit TestCase(TestingInstance* instance); - virtual ~TestCase(); - - // Optionally override to do testcase specific initialization. - // Default implementation just returns true. - virtual bool Init(); - - // Override to implement the test case. It will be called after the plugin is - // first displayed, passing a string. If the string is empty, RunTests should - // run all tests for this test case. Otherwise, it must be a comma-delimited - // list of test names, possibly prefixed. E.g.: - // "Foo_GoodTest,DISABLED_Foo_BadTest,Foo_OtherGoodTest" - // All listed tests which are not prefixed will be run. - // - // This should generally be implemented in a TestCase subclass using the - // RUN_TEST* macros. - virtual void RunTests(const std::string& test_filter) = 0; - - static std::string MakeFailureMessage(const char* file, int line, - const char* cmd); - -#if !(defined __native_client__) - // Returns the scriptable test object for the current test, if any. - // Internally, this uses CreateTestObject which each test overrides. - pp::VarPrivate GetTestObject(); - void ResetTestObject() { test_object_ = pp::VarPrivate(); } -#endif - - // A function that is invoked whenever HandleMessage is called on the - // associated TestingInstance. Default implementation does nothing. TestCases - // that want to handle incoming postMessage events should override this - // method. - virtual void HandleMessage(const pp::Var& message_data); - - // A function that is invoked whenever DidChangeView is called on the - // associated TestingInstance. Default implementation does nothing. TestCases - // that want to handle view changes should override this method. - virtual void DidChangeView(const pp::View& view); - - // A function that is invoked whenever HandleInputEvent is called on the - // associated TestingInstance. Default implementation returns false. TestCases - // that want to handle view changes should override this method. - virtual bool HandleInputEvent(const pp::InputEvent& event); - - void IgnoreLeakedVar(int64_t id); - - TestingInstance* instance() { return instance_; } - - const PPB_Testing_Private* testing_interface() { return testing_interface_; } - - static void QuitMainMessageLoop(PP_Instance instance); - - const std::map<std::string, bool>& remaining_tests() { - return remaining_tests_; - } - const std::set<std::string>& skipped_tests() { - return skipped_tests_; - } - - protected: -#if !(defined __native_client__) - // Overridden by each test to supply a ScriptableObject corresponding to the - // test. There can only be one object created for all tests in a given class, - // so be sure your object is designed to be re-used. - // - // This object should be created on the heap. Ownership will be passed to the - // caller. Return NULL if there is no supported test object (the default). - virtual pp::deprecated::ScriptableObject* CreateTestObject(); -#endif - - // Checks whether the testing interface is available. Returns true if it is, - // false otherwise. If it is not available, adds a descriptive error. This is - // for use by tests that require the testing interface. - bool CheckTestingInterface(); - - // Makes sure the test is run over HTTP. - bool EnsureRunningOverHTTP(); - - // Returns true if |filter| only contains a TestCase name, which normally - // means "run all tests". Some TestCases require special setup for individual - // tests, and can use this function to decide whether to ignore those tests. - bool ShouldRunAllTests(const std::string& filter); - - // Return true if the given test name matches the filter. This is true if - // (a) filter is empty or (b) test_name matches a test name listed in filter - // exactly. - bool ShouldRunTest(const std::string& test_name, const std::string& filter); - - // Check for leaked resources and vars at the end of the test. If any exist, - // return a string with some information about the error. Otherwise, return - // an empty string. - // - // You should pass the error string from the test so far; if it is non-empty, - // CheckResourcesAndVars will do nothing and return the same string. - std::string CheckResourcesAndVars(std::string errors); - - PP_TimeTicks NowInTimeTicks(); - - // Run the given test method on a background thread and return the result. - template <class T> - std::string RunOnThread(std::string(T::*test_to_run)()) { - if (!testing_interface_) { - return "Testing blocking callbacks requires the testing interface. In " - "Chrome, use the --enable-pepper-testing flag."; - } - // These tests are only valid if running out-of-process (threading is not - // supported in-process). For in-process, just consider it a pass. - if (!testing_interface_->IsOutOfProcess()) - return std::string(); - pp::MessageLoop background_loop(instance_); - ThreadedTestRunner<T> runner(instance_->pp_instance(), - static_cast<T*>(this), test_to_run, background_loop); - RunOnThreadInternal(&ThreadedTestRunner<T>::ThreadFunction, &runner, - testing_interface_); - return runner.result(); - } - - // Pointer to the instance that owns us. - TestingInstance* instance_; - - // NULL unless InitTestingInterface is called. - const PPB_Testing_Private* testing_interface_; - - void set_callback_type(CallbackType callback_type) { - callback_type_ = callback_type; - } - CallbackType callback_type() const { - return callback_type_; - } - - private: - template <class T> - class ThreadedTestRunner { - public: - typedef std::string(T::*TestMethodType)(); - ThreadedTestRunner(PP_Instance instance, - T* test_case, - TestMethodType test_to_run, - pp::MessageLoop loop) - : instance_(instance), - test_case_(test_case), - test_to_run_(test_to_run), - loop_(loop) { - } - const std::string& result() { return result_; } - static void ThreadFunction(void* runner) { - static_cast<ThreadedTestRunner<T>*>(runner)->Run(); - } - - private: - void Run() { - int32_t result = loop_.AttachToCurrentThread(); - static_cast<void>(result); // result is not used in the RELEASE build. - PP_DCHECK(PP_OK == result); - result_ = (test_case_->*test_to_run_)(); - // Now give the loop a chance to clean up. - loop_.PostQuit(true /* should_destroy */); - loop_.Run(); - // Tell the main thread to quit its nested run loop, now that the test - // is complete. - TestCase::QuitMainMessageLoop(instance_); - } - - std::string result_; - PP_Instance instance_; - T* test_case_; - TestMethodType test_to_run_; - pp::MessageLoop loop_; - }; - - // The internals for RunOnThread. This allows us to avoid including - // pp_thread.h in this header file, since it includes system headers like - // windows.h. - // RunOnThreadInternal launches a new thread to run |thread_func|, waits - // for it to complete using RunMessageLoop(), then joins. - void RunOnThreadInternal(void (*thread_func)(void*), - void* thread_param, - const PPB_Testing_Private* testing_interface); - - static void DoQuitMainMessageLoop(void* pp_instance, int32_t result); - - // Passed when creating completion callbacks in some tests. This determines - // what kind of callback we use for the test. - CallbackType callback_type_; - - // Var ids that should be ignored when checking for leaks on shutdown. - std::set<int64_t> ignored_leaked_vars_; - - // The tests that were found in test_filter. The bool indicates whether the - // test should be run (i.e., it will be false if the test name was prefixed in - // the test_filter string). - // - // This is initialized lazily the first time that ShouldRunTest is called. - std::map<std::string, bool> filter_tests_; - // Flag indicating whether we have populated filter_tests_ yet. - bool have_populated_filter_tests_; - // This is initialized with the contents of filter_tests_. As each test is - // run, it is removed from remaining_tests_. When RunTests is finished, - // remaining_tests_ should be empty. Any remaining tests are tests that were - // listed in the test_filter but didn't match any calls to ShouldRunTest, - // meaning it was probably a typo. TestingInstance should log this and - // consider it a failure. - std::map<std::string, bool> remaining_tests_; - - // If ShouldRunTest is called but the given test name doesn't match anything - // in the test_filter, the test name will be added here. This allows - // TestingInstance to detect when not all tests were listed. - std::set<std::string> skipped_tests_; - -#if !(defined __native_client__) - // Holds the test object, if any was retrieved from CreateTestObject. - pp::VarPrivate test_object_; -#endif -}; - -// This class is an implementation detail. -class TestCaseFactory { - public: - typedef TestCase* (*Method)(TestingInstance* instance); - - TestCaseFactory(const char* name, Method method) - : next_(head_), - name_(name), - method_(method) { - head_ = this; - } - - private: - friend class TestingInstance; - - TestCaseFactory* next_; - const char* name_; - Method method_; - - static TestCaseFactory* head_; -}; - -namespace internal { - -// The internal namespace contains implementation details that are used by -// the ASSERT macros. - -// This base class provides a ToString that works for classes that can be -// converted to a string using std::stringstream. Later, we'll do -// specializations for types that we know will work with this approach. -template <class T> -struct StringinatorBase { - static std::string ToString(const T& value) { - std::stringstream stream; - stream << value; - return stream.str(); - } - protected: - // Not implemented, do not use. - // Note, these are protected because Windows complains if I make these private - // and then inherit StringinatorBase (even though they're never used). - StringinatorBase(); - ~StringinatorBase(); -}; - -// This default class template is for types that we don't recognize as -// something we can convert into a string using stringstream. Types that we -// know *can* be turned to a string should have specializations below. -template <class T> -struct Stringinator { - static std::string ToString(const T& value) { - return std::string(); - } - private: - // Not implemented, do not use. - Stringinator(); - ~Stringinator(); -}; - -// Define some full specializations for types that can just use stringstream. -#define DEFINE_STRINGINATOR_FOR_TYPE(type) \ - template <> \ - struct Stringinator<type> : public StringinatorBase<type> {} -DEFINE_STRINGINATOR_FOR_TYPE(int32_t); -DEFINE_STRINGINATOR_FOR_TYPE(uint32_t); -DEFINE_STRINGINATOR_FOR_TYPE(int64_t); -DEFINE_STRINGINATOR_FOR_TYPE(uint64_t); -DEFINE_STRINGINATOR_FOR_TYPE(float); -DEFINE_STRINGINATOR_FOR_TYPE(double); -DEFINE_STRINGINATOR_FOR_TYPE(bool); -DEFINE_STRINGINATOR_FOR_TYPE(std::string); -#undef DEFINE_STRINGINATOR_FOR_TYPE - -template <class T> -std::string ToString(const T& param) { - return Stringinator<T>::ToString(param); -} - -// This overload is necessary to allow enum values (such as those from -// pp_errors.h, including PP_OK) to work. They won't automatically convert to -// an integral type to instantiate the above function template. -inline std::string ToString(int32_t param) { - return Stringinator<int32_t>::ToString(param); -} - -inline std::string ToString(const char* c_string) { - return std::string(c_string); -} - -// This overload deals with pointers. -template <class T> -std::string ToString(const T* ptr) { - uintptr_t ptr_val = reinterpret_cast<uintptr_t>(ptr); - std::stringstream stream; - stream << ptr_val; - return stream.str(); -} - -// ComparisonHelper classes wrap the left-hand parameter of a binary comparison -// ASSERT. The correct class gets chosen based on whether or not it's a NULL or -// 0 literal. If it is a NULL/0 literal, we use NullLiteralComparisonHelper. -// For all other parameters, we use ComparisonHelper. There's also a -// specialization of ComparisonHelper for int below (see below for why -// that is.) -// -// ComparisonHelper does two things for the left param: -// 1) Provides all the appropriate CompareXX functions (CompareEQ, etc). -// 2) Provides ToString. -template <class T> -struct ComparisonHelper { - explicit ComparisonHelper(const T& param) : value(param) {} - template <class U> - bool CompareEQ(const U& right) const { - return value == right; - } - template <class U> - bool CompareNE(const U& right) const { - return value != right; - } - template <class U> - bool CompareLT(const U& right) const { - return value < right; - } - template <class U> - bool CompareGT(const U& right) const { - return value > right; - } - template <class U> - bool CompareLE(const U& right) const { - return value <= right; - } - template <class U> - bool CompareGE(const U& right) const { - return value >= right; - } - std::string ToString() const { - return internal::ToString(value); - } - const T& value; -}; - -// Used for NULL or 0. -struct NullLiteralComparisonHelper { - NullLiteralComparisonHelper() : value(0) {} - template <class U> - bool CompareEQ(const U& right) const { - return 0 == right; - } - template <class U> - bool CompareNE(const U& right) const { - return 0 != right; - } - template <class U> - bool CompareLT(const U& right) const { - return 0 < right; - } - template <class U> - bool CompareGT(const U& right) const { - return 0 > right; - } - template <class U> - bool CompareLE(const U& right) const { - return 0 <= right; - } - template <class U> - bool CompareGE(const U& right) const { - return 0 >= right; - } - std::string ToString() const { - return std::string("0"); - } - const int value; -}; - -// This class makes it safe to use an integer literal (like 5, or 123) when -// comparing with an unsigned. For example: -// ASSERT_EQ(1, some_vector.size()); -// We do a lot of those comparisons, so this makes it easy to get it right -// (rather than forcing assertions to use unsigned literals like 5u or 123u). -// -// This is slightly risky; we're static_casting an int to whatever's on the -// right. If the left value is negative and the right hand side is a large -// unsigned value, it's possible that the comparison will succeed when maybe -// it shouldn't have. -// TODO(dmichael): It should be possible to fix this and upgrade int32_t and -// uint32_t to int64_t for the comparison, and make any unsafe -// comparisons into compile errors. -template <> -struct ComparisonHelper<int> { - explicit ComparisonHelper(int param) : value(param) {} - template <class U> - bool CompareEQ(const U& right) const { - return static_cast<U>(value) == right; - } - template <class U> - bool CompareNE(const U& right) const { - return static_cast<U>(value) != right; - } - template <class U> - bool CompareLT(const U& right) const { - return static_cast<U>(value) < right; - } - template <class U> - bool CompareGT(const U& right) const { - return static_cast<U>(value) > right; - } - template <class U> - bool CompareLE(const U& right) const { - return static_cast<U>(value) <= right; - } - template <class U> - bool CompareGE(const U& right) const { - return static_cast<U>(value) >= right; - } - std::string ToString() const { - return internal::ToString(value); - } - const int value; - private: -}; - -// The default is for the case there the parameter is *not* a NULL or 0 literal. -template <bool is_null_literal> -struct ParameterWrapper { - template <class T> - static ComparisonHelper<T> WrapValue(const T& value) { - return ComparisonHelper<T>(value); - } - // This overload is so that we can deal with values from anonymous enums, - // like the one in pp_errors.h. The function template above won't be - // considered a match by the compiler. - static ComparisonHelper<int> WrapValue(int value) { - return ComparisonHelper<int>(value); - } -}; - -// The parameter to WrapValue *is* a NULL or 0 literal. -template <> -struct ParameterWrapper<true> { - // We just use "..." and ignore the parameter. This sidesteps some problems we - // would run in to (not all compilers have the same set of constraints). - // - We can't use a pointer type, because int and enums won't convert. - // - We can't use an integral type, because pointers won't convert. - // - We can't overload, because it will sometimes be ambiguous. - // - We can't templatize and deduce the parameter. Some compilers will deduce - // int for NULL, and then refuse to convert NULL to an int. - // - // We know in this case that the value is 0, so there's no need to capture the - // value. We also know it's a fundamental type, so it's safe to pass to "...". - // (It's illegal to pass non-POD types to ...). - static NullLiteralComparisonHelper WrapValue(...) { - return NullLiteralComparisonHelper(); - } -}; - -// IS_NULL_LITERAL(type) is a little template metaprogramming for determining -// if a type is a null or zero literal (NULL or 0 or a constant that evaluates -// to one of those). -// The idea is that for NULL or 0, any pointer type is always a better match -// than "...". But no other pointer types or literals should convert -// automatically to InternalDummyClass. -struct InternalDummyClass {}; -char TestNullLiteral(const InternalDummyClass*); -struct BiggerThanChar { char dummy[2]; }; -BiggerThanChar TestNullLiteral(...); -// If the compiler chooses the overload of TestNullLiteral which returns char, -// then we know the value converts automatically to InternalDummyClass*, which -// should only be true of NULL and 0 constants. -#define IS_NULL_LITERAL(a) sizeof(internal::TestNullLiteral(a)) == sizeof(char) - -template <class T, class U> -static std::string MakeBinaryComparisonFailureMessage( - const char* comparator, - const T& left, - const U& right, - const char* left_precompiler_string, - const char* right_precompiler_string, - const char* file_name, - int line_number) { - std::string error_msg = - std::string("Failed ASSERT_") + comparator + "(" + - left_precompiler_string + ", " + right_precompiler_string + ")"; - std::string left_string(left.ToString()); - std::string right_string(ToString(right)); - if (!left_string.empty()) - error_msg += " Left: (" + left_string + ")"; - - if (!right_string.empty()) - error_msg += " Right: (" + right_string + ")"; - - return TestCase::MakeFailureMessage(file_name, line_number, - error_msg.c_str()); -} - -// The Comparison function templates allow us to pass the parameter for -// ASSERT macros below and have them be evaluated only once. This is important -// for cases where the parameter might be an expression with side-effects, like -// a function call. -#define DEFINE_COMPARE_FUNCTION(comparator_name) \ -template <class T, class U> \ -std::string Compare ## comparator_name ( \ - const T& left, \ - const U& right, \ - const char* left_precompiler_string, \ - const char* right_precompiler_string, \ - const char* file_name, \ - int line_num) { \ - if (!(left.Compare##comparator_name(right))) { \ - return MakeBinaryComparisonFailureMessage(#comparator_name, \ - left, \ - right, \ - left_precompiler_string, \ - right_precompiler_string, \ - file_name, \ - line_num); \ - } \ - return std::string(); \ -} -DEFINE_COMPARE_FUNCTION(EQ) -DEFINE_COMPARE_FUNCTION(NE) -DEFINE_COMPARE_FUNCTION(LT) -DEFINE_COMPARE_FUNCTION(LE) -DEFINE_COMPARE_FUNCTION(GT) -DEFINE_COMPARE_FUNCTION(GE) -#undef DEFINE_COMPARE_FUNCTION -inline std::string CompareDoubleEq(ComparisonHelper<double> left, - double right, - const char* left_precompiler_string, - const char* right_precompiler_string, - const char* file_name, - int linu_num) { - if (!(std::fabs(left.value - right) <= - std::numeric_limits<double>::epsilon())) { - return MakeBinaryComparisonFailureMessage( - "~=", left, right, left_precompiler_string, right_precompiler_string, - __FILE__, __LINE__); - } - return std::string(); -} - -} // namespace internal - -// Use the REGISTER_TEST_CASE macro in your TestCase implementation file to -// register your TestCase. If your test is named TestFoo, then add the -// following to test_foo.cc: -// -// REGISTER_TEST_CASE(Foo); -// -// This will cause your test to be included in the set of known tests. -// -#define REGISTER_TEST_CASE(name) \ - static TestCase* Test##name##_FactoryMethod(TestingInstance* instance) { \ - return new Test##name(instance); \ - } \ - static TestCaseFactory g_Test##name_factory( \ - #name, &Test##name##_FactoryMethod \ - ) - -// Helper macro for calling functions implementing specific tests in the -// RunTest function. This assumes the function name is TestFoo where Foo is the -// test |name|. -#define RUN_TEST(name, test_filter) \ - if (ShouldRunTest(#name, test_filter)) { \ - set_callback_type(PP_OPTIONAL); \ - PP_TimeTicks start_time(NowInTimeTicks()); \ - instance_->LogTest(#name, \ - CheckResourcesAndVars(Test##name()), \ - start_time); \ - } - -// Like RUN_TEST above but forces functions taking callbacks to complete -// asynchronously on success or error. -#define RUN_TEST_FORCEASYNC(name, test_filter) \ - if (ShouldRunTest(#name, test_filter)) { \ - set_callback_type(PP_REQUIRED); \ - PP_TimeTicks start_time(NowInTimeTicks()); \ - instance_->LogTest(#name"ForceAsync", \ - CheckResourcesAndVars(Test##name()), \ - start_time); \ - } - -#define RUN_TEST_BLOCKING(test_case, name, test_filter) \ - if (ShouldRunTest(#name, test_filter)) { \ - set_callback_type(PP_BLOCKING); \ - PP_TimeTicks start_time(NowInTimeTicks()); \ - instance_->LogTest( \ - #name"Blocking", \ - CheckResourcesAndVars(RunOnThread(&test_case::Test##name)), \ - start_time); \ - } - -#define RUN_TEST_BACKGROUND(test_case, name, test_filter) \ - if (ShouldRunTest(#name, test_filter)) { \ - PP_TimeTicks start_time(NowInTimeTicks()); \ - instance_->LogTest( \ - #name"Background", \ - CheckResourcesAndVars(RunOnThread(&test_case::Test##name)), \ - start_time); \ - } - -#define RUN_TEST_FORCEASYNC_AND_NOT(name, test_filter) \ - do { \ - RUN_TEST_FORCEASYNC(name, test_filter); \ - RUN_TEST(name, test_filter); \ - } while (false) - -// Run a test with all possible callback types. -#define RUN_CALLBACK_TEST(test_case, name, test_filter) \ - do { \ - RUN_TEST_FORCEASYNC(name, test_filter); \ - RUN_TEST(name, test_filter); \ - RUN_TEST_BLOCKING(test_case, name, test_filter); \ - RUN_TEST_BACKGROUND(test_case, name, test_filter); \ - } while (false) - -#define RUN_TEST_WITH_REFERENCE_CHECK(name, test_filter) \ - if (ShouldRunTest(#name, test_filter)) { \ - set_callback_type(PP_OPTIONAL); \ - uint32_t objects = testing_interface_->GetLiveObjectsForInstance( \ - instance_->pp_instance()); \ - std::string error_message = Test##name(); \ - if (error_message.empty() && \ - testing_interface_->GetLiveObjectsForInstance( \ - instance_->pp_instance()) != objects) \ - error_message = MakeFailureMessage(__FILE__, __LINE__, \ - "reference leak check"); \ - PP_TimeTicks start_time(NowInTimeTicks()); \ - instance_->LogTest(#name, \ - CheckResourcesAndVars(error_message), \ - start_time); \ - } -// TODO(dmichael): Add CheckResourcesAndVars above when Windows tests pass -// cleanly. crbug.com/173503 - -// Helper macros for checking values in tests, and returning a location -// description of the test fails. -#define ASSERT_TRUE(cmd) \ - do { \ - if (!(cmd)) \ - return MakeFailureMessage(__FILE__, __LINE__, #cmd); \ - } while (false) -#define ASSERT_FALSE(cmd) ASSERT_TRUE(!(cmd)) -#define COMPARE_BINARY_INTERNAL(comparison_type, a, b) \ - internal::Compare##comparison_type( \ - internal::ParameterWrapper<IS_NULL_LITERAL(a)>::WrapValue(a), \ - (b), \ - #a, \ - #b, \ - __FILE__, \ - __LINE__) -#define ASSERT_BINARY_INTERNAL(comparison_type, a, b) \ -do { \ - std::string internal_assert_result_string = \ - COMPARE_BINARY_INTERNAL(comparison_type, a, b); \ - if (!internal_assert_result_string.empty()) { \ - return internal_assert_result_string; \ - } \ -} while(false) -#define ASSERT_EQ(a, b) ASSERT_BINARY_INTERNAL(EQ, a, b) -#define ASSERT_NE(a, b) ASSERT_BINARY_INTERNAL(NE, a, b) -#define ASSERT_LT(a, b) ASSERT_BINARY_INTERNAL(LT, a, b) -#define ASSERT_LE(a, b) ASSERT_BINARY_INTERNAL(LE, a, b) -#define ASSERT_GT(a, b) ASSERT_BINARY_INTERNAL(GT, a, b) -#define ASSERT_GE(a, b) ASSERT_BINARY_INTERNAL(GE, a, b) -#define ASSERT_DOUBLE_EQ(a, b) \ -do { \ - std::string internal_assert_result_string = \ - internal::CompareDoubleEq( \ - internal::ParameterWrapper<IS_NULL_LITERAL(a)>::WrapValue(a), \ - (b), \ - #a, \ - #b, \ - __FILE__, \ - __LINE__); \ - if (!internal_assert_result_string.empty()) { \ - return internal_assert_result_string; \ - } \ -} while(false) -// Runs |function| as a subtest and asserts that it has passed. -#define ASSERT_SUBTEST_SUCCESS(function) \ - do { \ - std::string result = (function); \ - if (!result.empty()) \ - return TestCase::MakeFailureMessage(__FILE__, __LINE__, result.c_str()); \ - } while (false) - -#define PASS() return std::string() - -#endif // PPAPI_TESTS_TEST_CASE_H_
diff --git a/tests/test_case.html b/tests/test_case.html deleted file mode 100644 index 2202566..0000000 --- a/tests/test_case.html +++ /dev/null
@@ -1,371 +0,0 @@ -<html><head> -<meta http-equiv="Pragma" content="no-cache" /> -<meta http-equiv="Expires" content="-1" /> -<link rel="stylesheet" href="test_page.css"> -<script> -// Do a deep comparison of two values. Return true if their values are -// identical, false otherwise. -function deepCompare(left, right) { - if (typeof(left) !== typeof(right)) - return false; - // If their identity is the same or they're basic types with the same value, - // they are equal. - if (left === right) - return true; - // If it's a basic type and we got here, we know they're not equal. - if (["undefined", "boolean", "number", "string", "function"].indexOf( - typeof(left)) > -1) { - return false; - } - // Use right_keys as a set containing all keys from |right| which we haven't - // yet compared. - var right_keys = {}; - for (var key in right) - right_keys[key] = true; - for (var key in left) { - if (key in right_keys) { - if (!deepCompare(left[key], right[key])) - return false; - } else { - // |left| had a key that |right| didn't. - return false; - } - delete right_keys[key]; - } - // If there are keys left in |right_keys|, it means they didn't exist in - // |left|, so the objects aren't equal. - if (Object.keys(right_keys).length > 0) - return false; - return true; -} - -function AdjustHeight(frameWin) { - var div = frameWin.document.getElementsByTagName("div")[0]; - var height = frameWin.getComputedStyle(div).height; - frameWin.frameElement.style.height = height; -} - -// Called when the tests are completed. |result| should be "PASS" if the test(s) -// passed, or information about the failure if the test(s) did not pass. -function DidExecuteTests(result) { - var plugin = document.getElementById("plugin"); - if (plugin.parentNode.removePlugin) { - plugin.parentNode.removeChild(plugin); - plugin = undefined; - } - if (CheckPostConditions()) - sendAutomationMessage(result); - - if (window == top) - return; - - // Otherwise, we are in a subframe, so we can use this opportunity to resize - // ourselves. This can only be done if the parent frame has the same origin. - if (window.frameElement) - AdjustHeight(window); -} - -function AppendFrame(testcase, i) { - var p = document.createElement("P"); - p.setAttribute("class", "frame-container"); - - var title = document.createElement("H2"); - title.appendChild(document.createTextNode(testcase)); - p.appendChild(title); - - var frame = document.createElement("IFRAME"); - var mode = ExtractSearchParameter("mode"); - var websocket_host = ExtractSearchParameter("websocket_host"); - var websocket_port = ExtractSearchParameter("websocket_port"); - var ssl_server_port = ExtractSearchParameter("ssl_server_port"); - var src = "?testcase=" + testcase; - if (mode == "nacl") - src += "&mode=nacl"; - if (websocket_host != "") - src += "&websocket_host=" + websocket_host; - if (websocket_port != "") - src += "&websocket_port=" + websocket_port; - if (ssl_server_port != "") - src += "&ssl_server_port=" + ssl_server_port; - frame.setAttribute("src", src); - - frame.setAttribute("onload", "LoadNext(" + (i + 1) + ")"); - p.appendChild(frame); - - document.body.appendChild(p); -} - -function LoadNext(i) { - var links = document.links; - if (links.length > i) - AppendFrame(links[i].firstChild.nodeValue, i); -} - -function RunAll() { - // Remove any existing frames. - var existing = document.getElementsByClassName("frame-container"); - while (existing.length) - existing[0].parentNode.removeChild(existing[0]); - - // Add new frames for each test, but do so one frame at a time. - LoadNext(0); -} - -function ExtractSearchParameter(name) { - var nameIndex = location.search.indexOf(name + "="); - if (nameIndex != -1) { - var value = location.search.substring(nameIndex + name.length + 1); - var endIndex = value.indexOf("&"); - if (endIndex != -1) - value = value.substring(0, endIndex); - return value; - } - return ""; -} - -// Parses the message, looking for strings of the form: -// TESTING_MESSAGE:<message_type>:<message_contents> -// -// If the message_data is not a string or does not match the above format, then -// undefined is returned. -// -// Otherwise, returns an array containing 2 items. The 0th element is the -// message_type, one of: -// - AddPostCondition -// - ClearConsole -// - DidExecuteTests -// - EvalScript -// - LogHTML -// - RemovePluginWhenFinished -// - ReportProgress -// The second item is the verbatim message_contents. -function ParseTestingMessage(message_data) { - if (typeof(message_data) != "string") - return undefined; - var testing_message_prefix = "TESTING_MESSAGE"; - var delim_str = ":"; - var delim1 = message_data.indexOf(delim_str); - if (message_data.substring(0, delim1) !== testing_message_prefix) - return undefined; - var delim2 = message_data.indexOf(delim_str, delim1 + 1); - if (delim2 == -1) - delim2 = message_data.length; - var message_type = message_data.substring(delim1 + 1, delim2); - var message_contents = message_data.substring(delim2 + 1); - return [message_type, message_contents]; -} - -function ClearConsole() { - window.document.getElementById("console").innerHTML = ""; -} - -function LogHTML(html) { - window.document.getElementById("console").innerHTML += html; -} - -function RemovePluginWhenFinished() { - window.document.getElementById("container").removePlugin = true; -} - -function sendAutomationMessage(msg) { - if (window.domAutomationController) - window.domAutomationController.send(msg); -} - -function LogTestTime(test_time) { - console.log(test_time); -} - -// If something goes really wrong, the test running inside the plugin may not -// terminate. For example, if the plugin does not load, the test will never -// send "PASS" to the browser. In this case we should explicitly use the -// automation controller to terminate the test. -function InternalError(msg) { - LogHTML("<p>" + msg); - sendAutomationMessage(msg); -} - -function EvalScript(script) { - try { - eval(script); - } catch(ex) { - } -} - -var conditions = []; -// Add a "PostCondition". These are bits of script that are run after the plugin -// is destroyed. If they evaluate to false or throw an exception, it's -// considered a failure. -function AddPostCondition(script) { - conditions.push(script); -} -// Update the HTML to show the failure and update cookies so that ui_tests -// doesn't count this as a pass. -function ConditionFailed(error) { - error_string = "Post condition check failed: " + error; - InternalError(error_string); -} -// Iterate through the post conditions defined in |conditions| and check that -// they all pass. -function CheckPostConditions() { - var success = true; - for (var i = 0; i < conditions.length; ++i) { - var script = conditions[i]; - try { - if (!eval(script)) { - ConditionFailed("\"" + script + "\""); - success = false; - } - } catch (ex) { - ConditionFailed("\"" + script + "\"" + " failed with exception: " + - "\"" + ex.toString() + "\""); - success = false; - } - } - return success; -} - -function IsTestingMessage(message_data) { - return (ParseTestingMessage(message_data) != undefined); -} - -function handleTestingMessage(message_event) { - var type_contents_tuple = ParseTestingMessage(message_event.data); - if (type_contents_tuple) { - var type = type_contents_tuple[0]; - var contents = type_contents_tuple[1]; - if (type === "AddPostCondition") - AddPostCondition(contents); - else if (type === "ClearConsole") - ClearConsole(); - else if (type === "DidExecuteTests") - DidExecuteTests(contents); - else if (type === "EvalScript") - EvalScript(contents); - else if (type === "LogHTML") - LogHTML(contents); - else if (type === "RemovePluginWhenFinished") - RemovePluginWhenFinished(); - else if (type === "ReportProgress") - sendAutomationMessage(contents); - else if (type === "LogTestTime") - LogTestTime(contents); - } -} - -function sendProgress() { - // We send "..." to signal that we're still working. See - // ppapi/tests/testing_instance.h for how this works. - sendAutomationMessage("..."); -} - -onload = function() { - var testcase = ExtractSearchParameter("testcase"); - var mode = ExtractSearchParameter("mode"); - document.title = 'Test ' + testcase; - var obj; - if (mode == "nacl_newlib") { - obj = document.createElement("EMBED"); - obj.setAttribute("src", "ppapi_nacl_tests_newlib.nmf"); - obj.setAttribute("type", "application/x-nacl"); - obj.setAttribute("mode", mode); - } else if (mode == "nacl_glibc") { - obj = document.createElement("EMBED"); - obj.setAttribute("src", "ppapi_nacl_tests_glibc.nmf"); - obj.setAttribute("type", "application/x-nacl"); - obj.setAttribute("mode", mode); - } else if (mode == "nacl_pnacl") { - obj = document.createElement("EMBED"); - obj.setAttribute("src", "ppapi_nacl_tests_pnacl.nmf"); - obj.setAttribute("type", "application/x-nacl"); - obj.setAttribute("mode", mode); - } else if (mode == "mojo") { - obj = document.createElement("EMBED"); - obj.setAttribute("src", - "test_data/ppapi/tests/mojo/pnacl/ppapi_tests_mojo.nmf"); - obj.setAttribute("type", "application/x-pnacl"); - obj.setAttribute("mode", mode); - } else { - var mimeType = "application/x-ppapi-tests"; - if (mimeType in navigator.mimeTypes) { - obj = document.createElement("EMBED"); - obj.setAttribute("src", "http://a.b.c/test"); - obj.setAttribute("type", mimeType); - } else { - document.getElementById("console").innerHTML = - '<span class="fail">FAIL</span>: ' + - '<span class="err_msg">Test plugin is not registered.</span>'; - } - } - - if (obj) { - obj.setAttribute("width", 80); - obj.setAttribute("height", 80); - obj.setAttribute("style", - "background-color:#AAAAAA;border:1px solid black;"); - obj.setAttribute("id", "plugin"); - obj.setAttribute("testcase", testcase); - obj.setAttribute("protocol", window.location.protocol); - var websocket_host = ExtractSearchParameter("websocket_host"); - if (websocket_host != "") - obj.setAttribute("websocket_host", websocket_host); - var websocket_port = ExtractSearchParameter("websocket_port"); - if (websocket_port != "") - obj.setAttribute("websocket_port", websocket_port); - var ssl_server_port = ExtractSearchParameter("ssl_server_port"); - if (ssl_server_port != "") - obj.setAttribute("ssl_server_port", ssl_server_port); - - var container = document.getElementById("container"); - container.addEventListener("message", handleTestingMessage, true); - - // "error" and "crash" events will only fire for NaCl, but adding these - // listeners doesn't hurt in the non-NaCl cases. - obj.addEventListener("error", function() { - InternalError("Plugin did not load. '" + obj.lastError + "'"); - }, true); - obj.addEventListener("crash", function() { - InternalError("Plugin crashed. '" + obj.lastError + "'"); - }, true); - - // NaCl sends progress events while loading. When we get one, notify the - // domAutomationController so that it knows we're still working. - obj.addEventListener("loadstart", sendProgress, true); - obj.addEventListener("progress", sendProgress, true); - obj.addEventListener("load", sendProgress, true); - obj.addEventListener("loadend", sendProgress, true); - - // Register a bad dispatchEvent to make sure it isn't used. See 'EVIL' note - // below. - var original = obj.dispatchEvent; - obj.dispatchEvent = function() { - InternalError("Bad dispatchEvent called!"); - } - container.appendChild(obj); - } -} - -// EVIL Note: -// This part of the script does some nefarious things to make sure that it -// doesn't affect the behavior of PostMessage (on which all the tests rely). In -// particular, we replace document.createEvent, MessageEvent.initMessageEvent, -// and the MessageEvent constructor. Previously, the NaCl integration -// implementation made use of these and would fail (http://crbug.com/82604 -// and http://crbug.com/109775). -document.createEvent = function() { - InternalError("Bad document.createEvent called!"); -} -function MessageEvent() { - InternalError("Bad MessageEvent constructor called!"); -} -MessageEvent.prototype.initMessageEvent = function() { - InternalError("Bad MessageEvent.initMessageEvent called!"); -} - -</script> -</head><body> -<div> - <div id="container"></div> - <div id="console"><span class="load_msg">loading...</span></div> -</div> -</body></html>
diff --git a/tests/test_case.html.mock-http-headers b/tests/test_case.html.mock-http-headers deleted file mode 100644 index 6b253aa..0000000 --- a/tests/test_case.html.mock-http-headers +++ /dev/null
@@ -1,3 +0,0 @@ -HTTP/1.1 200 OK -Content-Type: text/html -Access-Control-Allow-Origin: *
diff --git a/tests/test_char_set.cc b/tests/test_char_set.cc deleted file mode 100644 index 7eba065..0000000 --- a/tests/test_char_set.cc +++ /dev/null
@@ -1,390 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_char_set.h" - -#include "ppapi/c/dev/ppb_char_set_dev.h" -#include "ppapi/c/trusted/ppb_char_set_trusted.h" -#include "ppapi/cpp/dev/memory_dev.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(CharSet); - -TestCharSet::TestCharSet(TestingInstance* instance) - : TestCase(instance), - char_set_interface_(NULL) { -} - -bool TestCharSet::Init() { - char_set_interface_ = static_cast<const PPB_CharSet_Dev*>( - pp::Module::Get()->GetBrowserInterface(PPB_CHAR_SET_DEV_INTERFACE)); - char_set_trusted_interface_ = static_cast<const PPB_CharSet_Trusted*>( - pp::Module::Get()->GetBrowserInterface(PPB_CHARSET_TRUSTED_INTERFACE)); - return char_set_interface_ && char_set_trusted_interface_; -} - -void TestCharSet::RunTests(const std::string& filter) { - RUN_TEST(UTF16ToCharSetDeprecated, filter); - RUN_TEST(UTF16ToCharSet, filter); - RUN_TEST(CharSetToUTF16Deprecated, filter); - RUN_TEST(CharSetToUTF16, filter); - RUN_TEST(GetDefaultCharSet, filter); -} - -// TODO(brettw) remove this when the old interface is removed. -std::string TestCharSet::TestUTF16ToCharSetDeprecated() { - // Empty string. - std::vector<uint16_t> utf16; - utf16.push_back(0); - uint32_t utf8result_len = 0; - pp::Memory_Dev memory; - char* utf8result = char_set_interface_->UTF16ToCharSet( - instance_->pp_instance(), &utf16[0], 0, "latin1", - PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len); - ASSERT_TRUE(utf8result); - ASSERT_TRUE(utf8result[0] == 0); - ASSERT_TRUE(utf8result_len == 0); - memory.MemFree(utf8result); - - // Try round-tripping some English & Chinese from UTF-8 through UTF-16 - std::string utf8source("Hello, world. \xe4\xbd\xa0\xe5\xa5\xbd"); - utf16 = UTF8ToUTF16(utf8source); - utf8result = char_set_interface_->UTF16ToCharSet( - instance_->pp_instance(), &utf16[0], static_cast<uint32_t>(utf16.size()), - "Utf-8", PP_CHARSET_CONVERSIONERROR_FAIL, &utf8result_len); - ASSERT_TRUE(utf8source == std::string(utf8result, utf8result_len)); - memory.MemFree(utf8result); - - // Test an un-encodable character with various modes. - utf16 = UTF8ToUTF16("h\xe4\xbd\xa0i"); - - // Fail mode. - utf8result_len = 1234; // Test that this gets 0'ed on failure. - utf8result = char_set_interface_->UTF16ToCharSet( - instance_->pp_instance(), &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_CONVERSIONERROR_FAIL, &utf8result_len); - ASSERT_TRUE(utf8result_len == 0); - ASSERT_TRUE(utf8result == NULL); - - // Skip mode. - utf8result = char_set_interface_->UTF16ToCharSet( - instance_->pp_instance(), &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_CONVERSIONERROR_SKIP, &utf8result_len); - ASSERT_TRUE(utf8result_len == 2); - ASSERT_TRUE(utf8result[0] == 'h' && utf8result[1] == 'i' && - utf8result[2] == 0); - memory.MemFree(utf8result); - - // Substitute mode. - utf8result = char_set_interface_->UTF16ToCharSet( - instance_->pp_instance(), &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len); - ASSERT_TRUE(utf8result_len == 3); - ASSERT_TRUE(utf8result[0] == 'h' && utf8result[1] == '?' && - utf8result[2] == 'i' && utf8result[3] == 0); - memory.MemFree(utf8result); - - // Try some invalid input encoding. - utf16.clear(); - utf16.push_back(0xD800); // High surrogate. - utf16.push_back('A'); // Not a low surrogate. - utf8result = char_set_interface_->UTF16ToCharSet( - instance_->pp_instance(), &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len); - ASSERT_TRUE(utf8result_len == 2); - ASSERT_TRUE(utf8result[0] == '?' && utf8result[1] == 'A' && - utf8result[2] == 0); - memory.MemFree(utf8result); - - // Invalid encoding name. - utf8result = char_set_interface_->UTF16ToCharSet( - instance_->pp_instance(), &utf16[0], static_cast<uint32_t>(utf16.size()), - "poopiepants", PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len); - ASSERT_TRUE(!utf8result); - ASSERT_TRUE(utf8result_len == 0); - - PASS(); -} - -std::string TestCharSet::TestUTF16ToCharSet() { - // Empty string. - std::vector<uint16_t> utf16; - utf16.push_back(0); - std::string output_buffer; - output_buffer.resize(1); - uint32_t utf8result_len = 0; - PP_Bool result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], 0, "latin1", PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_TRUE); - ASSERT_TRUE(utf8result_len == 0); - - // No output buffer returns length of string. - utf16 = UTF8ToUTF16("hello"); - utf8result_len = 0; - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), "latin1", - PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, NULL, &utf8result_len); - ASSERT_TRUE(result == PP_TRUE); - ASSERT_TRUE(utf8result_len == 5); - - // Giving too small of a buffer just fills in that many items and gives us - // the desired size. - output_buffer.resize(100); - utf8result_len = 2; - output_buffer[utf8result_len] = '$'; // Barrier character. - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), "latin1", - PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_TRUE); - ASSERT_TRUE(utf8result_len == 5); - ASSERT_TRUE(output_buffer[0] == 'h' && output_buffer[1] == 'e' && - output_buffer[2] == '$'); - - // Try round-tripping some English & Chinese from UTF-8 through UTF-16 - std::string utf8source("Hello, world. \xe4\xbd\xa0\xe5\xa5\xbd"); - utf16 = UTF8ToUTF16(utf8source); - output_buffer.resize(100); - utf8result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), - "Utf-8", PP_CHARSET_TRUSTED_CONVERSIONERROR_FAIL, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_TRUE); - output_buffer.resize(utf8result_len); - ASSERT_TRUE(utf8source == output_buffer); - - // Test an un-encodable character with various modes. - utf16 = UTF8ToUTF16("h\xe4\xbd\xa0i"); - - // Fail mode, size should get 0'ed on failure. - output_buffer.resize(100); - utf8result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_TRUSTED_CONVERSIONERROR_FAIL, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_FALSE); - ASSERT_TRUE(utf8result_len == 0); - - // Skip mode. - output_buffer.resize(100); - utf8result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_TRUSTED_CONVERSIONERROR_SKIP, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_TRUE); - ASSERT_TRUE(utf8result_len == 2); - ASSERT_TRUE(output_buffer[0] == 'h' && output_buffer[1] == 'i'); - - // Substitute mode. - output_buffer.resize(100); - utf8result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_TRUE); - ASSERT_TRUE(utf8result_len == 3); - output_buffer.resize(utf8result_len); - ASSERT_TRUE(output_buffer == "h?i"); - - // Try some invalid input encoding. - output_buffer.resize(100); - utf8result_len = static_cast<uint32_t>(output_buffer.size()); - utf16.clear(); - utf16.push_back(0xD800); // High surrogate. - utf16.push_back('A'); // Not a low surrogate. - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), - "latin1", PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_TRUE); - ASSERT_TRUE(utf8result_len == 2); - ASSERT_TRUE(output_buffer[0] == '?' && output_buffer[1] == 'A'); - - // Invalid encoding name. - output_buffer.resize(100); - utf8result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->UTF16ToCharSet( - &utf16[0], static_cast<uint32_t>(utf16.size()), - "poopiepants", PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, - &output_buffer[0], &utf8result_len); - ASSERT_TRUE(result == PP_FALSE); - ASSERT_TRUE(utf8result_len == 0); - - PASS(); -} - -// TODO(brettw) remove this when the old interface is removed. -std::string TestCharSet::TestCharSetToUTF16Deprecated() { - pp::Memory_Dev memory; - - // Empty string. - uint32_t utf16result_len; - uint16_t* utf16result = char_set_interface_->CharSetToUTF16( - instance_->pp_instance(), "", 0, "latin1", - PP_CHARSET_CONVERSIONERROR_FAIL, &utf16result_len); - ASSERT_TRUE(utf16result); - ASSERT_TRUE(utf16result_len == 0); - ASSERT_TRUE(utf16result[0] == 0); - memory.MemFree(utf16result); - - // Basic Latin1. - char latin1[] = "H\xef"; - utf16result = char_set_interface_->CharSetToUTF16( - instance_->pp_instance(), latin1, 2, "latin1", - PP_CHARSET_CONVERSIONERROR_FAIL, &utf16result_len); - ASSERT_TRUE(utf16result); - ASSERT_TRUE(utf16result_len == 2); - ASSERT_TRUE(utf16result[0] == 'H' && utf16result[1] == 0xef && - utf16result[2] == 0); - memory.MemFree(utf16result); - - // Invalid input encoding with FAIL. - char badutf8[] = "A\xe4Z"; - utf16result = char_set_interface_->CharSetToUTF16( - instance_->pp_instance(), badutf8, 3, "utf8", - PP_CHARSET_CONVERSIONERROR_FAIL, &utf16result_len); - ASSERT_TRUE(!utf16result); - ASSERT_TRUE(utf16result_len == 0); - memory.MemFree(utf16result); - - // Invalid input with SKIP. - utf16result = char_set_interface_->CharSetToUTF16( - instance_->pp_instance(), badutf8, 3, "utf8", - PP_CHARSET_CONVERSIONERROR_SKIP, &utf16result_len); - ASSERT_TRUE(utf16result); - ASSERT_TRUE(utf16result_len == 2); - ASSERT_TRUE(utf16result[0] == 'A' && utf16result[1] == 'Z' && - utf16result[2] == 0); - memory.MemFree(utf16result); - - // Invalid input with SUBSTITUTE. - utf16result = char_set_interface_->CharSetToUTF16( - instance_->pp_instance(), badutf8, 3, "utf8", - PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf16result_len); - ASSERT_TRUE(utf16result); - ASSERT_TRUE(utf16result_len == 3); - ASSERT_TRUE(utf16result[0] == 'A' && utf16result[1] == 0xFFFD && - utf16result[2] == 'Z' && utf16result[3] == 0); - memory.MemFree(utf16result); - - // Invalid encoding name. - utf16result = char_set_interface_->CharSetToUTF16( - instance_->pp_instance(), badutf8, 3, "poopiepants", - PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf16result_len); - ASSERT_TRUE(!utf16result); - ASSERT_TRUE(utf16result_len == 0); - memory.MemFree(utf16result); - - PASS(); -} - -std::string TestCharSet::TestCharSetToUTF16() { - std::vector<uint16_t> output_buffer; - output_buffer.resize(100); - - // Empty string. - output_buffer.resize(100); - uint32_t utf16result_len = static_cast<uint32_t>(output_buffer.size()); - PP_Bool result = char_set_trusted_interface_->CharSetToUTF16( - "", 0, "latin1", PP_CHARSET_TRUSTED_CONVERSIONERROR_FAIL, - &output_buffer[0], &utf16result_len); - ASSERT_TRUE(result); - ASSERT_TRUE(utf16result_len == 0); - ASSERT_TRUE(output_buffer[0] == 0); - - // Basic Latin1. - output_buffer.resize(100); - utf16result_len = static_cast<uint32_t>(output_buffer.size()); - char latin1[] = "H\xef"; - result = char_set_trusted_interface_->CharSetToUTF16( - latin1, 2, "latin1", PP_CHARSET_TRUSTED_CONVERSIONERROR_FAIL, - &output_buffer[0], &utf16result_len); - ASSERT_TRUE(result); - ASSERT_TRUE(utf16result_len == 2); - ASSERT_TRUE(output_buffer[0] == 'H' && output_buffer[1] == 0xef); - - // Invalid input encoding with FAIL. - output_buffer.resize(100); - utf16result_len = static_cast<uint32_t>(output_buffer.size()); - char badutf8[] = "A\xe4Z"; - result = char_set_trusted_interface_->CharSetToUTF16( - badutf8, 3, "utf8", PP_CHARSET_TRUSTED_CONVERSIONERROR_FAIL, - &output_buffer[0], &utf16result_len); - ASSERT_TRUE(!result); - ASSERT_TRUE(utf16result_len == 0); - - // Invalid input with SKIP. - output_buffer.resize(100); - utf16result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->CharSetToUTF16( - badutf8, 3, "utf8", PP_CHARSET_TRUSTED_CONVERSIONERROR_SKIP, - &output_buffer[0], &utf16result_len); - ASSERT_TRUE(result); - ASSERT_TRUE(utf16result_len == 2); - ASSERT_TRUE(output_buffer[0] == 'A' && output_buffer[1] == 'Z'); - - // Invalid input with SUBSTITUTE. - output_buffer.resize(100); - utf16result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->CharSetToUTF16( - badutf8, 3, "utf8", PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, - &output_buffer[0], &utf16result_len); - ASSERT_TRUE(result); - ASSERT_TRUE(utf16result_len == 3); - ASSERT_TRUE(output_buffer[0] == 'A' && output_buffer[1] == 0xFFFD && - output_buffer[2] == 'Z'); - - // Invalid encoding name. - output_buffer.resize(100); - utf16result_len = static_cast<uint32_t>(output_buffer.size()); - result = char_set_trusted_interface_->CharSetToUTF16( - badutf8, 3, "poopiepants", PP_CHARSET_TRUSTED_CONVERSIONERROR_SUBSTITUTE, - &output_buffer[0], &utf16result_len); - ASSERT_TRUE(!result); - ASSERT_TRUE(utf16result_len == 0); - - PASS(); -} - -std::string TestCharSet::TestGetDefaultCharSet() { - // Test invalid instance. - pp::Var result(pp::PASS_REF, char_set_interface_->GetDefaultCharSet(0)); - ASSERT_TRUE(result.is_undefined()); - - // Just make sure the default char set is a nonempty string. - result = pp::Var(pp::PASS_REF, - char_set_interface_->GetDefaultCharSet(instance_->pp_instance())); - ASSERT_TRUE(result.is_string()); - ASSERT_FALSE(result.AsString().empty()); - - PASS(); -} - -std::vector<uint16_t> TestCharSet::UTF8ToUTF16(const std::string& utf8) { - uint32_t result_len = 0; - uint16_t* result = char_set_interface_->CharSetToUTF16( - instance_->pp_instance(), utf8.c_str(), - static_cast<uint32_t>(utf8.size()), - "utf-8", PP_CHARSET_CONVERSIONERROR_FAIL, &result_len); - - std::vector<uint16_t> result_vector; - if (!result) - return result_vector; - - result_vector.assign(result, &result[result_len]); - pp::Memory_Dev memory; - memory.MemFree(result); - return result_vector; -}
diff --git a/tests/test_char_set.h b/tests/test_char_set.h deleted file mode 100644 index 3e15c61..0000000 --- a/tests/test_char_set.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_CHAR_SET_H_ -#define PPAPI_TESTS_TEST_CHAR_SET_H_ - -#include <stdint.h> - -#include <string> -#include <vector> - -#include "ppapi/c/dev/ppb_char_set_dev.h" -#include "ppapi/c/trusted/ppb_char_set_trusted.h" -#include "ppapi/tests/test_case.h" - -class TestCharSet : public TestCase { - public: - TestCharSet(TestingInstance* instance); - - // TestCase implementation. - - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestUTF16ToCharSetDeprecated(); - std::string TestUTF16ToCharSet(); - std::string TestCharSetToUTF16Deprecated(); - std::string TestCharSetToUTF16(); - std::string TestGetDefaultCharSet(); - - // Converts the given UTF-8 string to a NON-NULL TERMINATED UTF-16 string - // stored in the given vector. - std::vector<uint16_t> UTF8ToUTF16(const std::string& utf8); - - const PPB_CharSet_Dev* char_set_interface_; - const PPB_CharSet_Trusted* char_set_trusted_interface_; -}; - -#endif // PPAPI_TESTS_TEST_CHAR_SET_H_
diff --git a/tests/test_console.cc b/tests/test_console.cc deleted file mode 100644 index 518de2e..0000000 --- a/tests/test_console.cc +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_console.h" - -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var_array.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/cpp/var_dictionary.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(Console); - -TestConsole::TestConsole(TestingInstance* instance) - : TestCase(instance), - console_interface_(NULL) { -} - -bool TestConsole::Init() { - console_interface_ = static_cast<const PPB_Console*>( - pp::Module::Get()->GetBrowserInterface(PPB_CONSOLE_INTERFACE)); - return !!console_interface_; -} - -void TestConsole::RunTests(const std::string& filter) { - RUN_TEST(Smoke, filter); -} - -namespace { - -void TestConsoleSub(const PPB_Console* console_interface_, - PP_Instance instance, - pp::Var source, - pp::Var message) { - - console_interface_->Log(instance, PP_LOGLEVEL_ERROR, - message.pp_var()); - console_interface_->LogWithSource(instance, PP_LOGLEVEL_LOG, - source.pp_var(), message.pp_var()); -} - -} // anonymous namespace - -std::string TestConsole::TestSmoke() { - // This test does not verify the log message actually reaches the console, but - // it does test that the interface exists and that it can be called without - // crashing. - pp::Var source(std::string("somewhere")); - const PPB_Console* interface = console_interface_; - PP_Instance pp_instance = instance()->pp_instance(); - - TestConsoleSub(interface, pp_instance, source, pp::Var()); - TestConsoleSub(interface, pp_instance, source, pp::Var(pp::Var::Null())); - TestConsoleSub(interface, pp_instance, source, pp::Var(false)); - TestConsoleSub(interface, pp_instance, source, pp::Var(12345678)); - TestConsoleSub(interface, pp_instance, source, pp::Var(-0.0)); - TestConsoleSub(interface, pp_instance, source, pp::Var("Hello World!")); - TestConsoleSub(interface, pp_instance, source, pp::VarArray()); - TestConsoleSub(interface, pp_instance, source, pp::VarArrayBuffer()); - TestConsoleSub(interface, pp_instance, source, pp::VarDictionary()); - PASS(); -}
diff --git a/tests/test_console.h b/tests/test_console.h deleted file mode 100644 index 4aafabd..0000000 --- a/tests/test_console.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_CONSOLE_H_ -#define PPAPI_TESTS_TEST_CONSOLE_H_ - -#include <string> - -#include "ppapi/c/ppb_console.h" -#include "ppapi/tests/test_case.h" - -class TestConsole : public TestCase { - public: - explicit TestConsole(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestSmoke(); - - const PPB_Console* console_interface_; -}; - -#endif // PPAPI_TESTS_TEST_CONSOLE_H_
diff --git a/tests/test_core.cc b/tests/test_core.cc deleted file mode 100644 index 1557085..0000000 --- a/tests/test_core.cc +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_core.h" - -#include "ppapi/cpp/core.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(Core); - -bool TestCore::Init() { - return true; -} - -void TestCore::RunTests(const std::string& filter) { - RUN_TEST(Time, filter); - RUN_TEST(TimeTicks, filter); -} - -std::string TestCore::TestTime() { - pp::Core* core = pp::Module::Get()->core(); - PP_Time time1 = core->GetTime(); - ASSERT_TRUE(time1 > 0); - - PlatformSleep(100); // 0.1 second - - PP_Time time2 = core->GetTime(); - ASSERT_TRUE(time2 > time1); - - PASS(); -} - -std::string TestCore::TestTimeTicks() { - pp::Core* core = pp::Module::Get()->core(); - PP_Time time1 = core->GetTimeTicks(); - ASSERT_TRUE(time1 > 0); - - PlatformSleep(100); // 0.1 second - - PP_Time time2 = core->GetTimeTicks(); - ASSERT_TRUE(time2 > time1); - - PASS(); -} -
diff --git a/tests/test_core.h b/tests/test_core.h deleted file mode 100644 index e74f03e..0000000 --- a/tests/test_core.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_CORE_H_ -#define PPAPI_TESTS_TEST_CORE_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -class TestCore : public TestCase { - public: - explicit TestCore(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestTime(); - std::string TestTimeTicks(); -}; - -#endif // PPAPI_TESTS_TEST_CORE_H_
diff --git a/tests/test_cpp_includes.cc b/tests/test_cpp_includes.cc deleted file mode 100644 index 556ad00..0000000 --- a/tests/test_cpp_includes.cc +++ /dev/null
@@ -1,10 +0,0 @@ -// Copyright 2010 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// This test simply includes all the C++ headers to ensure they compile with a -// C++ compiler. If it compiles, it passes. -// - -#include "ppapi/tests/all_cpp_includes.h" -
diff --git a/tests/test_crypto.cc b/tests/test_crypto.cc deleted file mode 100644 index 7ee5171..0000000 --- a/tests/test_crypto.cc +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_crypto.h" - -#include "ppapi/c/dev/ppb_crypto_dev.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(Crypto); - -TestCrypto::TestCrypto(TestingInstance* instance) - : TestCase(instance), - crypto_interface_(NULL) { -} - -bool TestCrypto::Init() { - crypto_interface_ = static_cast<const PPB_Crypto_Dev*>( - pp::Module::Get()->GetBrowserInterface(PPB_CRYPTO_DEV_INTERFACE)); - return !!crypto_interface_; -} - -void TestCrypto::RunTests(const std::string& filter) { - RUN_TEST(GetRandomBytes, filter); -} - -std::string TestCrypto::TestGetRandomBytes() { - const int kBufSize = 16; - char buf[kBufSize] = {}; - - crypto_interface_->GetRandomBytes(buf, kBufSize); - - // Verify that the interface wrote "something" to the buffer. - bool found_nonzero = false; - for (int i = 0; i < kBufSize; i++) { - if (buf[i]) { - found_nonzero = true; - break; - } - } - ASSERT_TRUE(found_nonzero); - - PASS(); -}
diff --git a/tests/test_crypto.h b/tests/test_crypto.h deleted file mode 100644 index e68b409..0000000 --- a/tests/test_crypto.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_CRYPTO_H_ -#define PPAPI_TESTS_TEST_CRYPTO_H_ - -#include <string> - -#include "ppapi/c/dev/ppb_crypto_dev.h" -#include "ppapi/tests/test_case.h" - -class TestCrypto : public TestCase { - public: - TestCrypto(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestGetRandomBytes(); - - const PPB_Crypto_Dev* crypto_interface_; -}; - -#endif // PPAPI_TESTS_TEST_CRYPTO_H_
diff --git a/tests/test_cursor_control.cc b/tests/test_cursor_control.cc deleted file mode 100644 index 0a107cd..0000000 --- a/tests/test_cursor_control.cc +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_cursor_control.h" - -#include "ppapi/c/dev/ppb_cursor_control_dev.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(CursorControl); - -TestCursorControl::TestCursorControl(TestingInstance* instance) - : TestCase(instance), - cursor_control_interface_(NULL) { -} - -bool TestCursorControl::Init() { - cursor_control_interface_ = static_cast<const PPB_CursorControl_Dev*>( - pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE)); - return !!cursor_control_interface_; -} - -void TestCursorControl::RunTests(const std::string& filter) { - RUN_TEST(SetCursor, filter); -} - -std::string TestCursorControl::TestSetCursor() { - // Very simplistic test to make sure we can actually call the function and - // it reports success. This is a nice integration test to make sure the - // interface is hooked up. Obviously it's not easy in a plugin to test whether - // the mouse cursor actually changed. - ASSERT_TRUE(cursor_control_interface_->SetCursor(instance_->pp_instance(), - PP_CURSORTYPE_WAIT, 0, NULL)); - - PASS(); -}
diff --git a/tests/test_cursor_control.h b/tests/test_cursor_control.h deleted file mode 100644 index daba457..0000000 --- a/tests/test_cursor_control.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_CURSOR_CONTROL_H_ -#define PPAPI_TESTS_TEST_CURSOR_CONTROL_H_ - -#include <string> - -#include "ppapi/c/dev/ppb_cursor_control_dev.h" -#include "ppapi/tests/test_case.h" - -class TestCursorControl : public TestCase { - public: - TestCursorControl(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestSetCursor(); - - const PPB_CursorControl_Dev* cursor_control_interface_; -}; - -#endif // PPAPI_TESTS_TEST_CURSOR_CONTROL_H_
diff --git a/tests/test_empty.cc b/tests/test_empty.cc deleted file mode 100644 index 4b9af3d..0000000 --- a/tests/test_empty.cc +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_empty.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(Empty); -// This test checks only that the NaCl module loads successfully. -// This is needed when the NaCl module is launched under the debugger and -// so we want to check only the launching sequence. -TestEmpty::TestEmpty(TestingInstance* instance) - : TestCase(instance) { -} - -bool TestEmpty::Init() { - return true; -} - -void TestEmpty::RunTests(const std::string& filter) { - RUN_TEST(NaClLoad, filter); -} - -std::string TestEmpty::TestNaClLoad() { - PASS(); -}
diff --git a/tests/test_empty.h b/tests/test_empty.h deleted file mode 100644 index d1f268e..0000000 --- a/tests/test_empty.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_EMPTY_H_ -#define PPAPI_TESTS_TEST_EMPTY_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -class TestEmpty : public TestCase { - public: - explicit TestEmpty(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestNaClLoad(); -}; - -#endif // PPAPI_TESTS_TEST_EMPTY_H_
diff --git a/tests/test_file_chooser.cc b/tests/test_file_chooser.cc deleted file mode 100644 index 2620247..0000000 --- a/tests/test_file_chooser.cc +++ /dev/null
@@ -1,221 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_file_chooser.h" - -#include <stddef.h> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/cpp/dev/file_chooser_dev.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/trusted/file_chooser_trusted.h" -#include "ppapi/cpp/var.h" - -namespace { - -// Test data written by WriteDefaultContentsToFile(). -const char kTestFileContents[] = "Hello from PPAPI"; -const size_t kTestFileContentsSizeBytes = sizeof(kTestFileContents) - 1; - -} // namespace - -REGISTER_TEST_CASE(FileChooser); - -bool TestFileChooser::Init() { - return CheckTestingInterface() && EnsureRunningOverHTTP(); -} - -void TestFileChooser::RunTests(const std::string& filter) { - RUN_TEST(OpenSimple, filter); - RUN_TEST(OpenCancel, filter); - RUN_TEST(SaveAsSafeDefaultName, filter); - RUN_TEST(SaveAsUnsafeDefaultName, filter); - RUN_TEST(SaveAsCancel, filter); - RUN_TEST(SaveAsDangerousExecutableAllowed, filter); - RUN_TEST(SaveAsDangerousExecutableDisallowed, filter); - RUN_TEST(SaveAsDangerousExtensionListDisallowed, filter); -} - -bool TestFileChooser::WriteDefaultContentsToFile(const pp::FileRef& file_ref) { - TestCompletionCallback fileio_callback(instance_->pp_instance(), - callback_type()); - pp::FileIO fileio(instance()); - - fileio_callback.WaitForResult( - fileio.Open(file_ref, PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE, - fileio_callback.GetCallback())); - if (fileio_callback.result() != PP_OK) - return false; - - fileio_callback.WaitForResult(fileio.Write(0, kTestFileContents, - kTestFileContentsSizeBytes, - fileio_callback.GetCallback())); - return fileio_callback.result() == kTestFileContentsSizeBytes; -} - -// Tests that the plugin can invoke a simple file chooser and that the returned -// file can be read from. Note that this test doesn't test that the accepted -// file type list is honored. -std::string TestFileChooser::TestOpenSimple() { - pp::FileChooser_Dev file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, "*"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(1u, output_ref.size()); - - TestCompletionCallback fileio_callback(instance_->pp_instance(), - callback_type()); - pp::FileIO fileio(instance()); - fileio_callback.WaitForResult(fileio.Open( - output_ref.front(), PP_FILEOPENFLAG_READ, fileio_callback.GetCallback())); - ASSERT_EQ(PP_OK, fileio_callback.result()); - PASS(); -} - -// Tests the behavior when the user cancels the file chooser. Browser-side logic -// for simulating the cancellation can be found at -// ppapi_filechooser_browsertest.cc -std::string TestFileChooser::TestOpenCancel() { - pp::FileChooser_Dev file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, "*"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(0u, output_ref.size()); - PASS(); -} - -// Tests that the plugin can invoke a "Save as" dialog using the -// FileChooser_Trusted API and that the returned FileRef can be written to. -std::string TestFileChooser::TestSaveAsSafeDefaultName() { - pp::FileChooser_Trusted file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, - ".txt", true /* save_as */, - "innocuous.txt"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(1u, output_ref.size()); - - ASSERT_TRUE(WriteDefaultContentsToFile(output_ref.front())); - PASS(); -} - -// Similar to the previous test, but tests that an unsafe filename passed as the -// suggested name is sanitized. -std::string TestFileChooser::TestSaveAsUnsafeDefaultName() { - pp::FileChooser_Trusted file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, - "text/plain,.html", true /* save_as */, - "unsafe.txt "); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(1u, output_ref.size()); - ASSERT_EQ("unsafe.txt_", output_ref.front().GetName().AsString()); - - ASSERT_TRUE(WriteDefaultContentsToFile(output_ref.front())); - PASS(); -} - -// Tests the behavior when the user cancels a Save As file chooser. Requires -// that the test runner cancel the Save As dialog. -std::string TestFileChooser::TestSaveAsCancel() { - pp::FileChooser_Trusted file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, "*", - true /* save as */, "anything.txt"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(0u, output_ref.size()); - PASS(); -} - -// Checks that a dangerous file is allowed to be downloaded via the -// FileChooser_Trusted API. Chrome should delegate the decision of which files -// are allowed over to SafeBrowsing (if enabled), and the current SafeBrowsing -// configuration should allow downloading of dangerous files for this test to -// work. -std::string TestFileChooser::TestSaveAsDangerousExecutableAllowed() { - pp::FileChooser_Trusted file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, - ".exe", true /* save_as */, - "dangerous.exe"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(1u, output_ref.size()); - ASSERT_EQ("dangerous.exe", output_ref.front().GetName().AsString()); - - ASSERT_TRUE(WriteDefaultContentsToFile(output_ref.front())); - PASS(); -} - -// Checks that a dangerous file is not allowed to be downloaded via the -// FileChooser_Trusted API. Chrome should delegate the decision of which files -// are allowed over to SafeBrowsing (if enabled), and the current SafeBrowsing -// configuration should disallow downloading of dangerous files for this test to -// work. -std::string TestFileChooser::TestSaveAsDangerousExecutableDisallowed() { - pp::FileChooser_Trusted file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, - ".exe", true /* save_as */, - "dangerous.exe"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(0u, output_ref.size()); - PASS(); -} - -// Checks that a dangerous file is not allowed to be downloaded via the -// FileChooser_Trusted API. Chrome should delegate the decision of which files -// are allowed over to SafeBrowsing (if enabled), and the current SafeBrowsing -// configuration should disallow downloading of dangerous files for this test to -// work. -std::string TestFileChooser::TestSaveAsDangerousExtensionListDisallowed() { - pp::FileChooser_Trusted file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, - ".txt,.exe", true /* save_as */, - "innocuous.txt"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef>> - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(0u, output_ref.size()); - PASS(); -}
diff --git a/tests/test_file_chooser.h b/tests/test_file_chooser.h deleted file mode 100644 index e83024b..0000000 --- a/tests/test_file_chooser.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_FILE_CHOOSER_H_ -#define PPAPI_TESTS_TEST_FILE_CHOOSER_H_ - -#include "ppapi/tests/test_case.h" - -namespace pp { -class FileRef; -} - -class TestFileChooser : public TestCase { - public: - TestFileChooser(TestingInstance* instance) : TestCase(instance) {} - - // TestCase - bool Init() override; - void RunTests(const std::string& filter) override; - - private: - // Writes the string "Hello from PPAPI" into the file represented by - // |file_ref|. Returns true on success. - bool WriteDefaultContentsToFile(const pp::FileRef& file_ref); - - std::string TestOpenSimple(); - std::string TestOpenCancel(); - std::string TestSaveAsSafeDefaultName(); - std::string TestSaveAsUnsafeDefaultName(); - std::string TestSaveAsCancel(); - std::string TestSaveAsDangerousExecutableAllowed(); - std::string TestSaveAsDangerousExecutableDisallowed(); - std::string TestSaveAsDangerousExtensionListDisallowed(); -}; - -#endif // PPAPI_TESTS_TEST_FILE_CHOOSER_H_
diff --git a/tests/test_file_io.cc b/tests/test_file_io.cc deleted file mode 100644 index 2486787..0000000 --- a/tests/test_file_io.cc +++ /dev/null
@@ -1,1375 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_file_io.h" - -#include <errno.h> -#include <fcntl.h> -#include <stddef.h> -#include <stdio.h> -#include <string.h> -#include <sys/stat.h> -#include <sys/types.h> - -#include <algorithm> -#include <vector> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/c/private/pp_file_handle.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/file_io_private.h" -#include "ppapi/cpp/private/pass_file_handle.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -#if defined(PPAPI_OS_WIN) -# include <io.h> -# include <windows.h> -// TODO(hamaji): Use standard windows APIs instead of compatibility layer? -# define lseek _lseek -# define read _read -# define write _write -# define ssize_t int -#else -# include <sys/mman.h> -# include <unistd.h> -#endif - -REGISTER_TEST_CASE(FileIO); - -namespace { - -std::string ReportMismatch(const std::string& method_name, - const std::string& returned_result, - const std::string& expected_result) { - return method_name + " returned '" + returned_result + "'; '" + - expected_result + "' expected."; -} - -std::string ReportOpenError(int32_t open_flags) { - static const char* kFlagNames[] = { - "PP_FILEOPENFLAG_READ", - "PP_FILEOPENFLAG_WRITE", - "PP_FILEOPENFLAG_CREATE", - "PP_FILEOPENFLAG_TRUNCATE", - "PP_FILEOPENFLAG_EXCLUSIVE" - }; - - std::string result = "FileIO:Open had unexpected behavior with flags: "; - bool first_flag = true; - for (int32_t mask = 1, index = 0; mask <= PP_FILEOPENFLAG_EXCLUSIVE; - mask <<= 1, ++index) { - if (mask & open_flags) { - if (first_flag) { - first_flag = false; - } else { - result += " | "; - } - result += kFlagNames[index]; - } - } - if (first_flag) - result += "[None]"; - - return result; -} - -int32_t ReadEntireFile(PP_Instance instance, - pp::FileIO* file_io, - int32_t offset, - std::string* data, - CallbackType callback_type) { - TestCompletionCallback callback(instance, callback_type); - char buf[256]; - int32_t read_offset = offset; - - for (;;) { - callback.WaitForResult( - file_io->Read(read_offset, buf, sizeof(buf), callback.GetCallback())); - if (callback.result() < 0) - return callback.result(); - if (callback.result() == 0) - break; - read_offset += callback.result(); - data->append(buf, callback.result()); - } - - return PP_OK; -} - -int32_t ReadToArrayEntireFile(PP_Instance instance, - pp::FileIO* file_io, - int32_t offset, - std::string* data, - CallbackType callback_type) { - TestCompletionCallbackWithOutput< std::vector<char> > callback( - instance, callback_type); - - for (;;) { - callback.WaitForResult(file_io->Read(offset, 256, callback.GetCallback())); - int32_t rv = callback.result(); - if (rv < 0) - return rv; - if (rv == 0) - break; - const std::vector<char>& output = callback.output(); - assert(rv == static_cast<int32_t>(output.size())); - offset += rv; - data->append(output.begin(), output.end()); - } - - return PP_OK; -} - -#if !defined(PPAPI_OS_WIN) -bool ReadEntireFileFromFileHandle(int fd, std::string* data) { - if (lseek(fd, 0, SEEK_SET) < 0) - return false; - data->clear(); - - int ret; - do { - char buf[8192]; - ret = read(fd, buf, sizeof(buf)); - if (ret > 0) - data->append(buf, ret); - } while (ret > 0); - return ret == 0; -} -#endif // !defined(PPAPI_OS_WIN) - -int32_t WriteEntireBuffer(PP_Instance instance, - pp::FileIO* file_io, - int32_t offset, - const std::string& data, - CallbackType callback_type) { - TestCompletionCallback callback(instance, callback_type); - int32_t write_offset = offset; - const char* buf = data.c_str(); - int32_t size = static_cast<int32_t>(data.size()); - - while (write_offset < offset + size) { - callback.WaitForResult(file_io->Write(write_offset, - &buf[write_offset - offset], - size - write_offset + offset, - callback.GetCallback())); - if (callback.result() < 0) - return callback.result(); - if (callback.result() == 0) - return PP_ERROR_FAILED; - write_offset += callback.result(); - } - - return PP_OK; -} - -} // namespace - -bool TestFileIO::Init() { - return CheckTestingInterface() && EnsureRunningOverHTTP(); -} - -void TestFileIO::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestFileIO, Open, filter); - RUN_CALLBACK_TEST(TestFileIO, OpenDirectory, filter); - RUN_CALLBACK_TEST(TestFileIO, ReadWriteSetLength, filter); - RUN_CALLBACK_TEST(TestFileIO, ReadToArrayWriteSetLength, filter); - RUN_CALLBACK_TEST(TestFileIO, TouchQuery, filter); - RUN_CALLBACK_TEST(TestFileIO, AbortCalls, filter); - RUN_CALLBACK_TEST(TestFileIO, ParallelReads, filter); - RUN_CALLBACK_TEST(TestFileIO, ParallelWrites, filter); - RUN_CALLBACK_TEST(TestFileIO, NotAllowMixedReadWrite, filter); - RUN_CALLBACK_TEST(TestFileIO, RequestOSFileHandle, filter); - RUN_CALLBACK_TEST(TestFileIO, RequestOSFileHandleWithOpenExclusive, filter); - RUN_CALLBACK_TEST(TestFileIO, Mmap, filter); - - // TODO(viettrungluu): add tests: - // - that PP_ERROR_PENDING is correctly returned - // - that operations respect the file open modes (flags) -} - -std::string TestFileIO::TestOpen() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_open"); - - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - std::string result; - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_READ, - DONT_CREATE_IF_DOESNT_EXIST | OPEN_IF_EXISTS | DONT_TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - // Test the behavior of the power set of - // { PP_FILEOPENFLAG_CREATE, - // PP_FILEOPENFLAG_TRUNCATE, - // PP_FILEOPENFLAG_EXCLUSIVE }. - - // First of all, none of them are specified. - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE, - DONT_CREATE_IF_DOESNT_EXIST | OPEN_IF_EXISTS | DONT_TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE, - CREATE_IF_DOESNT_EXIST | OPEN_IF_EXISTS | DONT_TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_EXCLUSIVE, - DONT_CREATE_IF_DOESNT_EXIST | OPEN_IF_EXISTS | DONT_TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_TRUNCATE, - DONT_CREATE_IF_DOESNT_EXIST | OPEN_IF_EXISTS | TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_EXCLUSIVE, - CREATE_IF_DOESNT_EXIST | DONT_OPEN_IF_EXISTS | DONT_TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE | PP_FILEOPENFLAG_TRUNCATE, - CREATE_IF_DOESNT_EXIST | OPEN_IF_EXISTS | TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_EXCLUSIVE | - PP_FILEOPENFLAG_TRUNCATE, - DONT_CREATE_IF_DOESNT_EXIST | OPEN_IF_EXISTS | TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_EXCLUSIVE | PP_FILEOPENFLAG_TRUNCATE, - CREATE_IF_DOESNT_EXIST | DONT_OPEN_IF_EXISTS | DONT_TRUNCATE_IF_EXISTS); - if (!result.empty()) - return result; - - // Invalid combination: PP_FILEOPENFLAG_TRUNCATE without - // PP_FILEOPENFLAG_WRITE. - result = MatchOpenExpectations( - &file_system, - PP_FILEOPENFLAG_READ | PP_FILEOPENFLAG_TRUNCATE, - INVALID_FLAG_COMBINATION); - if (!result.empty()) - return result; - - PASS(); -} - -std::string TestFileIO::TestOpenDirectory() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Make a directory. - pp::FileRef dir_ref(file_system, "/test_dir_open_directory"); - callback.WaitForResult(dir_ref.MakeDirectory( - PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Open the directory. This is expected to fail since directories cannot be - // opened. - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(dir_ref, PP_FILEOPENFLAG_READ, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_NOTAFILE, callback.result()); - - PASS(); -} - -std::string TestFileIO::TestReadWriteSetLength() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_read_write_setlength"); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Write something to the file. - int32_t rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 0, - "test_test", callback_type()); - ASSERT_EQ(PP_OK, rv); - - // Attempt to read a negative number of bytes; it should fail. - char buf[256]; - callback.WaitForResult(file_io.Read(0, - buf, - -1, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - // Read the entire file. - std::string read_buffer; - rv = ReadEntireFile(instance_->pp_instance(), &file_io, 0, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test_test"), read_buffer); - - // Truncate the file. - callback.WaitForResult(file_io.SetLength(4, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Check the file contents. - read_buffer.clear(); - rv = ReadEntireFile(instance_->pp_instance(), &file_io, 0, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test"), read_buffer); - - // Try to read past the end of the file. - read_buffer.clear(); - rv = ReadEntireFile(instance_->pp_instance(), &file_io, 100, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_TRUE(read_buffer.empty()); - - // Write past the end of the file. The file should be zero-padded. - rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 8, "test", - callback_type()); - ASSERT_EQ(PP_OK, rv); - - // Check the contents of the file. - read_buffer.clear(); - rv = ReadEntireFile(instance_->pp_instance(), &file_io, 0, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test\0\0\0\0test", 12), read_buffer); - - // Extend the file. - callback.WaitForResult(file_io.SetLength(16, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Check the contents of the file. - read_buffer.clear(); - rv = ReadEntireFile(instance_->pp_instance(), &file_io, 0, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test\0\0\0\0test\0\0\0\0", 16), read_buffer); - - // Write in the middle of the file. - rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 4, "test", - callback_type()); - ASSERT_EQ(PP_OK, rv); - - // Check the contents of the file. - read_buffer.clear(); - rv = ReadEntireFile(instance_->pp_instance(), &file_io, 0, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("testtesttest\0\0\0\0", 16), read_buffer); - - // Read from the middle of the file. - read_buffer.clear(); - rv = ReadEntireFile(instance_->pp_instance(), &file_io, 4, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("testtest\0\0\0\0", 12), read_buffer); - - // Append to the end of the file. - pp::FileIO file_io2(instance_); - callback.WaitForResult(file_io2.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_APPEND, - callback.GetCallback())); - rv = WriteEntireBuffer(instance_->pp_instance(), &file_io2, 0, "appended", - callback_type()); - ASSERT_EQ(PP_OK, rv); - read_buffer.clear(); - rv = ReadEntireFile(instance_->pp_instance(), &file_io2, 0, &read_buffer, - callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("testtesttest\0\0\0\0appended", 24), read_buffer); - - PASS(); -} - -// This is basically a copy of TestReadWriteSetLength, but with the new Read -// API. With this test case, we can make sure the two Read's have the same -// behavior. -std::string TestFileIO::TestReadToArrayWriteSetLength() { - if (callback_type() == PP_BLOCKING) { - // This test does not make sense for blocking callbacks. - PASS(); - } - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_read_write_setlength"); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Write something to the file. - int32_t rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 0, - "test_test", callback_type()); - ASSERT_EQ(PP_OK, rv); - - TestCompletionCallbackWithOutput< std::vector<char> > callback2( - instance_->pp_instance(), callback_type()); - // Attempt to read a negative number of bytes; it should fail. - callback2.WaitForResult(file_io.Read(0, -1, callback2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback2); - ASSERT_EQ(PP_ERROR_FAILED, callback2.result()); - - // Read the entire file. - std::string read_buffer; - read_buffer.reserve(10); - rv = ReadToArrayEntireFile(instance_->pp_instance(), &file_io, 0, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test_test"), read_buffer); - - // Truncate the file. - callback.WaitForResult(file_io.SetLength(4, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, rv); - - // Check the file contents. - read_buffer.clear(); - rv = ReadToArrayEntireFile(instance_->pp_instance(), &file_io, 0, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test"), read_buffer); - - // Try to read past the end of the file. - read_buffer.clear(); - rv = ReadToArrayEntireFile(instance_->pp_instance(), &file_io, 100, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_TRUE(read_buffer.empty()); - - // Write past the end of the file. The file should be zero-padded. - rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 8, "test", - callback_type()); - ASSERT_EQ(PP_OK, rv); - - // Check the contents of the file. - read_buffer.clear(); - rv = ReadToArrayEntireFile(instance_->pp_instance(), &file_io, 0, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test\0\0\0\0test", 12), read_buffer); - - // Extend the file. - callback.WaitForResult(file_io.SetLength(16, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Check the contents of the file. - read_buffer.clear(); - rv = ReadToArrayEntireFile(instance_->pp_instance(), &file_io, 0, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("test\0\0\0\0test\0\0\0\0", 16), read_buffer); - - // Write in the middle of the file. - rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 4, "test", - callback_type()); - ASSERT_EQ(PP_OK, rv); - - // Check the contents of the file. - read_buffer.clear(); - rv = ReadToArrayEntireFile(instance_->pp_instance(), &file_io, 0, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("testtesttest\0\0\0\0", 16), read_buffer); - - // Read from the middle of the file. - read_buffer.clear(); - rv = ReadToArrayEntireFile(instance_->pp_instance(), &file_io, 4, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("testtest\0\0\0\0", 12), read_buffer); - - PASS(); -} - -std::string TestFileIO::TestTouchQuery() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef file_ref(file_system, "/file_touch"); - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Write some data to have a non-zero file size. - callback.WaitForResult(file_io.Write(0, "test", 4, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(4, callback.result()); - - const PP_Time last_access_time = 123 * 24 * 3600.0; - // last_modified_time's granularity is 2 seconds - // NOTE: In NaCl on Windows, NaClDescIO uses _fstat64 to retrieve file info. - // This function returns strange values for very small time values (near the - // Unix Epoch). For a value like 246.0, it returns -1. For larger values, it - // returns values that are exactly an hour less. The value below is handled - // correctly, and is only 100 days after the start of Unix time. - const PP_Time last_modified_time = 100 * 24 * 3600.0; - callback.WaitForResult(file_io.Touch(last_access_time, last_modified_time, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - PP_FileInfo info; - callback.WaitForResult(file_io.Query(&info, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - if ((info.size != 4) || - (info.type != PP_FILETYPE_REGULAR) || - (info.system_type != PP_FILESYSTEMTYPE_LOCALTEMPORARY)) - // Disabled due to DST-related failure: crbug.com/314579 - //(info.last_access_time != last_access_time) || - //(info.last_modified_time != last_modified_time)) - return "FileIO::Query() has returned bad data."; - - // Call |Query()| again, to make sure it works a second time. - callback.WaitForResult(file_io.Query(&info, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - PASS(); -} - -std::string TestFileIO::TestAbortCalls() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_abort_calls"); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - int32_t rv = PP_ERROR_FAILED; - // First, create a file on which to do ops. - { - pp::FileIO file_io(instance_); - callback.WaitForResult( - file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // N.B.: Should write at least 3 bytes. - rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 0, - "foobarbazquux", callback_type()); - ASSERT_EQ(PP_OK, rv); - } - - // Abort |Open()|. - { - rv = pp::FileIO(instance_) - .Open(file_ref, PP_FILEOPENFLAG_READ, callback.GetCallback()); - } - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - - // Abort |Query()|. - { - PP_FileInfo info = { 0 }; - // Save a copy and make sure |info| doesn't get written to if it is aborted. - PP_FileInfo info_copy; - memcpy(&info_copy, &info, sizeof(info)); - { - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, PP_FILEOPENFLAG_READ, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = file_io.Query(&info, callback.GetCallback()); - } // Destroy |file_io|. - callback.WaitForResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - if (callback_type() == PP_BLOCKING) { - ASSERT_EQ(PP_OK, callback.result()); - // The operation completed synchronously, so |info| should have changed. - ASSERT_NE(0, memcmp(&info_copy, &info, sizeof(info))); - } else { - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - ASSERT_EQ(0, memcmp(&info_copy, &info, sizeof(info))); - } - } - - // Abort |Touch()|. - { - { - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = file_io.Touch(0, 0, callback.GetCallback()); - } // Destroy |file_io|. - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - } - - // Abort |Read()|. - { - char buf[3] = { 0 }; - { - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, PP_FILEOPENFLAG_READ, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = file_io.Read(0, buf, sizeof(buf), callback.GetCallback()); - } // Destroy |file_io|. - // Save a copy to make sure buf isn't written to in the async case. - char buf_copy[3]; - memcpy(&buf_copy, &buf, sizeof(buf)); - callback.WaitForResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - if (callback_type() == PP_BLOCKING) { - ASSERT_EQ(callback.result(), sizeof(buf)); - } else { - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - ASSERT_EQ(0, memcmp(&buf_copy, &buf, sizeof(buf))); - } - } - - // Abort |Write()|. - { - char buf[3] = { 0 }; - { - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = file_io.Write(0, buf, sizeof(buf), callback.GetCallback()); - } // Destroy |file_io|. - callback.WaitForResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - if (callback_type() == PP_BLOCKING) - ASSERT_EQ(callback.result(), sizeof(buf)); - else - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - } - - // Abort |SetLength()|. - { - { - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = file_io.SetLength(3, callback.GetCallback()); - } // Destroy |file_io|. - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - } - - // Abort |Flush|. - { - { - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = file_io.Flush(callback.GetCallback()); - } // Destroy |file_io|. - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - } - - PASS(); -} - -std::string TestFileIO::TestParallelReads() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_parallel_reads"); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Set up testing contents. - int32_t rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 0, - "abcdefghijkl", callback_type()); - ASSERT_EQ(PP_OK, rv); - - // Parallel read operations. - const char* border = "__border__"; - const int32_t border_size = static_cast<int32_t>(strlen(border)); - - TestCompletionCallback callback_1(instance_->pp_instance(), callback_type()); - int32_t read_offset_1 = 0; - int32_t size_1 = 3; - std::vector<char> extended_buf_1(border_size * 2 + size_1); - char* buf_1 = &extended_buf_1[border_size]; - memcpy(&extended_buf_1[0], border, border_size); - memcpy(buf_1 + size_1, border, border_size); - - TestCompletionCallback callback_2(instance_->pp_instance(), callback_type()); - int32_t read_offset_2 = size_1; - int32_t size_2 = 9; - std::vector<char> extended_buf_2(border_size * 2 + size_2); - char* buf_2 = &extended_buf_2[border_size]; - memcpy(&extended_buf_2[0], border, border_size); - memcpy(buf_2 + size_2, border, border_size); - - int32_t rv_1 = PP_OK; - int32_t rv_2 = PP_OK; - while (size_1 >= 0 && size_2 >= 0 && size_1 + size_2 > 0) { - if (size_1 > 0) { - rv_1 = file_io.Read(read_offset_1, buf_1, size_1, - callback_1.GetCallback()); - } - if (size_2 > 0) { - rv_2 = file_io.Read(read_offset_2, buf_2, size_2, - callback_2.GetCallback()); - } - if (size_1 > 0) { - callback_1.WaitForResult(rv_1); - CHECK_CALLBACK_BEHAVIOR(callback_1); - ASSERT_TRUE(callback_1.result() > 0); - read_offset_1 += callback_1.result(); - buf_1 += callback_1.result(); - size_1 -= callback_1.result(); - } - - if (size_2 > 0) { - callback_2.WaitForResult(rv_2); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_TRUE(callback_2.result() > 0); - read_offset_2 += callback_2.result(); - buf_2 += callback_2.result(); - size_2 -= callback_2.result(); - } - } - - // If |size_1| or |size_2| is not 0, we have invoked wrong callback(s). - ASSERT_EQ(0, size_1); - ASSERT_EQ(0, size_2); - - // Make sure every read operation writes into the correct buffer. - const char expected_result_1[] = "__border__abc__border__"; - const char expected_result_2[] = "__border__defghijkl__border__"; - ASSERT_TRUE(strncmp(&extended_buf_1[0], expected_result_1, - strlen(expected_result_1)) == 0); - ASSERT_TRUE(strncmp(&extended_buf_2[0], expected_result_2, - strlen(expected_result_2)) == 0); - PASS(); -} - -std::string TestFileIO::TestParallelWrites() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_parallel_writes"); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Parallel write operations. - TestCompletionCallback callback_1(instance_->pp_instance(), callback_type()); - int32_t write_offset_1 = 0; - const char* buf_1 = "abc"; - int32_t size_1 = static_cast<int32_t>(strlen(buf_1)); - - TestCompletionCallback callback_2(instance_->pp_instance(), callback_type()); - int32_t write_offset_2 = size_1; - const char* buf_2 = "defghijkl"; - int32_t size_2 = static_cast<int32_t>(strlen(buf_2)); - - int32_t rv_1 = PP_OK; - int32_t rv_2 = PP_OK; - while (size_1 >= 0 && size_2 >= 0 && size_1 + size_2 > 0) { - if (size_1 > 0) { - // Copy the buffer so we can erase it below. - std::string str_1(buf_1); - rv_1 = file_io.Write( - write_offset_1, &str_1[0], static_cast<int32_t>(str_1.size()), - callback_1.GetCallback()); - // Erase the buffer to test that async writes copy it. - std::fill(str_1.begin(), str_1.end(), 0); - } - if (size_2 > 0) { - // Copy the buffer so we can erase it below. - std::string str_2(buf_2); - rv_2 = file_io.Write( - write_offset_2, &str_2[0], static_cast<int32_t>(str_2.size()), - callback_2.GetCallback()); - // Erase the buffer to test that async writes copy it. - std::fill(str_2.begin(), str_2.end(), 0); - } - - if (size_1 > 0) { - callback_1.WaitForResult(rv_1); - CHECK_CALLBACK_BEHAVIOR(callback_1); - ASSERT_TRUE(callback_1.result() > 0); - write_offset_1 += callback_1.result(); - buf_1 += callback_1.result(); - size_1 -= callback_1.result(); - } - - if (size_2 > 0) { - callback_2.WaitForResult(rv_2); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_TRUE(callback_2.result() > 0); - write_offset_2 += callback_2.result(); - buf_2 += callback_2.result(); - size_2 -= callback_2.result(); - } - } - - // If |size_1| or |size_2| is not 0, we have invoked wrong callback(s). - ASSERT_EQ(0, size_1); - ASSERT_EQ(0, size_2); - - // Check the file contents. - std::string read_buffer; - int32_t rv = ReadEntireFile(instance_->pp_instance(), &file_io, 0, - &read_buffer, callback_type()); - ASSERT_EQ(PP_OK, rv); - ASSERT_EQ(std::string("abcdefghijkl"), read_buffer); - - PASS(); -} - -std::string TestFileIO::TestNotAllowMixedReadWrite() { - if (callback_type() == PP_BLOCKING) { - // This test does not make sense for blocking callbacks. - PASS(); - } - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_not_allow_mixed_read_write"); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallback callback_1(instance_->pp_instance(), PP_REQUIRED); - int32_t write_offset_1 = 0; - const char* buf_1 = "mnopqrstuvw"; - int32_t rv_1 = file_io.Write(write_offset_1, buf_1, - static_cast<int32_t>(strlen(buf_1)), - callback_1.GetCallback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, rv_1); - - TestCompletionCallback callback_2(instance_->pp_instance(), callback_type()); - int32_t read_offset_2 = 4; - char buf_2[3]; - callback_2.WaitForResult(file_io.Read(read_offset_2, buf_2, sizeof(buf_2), - callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_EQ(PP_ERROR_INPROGRESS, callback_2.result()); - callback_1.WaitForResult(rv_1); - CHECK_CALLBACK_BEHAVIOR(callback_1); - - // Cannot query while a write is pending. - rv_1 = file_io.Write(write_offset_1, buf_1, - static_cast<int32_t>(strlen(buf_1)), - callback_1.GetCallback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, rv_1); - PP_FileInfo info; - callback_2.WaitForResult(file_io.Query(&info, callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_EQ(PP_ERROR_INPROGRESS, callback_2.result()); - callback_1.WaitForResult(rv_1); - CHECK_CALLBACK_BEHAVIOR(callback_1); - - // Cannot touch while a write is pending. - rv_1 = file_io.Write(write_offset_1, buf_1, - static_cast<int32_t>(strlen(buf_1)), - callback_1.GetCallback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, rv_1); - callback_2.WaitForResult(file_io.Touch(1234.0, 5678.0, - callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_EQ(PP_ERROR_INPROGRESS, callback_2.result()); - callback_1.WaitForResult(rv_1); - CHECK_CALLBACK_BEHAVIOR(callback_1); - - // Cannot set length while a write is pending. - rv_1 = file_io.Write(write_offset_1, buf_1, - static_cast<int32_t>(strlen(buf_1)), - callback_1.GetCallback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, rv_1); - callback_2.WaitForResult(file_io.SetLength(123, callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_EQ(PP_ERROR_INPROGRESS, callback_2.result()); - callback_1.WaitForResult(rv_1); - CHECK_CALLBACK_BEHAVIOR(callback_1); - - PASS(); -} - -std::string TestFileIO::TestRequestOSFileHandle() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_os_fd"); - - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileIO_Private file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallbackWithOutput<pp::PassFileHandle> output_callback( - instance_->pp_instance(), callback_type()); - output_callback.WaitForResult( - file_io.RequestOSFileHandle(output_callback.GetCallback())); - PP_FileHandle handle = output_callback.output().Release(); - ASSERT_EQ(PP_OK, output_callback.result()); - - if (handle == PP_kInvalidFileHandle) - return "FileIO::RequestOSFileHandle() returned a bad file handle."; -#if defined(PPAPI_OS_WIN) - int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle), - _O_RDWR | _O_BINARY); -#else - int fd = handle; -#endif - if (fd < 0) - return "FileIO::RequestOSFileHandle() returned a bad file descriptor."; - - // Check write(2) for the native FD. - const std::string msg = "foobar"; - ssize_t cnt = write(fd, msg.data(), static_cast<unsigned>(msg.size())); - if (cnt < 0) - return ReportError("write for native FD returned error", errno); - if (cnt != static_cast<ssize_t>(msg.size())) - return ReportError("write for native FD count mismatch", cnt); - - // Check lseek(2) for the native FD. - off_t off = lseek(fd, 0, SEEK_CUR); - if (off == static_cast<off_t>(-1)) - return ReportError("lseek for native FD returned error", errno); - if (off != static_cast<off_t>(msg.size())) - return ReportError("lseek for native FD offset mismatch", off); - - off = lseek(fd, 0, SEEK_SET); - if (off == static_cast<off_t>(-1)) - return ReportError("lseek for native FD returned error", errno); - if (off != 0) - return ReportError("lseek for native FD offset mismatch", off); - - // Check read(2) for the native FD. - std::string buf(msg.size(), '\0'); - cnt = read(fd, &buf[0], static_cast<unsigned>(msg.size())); - if (cnt < 0) - return ReportError("read for native FD returned error", errno); - if (cnt != static_cast<ssize_t>(msg.size())) - return ReportError("read for native FD count mismatch", cnt); - if (msg != buf) - return ReportMismatch("read for native FD", buf, msg); - PASS(); -} - -// Calling RequestOSFileHandle with the FileIO that is opened with -// PP_FILEOPENFLAG_EXCLUSIVE used to cause NaCl module to crash while loading. -// This is a regression test for crbug.com/243241. -std::string TestFileIO::TestRequestOSFileHandleWithOpenExclusive() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_os_fd2"); - - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - // Open with PP_FILEOPENFLAG_CREATE and PP_FILEOPENFLAG_EXCLUSIVE will fail - // if the file already exists. Delete it here to make sure it does not. - callback.WaitForResult(file_ref.Delete(callback.GetCallback())); - - pp::FileIO_Private file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE | - PP_FILEOPENFLAG_EXCLUSIVE, - callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallbackWithOutput<pp::PassFileHandle> output_callback( - instance_->pp_instance(), callback_type()); - output_callback.WaitForResult( - file_io.RequestOSFileHandle(output_callback.GetCallback())); - PP_FileHandle handle = output_callback.output().Release(); - if (handle == PP_kInvalidFileHandle) - return "FileIO::RequestOSFileHandle() returned a bad file handle."; - ASSERT_EQ(PP_OK, output_callback.result()); - - PASS(); -} - -std::string TestFileIO::TestMmap() { -#if !defined(PPAPI_OS_WIN) - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::FileRef file_ref(file_system, "/file_os_fd"); - - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileIO_Private file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_READ | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallbackWithOutput<pp::PassFileHandle> output_callback( - instance_->pp_instance(), callback_type()); - output_callback.WaitForResult( - file_io.RequestOSFileHandle(output_callback.GetCallback())); - PP_FileHandle handle = output_callback.output().Release(); - ASSERT_EQ(PP_OK, output_callback.result()); - - if (handle == PP_kInvalidFileHandle) - return "FileIO::RequestOSFileHandle() returned a bad file handle."; - int fd = handle; - if (fd < 0) - return "FileIO::RequestOSFileHandle() returned a bad file descriptor."; - - // Check write(2) for the native FD. - const std::string msg = "foobar"; - ssize_t cnt = write(fd, msg.data(), msg.size()); - if (cnt < 0) - return ReportError("write for native FD returned error", errno); - if (cnt != static_cast<ssize_t>(msg.size())) - return ReportError("write for native FD count mismatch", cnt); - - // BEGIN mmap(2) test with a file handle opened in READ-WRITE mode. - // Check mmap(2) for read. - { - char* mapped = reinterpret_cast<char*>( - mmap(NULL, msg.size(), PROT_READ, MAP_PRIVATE, fd, 0)); - if (mapped == MAP_FAILED) - return ReportError("mmap(r) for native FD returned errno", errno); - // Make sure the buffer is cleared. - std::string buf = std::string(msg.size(), '\0'); - memcpy(&buf[0], mapped, msg.size()); - if (msg != buf) - return ReportMismatch("mmap(r) for native FD", buf, msg); - int r = munmap(mapped, msg.size()); - if (r < 0) - return ReportError("munmap for native FD returned error", errno); - } - - // Check mmap(2) for write with MAP_PRIVATE - { - char* mapped = reinterpret_cast<char*>( - mmap(NULL, msg.size(), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)); - if (mapped == MAP_FAILED) - return ReportError("mmap(r) for native FD returned errno", errno); - // Make sure the file is not polluted by writing to privage mmap. - strncpy(mapped, "baz", 3); - std::string read_buffer; - ASSERT_TRUE(ReadEntireFileFromFileHandle(fd, &read_buffer)); - if (msg != read_buffer) - return ReportMismatch("file content != msg", read_buffer, msg); - int r = munmap(mapped, msg.size()); - if (r < 0) - return ReportError("munmap for native FD returned error", errno); - } - - // Check mmap(2) for write with MAP_SHARED. - { - char* mapped = reinterpret_cast<char*>( - mmap(NULL, msg.size(), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); - if (mapped == MAP_FAILED) - return ReportError("mmap(w) for native FD returned errno", errno); - // s/foo/baz/ - strncpy(mapped, "baz", 3); - std::string read_buffer; - ASSERT_TRUE(ReadEntireFileFromFileHandle(fd, &read_buffer)); - if (read_buffer != "bazbar") - return ReportMismatch("file content != msg", read_buffer, "bazbar"); - int r = munmap(mapped, msg.size()); - if (r < 0) - return ReportError("munmap for native FD returned error", errno); - } - // END mmap(2) test with a file handle opened in READ-WRITE mode. - - if (close(fd) < 0) - return ReportError("close for native FD returned error", errno); - - // BEGIN mmap(2) test with a file handle opened in READONLY mode. - file_io = pp::FileIO_Private(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_READ, - callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - output_callback = TestCompletionCallbackWithOutput<pp::PassFileHandle>( - instance_->pp_instance(), callback_type()); - output_callback.WaitForResult( - file_io.RequestOSFileHandle(output_callback.GetCallback())); - handle = output_callback.output().Release(); - ASSERT_EQ(PP_OK, output_callback.result()); - - if (handle == PP_kInvalidFileHandle) - return "FileIO::RequestOSFileHandle() returned a bad file handle."; - fd = handle; - if (fd < 0) - return "FileIO::RequestOSFileHandle() returned a bad file descriptor."; - - const std::string msg2 = "bazbar"; - - // Check mmap(2) for read. - { - char* mapped = reinterpret_cast<char*>( - mmap(NULL, msg2.size(), PROT_READ, MAP_PRIVATE, fd, 0)); - if (mapped == MAP_FAILED) - return ReportError("mmap(r) for native FD returned errno", errno); - // Make sure the buffer is cleared. - std::string buf = std::string(msg2.size(), '\0'); - memcpy(&buf[0], mapped, msg2.size()); - if (msg2 != buf) - return ReportMismatch("mmap(r) for native FD", buf, msg2); - int r = munmap(mapped, msg2.size()); - if (r < 0) - return ReportError("munmap for native FD returned error", errno); - } - - // Check mmap(2) for write with MAP_PRIVATE - { - char* mapped = reinterpret_cast<char*>( - mmap(NULL, msg2.size(), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)); - if (mapped == MAP_FAILED) - return ReportError("mmap(r) for native FD returned errno", errno); - // Make sure the file is not polluted by writing to privage mmap. - strncpy(mapped, "baz", 3); - std::string read_buffer; - ASSERT_TRUE(ReadEntireFileFromFileHandle(fd, &read_buffer)); - if (msg2 != read_buffer) - return ReportMismatch("file content != msg2", read_buffer, msg2); - int r = munmap(mapped, msg2.size()); - if (r < 0) - return ReportError("munmap for native FD returned error", errno); - } - - // Check mmap(2) for write with MAP_SHARED. - { - char* mapped = reinterpret_cast<char*>( - mmap(NULL, msg2.size(), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); - if (mapped != MAP_FAILED) - return ReportError("mmap(w) for native FD must fail when opened readonly", - -1); - } - // END mmap(2) test with a file handle opened in READONLY mode. - - if (close(fd) < 0) - return ReportError("close for native FD returned error", errno); -#endif // !defined(PPAPI_OS_WIN) - - PASS(); -} - -std::string TestFileIO::MatchOpenExpectations(pp::FileSystem* file_system, - int32_t open_flags, - int32_t expectations) { - std::string bad_argument = - "TestFileIO::MatchOpenExpectations has invalid input arguments."; - bool invalid_combination = !!(expectations & INVALID_FLAG_COMBINATION); - if (invalid_combination) { - if (expectations != INVALID_FLAG_COMBINATION) - return bad_argument; - } else { - // Validate that one and only one of <some_expectation> and - // DONT_<some_expectation> is specified. - for (size_t remains = expectations, end = END_OF_OPEN_EXPECATION_PAIRS; - end != 0; remains >>= 2, end >>= 2) { - if (!!(remains & 1) == !!(remains & 2)) - return bad_argument; - } - } - bool create_if_doesnt_exist = !!(expectations & CREATE_IF_DOESNT_EXIST); - bool open_if_exists = !!(expectations & OPEN_IF_EXISTS); - bool truncate_if_exists = !!(expectations & TRUNCATE_IF_EXISTS); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileRef existent_file_ref( - *file_system, "/match_open_expectation_existent_non_empty_file"); - pp::FileRef nonexistent_file_ref( - *file_system, "/match_open_expectation_nonexistent_file"); - - // Setup files for test. - { - callback.WaitForResult(existent_file_ref.Delete(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_TRUE(callback.result() == PP_OK || - callback.result() == PP_ERROR_FILENOTFOUND); - callback.WaitForResult(nonexistent_file_ref.Delete(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_TRUE(callback.result() == PP_OK || - callback.result() == PP_ERROR_FILENOTFOUND); - - pp::FileIO existent_file_io(instance_); - callback.WaitForResult(existent_file_io.Open( - existent_file_ref, - PP_FILEOPENFLAG_CREATE | PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - int32_t rv = WriteEntireBuffer(instance_->pp_instance(), &existent_file_io, - 0, "foobar", callback_type()); - ASSERT_EQ(PP_OK, rv); - } - - pp::FileIO existent_file_io(instance_); - callback.WaitForResult(existent_file_io.Open(existent_file_ref, open_flags, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - if ((invalid_combination && callback.result() == PP_OK) || - (!invalid_combination && - ((callback.result() == PP_OK) != open_if_exists))) { - return ReportOpenError(open_flags); - } - - if (!invalid_combination && open_if_exists) { - PP_FileInfo info; - callback.WaitForResult(existent_file_io.Query(&info, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - if (truncate_if_exists != (info.size == 0)) - return ReportOpenError(open_flags); - } - - pp::FileIO nonexistent_file_io(instance_); - callback.WaitForResult(nonexistent_file_io.Open(nonexistent_file_ref, - open_flags, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - if ((invalid_combination && callback.result() == PP_OK) || - (!invalid_combination && - ((callback.result() == PP_OK) != create_if_doesnt_exist))) { - return ReportOpenError(open_flags); - } - - return std::string(); -} - -// TODO(viettrungluu): Test Close(). crbug.com/69457
diff --git a/tests/test_file_io.h b/tests/test_file_io.h deleted file mode 100644 index 691b6bb..0000000 --- a/tests/test_file_io.h +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_FILE_IO_H_ -#define PPAPI_TESTS_TEST_FILE_IO_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/tests/test_case.h" - -namespace pp { -class FileSystem; -} // namespace pp - -class TestFileIO : public TestCase { - public: - explicit TestFileIO(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - enum OpenExpectation { - CREATE_IF_DOESNT_EXIST = 1 << 0, - DONT_CREATE_IF_DOESNT_EXIST = 1 << 1, - OPEN_IF_EXISTS = 1 << 2, - DONT_OPEN_IF_EXISTS = 1 << 3, - TRUNCATE_IF_EXISTS = 1 << 4, - DONT_TRUNCATE_IF_EXISTS = 1 << 5, - // All values above are defined in pairs: <some_expectation> and - // DONT_<some_expectation>. - END_OF_OPEN_EXPECATION_PAIRS = DONT_TRUNCATE_IF_EXISTS, - - INVALID_FLAG_COMBINATION = 1 << 6, - }; - - std::string TestOpen(); - std::string TestOpenDirectory(); - std::string TestReadWriteSetLength(); - std::string TestReadToArrayWriteSetLength(); - std::string TestTouchQuery(); - std::string TestAbortCalls(); - std::string TestParallelReads(); - std::string TestParallelWrites(); - std::string TestNotAllowMixedReadWrite(); - std::string TestRequestOSFileHandle(); - std::string TestRequestOSFileHandleWithOpenExclusive(); - std::string TestMmap(); - - // Helper method used by TestOpen(). - // |expectations| is a combination of OpenExpectation values. The followings - // are considered as valid input: - // 1) INVALID_FLAG_COMBINATION - // 2) (DONT_)?CREATE_IF_DOESNT_EXIST | (DONT_)?OPEN_IF_EXISTS | - // (DONT_)?TRUNCATE_IF_EXISTS - std::string MatchOpenExpectations(pp::FileSystem* file_system, - int32_t open_flags, - int32_t expectations); -}; - -#endif // PPAPI_TESTS_TEST_FILE_IO_H_
diff --git a/tests/test_file_ref.cc b/tests/test_file_ref.cc deleted file mode 100644 index deedb42..0000000 --- a/tests/test_file_ref.cc +++ /dev/null
@@ -1,737 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_file_ref.h" - -#include <stddef.h> -#include <stdio.h> - -#include <sstream> -#include <vector> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/dev/file_chooser_dev.h" -#include "ppapi/cpp/directory_entry.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/url_loader.h" -#include "ppapi/cpp/url_request_info.h" -#include "ppapi/cpp/url_response_info.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(FileRef); - -namespace { - -const char* kPersFileName = "persistent"; -const char* kTempFileName = "temporary"; -const char* kParentPath = "/foo/bar"; -const char* kPersFilePath = "/foo/bar/persistent"; -const char* kTempFilePath = "/foo/bar/temporary"; -const char* kTerribleName = "!@#$%^&*()-_=+{}[] ;:'\"|`~\t\n\r\b?"; - -typedef std::vector<pp::DirectoryEntry> DirEntries; - -std::string ReportMismatch(const std::string& method_name, - const std::string& returned_result, - const std::string& expected_result) { - return method_name + " returned '" + returned_result + "'; '" + - expected_result + "' expected."; -} - -} // namespace - -bool TestFileRef::Init() { - return CheckTestingInterface() && EnsureRunningOverHTTP(); -} - -std::string TestFileRef::MakeExternalFileRef(pp::FileRef* file_ref_ext) { - pp::FileChooser_Dev file_chooser(instance(), PP_FILECHOOSERMODE_OPEN, "*"); - ASSERT_FALSE(file_chooser.is_null()); - - TestCompletionCallbackWithOutput<std::vector<pp::FileRef> > - filechooser_callback(instance_->pp_instance(), callback_type()); - filechooser_callback.WaitForResult( - file_chooser.Show(filechooser_callback.GetCallback())); - - const std::vector<pp::FileRef>& output_ref = filechooser_callback.output(); - ASSERT_EQ(1u, output_ref.size()); - - *file_ref_ext = output_ref[0]; - ASSERT_EQ(PP_FILESYSTEMTYPE_EXTERNAL, file_ref_ext->GetFileSystemType()); - PASS(); -} - -int32_t TestFileRef::DeleteDirectoryRecursively(pp::FileRef* dir) { - if (!dir) - return PP_ERROR_BADARGUMENT; - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - TestCompletionCallbackWithOutput<DirEntries> output_callback( - instance_->pp_instance(), callback_type()); - - output_callback.WaitForResult( - dir->ReadDirectoryEntries(output_callback.GetCallback())); - int32_t rv = output_callback.result(); - if (rv != PP_OK && rv != PP_ERROR_FILENOTFOUND) - return rv; - - DirEntries entries = output_callback.output(); - for (DirEntries::const_iterator it = entries.begin(); - it != entries.end(); - ++it) { - pp::FileRef file_ref = it->file_ref(); - if (it->file_type() == PP_FILETYPE_DIRECTORY) { - rv = DeleteDirectoryRecursively(&file_ref); - if (rv != PP_OK && rv != PP_ERROR_FILENOTFOUND) - return rv; - } else { - callback.WaitForResult(file_ref.Delete(callback.GetCallback())); - rv = callback.result(); - if (rv != PP_OK && rv != PP_ERROR_FILENOTFOUND) - return rv; - } - } - callback.WaitForResult(dir->Delete(callback.GetCallback())); - return callback.result(); -} - -void TestFileRef::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestFileRef, Create, filter); - RUN_CALLBACK_TEST(TestFileRef, GetFileSystemType, filter); - RUN_CALLBACK_TEST(TestFileRef, GetName, filter); - RUN_CALLBACK_TEST(TestFileRef, GetPath, filter); - RUN_CALLBACK_TEST(TestFileRef, GetParent, filter); - RUN_CALLBACK_TEST(TestFileRef, MakeDirectory, filter); - RUN_CALLBACK_TEST(TestFileRef, QueryAndTouchFile, filter); - RUN_CALLBACK_TEST(TestFileRef, DeleteFileAndDirectory, filter); - RUN_CALLBACK_TEST(TestFileRef, RenameFileAndDirectory, filter); - RUN_CALLBACK_TEST(TestFileRef, Query, filter); - RUN_CALLBACK_TEST(TestFileRef, FileNameEscaping, filter); - RUN_CALLBACK_TEST(TestFileRef, ReadDirectoryEntries, filter); -} - -std::string TestFileRef::TestCreate() { - std::vector<std::string> invalid_paths; - invalid_paths.push_back("invalid_path"); // no '/' at the first character - invalid_paths.push_back(std::string()); // empty path - // The following are directory traversal checks - invalid_paths.push_back(".."); - invalid_paths.push_back("/../invalid_path"); - invalid_paths.push_back("/../../invalid_path"); - invalid_paths.push_back("/invalid/../../path"); - const size_t num_invalid_paths = invalid_paths.size(); - - pp::FileSystem file_system_pers( - instance_, PP_FILESYSTEMTYPE_LOCALPERSISTENT); - pp::FileSystem file_system_temp( - instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - for (size_t j = 0; j < num_invalid_paths; ++j) { - pp::FileRef file_ref_pers(file_system_pers, invalid_paths[j].c_str()); - if (file_ref_pers.pp_resource() != 0) { - return "file_ref_pers expected to be invalid for path: " + - invalid_paths[j]; - } - pp::FileRef file_ref_temp(file_system_temp, invalid_paths[j].c_str()); - if (file_ref_temp.pp_resource() != 0) { - return "file_ref_temp expected to be invalid for path: " + - invalid_paths[j]; - } - } - PASS(); -} - -std::string TestFileRef::TestGetFileSystemType() { - pp::FileSystem file_system_pers( - instance_, PP_FILESYSTEMTYPE_LOCALPERSISTENT); - pp::FileSystem file_system_temp( - instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - - pp::FileRef file_ref_pers(file_system_pers, kPersFilePath); - if (file_ref_pers.GetFileSystemType() != PP_FILESYSTEMTYPE_LOCALPERSISTENT) - return "file_ref_pers expected to be persistent."; - - pp::FileRef file_ref_temp(file_system_temp, kTempFilePath); - if (file_ref_temp.GetFileSystemType() != PP_FILESYSTEMTYPE_LOCALTEMPORARY) - return "file_ref_temp expected to be temporary."; - - pp::FileRef file_ref_ext; - std::string result = MakeExternalFileRef(&file_ref_ext); - if (!result.empty()) - return result; - PASS(); -} - -std::string TestFileRef::TestGetName() { - pp::FileSystem file_system_pers( - instance_, PP_FILESYSTEMTYPE_LOCALPERSISTENT); - pp::FileSystem file_system_temp( - instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - - pp::FileRef file_ref_pers(file_system_pers, kPersFilePath); - std::string name = file_ref_pers.GetName().AsString(); - if (name != kPersFileName) - return ReportMismatch("FileRef::GetName", name, kPersFileName); - - pp::FileRef file_ref_temp(file_system_temp, kTempFilePath); - name = file_ref_temp.GetName().AsString(); - if (name != kTempFileName) - return ReportMismatch("FileRef::GetName", name, kTempFileName); - - // Test the "/" case. - pp::FileRef file_ref_slash(file_system_temp, "/"); - name = file_ref_slash.GetName().AsString(); - if (name != "/") - return ReportMismatch("FileRef::GetName", name, "/"); - - pp::FileRef file_ref_ext; - std::string result = MakeExternalFileRef(&file_ref_ext); - if (!result.empty()) - return result; - name = file_ref_ext.GetName().AsString(); - ASSERT_FALSE(name.empty()); - - PASS(); -} - -std::string TestFileRef::TestGetPath() { - pp::FileSystem file_system_pers( - instance_, PP_FILESYSTEMTYPE_LOCALPERSISTENT); - pp::FileSystem file_system_temp( - instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - - pp::FileRef file_ref_pers(file_system_pers, kPersFilePath); - ASSERT_EQ(kPersFilePath, file_ref_pers.GetPath().AsString()); - - pp::FileRef file_ref_temp(file_system_temp, kTempFilePath); - ASSERT_EQ(kTempFilePath, file_ref_temp.GetPath().AsString()); - - pp::FileRef file_ref_ext; - std::string result = MakeExternalFileRef(&file_ref_ext); - if (!result.empty()) - return result; - ASSERT_TRUE(file_ref_ext.GetPath().is_undefined()); - - PASS(); -} - -std::string TestFileRef::TestGetParent() { - pp::FileSystem file_system_pers( - instance_, PP_FILESYSTEMTYPE_LOCALPERSISTENT); - pp::FileSystem file_system_temp( - instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - - pp::FileRef file_ref_pers(file_system_pers, kPersFilePath); - ASSERT_EQ(kParentPath, file_ref_pers.GetParent().GetPath().AsString()); - - pp::FileRef file_ref_temp(file_system_temp, kTempFilePath); - ASSERT_EQ(kParentPath, file_ref_temp.GetParent().GetPath().AsString()); - - // Test the "/" case. - pp::FileRef file_ref_slash(file_system_temp, "/"); - ASSERT_EQ("/", file_ref_slash.GetParent().GetPath().AsString()); - - // Test the "/foo" case (the parent is "/"). - pp::FileRef file_ref_with_root_parent(file_system_temp, "/foo"); - ASSERT_EQ("/", file_ref_with_root_parent.GetParent().GetPath().AsString()); - - pp::FileRef file_ref_ext; - std::string result = MakeExternalFileRef(&file_ref_ext); - if (!result.empty()) - return result; - ASSERT_TRUE(file_ref_ext.GetParent().is_null()); - - PASS(); -} - -std::string TestFileRef::TestMakeDirectory() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - // Open. - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Make a directory. - pp::FileRef dir_ref(file_system, "/dir_make_dir"); - callback.WaitForResult( - dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Make a directory on the existing path without exclusive flag. - callback.WaitForResult( - dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Making a directory should be aborted. - int32_t rv = PP_ERROR_FAILED; - { - rv = pp::FileRef(file_system, "/dir_make_dir_abort") - .MakeDirectory(PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback()); - } - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - - // Make nested directories. - dir_ref = pp::FileRef(file_system, "/dir_make_nested_dir_1/dir"); - callback.WaitForResult( - dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_WITH_ANCESTORS, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - dir_ref = pp::FileRef(file_system, "/dir_make_nested_dir_2/dir"); - callback.WaitForResult( - dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FILENOTFOUND, callback.result()); - - // Ensure there is no directory on the path to test exclusive cases. - dir_ref = pp::FileRef(file_system, "/dir_make_dir_exclusive"); - rv = DeleteDirectoryRecursively(&dir_ref); - ASSERT_TRUE(rv == PP_OK || rv == PP_ERROR_FILENOTFOUND); - - // Make a directory exclusively. - callback.WaitForResult( - dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_EXCLUSIVE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult( - dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_EXCLUSIVE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FILEEXISTS, callback.result()); - - PASS(); -} - -std::string TestFileRef::TestQueryAndTouchFile() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef file_ref(file_system, "/file_touch"); - pp::FileIO file_io(instance_); - callback.WaitForResult( - file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Write some data to have a non-zero file size. - callback.WaitForResult(file_io.Write(0, "test", 4, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(4, callback.result()); - - // Touch. - const PP_Time last_access_time = 123 * 24 * 3600.0; - // last_modified_time's granularity is 2 seconds - // See note in test_file_io.cc for why we use this time. - const PP_Time last_modified_time = 100 * 24 * 3600.0; - callback.WaitForResult(file_ref.Touch(last_access_time, last_modified_time, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Touch aborted. - int32_t rv = PP_ERROR_FAILED; - { - rv = pp::FileRef(file_system, "/file_touch_abort") - .Touch(last_access_time, last_modified_time, callback.GetCallback()); - } - callback.WaitForResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - if (rv == PP_OK_COMPLETIONPENDING) { - // Touch tried to run asynchronously and should have been aborted. - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - } else { - // Touch ran synchronously and should have failed because the file does not - // exist. - ASSERT_EQ(PP_ERROR_FILENOTFOUND, callback.result()); - } - - // Query. - PP_FileInfo info; - callback.WaitForResult(file_io.Query(&info, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_EQ(4, info.size); - ASSERT_EQ(PP_FILETYPE_REGULAR, info.type); - ASSERT_EQ(PP_FILESYSTEMTYPE_LOCALTEMPORARY, info.system_type); - - // Disabled due to DST-related failure: crbug.com/314579 - // ASSERT_EQ(last_access_time, info.last_access_time); - // ASSERT_EQ(last_modified_time, info.last_modified_time); - - // Cancellation test. - // TODO(viettrungluu): this test causes a bunch of LOG(WARNING)s; investigate. - // TODO(viettrungluu): check |info| for late writes. - { - rv = pp::FileRef(file_system, "/file_touch").Touch( - last_access_time, last_modified_time, callback.GetCallback()); - } - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - - PASS(); -} - -std::string TestFileRef::TestDeleteFileAndDirectory() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef file_ref(file_system, "/file_delete"); - pp::FileIO file_io(instance_); - callback.WaitForResult( - file_io.Open(file_ref, PP_FILEOPENFLAG_CREATE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult(file_ref.Delete(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef dir_ref(file_system, "/dir_delete"); - callback.WaitForResult(dir_ref.MakeDirectory( - PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult(dir_ref.Delete(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef nested_dir_ref(file_system, "/dir_delete_1/dir_delete_2"); - callback.WaitForResult( - nested_dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_WITH_ANCESTORS, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Attempt to delete the parent directory (should fail; it's non-empty). - pp::FileRef parent_dir_ref = nested_dir_ref.GetParent(); - callback.WaitForResult(parent_dir_ref.Delete(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - pp::FileRef nonexistent_file_ref(file_system, "/nonexistent_file_delete"); - callback.WaitForResult(nonexistent_file_ref.Delete(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FILENOTFOUND, callback.result()); - - // Delete aborted. - int32_t rv = PP_ERROR_FAILED; - { - pp::FileRef file_ref_abort(file_system, "/file_delete_abort"); - pp::FileIO file_io_abort(instance_); - callback.WaitForResult( - file_io_abort.Open(file_ref_abort, PP_FILEOPENFLAG_CREATE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - rv = file_ref_abort.Delete(callback.GetCallback()); - } - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - - PASS(); -} - -std::string TestFileRef::TestRenameFileAndDirectory() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef file_ref(file_system, "/file_rename"); - pp::FileIO file_io(instance_); - callback.WaitForResult( - file_io.Open(file_ref, PP_FILEOPENFLAG_CREATE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef target_file_ref(file_system, "/target_file_rename"); - callback.WaitForResult( - file_ref.Rename(target_file_ref, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef dir_ref(file_system, "/dir_rename"); - callback.WaitForResult(dir_ref.MakeDirectory( - PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef target_dir_ref(file_system, "/target_dir_rename"); - callback.WaitForResult( - dir_ref.Rename(target_dir_ref, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef nested_dir_ref(file_system, "/dir_rename_1/dir_rename_2"); - callback.WaitForResult( - nested_dir_ref.MakeDirectory(PP_MAKEDIRECTORYFLAG_WITH_ANCESTORS, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Try to rename nested directory to the parent name. Should fail. - pp::FileRef target_nested_dir_ref(file_system, "/dir_rename_1"); - callback.WaitForResult( - nested_dir_ref.Rename(target_nested_dir_ref, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - // Rename aborted. - // TODO(viettrungluu): Figure out what we want to do if the target file - // resource is destroyed before completion. - int32_t rv = PP_ERROR_FAILED; - pp::FileRef target_file_ref_abort(file_system, - "/target_file_rename_abort"); - { - pp::FileRef file_ref_abort(file_system, "/file_rename_abort"); - pp::FileIO file_io_abort(instance_); - callback.WaitForResult( - file_io_abort.Open(file_ref_abort, PP_FILEOPENFLAG_CREATE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = file_ref_abort.Rename(target_file_ref_abort, callback.GetCallback()); - } - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - - PASS(); -} - -std::string TestFileRef::TestQuery() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef file_ref(file_system, "/file"); - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, PP_FILEOPENFLAG_CREATE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // We touch the file so we can easily check access and modified time. - callback.WaitForResult(file_io.Touch(0, 0, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallbackWithOutput<PP_FileInfo> out_callback( - instance_->pp_instance(), callback_type()); - out_callback.WaitForResult(file_ref.Query(out_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(out_callback); - ASSERT_EQ(PP_OK, out_callback.result()); - - PP_FileInfo info = out_callback.output(); - ASSERT_EQ(0, info.size); - ASSERT_EQ(PP_FILETYPE_REGULAR, info.type); - ASSERT_EQ(PP_FILESYSTEMTYPE_LOCALTEMPORARY, info.system_type); - ASSERT_DOUBLE_EQ(0.0, info.last_access_time); - ASSERT_DOUBLE_EQ(0.0, info.last_modified_time); - - // Query a file ref on an external filesystem. - pp::FileRef file_ref_ext; - std::string result = MakeExternalFileRef(&file_ref_ext); - if (!result.empty()) - return result; - out_callback.WaitForResult(file_ref_ext.Query(out_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(out_callback); - if (out_callback.result() != PP_OK) - return ReportError("Query() result", out_callback.result()); - ASSERT_EQ(PP_OK, out_callback.result()); - - info = out_callback.output(); - ASSERT_EQ(PP_FILETYPE_REGULAR, info.type); - ASSERT_EQ(PP_FILESYSTEMTYPE_EXTERNAL, info.system_type); - - // We can't touch the file, so just sanity check the times. - ASSERT_TRUE(info.creation_time >= 0.0); - ASSERT_TRUE(info.last_modified_time >= 0.0); - ASSERT_TRUE(info.last_access_time >= 0.0); - - // Query a file ref for a file that doesn't exist. - pp::FileRef missing_file_ref(file_system, "/missing_file"); - out_callback.WaitForResult(missing_file_ref.Query( - out_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(out_callback); - ASSERT_EQ(PP_ERROR_FILENOTFOUND, out_callback.result()); - - PASS(); -} - -std::string TestFileRef::TestFileNameEscaping() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - std::string test_dir_path = "/dir_for_escaping_test"; - // Create a directory in which to test. - pp::FileRef test_dir_ref(file_system, test_dir_path.c_str()); - callback.WaitForResult(test_dir_ref.MakeDirectory( - PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Create the file with the terrible name. - std::string full_file_path = test_dir_path + "/" + kTerribleName; - pp::FileRef file_ref(file_system, full_file_path.c_str()); - pp::FileIO file_io(instance_); - callback.WaitForResult( - file_io.Open(file_ref, PP_FILEOPENFLAG_CREATE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // FileRef::ReadDirectoryEntries only works out-of-process. - if (testing_interface_->IsOutOfProcess()) { - TestCompletionCallbackWithOutput<DirEntries> - output_callback(instance_->pp_instance(), callback_type()); - - output_callback.WaitForResult( - test_dir_ref.ReadDirectoryEntries(output_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(output_callback); - ASSERT_EQ(PP_OK, output_callback.result()); - - DirEntries entries = output_callback.output(); - ASSERT_EQ(1, entries.size()); - ASSERT_EQ(kTerribleName, entries.front().file_ref().GetName().AsString()); - } - - PASS(); -} - -std::string TestFileRef::TestReadDirectoryEntries() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system( - instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Setup testing directories and files. - const char* test_dir_name = "/test_get_next_file"; - const char* file_prefix = "file_"; - const char* dir_prefix = "dir_"; - - pp::FileRef test_dir(file_system, test_dir_name); - int32_t rv = DeleteDirectoryRecursively(&test_dir); - ASSERT_TRUE(rv == PP_OK || rv == PP_ERROR_FILENOTFOUND); - - callback.WaitForResult(test_dir.MakeDirectory( - PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - static const int kNumFiles = 3; - std::set<std::string> expected_file_names; - for (int i = 1; i <= kNumFiles; ++i) { - std::ostringstream buffer; - buffer << test_dir_name << '/' << file_prefix << i; - pp::FileRef file_ref(file_system, buffer.str().c_str()); - - pp::FileIO file_io(instance_); - callback.WaitForResult( - file_io.Open(file_ref, PP_FILEOPENFLAG_CREATE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - expected_file_names.insert(buffer.str()); - } - - static const int kNumDirectories = 3; - std::set<std::string> expected_dir_names; - for (int i = 1; i <= kNumDirectories; ++i) { - std::ostringstream buffer; - buffer << test_dir_name << '/' << dir_prefix << i; - pp::FileRef file_ref(file_system, buffer.str().c_str()); - - callback.WaitForResult(file_ref.MakeDirectory( - PP_MAKEDIRECTORYFLAG_NONE, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - expected_dir_names.insert(buffer.str()); - } - - // Test that |ReadDirectoryEntries()| is able to fetch all - // directories and files that we created. - { - TestCompletionCallbackWithOutput<DirEntries> output_callback( - instance_->pp_instance(), callback_type()); - - output_callback.WaitForResult( - test_dir.ReadDirectoryEntries(output_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(output_callback); - ASSERT_EQ(PP_OK, output_callback.result()); - - DirEntries entries = output_callback.output(); - size_t sum = expected_file_names.size() + expected_dir_names.size(); - ASSERT_EQ(sum, entries.size()); - - for (DirEntries::const_iterator it = entries.begin(); - it != entries.end(); ++it) { - pp::FileRef file_ref = it->file_ref(); - std::string file_path = file_ref.GetPath().AsString(); - std::set<std::string>::iterator found = - expected_file_names.find(file_path); - if (found != expected_file_names.end()) { - if (it->file_type() != PP_FILETYPE_REGULAR) - return file_path + " should have been a regular file."; - expected_file_names.erase(found); - } else { - found = expected_dir_names.find(file_path); - if (found == expected_dir_names.end()) - return "Unexpected file path: " + file_path; - if (it->file_type() != PP_FILETYPE_DIRECTORY) - return file_path + " should have been a directory."; - expected_dir_names.erase(found); - } - } - ASSERT_TRUE(expected_file_names.empty()); - ASSERT_TRUE(expected_dir_names.empty()); - } - - // Test cancellation of asynchronous |ReadDirectoryEntries()|. - TestCompletionCallbackWithOutput<DirEntries> output_callback( - instance_->pp_instance(), callback_type()); - { - rv = pp::FileRef(file_system, test_dir_name) - .ReadDirectoryEntries(output_callback.GetCallback()); - } - output_callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(output_callback); - - - PASS(); -}
diff --git a/tests/test_file_ref.h b/tests/test_file_ref.h deleted file mode 100644 index f849fe5..0000000 --- a/tests/test_file_ref.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_FILE_REF_H_ -#define PPAPI_TESTS_TEST_FILE_REF_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/tests/test_case.h" - -namespace pp { -class FileRef; -} - -class TestFileRef : public TestCase { - public: - explicit TestFileRef(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - // Creates a FileRef on an external filesystem. - // Returns "" on success, a different string otherwise. - std::string MakeExternalFileRef(pp::FileRef* file_ref_ext); - - int32_t DeleteDirectoryRecursively(pp::FileRef* dir); - - std::string TestCreate(); - std::string TestGetFileSystemType(); - std::string TestGetName(); - std::string TestGetPath(); - std::string TestGetParent(); - std::string TestMakeDirectory(); - std::string TestQueryAndTouchFile(); - std::string TestDeleteFileAndDirectory(); - std::string TestRenameFileAndDirectory(); - std::string TestQuery(); - std::string TestFileNameEscaping(); - std::string TestReadDirectoryEntries(); -}; - -#endif // PPAPI_TESTS_TEST_FILE_REF_H_
diff --git a/tests/test_file_system.cc b/tests/test_file_system.cc deleted file mode 100644 index cc323c1..0000000 --- a/tests/test_file_system.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_file_system.h" - -#include <stdint.h> -#include <string.h> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/resource.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(FileSystem); - -bool TestFileSystem::Init() { - return CheckTestingInterface() && EnsureRunningOverHTTP(); -} - -void TestFileSystem::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestFileSystem, Open, filter); - RUN_CALLBACK_TEST(TestFileSystem, MultipleOpens, filter); - RUN_CALLBACK_TEST(TestFileSystem, ResourceConversion, filter); -} - -std::string TestFileSystem::TestOpen() { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - // Open. - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Open aborted. - int32_t rv = 0; - { - pp::FileSystem fs(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - rv = fs.Open(1024, callback.GetCallback()); - } - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - - PASS(); -} - -std::string TestFileSystem::TestMultipleOpens() { - // Should not allow multiple opens, regardless of whether or not the first - // open has completed. - TestCompletionCallback callback_1(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - int32_t rv_1 = file_system.Open(1024, callback_1.GetCallback()); - - TestCompletionCallback callback_2(instance_->pp_instance(), callback_type()); - callback_2.WaitForResult(file_system.Open(1024, callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - // FileSystem should not allow multiple opens. - ASSERT_NE(PP_OK, callback_2.result()); - - callback_1.WaitForResult(rv_1); - CHECK_CALLBACK_BEHAVIOR(callback_1); - ASSERT_EQ(PP_OK, callback_1.result()); - - TestCompletionCallback callback_3(instance_->pp_instance(), callback_type()); - callback_3.WaitForResult(file_system.Open(1024, callback_3.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_3); - ASSERT_NE(PP_OK, callback_3.result()); - - PASS(); -} - -std::string TestFileSystem::TestResourceConversion() { - // Test conversion from file system Resource to FileSystem. - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - pp::Resource file_system_resource(file_system); - ASSERT_TRUE(pp::FileSystem::IsFileSystem(file_system_resource)); - pp::FileSystem file_system_resource_file_system(file_system_resource); - ASSERT_FALSE(file_system_resource_file_system.is_null()); - - // Test conversion that a non-file system Resource does not register as a - // FileSystem. (We cannot test conversion, since this is an assertion on a - // debug build.) - pp::FileIO non_file_system(instance_); - pp::Resource non_file_system_resource(non_file_system); - ASSERT_FALSE(pp::FileSystem::IsFileSystem(non_file_system_resource)); - - PASS(); -}
diff --git a/tests/test_file_system.h b/tests/test_file_system.h deleted file mode 100644 index d19d07c..0000000 --- a/tests/test_file_system.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_FILE_SYSTEM_H_ -#define PPAPI_TESTS_TEST_FILE_SYSTEM_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -class TestFileSystem : public TestCase { - public: - explicit TestFileSystem(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestOpen(); - std::string TestMultipleOpens(); - std::string TestResourceConversion(); -}; - -#endif // PPAPI_TESTS_TEST_FILE_SYSTEM_H_ -
diff --git a/tests/test_fullscreen.cc b/tests/test_fullscreen.cc deleted file mode 100644 index d928442..0000000 --- a/tests/test_fullscreen.cc +++ /dev/null
@@ -1,307 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_fullscreen.h" - -#include <stdio.h> -#include <string.h> -#include <string> - -#include "ppapi/c/ppb_fullscreen.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/point.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(Fullscreen); - -namespace { - -const ColorPremul kSheerBlue = { 0x88, 0x00, 0x00, 0x88 }; -const ColorPremul kOpaqueYellow = { 0xFF, 0xFF, 0xFF, 0x00 }; -const int kBytesPerPixel = sizeof(uint32_t); // 4 bytes for BGRA or RGBA. - -uint32_t FormatColor(PP_ImageDataFormat format, ColorPremul color) { - if (format == PP_IMAGEDATAFORMAT_BGRA_PREMUL) - return (color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B); - else if (format == PP_IMAGEDATAFORMAT_RGBA_PREMUL) - return (color.A << 24) | (color.B << 16) | (color.G << 8) | (color.R); - else - return 0; -} - -bool HasMidScreen(const pp::Rect& position, const pp::Size& screen_size) { - static int32_t mid_x = screen_size.width() / 2; - static int32_t mid_y = screen_size.height() / 2; - return (position.Contains(mid_x, mid_y)); -} - -void FlushCallbackCheckImageData(void* data, int32_t result) { - static_cast<TestFullscreen*>(data)->CheckPluginPaint(); -} - -} // namespace - -TestFullscreen::TestFullscreen(TestingInstance* instance) - : TestCase(instance), - error_(), - screen_mode_(instance), - painted_color_(0), - fullscreen_pending_(false), - normal_pending_(false), - fullscreen_event_(instance->pp_instance()), - normal_event_(instance->pp_instance()) { - screen_mode_.GetScreenSize(&screen_size_); -} - -bool TestFullscreen::Init() { - if (screen_size_.IsEmpty()) { - instance_->AppendError("Failed to initialize screen_size_"); - return false; - } - graphics2d_ = pp::Graphics2D(instance_, screen_size_, true); - if (!instance_->BindGraphics(graphics2d_)) { - instance_->AppendError("Failed to initialize graphics2d_"); - return false; - } - return CheckTestingInterface(); -} - -void TestFullscreen::RunTests(const std::string& filter) { - RUN_TEST(GetScreenSize, filter); - RUN_TEST(NormalToFullscreenToNormal, filter); -} - -bool TestFullscreen::GotError() { - return !error_.empty(); -} - -std::string TestFullscreen::Error() { - std::string last_error = error_; - error_.clear(); - return last_error; -} - -// TODO(polina): consider adding custom logic to JS for this test to -// get screen.width and screen.height and postMessage those to this code, -// so the dimensions can be checked exactly. -std::string TestFullscreen::TestGetScreenSize() { - if (screen_size_.width() < 320 || screen_size_.width() > 2560) - return ReportError("screen_size.width()", screen_size_.width()); - if (screen_size_.height() < 200 || screen_size_.height() > 2048) - return ReportError("screen_size.height()", screen_size_.height()); - PASS(); -} - -std::string TestFullscreen::TestNormalToFullscreenToNormal() { - // 0. Start in normal mode. - if (screen_mode_.IsFullscreen()) - return ReportError("IsFullscreen() at start", true); - - // 1. Switch to fullscreen. - // This is only allowed within a context of a user gesture (e.g. mouse click). - if (screen_mode_.SetFullscreen(true)) - return ReportError("SetFullscreen(true) outside of user gesture", true); - // Trigger another call to SetFullscreen(true) from HandleInputEvent(). - // The transition is asynchronous and ends at the next DidChangeView(). - instance_->RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE); - SimulateUserGesture(); - // DidChangeView() will call the callback once in fullscreen mode. - fullscreen_event_.Wait(); - if (GotError()) - return Error(); - if (fullscreen_pending_) - return "fullscreen_pending_ has not been reset"; - if (!screen_mode_.IsFullscreen()) - return ReportError("IsFullscreen() in fullscreen", false); - - // 2. Stay in fullscreen. No change. - if (screen_mode_.SetFullscreen(true)) - return ReportError("SetFullscreen(true) in fullscreen", true); - if (!screen_mode_.IsFullscreen()) - return ReportError("IsFullscreen() in fullscreen^2", false); - - // 3. Switch to normal. - // The transition is asynchronous and ends at DidChangeView(). - // No graphics devices can be bound while in transition. - normal_pending_ = true; - if (!screen_mode_.SetFullscreen(false)) - return ReportError("SetFullscreen(false) in fullscreen", false); - // DidChangeView() will signal once out of fullscreen mode. - normal_event_.Wait(); - if (GotError()) - return Error(); - if (normal_pending_) - return "normal_pending_ has not been reset"; - if (screen_mode_.IsFullscreen()) - return ReportError("IsFullscreen() in normal", true); - - // 4. Stay in normal. No change. - if (screen_mode_.SetFullscreen(false)) - return ReportError("SetFullscreen(false) in normal", true); - if (screen_mode_.IsFullscreen()) - return ReportError("IsFullscreen() in normal^2", true); - - PASS(); -} - -void TestFullscreen::SimulateUserGesture() { - pp::Point plugin_center( - normal_position_.x() + normal_position_.width() / 2, - normal_position_.y() + normal_position_.height() / 2); - pp::Point mouse_movement; - pp::MouseInputEvent input_event( - instance_, - PP_INPUTEVENT_TYPE_MOUSEDOWN, - NowInTimeTicks(), // time_stamp - 0, // modifiers - PP_INPUTEVENT_MOUSEBUTTON_LEFT, - plugin_center, - 1, // click_count - mouse_movement); - - testing_interface_->SimulateInputEvent(instance_->pp_instance(), - input_event.pp_resource()); -} - -void TestFullscreen::FailFullscreenTest(const std::string& error) { - error_ = error; - fullscreen_event_.Signal(); -} - -void TestFullscreen::FailNormalTest(const std::string& error) { - error_ = error; - normal_event_.Signal(); -} - -void TestFullscreen::PassFullscreenTest() { - fullscreen_event_.Signal(); -} - -void TestFullscreen::PassNormalTest() { - normal_event_.Signal(); -} - -// Transition to fullscreen can only happen when processing a user gesture. -bool TestFullscreen::HandleInputEvent(const pp::InputEvent& event) { - // We only let mouse events through and only mouse clicks count. - if (event.GetType() != PP_INPUTEVENT_TYPE_MOUSEDOWN && - event.GetType() != PP_INPUTEVENT_TYPE_MOUSEUP) - return false; - // We got the gesture. No need to handle any more events. - instance_->ClearInputEventRequest(PP_INPUTEVENT_CLASS_MOUSE); - if (screen_mode_.IsFullscreen()) { - FailFullscreenTest( - ReportError("IsFullscreen() before fullscreen transition", true)); - return false; - } - fullscreen_pending_ = true; - if (!screen_mode_.SetFullscreen(true)) { - FailFullscreenTest(ReportError("SetFullscreen(true) in normal", false)); - return false; - } - // DidChangeView() will complete the transition to fullscreen. - return false; -} - -bool TestFullscreen::PaintPlugin(pp::Size size, ColorPremul color) { - painted_size_ = size; - PP_ImageDataFormat image_format = pp::ImageData::GetNativeImageDataFormat(); - painted_color_ = FormatColor(image_format, color); - if (painted_color_ == 0) - return false; - pp::Point origin(0, 0); - - pp::ImageData image(instance_, image_format, size, false); - if (image.is_null()) - return false; - uint32_t* pixels = static_cast<uint32_t*>(image.data()); - int num_pixels = image.stride() / kBytesPerPixel * image.size().height(); - for (int i = 0; i < num_pixels; i++) - pixels[i] = painted_color_; - graphics2d_.PaintImageData(image, origin); - pp::CompletionCallback cc(FlushCallbackCheckImageData, this); - if (graphics2d_.Flush(cc) != PP_OK_COMPLETIONPENDING) - return false; - - return true; -} - -void TestFullscreen::CheckPluginPaint() { - PP_ImageDataFormat image_format = pp::ImageData::GetNativeImageDataFormat(); - pp::ImageData readback(instance_, image_format, painted_size_, false); - pp::Point origin(0, 0); - if (readback.is_null() || - PP_TRUE != testing_interface_->ReadImageData(graphics2d_.pp_resource(), - readback.pp_resource(), - &origin.pp_point())) { - error_ = "Can't read plugin image"; - return; - } - for (int y = 0; y < painted_size_.height(); y++) { - for (int x = 0; x < painted_size_.width(); x++) { - uint32_t* readback_color = readback.GetAddr32(pp::Point(x, y)); - if (painted_color_ != *readback_color) { - error_ = "Plugin image contains incorrect pixel value"; - return; - } - } - } - if (screen_mode_.IsFullscreen()) - PassFullscreenTest(); - else - PassNormalTest(); -} - -// Transitions to/from fullscreen is asynchronous ending at DidChangeView. -// The number of calls to DidChangeView during fullscreen / normal transitions -// isn't specified by the API. The test waits until it the screen has -// transitioned to the desired state. -// -// WebKit does not change the plugin size, but Pepper does explicitly set -// it to screen width and height when SetFullscreen(true) is called and -// resets it back when ViewChanged is received indicating that we exited -// fullscreen. -// -// NOTE: The number of DidChangeView calls for <object> might be different. -// TODO(bbudge) Figure out how to test that the plugin positon eventually -// changes to normal_position_. -void TestFullscreen::DidChangeView(const pp::View& view) { - pp::Rect position = view.GetRect(); - pp::Rect clip = view.GetClipRect(); - - if (normal_position_.IsEmpty()) - normal_position_ = position; - - bool is_fullscreen = screen_mode_.IsFullscreen(); - if (fullscreen_pending_ && is_fullscreen) { - fullscreen_pending_ = false; - if (!HasMidScreen(position, screen_size_)) - FailFullscreenTest("DidChangeView is not in the middle of the screen"); - else if (position.size() != screen_size_) - FailFullscreenTest("DidChangeView does not have screen size"); - // NOTE: we cannot reliably test for clip size being equal to the screen - // because it might be affected by JS console, info bars, etc. - else if (!instance_->BindGraphics(graphics2d_)) - FailFullscreenTest("Failed to BindGraphics() in fullscreen"); - else if (!PaintPlugin(position.size(), kOpaqueYellow)) - FailFullscreenTest("Failed to paint plugin image in fullscreen"); - } else if (normal_pending_ && !is_fullscreen) { - normal_pending_ = false; - if (screen_mode_.IsFullscreen()) - FailNormalTest("DidChangeview is in fullscreen"); - else if (!instance_->BindGraphics(graphics2d_)) - FailNormalTest("Failed to BindGraphics() in normal"); - else if (!PaintPlugin(position.size(), kSheerBlue)) - FailNormalTest("Failed to paint plugin image in normal"); - } -}
diff --git a/tests/test_fullscreen.h b/tests/test_fullscreen.h deleted file mode 100644 index b7f32c7..0000000 --- a/tests/test_fullscreen.h +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_FULLSCREEN_H_ -#define PPAPI_TESTS_TEST_FULLSCREEN_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/cpp/fullscreen.h" -#include "ppapi/cpp/graphics_2d.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/cpp/size.h" -#include "ppapi/tests/test_case.h" -#include "ppapi/tests/test_utils.h" - -namespace pp { -class InputEvent; -} // namespace pp - -struct ColorPremul { uint32_t A, R, G, B; }; // Use premultipled Alpha. - -class TestFullscreen : public TestCase { - public: - explicit TestFullscreen(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - virtual bool HandleInputEvent(const pp::InputEvent& event); - virtual void DidChangeView(const pp::View& view); - - void CheckPluginPaint(); - - private: - std::string TestGetScreenSize(); - std::string TestNormalToFullscreenToNormal(); - - void SimulateUserGesture(); - void FailFullscreenTest(const std::string& error); - void FailNormalTest(const std::string& error); - void PassFullscreenTest(); - void PassNormalTest(); - bool PaintPlugin(pp::Size size, ColorPremul color); - - bool GotError(); - std::string Error(); - - std::string error_; - - pp::Fullscreen screen_mode_; - pp::Size screen_size_; - pp::Rect normal_position_; - pp::Size painted_size_; - uint32_t painted_color_; - - bool fullscreen_pending_; - bool normal_pending_; - pp::Graphics2D graphics2d_; - - NestedEvent fullscreen_event_; - NestedEvent normal_event_; -}; - -#endif // PPAPI_TESTS_TEST_FULLSCREEN_H_
diff --git a/tests/test_graphics_2d.cc b/tests/test_graphics_2d.cc deleted file mode 100644 index 6d22eea..0000000 --- a/tests/test_graphics_2d.cc +++ /dev/null
@@ -1,811 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_graphics_2d.h" - -#include <stdlib.h> -#include <string.h> - -#include <set> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_graphics_2d.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/graphics_2d.h" -#include "ppapi/cpp/graphics_3d.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(Graphics2D); - -namespace { - -bool CanFlushContext(pp::Instance* instance, pp::Graphics2D* context) { - TestCompletionCallback callback(instance->pp_instance()); - callback.WaitForResult(context->Flush(callback.GetCallback())); - return (callback.result() == PP_OK); -} - -bool CanFlushContextC(pp::Instance* instance, PP_Resource graphics_2d, - const PPB_Graphics2D_1_2* graphics_2d_if) { - TestCompletionCallback callback(instance->pp_instance()); - callback.WaitForResult(graphics_2d_if->Flush( - graphics_2d, callback.GetCallback().pp_completion_callback())); - return (callback.result() == PP_OK); -} - -} // namespace - -TestGraphics2D::TestGraphics2D(TestingInstance* instance) - : TestCase(instance), - is_view_changed_(false), - post_quit_on_view_changed_(false) { -} - -bool TestGraphics2D::Init() { - graphics_2d_interface_ = static_cast<const PPB_Graphics2D*>( - pp::Module::Get()->GetBrowserInterface(PPB_GRAPHICS_2D_INTERFACE_1_2)); - image_data_interface_ = static_cast<const PPB_ImageData*>( - pp::Module::Get()->GetBrowserInterface(PPB_IMAGEDATA_INTERFACE_1_0)); - return graphics_2d_interface_ && image_data_interface_ && - CheckTestingInterface(); -} - -void TestGraphics2D::RunTests(const std::string& filter) { - RUN_TEST(InvalidResource, filter); - RUN_TEST(InvalidSize, filter); - RUN_TEST(Humongous, filter); - RUN_TEST(InitToZero, filter); - RUN_TEST(Describe, filter); - RUN_TEST(Scale, filter); - RUN_TEST_FORCEASYNC_AND_NOT(Paint, filter); - RUN_TEST_FORCEASYNC_AND_NOT(Scroll, filter); - RUN_TEST_FORCEASYNC_AND_NOT(Replace, filter); - RUN_TEST_FORCEASYNC_AND_NOT(Flush, filter); - RUN_TEST_FORCEASYNC_AND_NOT(FlushOffscreenUpdate, filter); - RUN_TEST(Dev, filter); - RUN_TEST(ReplaceContentsCaching, filter); - RUN_TEST(BindNull, filter); -} - -void TestGraphics2D::QuitMessageLoop() { - testing_interface_->QuitMessageLoop(instance_->pp_instance()); -} - -bool TestGraphics2D::ReadImageData(const pp::Graphics2D& dc, - pp::ImageData* image, - const pp::Point& top_left) const { - return PP_ToBool(testing_interface_->ReadImageData( - dc.pp_resource(), - image->pp_resource(), - &top_left.pp_point())); -} - -bool TestGraphics2D::IsDCUniformColor(const pp::Graphics2D& dc, - uint32_t color) const { - pp::ImageData readback(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - dc.size(), false); - if (readback.is_null()) - return false; - if (!ReadImageData(dc, &readback, pp::Point(0, 0))) - return false; - return IsSquareInImage(readback, 0, pp::Rect(dc.size()), color); -} - -std::string TestGraphics2D::FlushAndWaitForDone(pp::Graphics2D* context) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(context->Flush(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -void TestGraphics2D::FillRectInImage(pp::ImageData* image, - const pp::Rect& rect, - uint32_t color) const { - for (int y = rect.y(); y < rect.bottom(); y++) { - uint32_t* row = image->GetAddr32(pp::Point(rect.x(), y)); - for (int pixel = 0; pixel < rect.width(); pixel++) - row[pixel] = color; - } -} - -void TestGraphics2D::FillImageWithGradient(pp::ImageData* image) const { - for (int y = 0; y < image->size().height(); y++) { - uint32_t red = ((y * 256) / image->size().height()) & 0xFF; - for (int x = 0; x < image->size().width(); x++) { - uint32_t green = ((x * 256) / image->size().width()) & 0xFF; - uint32_t blue = ((red + green) / 2) & 0xFF; - uint32_t* pixel = image->GetAddr32(pp::Point(x, y)); - *pixel = (blue << 24) | (green << 16) | (red << 8); - } - } -} - -bool TestGraphics2D::CompareImages(const pp::ImageData& image1, - const pp::ImageData& image2) { - return CompareImageRect( - image1, pp::Rect(0, 0, image1.size().width(), image1.size().height()), - image2, pp::Rect(0, 0, image2.size().width(), image2.size().height())); -} - -bool TestGraphics2D::CompareImageRect(const pp::ImageData& image1, - const pp::Rect& rc1, - const pp::ImageData& image2, - const pp::Rect& rc2) const { - if (rc1.width() != rc2.width() || rc1.height() != rc2.height()) - return false; - - for (int y = 0; y < rc1.height(); y++) { - for (int x = 0; x < rc1.width(); x++) { - if (*(image1.GetAddr32(pp::Point(rc1.x() + x, rc1.y() + y))) != - *(image2.GetAddr32(pp::Point(rc2.x() + x, rc2.y() + y)))) - return false; - } - } - return true; -} - -bool TestGraphics2D::IsSquareInImage(const pp::ImageData& image_data, - uint32_t background_color, - const pp::Rect& square, - uint32_t square_color) const { - for (int y = 0; y < image_data.size().height(); y++) { - for (int x = 0; x < image_data.size().width(); x++) { - uint32_t pixel = *image_data.GetAddr32(pp::Point(x, y)); - uint32_t desired_color; - if (square.Contains(x, y)) - desired_color = square_color; - else - desired_color = background_color; - if (pixel != desired_color) - return false; - } - } - return true; -} - -bool TestGraphics2D::IsSquareInDC(const pp::Graphics2D& dc, - uint32_t background_color, - const pp::Rect& square, - uint32_t square_color) const { - pp::ImageData readback(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - dc.size(), false); - if (readback.is_null()) - return false; - if (!ReadImageData(dc, &readback, pp::Point(0, 0))) - return false; - return IsSquareInImage(readback, background_color, square, square_color); -} - - -PP_Resource TestGraphics2D::ReplaceContentsAndReturnID( - pp::Graphics2D* dc, - const pp::Size& size) { - pp::ImageData image(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, size, true); - - PP_Resource id = image.pp_resource(); - - dc->ReplaceContents(&image); - std::string result = FlushAndWaitForDone(dc); - if (!result.empty()) - return 0; - - return id; -} - -// Test all the functions with an invalid handle. Most of these just check for -// a crash since the browser don't return a value. -std::string TestGraphics2D::TestInvalidResource() { - pp::Graphics2D null_context; - pp::ImageData image(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(16, 16), true); - - // Describe. - PP_Size size; - PP_Bool opaque; - graphics_2d_interface_->Describe(image.pp_resource(), &size, &opaque); - graphics_2d_interface_->Describe(null_context.pp_resource(), - &size, &opaque); - - // PaintImageData. - PP_Point zero_zero; - zero_zero.x = 0; - zero_zero.y = 0; - graphics_2d_interface_->PaintImageData(image.pp_resource(), - image.pp_resource(), - &zero_zero, NULL); - graphics_2d_interface_->PaintImageData(null_context.pp_resource(), - image.pp_resource(), - &zero_zero, NULL); - - // Scroll. - PP_Point zero_ten; - zero_ten.x = 0; - zero_ten.y = 10; - graphics_2d_interface_->Scroll(image.pp_resource(), NULL, &zero_ten); - graphics_2d_interface_->Scroll(null_context.pp_resource(), - NULL, &zero_ten); - - // ReplaceContents. - graphics_2d_interface_->ReplaceContents(image.pp_resource(), - image.pp_resource()); - graphics_2d_interface_->ReplaceContents(null_context.pp_resource(), - image.pp_resource()); - - // Flush. - TestCompletionCallback cb(instance_->pp_instance(), PP_OPTIONAL); - cb.WaitForResult( - graphics_2d_interface_->Flush(image.pp_resource(), - cb.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_BADRESOURCE, cb.result()); - cb.WaitForResult( - graphics_2d_interface_->Flush(null_context.pp_resource(), - cb.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_BADRESOURCE, cb.result()); - - // ReadImageData. - ASSERT_FALSE(testing_interface_->ReadImageData(image.pp_resource(), - image.pp_resource(), - &zero_zero)); - ASSERT_FALSE(testing_interface_->ReadImageData(null_context.pp_resource(), - image.pp_resource(), - &zero_zero)); - - PASS(); -} - -std::string TestGraphics2D::TestInvalidSize() { - pp::Graphics2D a(instance_, pp::Size(16, 0), false); - ASSERT_FALSE(CanFlushContext(instance_, &a)); - - pp::Graphics2D b(instance_, pp::Size(0, 16), false); - ASSERT_FALSE(CanFlushContext(instance_, &b)); - - // Need to use the C API since pp::Size prevents negative sizes. - PP_Size size; - size.width = 16; - size.height = -16; - PP_Resource graphics = graphics_2d_interface_->Create( - instance_->pp_instance(), &size, PP_FALSE); - ASSERT_FALSE(CanFlushContextC(instance_, graphics, graphics_2d_interface_)); - pp::Module::Get()->core()->ReleaseResource(graphics); - - size.width = -16; - size.height = 16; - graphics = graphics_2d_interface_->Create( - instance_->pp_instance(), &size, PP_FALSE); - ASSERT_FALSE(CanFlushContextC(instance_, graphics, graphics_2d_interface_)); - pp::Module::Get()->core()->ReleaseResource(graphics); - - // Overflow to negative size - size.width = std::numeric_limits<int32_t>::max(); - size.height = std::numeric_limits<int32_t>::max(); - graphics = graphics_2d_interface_->Create( - instance_->pp_instance(), &size, PP_FALSE); - ASSERT_FALSE(CanFlushContextC(instance_, graphics, graphics_2d_interface_)); - pp::Module::Get()->core()->ReleaseResource(graphics); - - PASS(); -} - -std::string TestGraphics2D::TestHumongous() { - pp::Graphics2D a(instance_, pp::Size(100000, 100000), false); - ASSERT_FALSE(CanFlushContext(instance_, &a)); - PASS(); -} - -std::string TestGraphics2D::TestInitToZero() { - const int w = 15, h = 17; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - - // Make an image with nonzero data in it (so we can test that zeros were - // actually read versus ReadImageData being a NOP). - pp::ImageData image(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(w, h), true); - ASSERT_FALSE(image.is_null()); - ASSERT_FALSE(image.size().IsEmpty()); - memset(image.data(), 0xFF, image.stride() * image.size().height() * 4); - - // Read out the initial data from the device & check. - ASSERT_TRUE(ReadImageData(dc, &image, pp::Point(0, 0))); - ASSERT_TRUE(IsSquareInImage(image, 0, pp::Rect(0, 0, w, h), 0)); - - PASS(); -} - -std::string TestGraphics2D::TestDescribe() { - const int w = 15, h = 17; - const bool always_opaque = (::rand() % 2 == 1); - pp::Graphics2D dc(instance_, pp::Size(w, h), always_opaque); - ASSERT_FALSE(dc.is_null()); - - PP_Size size; - size.width = -1; - size.height = -1; - PP_Bool is_always_opaque = PP_FALSE; - ASSERT_TRUE(graphics_2d_interface_->Describe(dc.pp_resource(), &size, - &is_always_opaque)); - ASSERT_EQ(w, size.width); - ASSERT_EQ(h, size.height); - ASSERT_EQ(PP_FromBool(always_opaque), is_always_opaque); - - PASS(); -} - -std::string TestGraphics2D::TestScale() { - // Tests GetScale/SetScale - const int w = 20, h = 16; - const float scale = 1.0f/2.0f; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - ASSERT_EQ(1.0, dc.GetScale()); - ASSERT_TRUE(dc.SetScale(scale)); - ASSERT_EQ(scale, dc.GetScale()); - // Try setting a few invalid scale factors. Ensure that we catch these errors - // and don't change the actual scale - ASSERT_FALSE(dc.SetScale(-1.0f)); - ASSERT_FALSE(dc.SetScale(0.0f)); - ASSERT_EQ(scale, dc.GetScale()); - - // Verify that the context has the specified number of pixels, despite the - // non-identity scale - PP_Size size; - size.width = -1; - size.height = -1; - PP_Bool is_always_opaque = PP_FALSE; - ASSERT_TRUE(graphics_2d_interface_->Describe(dc.pp_resource(), &size, - &is_always_opaque)); - ASSERT_EQ(w, size.width); - ASSERT_EQ(h, size.height); - ASSERT_EQ(PP_FALSE, is_always_opaque); - - PASS(); -} - -std::string TestGraphics2D::TestPaint() { - const int w = 15, h = 17; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - - // Make sure the device background is 0. - ASSERT_TRUE(IsDCUniformColor(dc, 0)); - - // Fill the backing store with white. - const uint32_t background_color = 0xFFFFFFFF; - pp::ImageData background(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(w, h), false); - FillRectInImage(&background, pp::Rect(0, 0, w, h), background_color); - dc.PaintImageData(background, pp::Point(0, 0)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - - // Make an image to paint with that's opaque white and enqueue a paint. - const int fill_w = 2, fill_h = 3; - pp::ImageData fill(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(fill_w, fill_h), true); - ASSERT_FALSE(fill.is_null()); - FillRectInImage(&fill, pp::Rect(fill.size()), background_color); - const int paint_x = 4, paint_y = 5; - dc.PaintImageData(fill, pp::Point(paint_x, paint_y)); - - // Validate that nothing has been actually painted. - ASSERT_TRUE(IsDCUniformColor(dc, background_color)); - - // The paint hasn't been flushed so we can still change the bitmap. Fill with - // 50% blue. This will also verify that the backing store is replaced - // with the contents rather than blended. - const uint32_t fill_color = 0x80000080; - FillRectInImage(&fill, pp::Rect(fill.size()), fill_color); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - - ASSERT_TRUE(IsSquareInDC(dc, background_color, - pp::Rect(paint_x, paint_y, fill_w, fill_h), - fill_color)); - - // Reset the DC to blank white & paint our image slightly off the buffer. - // This should succeed. We also try painting the same thing where the - // dirty rect falls outeside of the device, which should fail. - dc.PaintImageData(background, pp::Point(0, 0)); - const int second_paint_x = -1, second_paint_y = -2; - dc.PaintImageData(fill, pp::Point(second_paint_x, second_paint_y)); - dc.PaintImageData(fill, pp::Point(second_paint_x, second_paint_y), - pp::Rect(-second_paint_x, -second_paint_y, 1, 1)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - - // Now we should have a little bit of the image peeking out the top left. - ASSERT_TRUE(IsSquareInDC(dc, background_color, pp::Rect(0, 0, 1, 1), - fill_color)); - - // Now repaint that top left pixel by doing a subset of the source image. - pp::ImageData subset(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(w, h), false); - uint32_t subset_color = 0x80808080; - const int subset_x = 2, subset_y = 1; - *subset.GetAddr32(pp::Point(subset_x, subset_y)) = subset_color; - dc.PaintImageData(subset, pp::Point(-subset_x, -subset_y), - pp::Rect(subset_x, subset_y, 1, 1)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - ASSERT_TRUE(IsSquareInDC(dc, background_color, pp::Rect(0, 0, 1, 1), - subset_color)); - - PASS(); -} - -std::string TestGraphics2D::TestScroll() { - const int w = 115, h = 117; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - ASSERT_TRUE(instance_->BindGraphics(dc)); - - // Make sure the device background is 0. - ASSERT_TRUE(IsDCUniformColor(dc, 0)); - - const int image_width = 15, image_height = 23; - pp::ImageData test_image(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(image_width, image_height), false); - FillImageWithGradient(&test_image); - pp::ImageData no_image(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(image_width, image_height), false); - FillRectInImage(&no_image, pp::Rect(0, 0, image_width, image_height), 0); - pp::ImageData readback_image(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(image_width, image_height), false); - pp::ImageData readback_scroll(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(image_width, image_height), false); - - ASSERT_EQ(pp::Size(image_width, image_height), test_image.size()); - - int image_x = 51, image_y = 72; - dc.PaintImageData(test_image, pp::Point(image_x, image_y)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - - // Test Case 1. Incorrect usage when scrolling image to a free space. - // The clip area is *not* the area to shift around within the graphics device - // by specified amount. It's the area to which the scroll is limited. So if - // the clip area is the size of the image and the amount points to free space, - // the scroll won't result in additional images. - int dx = -40, dy = -48; - int scroll_x = image_x + dx, scroll_y = image_y + dy; - pp::Rect clip(image_x, image_y, image_width, image_height); - dc.Scroll(clip, pp::Point(dx, dy)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - ASSERT_TRUE( - ReadImageData(dc, &readback_scroll, pp::Point(scroll_x, scroll_y))); - ASSERT_TRUE(CompareImages(no_image, readback_scroll)); - - // Test Case 2. - // The amount is intended to place the image in the free space outside - // of the original, but the clip area extends beyond the graphics device area. - // This scroll is invalid and will be a noop. - scroll_x = 11, scroll_y = 24; - clip = pp::Rect(0, 0, w, h + 1); - dc.Scroll(clip, pp::Point(scroll_x - image_x, scroll_y - image_y)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - ASSERT_TRUE( - ReadImageData(dc, &readback_scroll, pp::Point(scroll_x, scroll_y))); - ASSERT_TRUE(CompareImages(no_image, readback_scroll)); - - // Test Case 3. - // The amount is intended to place the image in the free space outside - // of the original, but the clip area does not cover the image, - // so there is nothing to scroll. - scroll_x = 11, scroll_y = 24; - clip = pp::Rect(0, 0, image_x, image_y); - dc.Scroll(clip, pp::Point(scroll_x - image_x, scroll_y - image_y)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - ASSERT_TRUE( - ReadImageData(dc, &readback_scroll, pp::Point(scroll_x, scroll_y))); - ASSERT_TRUE(CompareImages(no_image, readback_scroll)); - - // Test Case 4. - // Same as TC3, but the clip covers part of the image. - // This part will be scrolled to the intended origin. - int part_w = image_width / 2, part_h = image_height / 2; - clip = pp::Rect(0, 0, image_x + part_w, image_y + part_h); - dc.Scroll(clip, pp::Point(scroll_x - image_x, scroll_y - image_y)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - ASSERT_TRUE( - ReadImageData(dc, &readback_scroll, pp::Point(scroll_x, scroll_y))); - ASSERT_FALSE(CompareImages(test_image, readback_scroll)); - pp::Rect part_rect(part_w, part_h); - ASSERT_TRUE( - CompareImageRect(test_image, part_rect, readback_scroll, part_rect)); - - // Test Case 5 - // Same as TC3, but the clip area covers the entire image. - // It will be scrolled to the intended origin. - clip = pp::Rect(0, 0, image_x + image_width, image_y + image_height); - dc.Scroll(clip, pp::Point(scroll_x - image_x, scroll_y - image_y)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - ASSERT_TRUE( - ReadImageData(dc, &readback_scroll, pp::Point(scroll_x, scroll_y))); - ASSERT_TRUE(CompareImages(test_image, readback_scroll)); - - // Note that the undefined area left by the scroll does not actually get - // cleared, so the original image is still there. This is not guaranteed and - // is not something for users to rely on, but we can test for this here, so - // we know when the underlying behavior changes. - ASSERT_TRUE(ReadImageData(dc, &readback_image, pp::Point(image_x, image_y))); - ASSERT_TRUE(CompareImages(test_image, readback_image)); - - // Test Case 6. - // Scroll image to an overlapping space. The clip area is limited - // to the image, so this will just modify its area. - dx = 6; - dy = 9; - scroll_x = image_x + dx; - scroll_y = image_y + dy; - clip = pp::Rect(image_x, image_y, image_width, image_height); - dc.Scroll(clip, pp::Point(dx, dy)); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - ASSERT_TRUE(ReadImageData(dc, &readback_image, pp::Point(image_x, image_y))); - ASSERT_FALSE(CompareImages(test_image, readback_image)); - pp::Rect scroll_rect(image_width - dx, image_height - dy); - ASSERT_TRUE( - ReadImageData(dc, &readback_scroll, pp::Point(scroll_x, scroll_y))); - ASSERT_TRUE( - CompareImageRect(test_image, scroll_rect, readback_scroll, scroll_rect)); - - PASS(); -} - -std::string TestGraphics2D::TestReplace() { - const int w = 15, h = 17; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - - // Replacing with a different size image should fail. - pp::ImageData weird_size(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(w - 1, h), true); - ASSERT_FALSE(weird_size.is_null()); - dc.ReplaceContents(&weird_size); - - // Fill the background with blue but don't flush yet. - const uint32_t background_color = 0xFF0000FF; - pp::ImageData background(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(w, h), true); - ASSERT_FALSE(background.is_null()); - FillRectInImage(&background, pp::Rect(0, 0, w, h), background_color); - dc.PaintImageData(background, pp::Point(0, 0)); - - // Replace with a green background but don't flush yet. - const int32_t swapped_color = 0x00FF00FF; - pp::ImageData swapped(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(w, h), true); - ASSERT_FALSE(swapped.is_null()); - FillRectInImage(&swapped, pp::Rect(0, 0, w, h), swapped_color); - dc.ReplaceContents(&swapped); - - // The background should be unchanged since we didn't flush yet. - ASSERT_TRUE(IsDCUniformColor(dc, 0)); - - // Test the C++ wrapper. The size of the swapped image should be reset. - ASSERT_TRUE(!swapped.pp_resource() && !swapped.size().width() && - !swapped.size().height() && !swapped.data()); - - // Painting with the swapped image should fail. - dc.PaintImageData(swapped, pp::Point(0, 0)); - - // Flush and make sure the result is correct. - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - - // The background should be green from the swapped image. - ASSERT_TRUE(IsDCUniformColor(dc, swapped_color)); - - PASS(); -} - -std::string TestGraphics2D::TestFlush() { - // Tests that synchronous flushes (NULL callback) fail on the main thread - // (which is the current one). - const int w = 15, h = 17; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - - // Fill the background with blue but don't flush yet. - pp::ImageData background(instance_, PP_IMAGEDATAFORMAT_BGRA_PREMUL, - pp::Size(w, h), true); - ASSERT_FALSE(background.is_null()); - dc.PaintImageData(background, pp::Point(0, 0)); - - int32_t rv = dc.Flush(pp::BlockUntilComplete()); - ASSERT_EQ(PP_ERROR_BLOCKS_MAIN_THREAD, rv); - - // Test flushing with no operations still issues a callback. - // (This may also hang if the browser never issues the callback). - pp::Graphics2D dc_nopaints(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc_nopaints)); - - TestCompletionCallback callback_1(instance_->pp_instance(), callback_type()); - - // Test that multiple flushes fail if we don't get a callback in between. - rv = dc_nopaints.Flush(callback_1.GetCallback()); - if (rv == PP_OK_COMPLETIONPENDING) { - // If the first flush completes asynchronously, then a second should fail. - TestCompletionCallback callback_2(instance_->pp_instance(), - callback_type()); - callback_2.WaitForResult(dc_nopaints.Flush(callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_EQ(PP_ERROR_INPROGRESS, callback_2.result()); - } - callback_1.WaitForResult(rv); - ASSERT_EQ(PP_OK, callback_1.result()); - - PASS(); -} - -void TestGraphics2D::DidChangeView(const pp::View& view) { - if (post_quit_on_view_changed_) { - post_quit_on_view_changed_ = false; - is_view_changed_ = true; - testing_interface_->QuitMessageLoop(instance_->pp_instance()); - } -} - -void TestGraphics2D::ResetViewChangedState() { - is_view_changed_ = false; -} - -bool TestGraphics2D::WaitUntilViewChanged() { - // Run a nested run loop. It will exit either on ViewChanged or if the - // timeout happens. - - // If view changed before we have chance to run message loop, return directly. - if (is_view_changed_) - return true; - - post_quit_on_view_changed_ = true; - testing_interface_->RunMessageLoop(instance_->pp_instance()); - post_quit_on_view_changed_ = false; - - return is_view_changed_; -} - -std::string TestGraphics2D::TestFlushOffscreenUpdate() { - // Tests that callback of offscreen updates should be delayed. - const PP_Time kFlushDelaySec = 1. / 30; // 30 fps - const int w = 80, h = 80; - pp::Graphics2D dc(instance_, pp::Size(w, h), true); - ASSERT_FALSE(dc.is_null()); - ASSERT_TRUE(instance_->BindGraphics(dc)); - - // Squeeze from top until bottom half of plugin is out of screen. - ResetViewChangedState(); - instance_->EvalScript( - "var big = document.createElement('div');" - "var offset = " - " window.innerHeight - plugin.offsetTop - plugin.offsetHeight / 2;" - "big.setAttribute('id', 'big-div');" - "big.setAttribute('style', 'height: ' + offset + '; width: 100%;');" - "document.body.insertBefore(big, document.body.firstChild);"); - ASSERT_TRUE(WaitUntilViewChanged()); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - - // Allocate a red image chunk - pp::ImageData chunk(instance_, PP_IMAGEDATAFORMAT_RGBA_PREMUL, - pp::Size(w/8, h/8), true); - ASSERT_FALSE(chunk.is_null()); - const uint32_t kRed = 0xff0000ff; - FillRectInImage(&chunk, pp::Rect(chunk.size()), kRed); - - // Paint a invisable chunk, expecting Flush to invoke callback slowly. - dc.PaintImageData(chunk, pp::Point(0, h*0.75)); - - PP_Time begin = pp::Module::Get()->core()->GetTime(); - ASSERT_SUBTEST_SUCCESS(FlushAndWaitForDone(&dc)); - PP_Time actual_time_elapsed = pp::Module::Get()->core()->GetTime() - begin; - // Expect actual_time_elapsed >= kFlushDelaySec, but loose a bit to avoid - // precision issue. - ASSERT_GE(actual_time_elapsed, kFlushDelaySec * 0.9); - - // Remove the padding on the top since test cases here isn't independent. - instance_->EvalScript( - "var big = document.getElementById('big-div');" - "big.parentNode.removeChild(big);"); - ResetViewChangedState(); - ASSERT_TRUE(WaitUntilViewChanged()); - - PASS(); -} - -std::string TestGraphics2D::TestDev() { - // Tests GetScale/SetScale via the Graphics2D_Dev C++ wrapper - const int w = 20, h = 16; - const float scale = 1.0f/2.0f; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - ASSERT_EQ(1.0f, dc.GetScale()); - ASSERT_TRUE(dc.SetScale(scale)); - ASSERT_EQ(scale, dc.GetScale()); - // Try setting a few invalid scale factors. Ensure that we catch these errors - // and don't change the actual scale - ASSERT_FALSE(dc.SetScale(-1.0f)); - ASSERT_FALSE(dc.SetScale(0.0f)); - ASSERT_EQ(scale, dc.GetScale()); - - // Verify that the context has the specified number of pixels, despite the - // non-identity scale - PP_Size size; - size.width = -1; - size.height = -1; - PP_Bool is_always_opaque = PP_FALSE; - ASSERT_TRUE(graphics_2d_interface_->Describe(dc.pp_resource(), &size, - &is_always_opaque)); - ASSERT_EQ(w, size.width); - ASSERT_EQ(h, size.height); - ASSERT_EQ(PP_FALSE, is_always_opaque); - - PASS(); -} - -// This test makes sure that the out-of-process image data caching works as -// expected. Doing ReplaceContents quickly should re-use the image data from -// older ones. -std::string TestGraphics2D::TestReplaceContentsCaching() { - // The cache is only active when running in the proxy, so skip it otherwise. - if (!testing_interface_->IsOutOfProcess()) - PASS(); - - // Here we test resource IDs as a way to determine if the resource is being - // cached and re-used. This is non-optimal since it's entirely possible - // (and maybe better) for the proxy to return new resource IDs for the - // re-used objects. Howevever, our current implementation does this so it is - // an easy thing to check for. - // - // You could check for the shared memory pointers getting re-used, but the - // OS is very likely to use the same memory location for a newly-mapped image - // if one was deleted, meaning that it could pass even if the cache is broken. - // This would then require that we add some address-re-use-preventing code - // which would be tricky. - std::set<PP_Resource> resources; - - pp::Size size(16, 16); - pp::Graphics2D dc(instance_, size, false); - - // Do two replace contentses, adding the old resource IDs to our map. - PP_Resource imageres = ReplaceContentsAndReturnID(&dc, size); - ASSERT_TRUE(imageres); - resources.insert(imageres); - imageres = ReplaceContentsAndReturnID(&dc, size); - ASSERT_TRUE(imageres); - resources.insert(imageres); - - // Now doing more replace contents should re-use older IDs if the cache is - // working. - imageres = ReplaceContentsAndReturnID(&dc, size); - ASSERT_TRUE(resources.find(imageres) != resources.end()); - imageres = ReplaceContentsAndReturnID(&dc, size); - ASSERT_TRUE(resources.find(imageres) != resources.end()); - - PASS(); -} - -std::string TestGraphics2D::TestBindNull() { - // Binding a null resource is not an error, it should clear all bound - // resources. We can't easily test what resource is bound, but we can test - // that this doesn't throw an error. - ASSERT_TRUE(instance_->BindGraphics(pp::Graphics2D())); - ASSERT_TRUE(instance_->BindGraphics(pp::Graphics3D())); - - const int w = 115, h = 117; - pp::Graphics2D dc(instance_, pp::Size(w, h), false); - ASSERT_FALSE(dc.is_null()); - ASSERT_TRUE(instance_->BindGraphics(dc)); - - ASSERT_TRUE(instance_->BindGraphics(pp::Graphics2D())); - ASSERT_TRUE(instance_->BindGraphics(pp::Graphics3D())); - - PASS(); -} -
diff --git a/tests/test_graphics_2d.h b/tests/test_graphics_2d.h deleted file mode 100644 index eff4d7e..0000000 --- a/tests/test_graphics_2d.h +++ /dev/null
@@ -1,120 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_GRAPHICS_2D_H_ -#define PPAPI_TESTS_TEST_GRAPHICS_2D_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/ppb_graphics_2d.h" -#include "ppapi/c/ppb_image_data.h" -#include "ppapi/tests/test_case.h" - -namespace pp { -class Graphics2D; -class ImageData; -class Point; -class Rect; -} - -class TestGraphics2D : public TestCase { - public: - explicit TestGraphics2D(TestingInstance* instance); - - // TestCase implementation. - virtual void DidChangeView(const pp::View& view); - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - void QuitMessageLoop(); - - private: - bool ReadImageData(const pp::Graphics2D& dc, - pp::ImageData* image, - const pp::Point& top_left) const; - - void FillRectInImage(pp::ImageData* image, - const pp::Rect& rect, - uint32_t color) const; - - // Fill image with gradient colors. - void FillImageWithGradient(pp::ImageData* image) const; - - // Return true if images are the same. - bool CompareImages(const pp::ImageData& image1, - const pp::ImageData& image2); - - // Return true if images within specified rectangles are the same. - bool CompareImageRect(const pp::ImageData& image1, - const pp::Rect& rc1, - const pp::ImageData& image2, - const pp::Rect& rc2) const; - - // Validates that the given image is a single color with a square of another - // color inside it. - bool IsSquareInImage(const pp::ImageData& image_data, - uint32_t background_color, - const pp::Rect& square, uint32_t square_color) const; - - // Validates that the given device context is a single color with a square of - // another color inside it. - bool IsSquareInDC(const pp::Graphics2D& dc, uint32_t background_color, - const pp::Rect& square, uint32_t square_color) const; - - // Validates that the given device context is filled with the given color. - bool IsDCUniformColor(const pp::Graphics2D& dc, uint32_t color) const; - - // Issues a flush on the given device context and blocks until the flush - // has issued its callback. Returns an empty string on success or an error - // message on failure. - std::string FlushAndWaitForDone(pp::Graphics2D* context); - - // Creates an image and replaces the contents of the Graphics2D with the - // image, waiting for completion. This returns the resource ID of the image - // data we created. This image data will be released by the time the call - // completes, but it can be used for comparisons later. - // - // Returns 0 on failure. - PP_Resource ReplaceContentsAndReturnID(pp::Graphics2D* dc, - const pp::Size& size); - - // Resets the internal state of view change. - void ResetViewChangedState(); - - // Waits until we get a view change event. Note that it's possible to receive - // an unexpected event, thus post_quit_on_view_changed_ is introduced so that - // DidChangeView can check whether the event is from here. - bool WaitUntilViewChanged(); - - std::string TestInvalidResource(); - std::string TestInvalidSize(); - std::string TestHumongous(); - std::string TestInitToZero(); - std::string TestDescribe(); - std::string TestScale(); - std::string TestPaint(); - std::string TestScroll(); - std::string TestReplace(); - std::string TestFlush(); - std::string TestFlushOffscreenUpdate(); - std::string TestDev(); - std::string TestReplaceContentsCaching(); - std::string TestBindNull(); - - // Used by the tests that access the C API directly. - const PPB_Graphics2D_1_2* graphics_2d_interface_; - const PPB_ImageData_1_0* image_data_interface_; - - // Used to indicate that DidChangeView has happened, in order to make plugin - // and ui synchronous. - bool is_view_changed_; - - // Set to true to request that the next invocation of DidChangeView should - // post a quit to the message loop. DidChangeView will also reset the flag so - // this will only happen once. - bool post_quit_on_view_changed_; -}; - -#endif // PPAPI_TESTS_TEST_GRAPHICS_2D_H_
diff --git a/tests/test_graphics_3d.cc b/tests/test_graphics_3d.cc deleted file mode 100644 index fb203e9..0000000 --- a/tests/test_graphics_3d.cc +++ /dev/null
@@ -1,249 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_graphics_3d.h" - -#include <GLES2/gl2.h> -#include <GLES2/gl2ext.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "ppapi/c/ppb_opengles2.h" -#include "ppapi/cpp/graphics_3d.h" -#include "ppapi/cpp/module.h" -#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h" -#include "ppapi/tests/test_case.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -const int32_t kInvalidContext = 0; - -REGISTER_TEST_CASE(Graphics3D); - -bool TestGraphics3D::Init() { - opengl_es2_ = static_cast<const PPB_OpenGLES2*>( - pp::Module::Get()->GetBrowserInterface(PPB_OPENGLES2_INTERFACE)); - glInitializePPAPI(pp::Module::Get()->get_browser_interface()); - return opengl_es2_ && CheckTestingInterface(); -} - -void TestGraphics3D::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestGraphics3D, FramePPAPI, filter); - RUN_CALLBACK_TEST(TestGraphics3D, FrameGL, filter); - RUN_CALLBACK_TEST(TestGraphics3D, ExtensionsGL, filter); - RUN_CALLBACK_TEST(TestGraphics3D, BadResource, filter); - RUN_CALLBACK_TEST(TestGraphics3D, Attributes, filter); -} - -// Tests that all valid context attributes are allowed. -std::string TestGraphics3D::TestAttributes() { - const int width = 16; - const int height = 16; - const int32_t attribs[] = {PP_GRAPHICS3DATTRIB_ALPHA_SIZE, - 8, - PP_GRAPHICS3DATTRIB_BLUE_SIZE, - 8, - PP_GRAPHICS3DATTRIB_GREEN_SIZE, - 8, - PP_GRAPHICS3DATTRIB_RED_SIZE, - 8, - PP_GRAPHICS3DATTRIB_DEPTH_SIZE, - 0, - PP_GRAPHICS3DATTRIB_STENCIL_SIZE, - 0, - PP_GRAPHICS3DATTRIB_SAMPLES, - 0, - PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, - 0, - PP_GRAPHICS3DATTRIB_SWAP_BEHAVIOR, - PP_GRAPHICS3DATTRIB_BUFFER_PRESERVED, - PP_GRAPHICS3DATTRIB_SINGLE_BUFFER, - 0, - PP_GRAPHICS3DATTRIB_GPU_PREFERENCE, - PP_GRAPHICS3DATTRIB_GPU_PREFERENCE_LOW_POWER, - PP_GRAPHICS3DATTRIB_WIDTH, - width, - PP_GRAPHICS3DATTRIB_HEIGHT, - height, - PP_GRAPHICS3DATTRIB_NONE}; - pp::Graphics3D context(instance_, attribs); - ASSERT_FALSE(context.is_null()); - PASS(); -} - -std::string TestGraphics3D::TestFramePPAPI() { - const int width = 16; - const int height = 16; - const int32_t attribs[] = { - PP_GRAPHICS3DATTRIB_WIDTH, width, - PP_GRAPHICS3DATTRIB_HEIGHT, height, - PP_GRAPHICS3DATTRIB_NONE - }; - pp::Graphics3D context(instance_, attribs); - ASSERT_FALSE(context.is_null()); - - const uint8_t red_color[4] = {255, 0, 0, 255}; - - // Access OpenGLES API through the PPAPI interface. - // Clear color buffer to opaque red. - opengl_es2_->ClearColor(context.pp_resource(), 1.0f, 0.0f, 0.0f, 1.0f); - opengl_es2_->Clear(context.pp_resource(), GL_COLOR_BUFFER_BIT); - // Check if the color buffer has opaque red. - std::string error = CheckPixelPPAPI(&context, width/2, height/2, red_color); - if (!error.empty()) - return error; - - int32_t rv = SwapBuffersSync(&context); - ASSERT_EQ(PP_OK, rv); - - PASS(); -} - -std::string TestGraphics3D::TestFrameGL() { - const int width = 16; - const int height = 16; - const int32_t attribs[] = { - PP_GRAPHICS3DATTRIB_WIDTH, width, - PP_GRAPHICS3DATTRIB_HEIGHT, height, - PP_GRAPHICS3DATTRIB_NONE - }; - pp::Graphics3D context(instance_, attribs); - ASSERT_FALSE(context.is_null()); - - const uint8_t red_color[4] = {255, 0, 0, 255}; - // Perform same operations as TestFramePPAPI, but use OpenGLES API directly. - // This is how most developers will use OpenGLES. - glSetCurrentContextPPAPI(context.pp_resource()); - glClearColor(1.0f, 0.0f, 0.0f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - std::string error = CheckPixelGL(width/2, height/2, red_color); - glSetCurrentContextPPAPI(kInvalidContext); - if (!error.empty()) - return error; - - int32_t rv = SwapBuffersSync(&context); - ASSERT_EQ(PP_OK, rv); - - PASS(); -} - -std::string TestGraphics3D::TestExtensionsGL() { - const int width = 16; - const int height = 16; - const int32_t attribs[] = { - PP_GRAPHICS3DATTRIB_WIDTH, width, - PP_GRAPHICS3DATTRIB_HEIGHT, height, - PP_GRAPHICS3DATTRIB_NONE - }; - pp::Graphics3D context(instance_, attribs); - ASSERT_FALSE(context.is_null()); - - glSetCurrentContextPPAPI(context.pp_resource()); - glClearColor(1.0f, 1.0f, 1.0f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - - // Ask about a couple of extensions via glGetString. If an extension is - // available, try a couple of trivial calls. This test is not intended - // to be exhaustive; check the source can compile, link, and run without - // crashing. - ASSERT_NE(NULL, glGetString(GL_VERSION)); - const char* ext = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)); - if (strstr(ext, "GL_EXT_occlusion_query_boolean")) { - GLuint a_query = 0; - glGenQueriesEXT(1, &a_query); - ASSERT_NE(0, a_query); - glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, a_query); - GLboolean is_a_query = glIsQueryEXT(a_query); - ASSERT_EQ(is_a_query, GL_TRUE); - glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT); - glDeleteQueriesEXT(1, &a_query); - } - if (strstr(ext, "GL_ANGLE_instanced_arrays")) { - glDrawArraysInstancedANGLE(GL_TRIANGLE_STRIP, 0, 0, 0); - } - if (strstr(ext, "GL_OES_vertex_array_object")) { - GLuint a_vertex_array = 0; - glGenVertexArraysOES(1, &a_vertex_array); - ASSERT_NE(0, a_vertex_array); - glBindVertexArrayOES(a_vertex_array); - GLboolean is_a_vertex_array = glIsVertexArrayOES(a_vertex_array); - ASSERT_EQ(is_a_vertex_array, GL_TRUE); - glBindVertexArrayOES(0); - glDeleteVertexArraysOES(1, &a_vertex_array); - } - glSetCurrentContextPPAPI(kInvalidContext); - - int32_t rv = SwapBuffersSync(&context); - ASSERT_EQ(PP_OK, rv); - - PASS(); -} - -int32_t TestGraphics3D::SwapBuffersSync(pp::Graphics3D* context) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(context->SwapBuffers(callback.GetCallback())); - return callback.result(); -} - -std::string TestGraphics3D::CheckPixelPPAPI( - pp::Graphics3D* context, - int x, int y, const uint8_t expected_color[4]) { - GLubyte pixel_color[4]; - opengl_es2_->ReadPixels(context->pp_resource(), - x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel_color); - - ASSERT_EQ(pixel_color[0], expected_color[0]); - ASSERT_EQ(pixel_color[1], expected_color[1]); - ASSERT_EQ(pixel_color[2], expected_color[2]); - ASSERT_EQ(pixel_color[3], expected_color[3]); - PASS(); -} - -std::string TestGraphics3D::CheckPixelGL( - int x, int y, const uint8_t expected_color[4]) { - GLubyte pixel_color[4]; - glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel_color); - - ASSERT_EQ(pixel_color[0], expected_color[0]); - ASSERT_EQ(pixel_color[1], expected_color[1]); - ASSERT_EQ(pixel_color[2], expected_color[2]); - ASSERT_EQ(pixel_color[3], expected_color[3]); - PASS(); -} - -std::string TestGraphics3D::TestBadResource() { - // The point of this test is mostly just to make sure that we don't crash and - // provide reasonable (error) results when the resource is bad. - const PP_Resource kBadResource = 123; - - // Access OpenGLES API through the PPAPI interface. - opengl_es2_->ClearColor(kBadResource, 0.0f, 0.0f, 0.0f, 0.0f); - opengl_es2_->Clear(kBadResource, GL_COLOR_BUFFER_BIT); - ASSERT_EQ(0, opengl_es2_->GetError(kBadResource)); - ASSERT_EQ(NULL, opengl_es2_->GetString(kBadResource, GL_VERSION)); - ASSERT_EQ(-1, opengl_es2_->GetUniformLocation(kBadResource, 0, NULL)); - ASSERT_EQ(GL_FALSE, opengl_es2_->IsBuffer(kBadResource, 0)); - ASSERT_EQ(0, opengl_es2_->CheckFramebufferStatus(kBadResource, - GL_DRAW_FRAMEBUFFER)); - - glSetCurrentContextPPAPI(kBadResource); - glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - glClear(GL_COLOR_BUFFER_BIT); - ASSERT_EQ(0, glGetError()); - ASSERT_EQ(NULL, glGetString(GL_VERSION)); - ASSERT_EQ(-1, glGetUniformLocation(0, NULL)); - ASSERT_EQ(GL_FALSE, glIsBuffer(0)); - ASSERT_EQ(0, glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - glClearColor(1.0f, 1.0f, 1.0f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - - PASS(); -} -
diff --git a/tests/test_graphics_3d.h b/tests/test_graphics_3d.h deleted file mode 100644 index 9aeb22a..0000000 --- a/tests/test_graphics_3d.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_GRAPHICS_3D_H_ -#define PPAPI_TESTS_TEST_GRAPHICS_3D_H_ - -#include <stdint.h> - -#include <string> -#include "ppapi/tests/test_case.h" - -struct PPB_OpenGLES2; - -namespace pp { -class Graphics3D; -} // namespace pp - -class TestGraphics3D : public TestCase { - public: - TestGraphics3D(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - // Various tests. - std::string TestExtensionsGL(); - std::string TestFrameGL(); - std::string TestFramePPAPI(); - std::string TestBadResource(); - std::string TestAttributes(); - - // Utils used by various tests. - int32_t SwapBuffersSync(pp::Graphics3D* context); - std::string CheckPixelPPAPI(pp::Graphics3D* context, - int x, int y, const uint8_t expected_color[4]); - std::string CheckPixelGL(int x, int y, const uint8_t expected_color[4]); - - // OpenGL ES2 interface. - const PPB_OpenGLES2* opengl_es2_; -}; - -#endif // PPAPI_TESTS_TEST_GRAPHICS_3D_H_
diff --git a/tests/test_host_resolver.cc b/tests/test_host_resolver.cc deleted file mode 100644 index 36d146a..0000000 --- a/tests/test_host_resolver.cc +++ /dev/null
@@ -1,174 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_host_resolver.h" - -#include <stddef.h> - -#include "ppapi/cpp/host_resolver.h" -#include "ppapi/cpp/net_address.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(HostResolver); - -TestHostResolver::TestHostResolver(TestingInstance* instance) - : TestCase(instance) { -} - -bool TestHostResolver::Init() { - bool host_resolver_is_available = pp::HostResolver::IsAvailable(); - if (!host_resolver_is_available) - instance_->AppendError("PPB_HostResolver interface not available"); - - bool tcp_socket_is_available = pp::TCPSocket::IsAvailable(); - if (!tcp_socket_is_available) - instance_->AppendError("PPB_TCPSocket interface not available"); - - bool init_host_port = - GetLocalHostPort(instance_->pp_instance(), &host_, &port_); - if (!init_host_port) - instance_->AppendError("Can't init host and port"); - - return host_resolver_is_available && - tcp_socket_is_available && - init_host_port && - CheckTestingInterface() && - EnsureRunningOverHTTP(); -} - -void TestHostResolver::RunTests(const std::string& filter) { - RUN_TEST(Empty, filter); - RUN_CALLBACK_TEST(TestHostResolver, Resolve, filter); - RUN_CALLBACK_TEST(TestHostResolver, ResolveIPv4, filter); -} - -std::string TestHostResolver::SyncConnect( - pp::TCPSocket* socket, - const pp::NetAddress& address) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket->Connect(address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -std::string TestHostResolver::SyncRead(pp::TCPSocket* socket, - char* buffer, - int32_t num_bytes, - int32_t* bytes_read) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Read(buffer, num_bytes, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(num_bytes, callback.result()); - *bytes_read = callback.result(); - PASS(); -} - -std::string TestHostResolver::SyncWrite(pp::TCPSocket* socket, - const char* buffer, - int32_t num_bytes, - int32_t* bytes_written) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Write(buffer, num_bytes, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(num_bytes, callback.result()); - *bytes_written = callback.result(); - PASS(); -} - -std::string TestHostResolver::CheckHTTPResponse(pp::TCPSocket* socket, - const std::string& request, - const std::string& response) { - int32_t rv = 0; - ASSERT_SUBTEST_SUCCESS( - SyncWrite(socket, request.c_str(), static_cast<int32_t>(request.size()), - &rv)); - std::vector<char> response_buffer(response.size()); - ASSERT_SUBTEST_SUCCESS( - SyncRead(socket, &response_buffer[0], - static_cast<int32_t>(response.size()), &rv)); - std::string actual_response(&response_buffer[0], rv); - if (response != actual_response) { - return "CheckHTTPResponse failed, expected: " + response + - ", actual: " + actual_response; - } - PASS(); -} - -std::string TestHostResolver::SyncResolve( - pp::HostResolver* host_resolver, - const std::string& host, - uint16_t port, - const PP_HostResolver_Hint& hint) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - host_resolver->Resolve(host.c_str(), port, hint, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -std::string TestHostResolver::ParameterizedTestResolve( - const PP_HostResolver_Hint& hint) { - pp::HostResolver host_resolver(instance_); - - ASSERT_SUBTEST_SUCCESS( - SyncResolve(&host_resolver, "host_resolver.test", port_, hint)); - - size_t size = host_resolver.GetNetAddressCount(); - ASSERT_EQ(1u, size); - - pp::NetAddress address; - for (size_t i = 0; i < size; ++i) { - address = host_resolver.GetNetAddress(static_cast<uint32_t>(i)); - ASSERT_NE(0, address.pp_resource()); - - pp::TCPSocket socket(instance_); - ASSERT_SUBTEST_SUCCESS(SyncConnect(&socket, address)); - ASSERT_SUBTEST_SUCCESS(CheckHTTPResponse(&socket, - "GET / HTTP/1.0\r\n\r\n", - "HTTP")); - socket.Close(); - } - - address = host_resolver.GetNetAddress(static_cast<uint32_t>(size)); - ASSERT_EQ(0, address.pp_resource()); - pp::Var canonical_name = host_resolver.GetCanonicalName(); - ASSERT_TRUE(canonical_name.is_string()); - - ASSERT_SUBTEST_SUCCESS(SyncResolve(&host_resolver, canonical_name.AsString(), - port_, hint)); - size = host_resolver.GetNetAddressCount(); - ASSERT_TRUE(size >= 1); - - PASS(); -} - -std::string TestHostResolver::TestEmpty() { - pp::HostResolver host_resolver(instance_); - ASSERT_EQ(0, host_resolver.GetNetAddressCount()); - pp::NetAddress address = host_resolver.GetNetAddress(0); - ASSERT_EQ(0, address.pp_resource()); - - PASS(); -} - -std::string TestHostResolver::TestResolve() { - PP_HostResolver_Hint hint; - hint.family = PP_NETADDRESS_FAMILY_UNSPECIFIED; - hint.flags = PP_HOSTRESOLVER_FLAG_CANONNAME; - return ParameterizedTestResolve(hint); -} - -std::string TestHostResolver::TestResolveIPv4() { - PP_HostResolver_Hint hint; - hint.family = PP_NETADDRESS_FAMILY_IPV4; - hint.flags = PP_HOSTRESOLVER_FLAG_CANONNAME; - return ParameterizedTestResolve(hint); -}
diff --git a/tests/test_host_resolver.h b/tests/test_host_resolver.h deleted file mode 100644 index fd9ace2..0000000 --- a/tests/test_host_resolver.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_HOST_RESOLVER_H_ -#define PPAPI_TESTS_TEST_HOST_RESOLVER_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/c/ppb_host_resolver.h" -#include "ppapi/tests/test_case.h" - -namespace pp { -class HostResolver; -class NetAddress; -class TCPSocket; -} // namespace pp - -class TestHostResolver : public TestCase { - public: - explicit TestHostResolver(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string SyncConnect(pp::TCPSocket* socket, - const pp::NetAddress& address); - std::string SyncRead(pp::TCPSocket* socket, - char* buffer, - int32_t num_bytes, - int32_t* bytes_read); - std::string SyncWrite(pp::TCPSocket* socket, - const char* buffer, - int32_t num_bytes, - int32_t* bytes_written); - std::string CheckHTTPResponse(pp::TCPSocket* socket, - const std::string& request, - const std::string& response); - std::string SyncResolve(pp::HostResolver* host_resolver, - const std::string& host, - uint16_t port, - const PP_HostResolver_Hint& hint); - std::string ParameterizedTestResolve(const PP_HostResolver_Hint& hint); - - std::string TestEmpty(); - std::string TestResolve(); - std::string TestResolveIPv4(); - - std::string host_; - uint16_t port_; -}; - -#endif // PPAPI_TESTS_TEST_HOST_RESOLVER_H_
diff --git a/tests/test_host_resolver_crash.cc b/tests/test_host_resolver_crash.cc deleted file mode 100644 index 3b21883..0000000 --- a/tests/test_host_resolver_crash.cc +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_host_resolver_crash.h" - -#include <stddef.h> - -#include "ppapi/cpp/host_resolver.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(HostResolverCrash); - -TestHostResolverCrash::TestHostResolverCrash(TestingInstance* instance) - : TestCase(instance) {} - -bool TestHostResolverCrash::Init() { - return pp::HostResolver::IsAvailable(); -} - -void TestHostResolverCrash::RunTests(const std::string& filter) { - // No need to run this test with the various callback types since that's - // orthogonal from the functionality being tested. It would also make the - // test more complicated because it would have to keep watching the network - // process restart and telling it to crash again on crash.com. - RUN_TEST(Basic, filter); -} - -std::string TestHostResolverCrash::TestBasic() { - pp::HostResolver host_resolver(instance_); - - PP_HostResolver_Hint hint; - hint.family = PP_NETADDRESS_FAMILY_UNSPECIFIED; - hint.flags = PP_HOSTRESOLVER_FLAG_CANONNAME; - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - std::string host("crash.com"); - callback.WaitForResult( - host_resolver.Resolve(host.c_str(), 80, hint, callback.GetCallback())); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - PASS(); -}
diff --git a/tests/test_host_resolver_crash.h b/tests/test_host_resolver_crash.h deleted file mode 100644 index 32e380a..0000000 --- a/tests/test_host_resolver_crash.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_HOST_RESOLVER_CRASH_H_ -#define PPAPI_TESTS_TEST_HOST_RESOLVER_CRASH_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -class TestHostResolverCrash : public TestCase { - public: - explicit TestHostResolverCrash(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestBasic(); -}; - -#endif // PPAPI_TESTS_TEST_HOST_RESOLVER_CRASH_H_
diff --git a/tests/test_host_resolver_private.cc b/tests/test_host_resolver_private.cc deleted file mode 100644 index 7bf7848..0000000 --- a/tests/test_host_resolver_private.cc +++ /dev/null
@@ -1,190 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_host_resolver_private.h" - -#include <stddef.h> - -#include "ppapi/c/private/ppb_net_address_private.h" -#include "ppapi/cpp/module_impl.h" -#include "ppapi/cpp/private/host_resolver_private.h" -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(HostResolverPrivate); - -TestHostResolverPrivate::TestHostResolverPrivate(TestingInstance* instance) - : TestCase(instance) { -} - -bool TestHostResolverPrivate::Init() { - bool host_resolver_private_is_available = - pp::HostResolverPrivate::IsAvailable(); - if (!host_resolver_private_is_available) - instance_->AppendError("PPB_HostResolver_Private interface not available"); - - bool tcp_socket_private_is_available = pp::TCPSocketPrivate::IsAvailable(); - if (!tcp_socket_private_is_available) - instance_->AppendError("PPB_TCPSocket_Private interface not available"); - - bool init_host_port = - GetLocalHostPort(instance_->pp_instance(), &host_, &port_); - if (!init_host_port) - instance_->AppendError("Can't init host and port"); - - return host_resolver_private_is_available && - tcp_socket_private_is_available && - init_host_port && - CheckTestingInterface() && - EnsureRunningOverHTTP(); -} - -void TestHostResolverPrivate::RunTests(const std::string& filter) { - RUN_TEST(Empty, filter); - RUN_CALLBACK_TEST(TestHostResolverPrivate, Resolve, filter); - RUN_CALLBACK_TEST(TestHostResolverPrivate, ResolveIPv4, filter); -} - -std::string TestHostResolverPrivate::SyncConnect(pp::TCPSocketPrivate* socket, - const std::string& host, - uint16_t port) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Connect(host.c_str(), port, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -std::string TestHostResolverPrivate::SyncConnect( - pp::TCPSocketPrivate* socket, - const PP_NetAddress_Private& address) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->ConnectWithNetAddress(&address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -std::string TestHostResolverPrivate::SyncRead(pp::TCPSocketPrivate* socket, - char* buffer, - int32_t num_bytes, - int32_t* bytes_read) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Read(buffer, num_bytes, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(num_bytes, callback.result()); - *bytes_read = callback.result(); - PASS(); -} - -std::string TestHostResolverPrivate::SyncWrite(pp::TCPSocketPrivate* socket, - const char* buffer, - int32_t num_bytes, - int32_t* bytes_written) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Write(buffer, num_bytes, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(num_bytes, callback.result()); - *bytes_written = callback.result(); - PASS(); -} - -std::string TestHostResolverPrivate::CheckHTTPResponse( - pp::TCPSocketPrivate* socket, - const std::string& request, - const std::string& response) { - int32_t rv = 0; - ASSERT_SUBTEST_SUCCESS( - SyncWrite(socket, request.c_str(), static_cast<int32_t>(request.size()), - &rv)); - std::vector<char> response_buffer(response.size()); - ASSERT_SUBTEST_SUCCESS( - SyncRead(socket, &response_buffer[0], - static_cast<int32_t>(response.size()), &rv)); - std::string actual_response(&response_buffer[0], rv); - if (response != actual_response) { - return "CheckHTTPResponse failed, expected: " + response + - ", actual: " + actual_response; - } - PASS(); -} - -std::string TestHostResolverPrivate::SyncResolve( - pp::HostResolverPrivate* host_resolver, - const std::string& host, - uint16_t port, - const PP_HostResolver_Private_Hint& hint) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - host_resolver->Resolve(host, port, hint, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - PASS(); -} - -std::string TestHostResolverPrivate::TestEmpty() { - pp::HostResolverPrivate host_resolver(instance_); - ASSERT_EQ(0, host_resolver.GetSize()); - PP_NetAddress_Private address; - ASSERT_FALSE(host_resolver.GetNetAddress(0, &address)); - - PASS(); -} - -std::string TestHostResolverPrivate::ParametrizedTestResolve( - const PP_HostResolver_Private_Hint &hint) { - pp::HostResolverPrivate host_resolver(instance_); - - ASSERT_SUBTEST_SUCCESS(SyncResolve(&host_resolver, host_, port_, hint)); - - const size_t size = host_resolver.GetSize(); - ASSERT_TRUE(size >= 1); - - PP_NetAddress_Private address; - for (size_t i = 0; i < size; ++i) { - ASSERT_TRUE(host_resolver.GetNetAddress( - static_cast<uint32_t>(i), &address)); - - pp::TCPSocketPrivate socket(instance_); - ASSERT_SUBTEST_SUCCESS(SyncConnect(&socket, address)); - ASSERT_SUBTEST_SUCCESS(CheckHTTPResponse(&socket, - "GET / HTTP/1.0\r\n\r\n", - "HTTP")); - socket.Disconnect(); - } - - ASSERT_FALSE(host_resolver.GetNetAddress( - static_cast<uint32_t>(size), &address)); - pp::Var canonical_name = host_resolver.GetCanonicalName(); - ASSERT_TRUE(canonical_name.is_string()); - pp::TCPSocketPrivate socket(instance_); - ASSERT_SUBTEST_SUCCESS(SyncConnect(&socket, - canonical_name.AsString(), - port_)); - ASSERT_SUBTEST_SUCCESS(CheckHTTPResponse(&socket, - "GET / HTTP/1.0\r\n\r\n", - "HTTP")); - socket.Disconnect(); - - PASS(); -} - -std::string TestHostResolverPrivate::TestResolve() { - PP_HostResolver_Private_Hint hint; - hint.family = PP_NETADDRESSFAMILY_PRIVATE_UNSPECIFIED; - hint.flags = PP_HOST_RESOLVER_PRIVATE_FLAGS_CANONNAME; - return ParametrizedTestResolve(hint); -} - -std::string TestHostResolverPrivate::TestResolveIPv4() { - PP_HostResolver_Private_Hint hint; - hint.family = PP_NETADDRESSFAMILY_PRIVATE_IPV4; - hint.flags = PP_HOST_RESOLVER_PRIVATE_FLAGS_CANONNAME; - return ParametrizedTestResolve(hint); -}
diff --git a/tests/test_host_resolver_private.h b/tests/test_host_resolver_private.h deleted file mode 100644 index 2907380..0000000 --- a/tests/test_host_resolver_private.h +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_HOST_RESOLVER_PRIVATE_H_ -#define PPAPI_TESTS_TEST_HOST_RESOLVER_PRIVATE_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/tests/test_case.h" - -struct PP_HostResolver_Private_Hint; -struct PP_NetAddress_Private; - -namespace pp { - -class HostResolverPrivate; -class TCPSocketPrivate; - -} // namespace pp - -class TestHostResolverPrivate : public TestCase { - public: - explicit TestHostResolverPrivate(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string SyncConnect(pp::TCPSocketPrivate* socket, - const std::string& host, - uint16_t port); - std::string SyncConnect(pp::TCPSocketPrivate* socket, - const PP_NetAddress_Private& address); - std::string SyncRead(pp::TCPSocketPrivate* socket, - char* buffer, - int32_t num_bytes, - int32_t* bytes_read); - std::string SyncWrite(pp::TCPSocketPrivate* socket, - const char* buffer, - int32_t num_bytes, - int32_t* bytes_written); - std::string CheckHTTPResponse(pp::TCPSocketPrivate* socket, - const std::string& request, - const std::string& response); - std::string SyncResolve(pp::HostResolverPrivate* host_resolver, - const std::string& host, - uint16_t port, - const PP_HostResolver_Private_Hint& hint); - std::string ParametrizedTestResolve(const PP_HostResolver_Private_Hint& hint); - - std::string TestEmpty(); - std::string TestResolve(); - std::string TestResolveIPv4(); - - std::string host_; - uint16_t port_; -}; - -#endif // PPAPI_TESTS_TEST_HOST_RESOLVER_PRIVATE_H_
diff --git a/tests/test_host_resolver_private_disallowed.cc b/tests/test_host_resolver_private_disallowed.cc deleted file mode 100644 index 6a69304..0000000 --- a/tests/test_host_resolver_private_disallowed.cc +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_host_resolver_private_disallowed.h" - -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(HostResolverPrivateDisallowed); - -TestHostResolverPrivateDisallowed::TestHostResolverPrivateDisallowed( - TestingInstance* instance) - : TestCase(instance) { -} - -bool TestHostResolverPrivateDisallowed::Init() { - bool host_resolver_private_is_available = - pp::HostResolverPrivate::IsAvailable(); - if (!host_resolver_private_is_available) - instance_->AppendError("PPB_HostResolver_Private interface not available"); - - bool init_host_port = - GetLocalHostPort(instance_->pp_instance(), &host_, &port_); - if (!init_host_port) - instance_->AppendError("Can't init host and port"); - - return host_resolver_private_is_available && - init_host_port && - EnsureRunningOverHTTP(); -} - -void TestHostResolverPrivateDisallowed::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestHostResolverPrivateDisallowed, Resolve, filter); -} - -std::string TestHostResolverPrivateDisallowed::TestResolve() { - pp::HostResolverPrivate host_resolver(instance_); - PP_HostResolver_Private_Hint hint; - hint.family = PP_NETADDRESSFAMILY_PRIVATE_UNSPECIFIED; - hint.flags = PP_HOST_RESOLVER_PRIVATE_FLAGS_CANONNAME; - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - host_resolver.Resolve(host_, port_, hint, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - PASS(); -}
diff --git a/tests/test_host_resolver_private_disallowed.h b/tests/test_host_resolver_private_disallowed.h deleted file mode 100644 index 39387a2..0000000 --- a/tests/test_host_resolver_private_disallowed.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_HOST_RESOLVER_PRIVATE_DISALLOWED_H_ -#define PPAPI_TESTS_TEST_HOST_RESOLVER_PRIVATE_DISALLOWED_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/cpp/private/host_resolver_private.h" -#include "ppapi/tests/test_case.h" - -class TestHostResolverPrivateDisallowed : public TestCase { - public: - explicit TestHostResolverPrivateDisallowed(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestResolve(); - - std::string host_; - uint16_t port_; -}; - -#endif // PPAPI_TESTS_TEST_HOST_RESOLVER_PRIVATE_DISALLOWED_H_
diff --git a/tests/test_image.png b/tests/test_image.png deleted file mode 100644 index 0806141..0000000 --- a/tests/test_image.png +++ /dev/null Binary files differ
diff --git a/tests/test_image.png.mock-http-headers b/tests/test_image.png.mock-http-headers deleted file mode 100644 index fe70df0..0000000 --- a/tests/test_image.png.mock-http-headers +++ /dev/null
@@ -1,3 +0,0 @@ -HTTP/1.1 200 OK -Content-Type: image/png -Access-Control-Allow-Origin: *
diff --git a/tests/test_image_data.cc b/tests/test_image_data.cc deleted file mode 100644 index dfb35d2..0000000 --- a/tests/test_image_data.cc +++ /dev/null
@@ -1,190 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_image_data.h" - -#include <stdint.h> - -#include "ppapi/cpp/graphics_2d.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(ImageData); - -bool TestImageData::Init() { - image_data_interface_ = static_cast<const PPB_ImageData*>( - pp::Module::Get()->GetBrowserInterface(PPB_IMAGEDATA_INTERFACE)); - return !!image_data_interface_; -} - -void TestImageData::RunTests(const std::string& filter) { - RUN_TEST(InvalidFormat, filter); - RUN_TEST(GetNativeFormat, filter); - RUN_TEST(FormatSupported, filter); - RUN_TEST(InvalidSize, filter); - RUN_TEST(HugeSize, filter); - RUN_TEST(InitToZero, filter); - RUN_TEST(IsImageData, filter); -} - -std::string TestImageData::TestInvalidFormat() { - pp::ImageData a(instance_, static_cast<PP_ImageDataFormat>(1337), - pp::Size(16, 16), true); - if (!a.is_null()) - return "Crazy image data format accepted"; - - pp::ImageData b(instance_, static_cast<PP_ImageDataFormat>(-1), - pp::Size(16, 16), true); - if (!b.is_null()) - return "Negative image data format accepted"; - PASS(); -} - -std::string TestImageData::SubTestFormatSupported(PP_ImageDataFormat format) { - if (!pp::ImageData::IsImageDataFormatSupported(format)) - return "ImageData::IsImageDataFormatSupported(format) returned false"; - PASS(); -} - -std::string TestImageData::TestFormatSupported() { - ASSERT_SUBTEST_SUCCESS(SubTestFormatSupported( - PP_IMAGEDATAFORMAT_BGRA_PREMUL)); - ASSERT_SUBTEST_SUCCESS(SubTestFormatSupported( - PP_IMAGEDATAFORMAT_RGBA_PREMUL)); - PASS(); -} - -std::string TestImageData::TestGetNativeFormat() { - PP_ImageDataFormat format = pp::ImageData::GetNativeImageDataFormat(); - if (!pp::ImageData::IsImageDataFormatSupported(format)) - return "ImageData::GetNativeImageDataFormat() returned unsupported format"; - PASS(); -} - -std::string TestImageData::SubTestInvalidSize(PP_ImageDataFormat format) { - pp::ImageData zero_size(instance_, format, pp::Size(0, 0), true); - if (!zero_size.is_null()) - return "Zero width and height accepted"; - - pp::ImageData zero_height(instance_, format, pp::Size(16, 0), true); - if (!zero_height.is_null()) - return "Zero height accepted"; - - pp::ImageData zero_width(instance_, format, pp::Size(0, 16), true); - if (!zero_width.is_null()) - return "Zero width accepted"; - - PP_Size negative_height; - negative_height.width = 16; - negative_height.height = -2; - PP_Resource rsrc = image_data_interface_->Create( - instance_->pp_instance(), - format, - &negative_height, PP_TRUE); - if (rsrc) - return "Negative height accepted"; - - PP_Size negative_width; - negative_width.width = -2; - negative_width.height = 16; - rsrc = image_data_interface_->Create( - instance_->pp_instance(), - format, - &negative_width, PP_TRUE); - if (rsrc) - return "Negative width accepted"; - - PASS(); -} - -std::string TestImageData::TestInvalidSize() { - ASSERT_SUBTEST_SUCCESS(SubTestInvalidSize(PP_IMAGEDATAFORMAT_BGRA_PREMUL)); - ASSERT_SUBTEST_SUCCESS(SubTestInvalidSize(PP_IMAGEDATAFORMAT_RGBA_PREMUL)); - PASS(); -} - -std::string TestImageData::SubTestHugeSize(PP_ImageDataFormat format) { - pp::ImageData huge_size(instance_, format, - pp::Size(100000000, 100000000), true); - if (!huge_size.is_null()) - return "31-bit overflow size accepted"; - PASS(); -} - -std::string TestImageData::TestHugeSize() { - ASSERT_SUBTEST_SUCCESS(SubTestHugeSize(PP_IMAGEDATAFORMAT_BGRA_PREMUL)); - ASSERT_SUBTEST_SUCCESS(SubTestHugeSize(PP_IMAGEDATAFORMAT_RGBA_PREMUL)); - PASS(); -} - -std::string TestImageData::SubTestInitToZero(PP_ImageDataFormat format) { - const int w = 5; - const int h = 6; - pp::ImageData img(instance_, format, pp::Size(w, h), true); - if (img.is_null()) - return "Could not create bitmap"; - - // Basic validity checking of the bitmap. This also tests "describe" since - // that's where the image data object got its info from. - if (img.size().width() != w || img.size().height() != h) - return "Wrong size"; - if (img.format() != format) - return "Wrong format"; - if (img.stride() < w * 4) - return "Stride too small"; - - // Now check that everything is 0. - for (int y = 0; y < h; y++) { - uint32_t* row = img.GetAddr32(pp::Point(0, y)); - for (int x = 0; x < w; x++) { - if (row[x] != 0) - return "Image data isn't entirely zero"; - } - } - - PASS(); -} - -std::string TestImageData::TestInitToZero() { - ASSERT_SUBTEST_SUCCESS(SubTestInitToZero(PP_IMAGEDATAFORMAT_BGRA_PREMUL)); - ASSERT_SUBTEST_SUCCESS(SubTestInitToZero(PP_IMAGEDATAFORMAT_RGBA_PREMUL)); - PASS(); -} - -std::string TestImageData::SubTestIsImageData(PP_ImageDataFormat format) { - // Make a valid image resource. - const int w = 16, h = 16; - pp::ImageData img(instance_, format, pp::Size(w, h), true); - if (img.is_null()) - return "Couldn't create image data"; - if (!image_data_interface_->IsImageData(img.pp_resource())) - return "Image data should be identified as an image"; - PASS(); -} - -std::string TestImageData::TestIsImageData() { - // Test that a NULL resource isn't an image data. - pp::Resource null_resource; - if (image_data_interface_->IsImageData(null_resource.pp_resource())) - return "Null resource was reported as a valid image"; - - // Make another resource type and test it. - const int w = 16, h = 16; - pp::Graphics2D device(instance_, pp::Size(w, h), true); - if (device.is_null()) - return "Couldn't create device context"; - if (image_data_interface_->IsImageData(device.pp_resource())) - return "Device context was reported as an image"; - - ASSERT_SUBTEST_SUCCESS(SubTestIsImageData(PP_IMAGEDATAFORMAT_BGRA_PREMUL)); - ASSERT_SUBTEST_SUCCESS(SubTestIsImageData(PP_IMAGEDATAFORMAT_RGBA_PREMUL)); - PASS(); -}
diff --git a/tests/test_image_data.h b/tests/test_image_data.h deleted file mode 100644 index 1e51df4..0000000 --- a/tests/test_image_data.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_IMAGE_DATA_H_ -#define PPAPI_TESTS_TEST_IMAGE_DATA_H_ - -#include <string> - -#include "ppapi/c/ppb_image_data.h" -#include "ppapi/tests/test_case.h" - -class TestImageData : public TestCase { - public: - TestImageData(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestInvalidFormat(); - std::string TestGetNativeFormat(); - std::string TestFormatSupported(); - std::string TestInvalidSize(); - std::string TestHugeSize(); - std::string TestInitToZero(); - std::string TestIsImageData(); - - // Subtests used by tests above; pass in a pixel format. - std::string SubTestFormatSupported(PP_ImageDataFormat format); - std::string SubTestInvalidSize(PP_ImageDataFormat format); - std::string SubTestHugeSize(PP_ImageDataFormat format); - std::string SubTestInitToZero(PP_ImageDataFormat format); - std::string SubTestIsImageData(PP_ImageDataFormat format); - - // Used by the tests that access the C API directly. - const PPB_ImageData* image_data_interface_; -}; - -#endif // PPAPI_TESTS_TEST_IMAGE_DATA_H_
diff --git a/tests/test_ime_input_event.cc b/tests/test_ime_input_event.cc deleted file mode 100644 index a562549..0000000 --- a/tests/test_ime_input_event.cc +++ /dev/null
@@ -1,424 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_ime_input_event.h" - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_input_event.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(ImeInputEvent); - -namespace { - -// Japanese Kanji letters -const char* kCompositionChar[] = { - "\xE6\x96\x87", // An example character of normal unicode. - "\xF0\xA0\xAE\x9F", // An example character of surrogate pair. - "\xF0\x9F\x98\x81" // An example character of surrogate pair(emoji). -}; - -const char kCompositionText[] = "\xE6\x96\x87\xF0\xA0\xAE\x9F\xF0\x9F\x98\x81"; - -#define FINISHED_WAITING_MESSAGE "TEST_IME_INPUT_EVENT_FINISHED_WAITING" - -} // namespace - -TestImeInputEvent::TestImeInputEvent(TestingInstance* instance) - : TestCase(instance), - input_event_interface_(NULL), - keyboard_input_event_interface_(NULL), - ime_input_event_interface_(NULL), - received_unexpected_event_(true), - received_finish_message_(false) { -} - -TestImeInputEvent::~TestImeInputEvent() { - // Remove the special listener that only responds to a - // FINISHED_WAITING_MESSAGE string. See Init for where it gets added. - std::string js_code; - js_code = "var plugin = document.getElementById('plugin');" - "plugin.removeEventListener('message'," - " plugin.wait_for_messages_handler);" - "delete plugin.wait_for_messages_handler;"; - instance_->EvalScript(js_code); -} - -void TestImeInputEvent::RunTests(const std::string& filter) { - RUN_TEST(ImeCommit, filter); - RUN_TEST(ImeCancel, filter); - RUN_TEST(ImeUnawareCommit, filter); - RUN_TEST(ImeUnawareCancel, filter); -} - -bool TestImeInputEvent::Init() { - input_event_interface_ = static_cast<const PPB_InputEvent*>( - pp::Module::Get()->GetBrowserInterface(PPB_INPUT_EVENT_INTERFACE)); - keyboard_input_event_interface_ = - static_cast<const PPB_KeyboardInputEvent*>( - pp::Module::Get()->GetBrowserInterface( - PPB_KEYBOARD_INPUT_EVENT_INTERFACE)); - ime_input_event_interface_ = static_cast<const PPB_IMEInputEvent*>( - pp::Module::Get()->GetBrowserInterface( - PPB_IME_INPUT_EVENT_INTERFACE)); - - bool success = - input_event_interface_ && - keyboard_input_event_interface_ && - ime_input_event_interface_ && - CheckTestingInterface(); - - // Set up a listener for our message that signals that all input events have - // been received. - // Note the following code is dependent on some features of test_case.html. - // E.g., it is assumed that the DOM element where the plugin is embedded has - // an id of 'plugin', and there is a function 'IsTestingMessage' that allows - // us to ignore the messages that are intended for use by the testing - // framework itself. - std::string js_code = - "var plugin = document.getElementById('plugin');" - "var wait_for_messages_handler = function(message_event) {" - " if (!IsTestingMessage(message_event.data) &&" - " message_event.data === '" FINISHED_WAITING_MESSAGE "') {" - " plugin.postMessage('" FINISHED_WAITING_MESSAGE "');" - " }" - "};" - "plugin.addEventListener('message', wait_for_messages_handler);" - // Stash it on the plugin so we can remove it in the destructor. - "plugin.wait_for_messages_handler = wait_for_messages_handler;"; - instance_->EvalScript(js_code); - - return success; -} - -bool TestImeInputEvent::HandleInputEvent(const pp::InputEvent& input_event) { - // Check whether the IME related events comes in the expected order. - switch (input_event.GetType()) { - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START: - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE: - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END: - case PP_INPUTEVENT_TYPE_IME_TEXT: - case PP_INPUTEVENT_TYPE_CHAR: - if (expected_events_.empty()) { - received_unexpected_event_ = true; - } else { - received_unexpected_event_ = - !AreEquivalentEvents(input_event.pp_resource(), - expected_events_.front().pp_resource()); - expected_events_.erase(expected_events_.begin()); - } - break; - - default: - // Don't care for any other input event types for this test. - break; - } - - // Handle all input events. - return true; -} - -void TestImeInputEvent::HandleMessage(const pp::Var& message_data) { - if (message_data.is_string() && - (message_data.AsString() == FINISHED_WAITING_MESSAGE)) { - testing_interface_->QuitMessageLoop(instance_->pp_instance()); - received_finish_message_ = true; - } -} - -void TestImeInputEvent::DidChangeView(const pp::View& view) { - view_rect_ = view.GetRect(); -} - -pp::InputEvent TestImeInputEvent::CreateImeCompositionStartEvent() { - return pp::IMEInputEvent( - instance_, - PP_INPUTEVENT_TYPE_IME_COMPOSITION_START, - 100, // time_stamp - pp::Var(""), - std::vector<uint32_t>(), - -1, // target_segment - std::make_pair(0U, 0U) // selection - ); -} - -pp::InputEvent TestImeInputEvent::CreateImeCompositionUpdateEvent( - const std::string& text, - const std::vector<uint32_t>& segments, - int32_t target_segment, - const std::pair<uint32_t, uint32_t>& selection) { - return pp::IMEInputEvent( - instance_, - PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE, - 100, // time_stamp - text, - segments, - target_segment, - selection - ); -} - -pp::InputEvent TestImeInputEvent::CreateImeCompositionEndEvent( - const std::string& text) { - return pp::IMEInputEvent( - instance_, - PP_INPUTEVENT_TYPE_IME_COMPOSITION_END, - 100, // time_stamp - pp::Var(text), - std::vector<uint32_t>(), - -1, // target_segment - std::make_pair(0U, 0U) // selection - ); -} - -pp::InputEvent TestImeInputEvent::CreateImeTextEvent(const std::string& text) { - return pp::IMEInputEvent( - instance_, - PP_INPUTEVENT_TYPE_IME_TEXT, - 100, // time_stamp - pp::Var(text), - std::vector<uint32_t>(), - -1, // target_segment - std::make_pair(0U, 0U) // selection - ); -} - -pp::InputEvent TestImeInputEvent::CreateCharEvent(const std::string& text) { - return pp::KeyboardInputEvent( - instance_, - PP_INPUTEVENT_TYPE_CHAR, - 100, // time_stamp - 0, // modifiers - 0, // keycode - pp::Var(text), - pp::Var()); -} - -void TestImeInputEvent::GetFocusBySimulatingMouseClick() { - // For receiving IME events, the plugin DOM node needs to be focused. - // The following code is for achieving that by simulating a mouse click event. - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_MOUSE); - SimulateInputEvent(pp::MouseInputEvent( - instance_, - PP_INPUTEVENT_TYPE_MOUSEDOWN, - 100, // time_stamp - 0, // modifiers - PP_INPUTEVENT_MOUSEBUTTON_LEFT, - pp::Point( - view_rect_.x() + view_rect_.width() / 2, - view_rect_.y() + view_rect_.height() / 2), - 1, // click count - pp::Point())); // movement -} - -// Simulates the input event and calls PostMessage to let us know when -// we have received all resulting events from the browser. -bool TestImeInputEvent::SimulateInputEvent(const pp::InputEvent& input_event) { - received_unexpected_event_ = false; - received_finish_message_ = false; - testing_interface_->SimulateInputEvent(instance_->pp_instance(), - input_event.pp_resource()); - instance_->PostMessage(pp::Var(FINISHED_WAITING_MESSAGE)); - testing_interface_->RunMessageLoop(instance_->pp_instance()); - return received_finish_message_ && !received_unexpected_event_; -} - -bool TestImeInputEvent::AreEquivalentEvents(PP_Resource received, - PP_Resource expected) { - if (!input_event_interface_->IsInputEvent(received) || - !input_event_interface_->IsInputEvent(expected)) { - return false; - } - - // Test common fields, except modifiers and time stamp, which may be changed - // by the browser. - int32_t received_type = input_event_interface_->GetType(received); - int32_t expected_type = input_event_interface_->GetType(expected); - if (received_type != expected_type) - return false; - - // Test event type-specific fields. - switch (received_type) { - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START: - // COMPOSITION_START does not convey further information. - break; - - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END: - case PP_INPUTEVENT_TYPE_IME_TEXT: - // For COMPOSITION_END and TEXT, GetText() has meaning. - return pp::Var(pp::PASS_REF, - ime_input_event_interface_->GetText(received)) == - pp::Var(pp::PASS_REF, - ime_input_event_interface_->GetText(expected)); - - case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE: - // For COMPOSITION_UPDATE, all fields must be checked. - { - uint32_t received_segment_number = - ime_input_event_interface_->GetSegmentNumber(received); - uint32_t expected_segment_number = - ime_input_event_interface_->GetSegmentNumber(expected); - if (received_segment_number != expected_segment_number) - return false; - - // The "<=" is not a bug. i-th segment is represented as the pair of - // i-th and (i+1)-th offsets in Pepper IME API. - for (uint32_t i = 0; i <= received_segment_number; ++i) { - if (ime_input_event_interface_->GetSegmentOffset(received, i) != - ime_input_event_interface_->GetSegmentOffset(expected, i)) - return false; - } - - uint32_t received_selection_start = 0; - uint32_t received_selection_end = 0; - uint32_t expected_selection_start = 0; - uint32_t expected_selection_end = 0; - ime_input_event_interface_->GetSelection( - received, &received_selection_start, &received_selection_end); - ime_input_event_interface_->GetSelection( - expected, &expected_selection_start, &expected_selection_end); - if (received_selection_start != expected_selection_start || - received_selection_end != expected_selection_end) { - return true; - } - - return pp::Var(pp::PASS_REF, - ime_input_event_interface_->GetText(received)) == - pp::Var(pp::PASS_REF, - ime_input_event_interface_->GetText(expected)) && - ime_input_event_interface_->GetTargetSegment(received) == - ime_input_event_interface_->GetTargetSegment(expected); - } - - case PP_INPUTEVENT_TYPE_CHAR: - return - keyboard_input_event_interface_->GetKeyCode(received) == - keyboard_input_event_interface_->GetKeyCode(expected) && - pp::Var(pp::PASS_REF, - keyboard_input_event_interface_->GetCharacterText(received)) == - pp::Var(pp::PASS_REF, - keyboard_input_event_interface_->GetCharacterText(expected)); - - default: - break; - } - return true; -} - -std::string TestImeInputEvent::TestImeCommit() { - GetFocusBySimulatingMouseClick(); - - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_KEYBOARD | - PP_INPUTEVENT_CLASS_IME); - - std::vector<uint32_t> segments; - segments.push_back(0U); - segments.push_back(3U); - segments.push_back(7U); - segments.push_back(11U); - pp::InputEvent update_event = CreateImeCompositionUpdateEvent( - kCompositionText, segments, 1, std::make_pair(3U, 7U)); - - expected_events_.clear(); - expected_events_.push_back(CreateImeCompositionStartEvent()); - expected_events_.push_back(update_event); - expected_events_.push_back(CreateImeCompositionEndEvent(kCompositionText)); - expected_events_.push_back(CreateImeTextEvent(kCompositionText)); - - // Simulate the case when IME successfully committed some text. - ASSERT_TRUE(SimulateInputEvent(update_event)); - ASSERT_TRUE(SimulateInputEvent(CreateImeTextEvent(kCompositionText))); - - ASSERT_TRUE(expected_events_.empty()); - PASS(); -} - -std::string TestImeInputEvent::TestImeCancel() { - GetFocusBySimulatingMouseClick(); - - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_KEYBOARD | - PP_INPUTEVENT_CLASS_IME); - - std::vector<uint32_t> segments; - segments.push_back(0U); - segments.push_back(3U); - segments.push_back(7U); - segments.push_back(11U); - pp::InputEvent update_event = CreateImeCompositionUpdateEvent( - kCompositionText, segments, 1, std::make_pair(3U, 7U)); - - expected_events_.clear(); - expected_events_.push_back(CreateImeCompositionStartEvent()); - expected_events_.push_back(update_event); - expected_events_.push_back(CreateImeCompositionEndEvent(std::string())); - - // Simulate the case when IME canceled composition. - ASSERT_TRUE(SimulateInputEvent(update_event)); - ASSERT_TRUE(SimulateInputEvent(CreateImeCompositionEndEvent(std::string()))); - - ASSERT_TRUE(expected_events_.empty()); - PASS(); -} - -std::string TestImeInputEvent::TestImeUnawareCommit() { - GetFocusBySimulatingMouseClick(); - - input_event_interface_->ClearInputEventRequest(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_IME); - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_KEYBOARD); - - std::vector<uint32_t> segments; - segments.push_back(0U); - segments.push_back(3U); - segments.push_back(7U); - segments.push_back(11U); - pp::InputEvent update_event = CreateImeCompositionUpdateEvent( - kCompositionText, segments, 1, std::make_pair(3U, 7U)); - - expected_events_.clear(); - expected_events_.push_back(CreateCharEvent(kCompositionChar[0])); - expected_events_.push_back(CreateCharEvent(kCompositionChar[1])); - expected_events_.push_back(CreateCharEvent(kCompositionChar[2])); - - // Test for IME-unaware plugins. Commit event is translated to char events. - ASSERT_TRUE(SimulateInputEvent(update_event)); - ASSERT_TRUE(SimulateInputEvent(CreateImeTextEvent(kCompositionText))); - - ASSERT_TRUE(expected_events_.empty()); - PASS(); -} - - -std::string TestImeInputEvent::TestImeUnawareCancel() { - GetFocusBySimulatingMouseClick(); - - input_event_interface_->ClearInputEventRequest(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_IME); - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_KEYBOARD); - - std::vector<uint32_t> segments; - segments.push_back(0U); - segments.push_back(3U); - segments.push_back(7U); - segments.push_back(11U); - pp::InputEvent update_event = CreateImeCompositionUpdateEvent( - kCompositionText, segments, 1, std::make_pair(3U, 7U)); - - expected_events_.clear(); - - // Test for IME-unaware plugins. Cancel won't issue any events. - ASSERT_TRUE(SimulateInputEvent(update_event)); - ASSERT_TRUE(SimulateInputEvent(CreateImeCompositionEndEvent(std::string()))); - - ASSERT_TRUE(expected_events_.empty()); - PASS(); -}
diff --git a/tests/test_ime_input_event.h b/tests/test_ime_input_event.h deleted file mode 100644 index 99cb99f..0000000 --- a/tests/test_ime_input_event.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_IME_INPUT_EVENT_H_ -#define PPAPI_TESTS_TEST_IME_INPUT_EVENT_H_ - -#include <stdint.h> - -#include <string> -#include <utility> -#include <vector> - -#include "ppapi/c/ppb_input_event.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/tests/test_case.h" - -class TestImeInputEvent : public TestCase { - public: - explicit TestImeInputEvent(TestingInstance* instance); - ~TestImeInputEvent(); - - // TestCase implementation. - virtual void RunTests(const std::string& test_filter); - virtual bool Init(); - virtual bool HandleInputEvent(const pp::InputEvent& input_event); - virtual void HandleMessage(const pp::Var& message_data); - virtual void DidChangeView(const pp::View& view); - - private: - pp::InputEvent CreateImeCompositionStartEvent(); - pp::InputEvent CreateImeCompositionUpdateEvent( - const std::string& text, - const std::vector<uint32_t>& segments, - int32_t target_segment, - const std::pair<uint32_t, uint32_t>& selection); - pp::InputEvent CreateImeCompositionEndEvent(const std::string& text); - pp::InputEvent CreateImeTextEvent(const std::string& text); - pp::InputEvent CreateCharEvent(const std::string& text); - - void GetFocusBySimulatingMouseClick(); - bool SimulateInputEvent(const pp::InputEvent& input_event); - bool AreEquivalentEvents(PP_Resource first, PP_Resource second); - - // The test cases. - std::string TestImeCommit(); - std::string TestImeCancel(); - std::string TestImeUnawareCommit(); - std::string TestImeUnawareCancel(); - - const PPB_InputEvent* input_event_interface_; - const PPB_KeyboardInputEvent* keyboard_input_event_interface_; - const PPB_IMEInputEvent* ime_input_event_interface_; - - pp::Rect view_rect_; - bool received_unexpected_event_; - bool received_finish_message_; - std::vector<pp::InputEvent> expected_events_; -}; - -#endif // PPAPI_TESTS_TEST_IME_INPUT_EVENT_H_
diff --git a/tests/test_input_event.cc b/tests/test_input_event.cc deleted file mode 100644 index e43887f..0000000 --- a/tests/test_input_event.cc +++ /dev/null
@@ -1,423 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_input_event.h" - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_input_event.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(InputEvent); - -namespace { - -const uint32_t kSpaceChar = 0x20; -const char* kSpaceString = " "; -const char* kSpaceCode = "Space"; - -#define FINISHED_WAITING_MESSAGE "TEST_INPUT_EVENT_FINISHED_WAITING" - -pp::Point GetCenter(const pp::Rect& rect) { - return pp::Point( - rect.x() + rect.width() / 2, - rect.y() + rect.height() / 2); -} - -} // namespace - -void TestInputEvent::RunTests(const std::string& filter) { - RUN_TEST(Events, filter); - - // The AcceptTouchEvent_N tests should not be run when the filter is empty; - // they can only be run one at a time. - // TODO(dmichael): Figure out a way to make these run in the same test fixture - // instance. - if (!ShouldRunAllTests(filter)) { - RUN_TEST(AcceptTouchEvent_1, filter); - RUN_TEST(AcceptTouchEvent_2, filter); - RUN_TEST(AcceptTouchEvent_3, filter); - RUN_TEST(AcceptTouchEvent_4, filter); - } -} - -TestInputEvent::TestInputEvent(TestingInstance* instance) - : TestCase(instance), - input_event_interface_(NULL), - mouse_input_event_interface_(NULL), - wheel_input_event_interface_(NULL), - keyboard_input_event_interface_(NULL), - touch_input_event_interface_(NULL), - nested_event_(instance->pp_instance()), - view_rect_(), - expected_input_event_(0), - received_expected_event_(false), - received_finish_message_(false) { -} - -TestInputEvent::~TestInputEvent() { - // Remove the special listener that only responds to a - // FINISHED_WAITING_MESSAGE string. See Init for where it gets added. - std::string js_code; - js_code += "var plugin = document.getElementById('plugin');" - "plugin.removeEventListener('message'," - " plugin.wait_for_messages_handler);" - "delete plugin.wait_for_messages_handler;"; - instance_->EvalScript(js_code); -} - -bool TestInputEvent::Init() { - input_event_interface_ = static_cast<const PPB_InputEvent*>( - pp::Module::Get()->GetBrowserInterface(PPB_INPUT_EVENT_INTERFACE)); - mouse_input_event_interface_ = static_cast<const PPB_MouseInputEvent*>( - pp::Module::Get()->GetBrowserInterface( - PPB_MOUSE_INPUT_EVENT_INTERFACE)); - wheel_input_event_interface_ = static_cast<const PPB_WheelInputEvent*>( - pp::Module::Get()->GetBrowserInterface( - PPB_WHEEL_INPUT_EVENT_INTERFACE)); - keyboard_input_event_interface_ = static_cast<const PPB_KeyboardInputEvent*>( - pp::Module::Get()->GetBrowserInterface( - PPB_KEYBOARD_INPUT_EVENT_INTERFACE)); - touch_input_event_interface_ = static_cast<const PPB_TouchInputEvent*>( - pp::Module::Get()->GetBrowserInterface( - PPB_TOUCH_INPUT_EVENT_INTERFACE)); - - bool success = - input_event_interface_ && - mouse_input_event_interface_ && - wheel_input_event_interface_ && - keyboard_input_event_interface_ && - touch_input_event_interface_ && - CheckTestingInterface(); - - // Set up a listener for our message that signals that all input events have - // been received. - std::string js_code; - // Note the following code is dependent on some features of test_case.html. - // E.g., it is assumed that the DOM element where the plugin is embedded has - // an id of 'plugin', and there is a function 'IsTestingMessage' that allows - // us to ignore the messages that are intended for use by the testing - // framework itself. - js_code += "var plugin = document.getElementById('plugin');" - "var wait_for_messages_handler = function(message_event) {" - " if (!IsTestingMessage(message_event.data) &&" - " message_event.data === '" FINISHED_WAITING_MESSAGE "') {" - " plugin.postMessage('" FINISHED_WAITING_MESSAGE "');" - " }" - "};" - "plugin.addEventListener('message', wait_for_messages_handler);" - // Stash it on the plugin so we can remove it in the destructor. - "plugin.wait_for_messages_handler = wait_for_messages_handler;"; - instance_->EvalScript(js_code); - - return success; -} - -pp::InputEvent TestInputEvent::CreateMouseEvent( - PP_InputEvent_Type type, - PP_InputEvent_MouseButton buttons) { - return pp::MouseInputEvent( - instance_, - type, - 100, // time_stamp - 0, // modifiers - buttons, - GetCenter(view_rect_), - 1, // click count - pp::Point()); // movement -} - -pp::InputEvent TestInputEvent::CreateWheelEvent() { - return pp::WheelInputEvent( - instance_, - 100, // time_stamp - 0, // modifiers - pp::FloatPoint(1, 2), - pp::FloatPoint(3, 4), - PP_TRUE); // scroll_by_page -} - -pp::InputEvent TestInputEvent::CreateKeyEvent(PP_InputEvent_Type type, - uint32_t key_code, - const std::string& code) { - return pp::KeyboardInputEvent( - instance_, - type, - 100, // time_stamp - 0, // modifiers - key_code, - pp::Var(), - pp::Var(code)); -} - -pp::InputEvent TestInputEvent::CreateCharEvent(const std::string& text) { - return pp::KeyboardInputEvent( - instance_, - PP_INPUTEVENT_TYPE_CHAR, - 100, // time_stamp - 0, // modifiers - 0, // keycode - pp::Var(text), - pp::Var()); -} - -pp::InputEvent TestInputEvent::CreateTouchEvent(PP_InputEvent_Type type, - const pp::FloatPoint& point) { - PP_TouchPoint touch_point = PP_MakeTouchPoint(); - touch_point.position = point; - - pp::TouchInputEvent touch_event(instance_, type, 100, 0); - touch_event.AddTouchPoint(PP_TOUCHLIST_TYPE_TOUCHES, touch_point); - touch_event.AddTouchPoint(PP_TOUCHLIST_TYPE_CHANGEDTOUCHES, touch_point); - touch_event.AddTouchPoint(PP_TOUCHLIST_TYPE_TARGETTOUCHES, touch_point); - - return touch_event; -} - -void TestInputEvent::PostMessageBarrier() { - received_finish_message_ = false; - instance_->PostMessage(pp::Var(FINISHED_WAITING_MESSAGE)); - testing_interface_->RunMessageLoop(instance_->pp_instance()); - nested_event_.Wait(); -} - -// Simulates the input event and calls PostMessage to let us know when -// we have received all resulting events from the browser. -bool TestInputEvent::SimulateInputEvent( - const pp::InputEvent& input_event) { - expected_input_event_ = pp::InputEvent(input_event.pp_resource()); - received_expected_event_ = false; - testing_interface_->SimulateInputEvent(instance_->pp_instance(), - input_event.pp_resource()); - PostMessageBarrier(); - return received_expected_event_; -} - -bool TestInputEvent::AreEquivalentEvents(PP_Resource received, - PP_Resource expected) { - if (!input_event_interface_->IsInputEvent(received) || - !input_event_interface_->IsInputEvent(expected)) { - return false; - } - - // Test common fields, except modifiers and time stamp, which may be changed - // by the browser. - int32_t received_type = input_event_interface_->GetType(received); - int32_t expected_type = input_event_interface_->GetType(expected); - if (received_type != expected_type) { - // Allow key down events to match "raw" key down events. - if (expected_type != PP_INPUTEVENT_TYPE_KEYDOWN && - received_type != PP_INPUTEVENT_TYPE_RAWKEYDOWN) { - return false; - } - } - - // Test event type-specific fields. - switch (input_event_interface_->GetType(received)) { - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - case PP_INPUTEVENT_TYPE_MOUSEUP: - case PP_INPUTEVENT_TYPE_MOUSEMOVE: - case PP_INPUTEVENT_TYPE_MOUSEENTER: - case PP_INPUTEVENT_TYPE_MOUSELEAVE: - // Check mouse fields, except position and movement, which may be - // modified by the renderer. - return - mouse_input_event_interface_->GetButton(received) == - mouse_input_event_interface_->GetButton(expected) && - mouse_input_event_interface_->GetClickCount(received) == - mouse_input_event_interface_->GetClickCount(expected); - - case PP_INPUTEVENT_TYPE_WHEEL: - return - pp::FloatPoint(wheel_input_event_interface_->GetDelta(received)) == - pp::FloatPoint(wheel_input_event_interface_->GetDelta(expected)) && - pp::FloatPoint(wheel_input_event_interface_->GetTicks(received)) == - pp::FloatPoint(wheel_input_event_interface_->GetTicks(expected)) && - wheel_input_event_interface_->GetScrollByPage(received) == - wheel_input_event_interface_->GetScrollByPage(expected); - - case PP_INPUTEVENT_TYPE_RAWKEYDOWN: - case PP_INPUTEVENT_TYPE_KEYDOWN: - case PP_INPUTEVENT_TYPE_KEYUP: - return - keyboard_input_event_interface_->GetKeyCode(received) == - keyboard_input_event_interface_->GetKeyCode(expected); - - case PP_INPUTEVENT_TYPE_CHAR: - return - keyboard_input_event_interface_->GetKeyCode(received) == - keyboard_input_event_interface_->GetKeyCode(expected) && - pp::Var(pp::PASS_REF, - keyboard_input_event_interface_->GetCharacterText(received)) == - pp::Var(pp::PASS_REF, - keyboard_input_event_interface_->GetCharacterText(expected)); - - case PP_INPUTEVENT_TYPE_TOUCHSTART: - case PP_INPUTEVENT_TYPE_TOUCHMOVE: - case PP_INPUTEVENT_TYPE_TOUCHEND: - case PP_INPUTEVENT_TYPE_TOUCHCANCEL: { - if (!touch_input_event_interface_->IsTouchInputEvent(received) || - !touch_input_event_interface_->IsTouchInputEvent(expected)) - return false; - - uint32_t touch_count = touch_input_event_interface_->GetTouchCount( - received, PP_TOUCHLIST_TYPE_TOUCHES); - if (touch_count <= 0 || - touch_count != touch_input_event_interface_->GetTouchCount(expected, - PP_TOUCHLIST_TYPE_TOUCHES)) - return false; - - for (uint32_t i = 0; i < touch_count; ++i) { - PP_TouchPoint expected_point = touch_input_event_interface_-> - GetTouchByIndex(expected, PP_TOUCHLIST_TYPE_TOUCHES, i); - PP_TouchPoint received_point = touch_input_event_interface_-> - GetTouchByIndex(received, PP_TOUCHLIST_TYPE_TOUCHES, i); - - if (expected_point.id != received_point.id || - expected_point.radius != received_point.radius || - expected_point.rotation_angle != received_point.rotation_angle || - expected_point.pressure != received_point.pressure) - return false; - - if (expected_point.position.x != received_point.position.x || - expected_point.position.y != received_point.position.y) - return false; - } - return true; - } - - default: - break; - } - - return false; -} - -bool TestInputEvent::HandleInputEvent(const pp::InputEvent& input_event) { - // Some events may cause extra events to be generated, so look for the - // first one that matches. - if (!received_expected_event_) { - received_expected_event_ = AreEquivalentEvents( - input_event.pp_resource(), - expected_input_event_.pp_resource()); - } - // Handle all input events. - return true; -} - -void TestInputEvent::HandleMessage(const pp::Var& message_data) { - if (message_data.is_string() && - (message_data.AsString() == FINISHED_WAITING_MESSAGE)) { - testing_interface_->QuitMessageLoop(instance_->pp_instance()); - received_finish_message_ = true; - nested_event_.Signal(); - } -} - -void TestInputEvent::DidChangeView(const pp::View& view) { - view_rect_ = view.GetRect(); -} - -std::string TestInputEvent::TestEvents() { - // Request all input event classes. - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_MOUSE | - PP_INPUTEVENT_CLASS_WHEEL | - PP_INPUTEVENT_CLASS_KEYBOARD | - PP_INPUTEVENT_CLASS_TOUCH); - PostMessageBarrier(); - - // Send the events and check that we received them. - ASSERT_TRUE( - SimulateInputEvent(CreateMouseEvent(PP_INPUTEVENT_TYPE_MOUSEDOWN, - PP_INPUTEVENT_MOUSEBUTTON_LEFT))); - ASSERT_TRUE( - SimulateInputEvent(CreateWheelEvent())); - ASSERT_TRUE( - SimulateInputEvent(CreateKeyEvent(PP_INPUTEVENT_TYPE_KEYDOWN, - kSpaceChar, kSpaceCode))); - ASSERT_TRUE( - SimulateInputEvent(CreateCharEvent(kSpaceString))); - ASSERT_TRUE(SimulateInputEvent(CreateTouchEvent(PP_INPUTEVENT_TYPE_TOUCHSTART, - pp::FloatPoint(12, 23)))); - // Request only mouse events. - input_event_interface_->ClearInputEventRequest(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_WHEEL | - PP_INPUTEVENT_CLASS_KEYBOARD); - PostMessageBarrier(); - - // Check that we only receive mouse events. - ASSERT_TRUE( - SimulateInputEvent(CreateMouseEvent(PP_INPUTEVENT_TYPE_MOUSEDOWN, - PP_INPUTEVENT_MOUSEBUTTON_LEFT))); - ASSERT_FALSE( - SimulateInputEvent(CreateWheelEvent())); - ASSERT_FALSE( - SimulateInputEvent(CreateKeyEvent(PP_INPUTEVENT_TYPE_KEYDOWN, - kSpaceChar, kSpaceCode))); - ASSERT_FALSE( - SimulateInputEvent(CreateCharEvent(kSpaceString))); - - PASS(); -} - -std::string TestInputEvent::TestAcceptTouchEvent_1() { - // The browser normally sends touch-events to the renderer only if the page - // has touch-event handlers. Since test-case.html does not have any - // touch-event handler, it would normally not receive any touch events from - // the browser. However, if a plugin in the page does accept touch events, - // then the browser should start sending touch-events to the page. In this - // test, the plugin simply registers for touch-events. The real test is to - // verify that the browser knows to send touch-events to the renderer. - // If the plugin is removed from the page, then there are no more touch-event - // handlers in the page, and browser stops sending touch-events. So to make - // it possible to test this properly, the plugin is not removed from the page - // at the end of the test. - instance_->set_remove_plugin(false); - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_MOUSE | - PP_INPUTEVENT_CLASS_WHEEL | - PP_INPUTEVENT_CLASS_KEYBOARD | - PP_INPUTEVENT_CLASS_TOUCH); - PASS(); -} - -std::string TestInputEvent::TestAcceptTouchEvent_2() { - // See comment in TestAcceptTouchEvent_1. - instance_->set_remove_plugin(false); - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_MOUSE | - PP_INPUTEVENT_CLASS_WHEEL | - PP_INPUTEVENT_CLASS_KEYBOARD | - PP_INPUTEVENT_CLASS_TOUCH); - input_event_interface_->ClearInputEventRequest(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_TOUCH); - PASS(); -} - -std::string TestInputEvent::TestAcceptTouchEvent_3() { - // See comment in TestAcceptTouchEvent_1. - instance_->set_remove_plugin(false); - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_MOUSE | - PP_INPUTEVENT_CLASS_WHEEL | - PP_INPUTEVENT_CLASS_KEYBOARD); - input_event_interface_->RequestFilteringInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_TOUCH); - PASS(); -} - -std::string TestInputEvent::TestAcceptTouchEvent_4() { - // See comment in TestAcceptTouchEvent_1. - instance_->set_remove_plugin(false); - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_MOUSE | - PP_INPUTEVENT_CLASS_WHEEL | - PP_INPUTEVENT_CLASS_KEYBOARD); - input_event_interface_->RequestInputEvents(instance_->pp_instance(), - PP_INPUTEVENT_CLASS_TOUCH); - PASS(); -}
diff --git a/tests/test_input_event.h b/tests/test_input_event.h deleted file mode 100644 index 3299239..0000000 --- a/tests/test_input_event.h +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_INPUT_EVENT_H_ -#define PPAPI_TESTS_TEST_INPUT_EVENT_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/c/ppb_input_event.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/point.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/tests/test_case.h" -#include "ppapi/tests/test_utils.h" - -class TestInputEvent : public TestCase { - public: - explicit TestInputEvent(TestingInstance* instance); - ~TestInputEvent(); - - virtual bool HandleInputEvent(const pp::InputEvent& input_event); - virtual void HandleMessage(const pp::Var& message_data); - virtual void DidChangeView(const pp::View& view); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& test_filter); - - private: - pp::InputEvent CreateMouseEvent(PP_InputEvent_Type type, - PP_InputEvent_MouseButton buttons); - pp::InputEvent CreateWheelEvent(); - pp::InputEvent CreateKeyEvent(PP_InputEvent_Type type, - uint32_t key_code, const std::string& code); - pp::InputEvent CreateCharEvent(const std::string& text); - pp::InputEvent CreateTouchEvent(PP_InputEvent_Type type, - const pp::FloatPoint& location); - - void PostMessageBarrier(); - bool SimulateInputEvent(const pp::InputEvent& input_event); - bool AreEquivalentEvents(PP_Resource first, PP_Resource second); - - std::string TestEvents(); - std::string TestAcceptTouchEvent_1(); - std::string TestAcceptTouchEvent_2(); - std::string TestAcceptTouchEvent_3(); - std::string TestAcceptTouchEvent_4(); - - const PPB_InputEvent* input_event_interface_; - const PPB_MouseInputEvent* mouse_input_event_interface_; - const PPB_WheelInputEvent* wheel_input_event_interface_; - const PPB_KeyboardInputEvent* keyboard_input_event_interface_; - const PPB_TouchInputEvent* touch_input_event_interface_; - - NestedEvent nested_event_; - - pp::Rect view_rect_; - pp::InputEvent expected_input_event_; - bool received_expected_event_; - bool received_finish_message_; -}; - -#endif // PPAPI_TESTS_TEST_INPUT_EVENT_H_
diff --git a/tests/test_instance_deprecated.cc b/tests/test_instance_deprecated.cc deleted file mode 100644 index c9b5105..0000000 --- a/tests/test_instance_deprecated.cc +++ /dev/null
@@ -1,272 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_instance_deprecated.h" - -#include <assert.h> - -#include "ppapi/c/ppb_var.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -static const char kSetValueFunction[] = "SetValue"; -static const char kSetExceptionFunction[] = "SetException"; -static const char kReturnValueFunction[] = "ReturnValue"; - -InstanceSO::InstanceSO(TestInstance* i) - : test_instance_(i), - testing_interface_(i->testing_interface()) { -} - -InstanceSO::~InstanceSO() { - if (test_instance_) - test_instance_->clear_instance_so(); -} - -bool InstanceSO::HasMethod(const pp::Var& name, pp::Var* exception) { - if (!name.is_string()) - return false; - return name.AsString() == kSetValueFunction || - name.AsString() == kSetExceptionFunction || - name.AsString() == kReturnValueFunction; -} - -pp::Var InstanceSO::Call(const pp::Var& method_name, - const std::vector<pp::Var>& args, - pp::Var* exception) { - if (!method_name.is_string()) - return false; - std::string name = method_name.AsString(); - - if (name == kSetValueFunction) { - if (args.size() != 1 || !args[0].is_string()) - *exception = pp::Var("Bad argument to SetValue(<string>)"); - else if (test_instance_) - test_instance_->set_string(args[0].AsString()); - } else if (name == kSetExceptionFunction) { - if (args.size() != 1 || !args[0].is_string()) - *exception = pp::Var("Bad argument to SetException(<string>)"); - else - *exception = args[0]; - } else if (name == kReturnValueFunction) { - if (args.size() != 1) - *exception = pp::Var("Need single arg to call ReturnValue"); - else - return args[0]; - } else { - *exception = pp::Var("Bad function call"); - } - - return pp::Var(); -} - -REGISTER_TEST_CASE(Instance); - -TestInstance::TestInstance(TestingInstance* instance) - : TestCase(instance), - instance_so_(NULL) {} - -bool TestInstance::Init() { - return true; -} - -TestInstance::~TestInstance() { - ResetTestObject(); - if (testing_interface_->IsOutOfProcess() == PP_FALSE) { - // This should cause the instance object's destructor to be called. - testing_interface_->RunV8GC(instance_->pp_instance()); - - // Test a post-condition which ensures the instance objects destructor is - // called. This only works reliably in-process. Out-of-process, it only - // can work when the renderer stays alive a short while after the plugin - // instance is destroyed. If the renderer is being shut down, too much - // happens asynchronously for the out-of-process case to work reliably. In - // particular: - // - The Var ReleaseObject message is asynchronous. - // - The PPB_Var_Deprecated host-side proxy posts a task to actually - // release the object when the ReleaseObject message is received. - // - The PPP_Class Deallocate message is asynchronous. - // At time of writing this comment, if you modify the code so that the above - // happens synchronously, and you remove the restriction that the plugin - // can't be unblocked by a sync message, then this check actually passes - // reliably for out-of-process. But we don't want to make any of those - // changes so we just skip the check. - PP_DCHECK(!instance_so_); - } else { - // Out-of-process, this destructor might not actually get invoked. Clear - // the InstanceSOs reference to the instance so there is no UAF. - if (instance_so_) - instance_so_->clear_test_instance(); - } - - // Save the fact that we were destroyed in sessionStorage. This tests that - // we can ExecuteScript at instance destruction without crashing. It also - // allows us to check that ExecuteScript will run and succeed in certain - // cases. In particular, when the instance is destroyed by normal DOM - // deletion, ExecuteScript will actually work. See - // TestExecuteScriptInInstanceShutdown for that test. Note, however, that - // ExecuteScript will *not* have an effect when the instance is destroyed - // because the renderer was shut down. - pp::Var ret = instance()->ExecuteScript( - "sessionStorage.setItem('instance_destroyed', 'true');"); -} - -void TestInstance::RunTests(const std::string& filter) { - RUN_TEST(ExecuteScript, filter); - RUN_TEST(RecursiveObjects, filter); - RUN_TEST(LeakedObjectDestructors, filter); - RUN_TEST(SetupExecuteScriptAtInstanceShutdown, filter); - RUN_TEST(ExecuteScriptAtInstanceShutdown, filter); -} - -void TestInstance::LeakReferenceAndIgnore(const pp::Var& leaked) { - static const PPB_Var* var_interface = static_cast<const PPB_Var*>( - pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE)); - var_interface->AddRef(leaked.pp_var()); - IgnoreLeakedVar(leaked.pp_var().value.as_id); -} - -pp::deprecated::ScriptableObject* TestInstance::CreateTestObject() { - if (!instance_so_) - instance_so_ = new InstanceSO(this); - return instance_so_; -} - -std::string TestInstance::TestExecuteScript() { - // Simple call back into the plugin. - pp::Var exception; - pp::Var ret = instance_->ExecuteScript( - "document.getElementById('plugin').SetValue('hello, world');", - &exception); - ASSERT_TRUE(ret.is_undefined()); - ASSERT_TRUE(exception.is_undefined()); - ASSERT_TRUE(string_ == "hello, world"); - - // Return values from the plugin should be returned. - ret = instance_->ExecuteScript( - "document.getElementById('plugin').ReturnValue('return value');", - &exception); - ASSERT_TRUE(ret.is_string() && ret.AsString() == "return value"); - ASSERT_TRUE(exception.is_undefined()); - - // Exception thrown by the plugin should be caught. - ret = instance_->ExecuteScript( - "document.getElementById('plugin').SetException('plugin exception');", - &exception); - ASSERT_TRUE(ret.is_undefined()); - ASSERT_TRUE(exception.is_string()); - // Due to a limitation in the implementation of TryCatch, it doesn't actually - // pass the strings up. Since this is a trusted only interface, we've decided - // not to bother fixing this for now. - - // Exception caused by string evaluation should be caught. - exception = pp::Var(); - ret = instance_->ExecuteScript("document.doesntExist()", &exception); - ASSERT_TRUE(ret.is_undefined()); - ASSERT_TRUE(exception.is_string()); // Don't know exactly what it will say. - - PASS(); -} - -// A scriptable object that contains other scriptable objects recursively. This -// is used to help verify that our scriptable object clean-up code works -// properly. -class ObjectWithChildren : public pp::deprecated::ScriptableObject { - public: - ObjectWithChildren(TestInstance* i, int num_descendents) { - if (num_descendents > 0) { - child_ = pp::VarPrivate(i->instance(), - new ObjectWithChildren(i, num_descendents - 1)); - } - } - struct IgnoreLeaks {}; - ObjectWithChildren(TestInstance* i, int num_descendents, IgnoreLeaks) { - if (num_descendents > 0) { - child_ = pp::VarPrivate(i->instance(), - new ObjectWithChildren(i, num_descendents - 1, - IgnoreLeaks())); - i->IgnoreLeakedVar(child_.pp_var().value.as_id); - } - } - private: - pp::VarPrivate child_; -}; - -std::string TestInstance::TestRecursiveObjects() { - const int kNumChildren = 20; - { - // These should be deleted when we exit scope, so should not leak. - pp::VarPrivate not_leaked(instance(), new ObjectWithChildren(this, - kNumChildren)); - } - // We need to run the GC multiple times until all of the vars are released. - // Each GC invocation will result in releasing a var, which will result in its - // children not having any references, allowing them also to be collected. - for (int i = 0; i < kNumChildren; ++i) - testing_interface_->RunV8GC(instance_->pp_instance()); - - // Leak some, but tell TestCase to ignore the leaks. This test is run and then - // reloaded (see ppapi_uitest.cc). If these aren't cleaned up when the first - // run is torn down, they will show up as leaks in the second run. - // NOTE: The ScriptableObjects are actually leaked, but they should be removed - // from the tracker. See below for a test that verifies that the - // destructor is not run. - pp::VarPrivate leaked( - instance(), - new ObjectWithChildren(this, kNumChildren, - ObjectWithChildren::IgnoreLeaks())); - // Now leak a reference to the root object. This should force the root and - // all its descendents to stay in the tracker. - LeakReferenceAndIgnore(leaked); - - PASS(); -} - -// A scriptable object that should cause a crash if its destructor is run. We -// don't run the destructor for objects which the plugin leaks. This is to -// prevent them doing dangerous things at cleanup time, such as executing script -// or creating new objects. -class BadDestructorObject : public pp::deprecated::ScriptableObject { - public: - BadDestructorObject() {} - ~BadDestructorObject() { - assert(false); - } -}; - -std::string TestInstance::TestLeakedObjectDestructors() { - pp::VarPrivate leaked(instance(), new BadDestructorObject()); - // Leak a reference so it gets deleted on instance shutdown. - LeakReferenceAndIgnore(leaked); - PASS(); -} - -std::string TestInstance::TestSetupExecuteScriptAtInstanceShutdown() { - // This test only exists so that it can be run before - // TestExecuteScriptAtInstanceShutdown. See the comment for that test. - pp::Var exception; - pp::Var result = instance()->ExecuteScript( - "sessionStorage.removeItem('instance_destroyed');", &exception); - ASSERT_TRUE(exception.is_undefined()); - ASSERT_TRUE(result.is_undefined()); - PASS(); -} - -std::string TestInstance::TestExecuteScriptAtInstanceShutdown() { - // This test relies on the previous test being run in the same browser - // session, but in such a way that the instance is destroyed. See - // chrome/test/ppapi/ppapi_browsertest.cc for how the navigation happens. - // - // Given those constraints, ~TestInstance should have been invoked to set - // instance_destroyed in sessionStorage. So all we have to do is make sure - // that it was set as expected. - pp::Var result = instance()->ExecuteScript( - "sessionStorage.getItem('instance_destroyed');"); - ASSERT_TRUE(result.is_string()); - ASSERT_EQ(std::string("true"), result.AsString()); - instance()->ExecuteScript("sessionStorage.removeItem('instance_destroyed');"); - - PASS(); -} -
diff --git a/tests/test_instance_deprecated.h b/tests/test_instance_deprecated.h deleted file mode 100644 index f995f8f..0000000 --- a/tests/test_instance_deprecated.h +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_INSTANCE_DEPRECATED_H_ -#define PPAPI_TESTS_TEST_INSTANCE_DEPRECATED_H_ - -#include <string> -#include <vector> - -#include "ppapi/cpp/dev/scriptable_object_deprecated.h" -#include "ppapi/tests/test_case.h" - -class TestInstance; - -// ScriptableObject used by TestInstance. -class InstanceSO : public pp::deprecated::ScriptableObject { - public: - explicit InstanceSO(TestInstance* i); - virtual ~InstanceSO(); - - // pp::deprecated::ScriptableObject overrides. - bool HasMethod(const pp::Var& name, pp::Var* exception); - pp::Var Call(const pp::Var& name, - const std::vector<pp::Var>& args, - pp::Var* exception); - - // For out-of-process, the InstanceSO might be deleted after the instance was - // already destroyed, so we can't rely on test_instance_ being valid. - void clear_test_instance() { test_instance_ = NULL; } - - private: - TestInstance* test_instance_; - const PPB_Testing_Private* testing_interface_; -}; - -class TestInstance : public TestCase { - public: - TestInstance(TestingInstance* instance); - virtual ~TestInstance(); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - void set_string(const std::string& s) { string_ = s; } - - // Leak a reference to the given var, but ignore the leak in the leak checking - // that happens at shutdown. This allows us to test the "ForceFree" that - // happens on instance shutdown. - void LeakReferenceAndIgnore(const pp::Var& leaked); - - // This resets the scriptable object if it gets destroyed before the instance - // which should be the case for in-process tests. - void clear_instance_so() { instance_so_ = NULL; } - - protected: - // Test case protected overrides. - virtual pp::deprecated::ScriptableObject* CreateTestObject(); - - private: - std::string TestExecuteScript(); - std::string TestRecursiveObjects(); - std::string TestLeakedObjectDestructors(); - std::string TestSetupExecuteScriptAtInstanceShutdown(); - std::string TestExecuteScriptAtInstanceShutdown(); - - // Value written by set_string which is called by the ScriptableObject. This - // allows us to keep track of what was called. - std::string string_; - - // The scriptable object for this test. - InstanceSO* instance_so_; -}; - -#endif // PPAPI_TESTS_TEST_INSTANCE_DEPRECATED_H_
diff --git a/tests/test_media_stream_audio_track.cc b/tests/test_media_stream_audio_track.cc deleted file mode 100644 index ab39bb7..0000000 --- a/tests/test_media_stream_audio_track.cc +++ /dev/null
@@ -1,479 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Tests PPB_MediaStreamAudioTrack interface. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_media_stream_audio_track.h" - -// For MSVC. -#define _USE_MATH_DEFINES -#include <math.h> -#include <stddef.h> -#include <stdint.h> - -#include <algorithm> - -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/audio_buffer.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(MediaStreamAudioTrack); - -namespace { - -// Real constants defined in -// content/renderer/pepper/pepper_media_stream_audio_track_host.cc. -const int32_t kMaxNumberOfBuffers = 1000; -const int32_t kMinDuration = 10; -const int32_t kMaxDuration = 10000; -const int32_t kTimes = 3; -const char kJSCode[] = - "function gotStream(stream) {" - " test_stream = stream;" - " var track = stream.getAudioTracks()[0];" - " var plugin = document.getElementById('plugin');" - " plugin.postMessage(track);" - "}" - "var constraints = {" - " audio: true," - " video: false," - "};" - "navigator.getUserMedia = " - " navigator.getUserMedia || navigator.webkitGetUserMedia;" - "navigator.getUserMedia(constraints," - " gotStream, function() {});"; - -const char kSineJSCode[] = - // Create oscillators for the left and right channels. Use a sine wave, - // which is the easiest to calculate expected values. The oscillator output - // is low-pass filtered (as per spec) making comparison hard. - "var context = new AudioContext();" - "var l_osc = context.createOscillator();" - "l_osc.type = \"sine\";" - "l_osc.frequency.value = 25;" - "var r_osc = context.createOscillator();" - "r_osc.type = \"sine\";" - "r_osc.frequency.value = 100;" - // Combine the left and right channels. - "var merger = context.createChannelMerger(2);" - "merger.channelInterpretation = \"discrete\";" - "l_osc.connect(merger, 0, 0);" - "r_osc.connect(merger, 0, 1);" - "var dest_stream = context.createMediaStreamDestination();" - "merger.connect(dest_stream);" - // Dump the generated waveform to a MediaStream output. - "l_osc.start();" - "r_osc.start();" - "var track = dest_stream.stream.getAudioTracks()[0];" - "var plugin = document.getElementById('plugin');" - "plugin.postMessage(track);"; - -// Helper to check if the |sample_rate| is listed in PP_AudioBuffer_SampleRate -// enum. -bool IsSampleRateValid(PP_AudioBuffer_SampleRate sample_rate) { - switch (sample_rate) { - case PP_AUDIOBUFFER_SAMPLERATE_8000: - case PP_AUDIOBUFFER_SAMPLERATE_16000: - case PP_AUDIOBUFFER_SAMPLERATE_22050: - case PP_AUDIOBUFFER_SAMPLERATE_32000: - case PP_AUDIOBUFFER_SAMPLERATE_44100: - case PP_AUDIOBUFFER_SAMPLERATE_48000: - case PP_AUDIOBUFFER_SAMPLERATE_96000: - case PP_AUDIOBUFFER_SAMPLERATE_192000: - return true; - default: - return false; - } -} - -} // namespace - -TestMediaStreamAudioTrack::TestMediaStreamAudioTrack(TestingInstance* instance) - : TestCase(instance), - event_(instance_->pp_instance()) { -} - -bool TestMediaStreamAudioTrack::Init() { - return true; -} - -TestMediaStreamAudioTrack::~TestMediaStreamAudioTrack() { -} - -void TestMediaStreamAudioTrack::RunTests(const std::string& filter) { - RUN_TEST(Create, filter); - RUN_TEST(GetBuffer, filter); - RUN_TEST(Configure, filter); - RUN_TEST(ConfigureClose, filter); - RUN_TEST(VerifyWaveform, filter); -} - -void TestMediaStreamAudioTrack::HandleMessage(const pp::Var& message) { - if (message.is_resource()) { - audio_track_ = pp::MediaStreamAudioTrack(message.AsResource()); - } - event_.Signal(); -} - -std::string TestMediaStreamAudioTrack::TestCreate() { - // Create a track. - instance_->EvalScript(kJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(audio_track_.is_null()); - ASSERT_FALSE(audio_track_.HasEnded()); - ASSERT_FALSE(audio_track_.GetId().empty()); - - // Close the track. - audio_track_.Close(); - ASSERT_TRUE(audio_track_.HasEnded()); - audio_track_ = pp::MediaStreamAudioTrack(); - PASS(); -} - -std::string TestMediaStreamAudioTrack::TestGetBuffer() { - // Create a track. - instance_->EvalScript(kJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(audio_track_.is_null()); - ASSERT_FALSE(audio_track_.HasEnded()); - ASSERT_FALSE(audio_track_.GetId().empty()); - - PP_TimeDelta timestamp = 0.0; - - // Get |kTimes| buffers. - for (int i = 0; i < kTimes; ++i) { - TestCompletionCallbackWithOutput<pp::AudioBuffer> cc( - instance_->pp_instance(), false); - cc.WaitForResult(audio_track_.GetBuffer(cc.GetCallback())); - ASSERT_EQ(PP_OK, cc.result()); - pp::AudioBuffer buffer = cc.output(); - ASSERT_FALSE(buffer.is_null()); - ASSERT_TRUE(IsSampleRateValid(buffer.GetSampleRate())); - ASSERT_EQ(buffer.GetSampleSize(), PP_AUDIOBUFFER_SAMPLESIZE_16_BITS); - - ASSERT_GE(buffer.GetTimestamp(), timestamp); - timestamp = buffer.GetTimestamp(); - - ASSERT_GT(buffer.GetDataBufferSize(), 0U); - ASSERT_TRUE(buffer.GetDataBuffer() != NULL); - - audio_track_.RecycleBuffer(buffer); - - // A recycled buffer should be invalidated. - ASSERT_EQ(buffer.GetSampleRate(), PP_AUDIOBUFFER_SAMPLERATE_UNKNOWN); - ASSERT_EQ(buffer.GetSampleSize(), PP_AUDIOBUFFER_SAMPLESIZE_UNKNOWN); - ASSERT_EQ(buffer.GetDataBufferSize(), 0U); - ASSERT_TRUE(buffer.GetDataBuffer() == NULL); - } - - // Close the track. - audio_track_.Close(); - ASSERT_TRUE(audio_track_.HasEnded()); - audio_track_ = pp::MediaStreamAudioTrack(); - PASS(); -} - -std::string TestMediaStreamAudioTrack::CheckConfigure( - int32_t attrib_list[], int32_t expected_result) { - TestCompletionCallback cc_configure(instance_->pp_instance(), false); - cc_configure.WaitForResult( - audio_track_.Configure(attrib_list, cc_configure.GetCallback())); - ASSERT_EQ(expected_result, cc_configure.result()); - PASS(); -} - -std::string TestMediaStreamAudioTrack::CheckGetBuffer( - int times, int expected_duration) { - PP_TimeDelta timestamp = 0.0; - for (int j = 0; j < times; ++j) { - TestCompletionCallbackWithOutput<pp::AudioBuffer> cc_get_buffer( - instance_->pp_instance(), false); - cc_get_buffer.WaitForResult( - audio_track_.GetBuffer(cc_get_buffer.GetCallback())); - ASSERT_EQ(PP_OK, cc_get_buffer.result()); - pp::AudioBuffer buffer = cc_get_buffer.output(); - ASSERT_FALSE(buffer.is_null()); - ASSERT_TRUE(IsSampleRateValid(buffer.GetSampleRate())); - ASSERT_EQ(buffer.GetSampleSize(), PP_AUDIOBUFFER_SAMPLESIZE_16_BITS); - - ASSERT_GE(buffer.GetTimestamp(), timestamp); - timestamp = buffer.GetTimestamp(); - - ASSERT_TRUE(buffer.GetDataBuffer() != NULL); - if (expected_duration > 0) { - uint32_t buffer_size = buffer.GetDataBufferSize(); - uint32_t channels = buffer.GetNumberOfChannels(); - uint32_t sample_rate = buffer.GetSampleRate(); - uint32_t bytes_per_frame = channels * 2; - int32_t duration = expected_duration; - ASSERT_EQ(buffer_size % bytes_per_frame, 0U); - ASSERT_EQ(buffer_size, - (duration * sample_rate * bytes_per_frame) / 1000); - } else { - ASSERT_GT(buffer.GetDataBufferSize(), 0U); - } - - audio_track_.RecycleBuffer(buffer); - } - PASS(); -} - -std::string TestMediaStreamAudioTrack::TestConfigure() { - // Create a track. - instance_->EvalScript(kJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(audio_track_.is_null()); - ASSERT_FALSE(audio_track_.HasEnded()); - ASSERT_FALSE(audio_track_.GetId().empty()); - - // Perform a |Configure()| with no attributes. This ends up making an IPC - // call, but the host implementation has a fast-path when there are no changes - // to the configuration. This test is intended to hit that fast-path and make - // sure it works correctly. - { - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - ASSERT_SUBTEST_SUCCESS(CheckConfigure(attrib_list, PP_OK)); - } - - // Configure number of buffers. - struct { - int32_t buffers; - int32_t expect_result; - } buffers[] = { - { 8, PP_OK }, - { 100, PP_OK }, - { kMaxNumberOfBuffers, PP_OK }, - { -1, PP_ERROR_BADARGUMENT }, - { kMaxNumberOfBuffers + 1, PP_OK }, // Clipped to max value. - { 0, PP_OK }, // Use default. - }; - for (size_t i = 0; i < sizeof(buffers) / sizeof(buffers[0]); ++i) { - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_BUFFERS, buffers[i].buffers, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - ASSERT_SUBTEST_SUCCESS(CheckConfigure(attrib_list, - buffers[i].expect_result)); - // Get some buffers. This should also succeed when configure fails. - ASSERT_SUBTEST_SUCCESS(CheckGetBuffer(kTimes, -1)); - } - - // Configure buffer duration. - struct { - int32_t duration; - int32_t expect_result; - } durations[] = { - { kMinDuration, PP_OK }, - { 123, PP_OK }, - { kMinDuration - 1, PP_ERROR_BADARGUMENT }, - { kMaxDuration + 1, PP_ERROR_BADARGUMENT }, - }; - for (size_t i = 0; i < sizeof(durations) / sizeof(durations[0]); ++i) { - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_DURATION, durations[i].duration, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - ASSERT_SUBTEST_SUCCESS(CheckConfigure(attrib_list, - durations[i].expect_result)); - - // Get some buffers. This always works, but the buffer size will vary. - int duration = - durations[i].expect_result == PP_OK ? durations[i].duration : -1; - ASSERT_SUBTEST_SUCCESS(CheckGetBuffer(kTimes, duration)); - } - // Test kMaxDuration separately since each GetBuffer will take 10 seconds. - { - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_DURATION, kMaxDuration, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - ASSERT_SUBTEST_SUCCESS(CheckConfigure(attrib_list, PP_OK)); - } - - // Reset the duration to prevent the next part from taking 10 seconds. - { - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_DURATION, kMinDuration, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - ASSERT_SUBTEST_SUCCESS(CheckConfigure(attrib_list, PP_OK)); - } - - // Configure should fail while plugin holds buffers. - { - TestCompletionCallbackWithOutput<pp::AudioBuffer> cc_get_buffer( - instance_->pp_instance(), false); - cc_get_buffer.WaitForResult( - audio_track_.GetBuffer(cc_get_buffer.GetCallback())); - ASSERT_EQ(PP_OK, cc_get_buffer.result()); - pp::AudioBuffer buffer = cc_get_buffer.output(); - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_BUFFERS, 0, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - TestCompletionCallback cc_configure(instance_->pp_instance(), false); - cc_configure.WaitForResult( - audio_track_.Configure(attrib_list, cc_configure.GetCallback())); - ASSERT_EQ(PP_ERROR_INPROGRESS, cc_configure.result()); - audio_track_.RecycleBuffer(buffer); - } - - // Close the track. - audio_track_.Close(); - ASSERT_TRUE(audio_track_.HasEnded()); - audio_track_ = pp::MediaStreamAudioTrack(); - PASS(); -} - -std::string TestMediaStreamAudioTrack::TestConfigureClose() { - // Create a track. - instance_->EvalScript(kJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(audio_track_.is_null()); - ASSERT_FALSE(audio_track_.HasEnded()); - ASSERT_FALSE(audio_track_.GetId().empty()); - - // Configure the audio track and close it immediately. The Configure() call - // should complete. - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_BUFFERS, 10, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - TestCompletionCallback cc_configure(instance_->pp_instance(), false); - int32_t result = audio_track_.Configure(attrib_list, - cc_configure.GetCallback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - audio_track_.Close(); - cc_configure.WaitForResult(result); - result = cc_configure.result(); - // Unfortunately, we can't control whether the configure succeeds or is - // aborted. - ASSERT_TRUE(result == PP_OK || result == PP_ERROR_ABORTED); - - PASS(); -} - -uint32_t CalculateWaveStartingTime(int16_t sample, int16_t next_sample, - uint32_t period) { - int16_t slope = next_sample - sample; - double angle = asin(sample / (double)INT16_MAX); - if (slope < 0) { - angle = M_PI - angle; - } - if (angle < 0) { - angle += 2 * M_PI; - } - return round(angle * period / (2 * M_PI)); -} - -std::string TestMediaStreamAudioTrack::TestVerifyWaveform() { - // Create a track. - instance_->EvalScript(kSineJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(audio_track_.is_null()); - ASSERT_FALSE(audio_track_.HasEnded()); - ASSERT_FALSE(audio_track_.GetId().empty()); - - // Use a weird buffer length and number of buffers. - const int32_t kBufferSize = 13; - const int32_t kNumBuffers = 3; - - const uint32_t kChannels = 2; - const uint32_t kFreqLeft = 25; - const uint32_t kFreqRight = 100; - - int32_t attrib_list[] = { - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_DURATION, kBufferSize, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_BUFFERS, kNumBuffers, - PP_MEDIASTREAMAUDIOTRACK_ATTRIB_NONE, - }; - ASSERT_SUBTEST_SUCCESS(CheckConfigure(attrib_list, PP_OK)); - - // Get kNumBuffers buffers and verify they conform to the expected waveform. - PP_TimeDelta timestamp = 0.0; - int sample_time = 0; - uint32_t left_start = 0; - uint32_t right_start = 0; - for (int j = 0; j < kNumBuffers; ++j) { - TestCompletionCallbackWithOutput<pp::AudioBuffer> cc_get_buffer( - instance_->pp_instance(), false); - cc_get_buffer.WaitForResult( - audio_track_.GetBuffer(cc_get_buffer.GetCallback())); - ASSERT_EQ(PP_OK, cc_get_buffer.result()); - pp::AudioBuffer buffer = cc_get_buffer.output(); - ASSERT_FALSE(buffer.is_null()); - ASSERT_TRUE(IsSampleRateValid(buffer.GetSampleRate())); - ASSERT_EQ(buffer.GetSampleSize(), PP_AUDIOBUFFER_SAMPLESIZE_16_BITS); - ASSERT_EQ(buffer.GetNumberOfChannels(), kChannels); - ASSERT_GE(buffer.GetTimestamp(), timestamp); - timestamp = buffer.GetTimestamp(); - - uint32_t buffer_size = buffer.GetDataBufferSize(); - uint32_t sample_rate = buffer.GetSampleRate(); - uint32_t num_samples = buffer.GetNumberOfSamples(); - uint32_t bytes_per_frame = kChannels * 2; - ASSERT_EQ(num_samples, (kChannels * kBufferSize * sample_rate) / 1000); - ASSERT_EQ(buffer_size % bytes_per_frame, 0U); - ASSERT_EQ(buffer_size, num_samples * 2); - - // Period of sine wave, in samples. - uint32_t left_period = sample_rate / kFreqLeft; - uint32_t right_period = sample_rate / kFreqRight; - - int16_t* data_buffer = static_cast<int16_t*>(buffer.GetDataBuffer()); - ASSERT_TRUE(data_buffer != NULL); - - if (j == 0) { - // The generated wave doesn't necessarily start at 0, so compensate for - // this. - left_start = CalculateWaveStartingTime(data_buffer[0], data_buffer[2], - left_period); - right_start = CalculateWaveStartingTime(data_buffer[1], data_buffer[3], - right_period); - } - - for (uint32_t sample = 0; sample < num_samples; - sample += 2, sample_time++) { - int16_t left = data_buffer[sample]; - int16_t right = data_buffer[sample + 1]; - double angle = (2.0 * M_PI * ((sample_time + left_start) % left_period)) / - left_period; - int16_t expected = INT16_MAX * sin(angle); - // Account for off-by-one errors due to rounding. - ASSERT_GE(left, std::max<int16_t>(expected, INT16_MIN + 1) - 1); - ASSERT_LE(left, std::min<int16_t>(expected, INT16_MAX - 1) + 1); - - angle = (2 * M_PI * ((sample_time + right_start) % right_period)) / - right_period; - expected = INT16_MAX * sin(angle); - ASSERT_GE(right, std::max<int16_t>(expected, INT16_MIN + 1) - 1); - ASSERT_LE(right, std::min<int16_t>(expected, INT16_MAX - 1) + 1); - } - - audio_track_.RecycleBuffer(buffer); - } - - PASS(); -}
diff --git a/tests/test_media_stream_audio_track.h b/tests/test_media_stream_audio_track.h deleted file mode 100644 index 7920500..0000000 --- a/tests/test_media_stream_audio_track.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_MEDIA_STREAM_AUDIO_TRACK_H_ -#define PPAPI_TESTS_TEST_MEDIA_STREAM_AUDIO_TRACK_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/cpp/media_stream_audio_track.h" -#include "ppapi/cpp/video_frame.h" -#include "ppapi/tests/test_case.h" - -class TestMediaStreamAudioTrack : public TestCase { - public: - explicit TestMediaStreamAudioTrack(TestingInstance* instance); - virtual ~TestMediaStreamAudioTrack(); - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - // Overrides. - virtual void HandleMessage(const pp::Var& message_data); - - // Test helpers. - std::string CheckConfigure(int32_t attrib_list[], int32_t expected_result); - std::string CheckGetBuffer(int times, int expected_duration); - - std::string TestCreate(); - std::string TestGetBuffer(); - std::string TestConfigure(); - std::string TestConfigureClose(); - std::string TestVerifyWaveform(); - - pp::MediaStreamAudioTrack audio_track_; - - NestedEvent event_; -}; - -#endif // PPAPI_TESTS_TEST_MEDIA_STREAM_AUDIO_TRACK_H_
diff --git a/tests/test_media_stream_video_track.cc b/tests/test_media_stream_video_track.cc deleted file mode 100644 index 7358aa9..0000000 --- a/tests/test_media_stream_video_track.cc +++ /dev/null
@@ -1,244 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Tests PPB_MediaStreamVideoTrack interface. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_media_stream_video_track.h" - -#include <stddef.h> -#include <stdint.h> - -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/video_frame.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(MediaStreamVideoTrack); - -namespace { - -const int32_t kTimes = 3; -const int32_t kDefaultWidth = 640; -const int32_t kDefaultHeight = 480; -const char kJSCode[] = - "function gotStream(stream) {" - " var track = stream.getVideoTracks()[0];" - " var plugin = document.getElementById('plugin');" - " plugin.postMessage(track);" - "}" - "var constraints = {" - " audio: false," - " video: { mandatory: { minWidth: 640, minHeight: 480 } }" - "};" - "navigator.getUserMedia =" - " navigator.getUserMedia || navigator.webkitGetUserMedia;" - "navigator.getUserMedia(constraints," - " gotStream, function() {});"; -} - -TestMediaStreamVideoTrack::TestMediaStreamVideoTrack(TestingInstance* instance) - : TestCase(instance), - event_(instance_->pp_instance()) { -} - -bool TestMediaStreamVideoTrack::Init() { - return true; -} - -TestMediaStreamVideoTrack::~TestMediaStreamVideoTrack() { -} - -void TestMediaStreamVideoTrack::RunTests(const std::string& filter) { - RUN_TEST(Create, filter); - RUN_TEST(GetFrame, filter); - RUN_TEST(Configure, filter); -} - -void TestMediaStreamVideoTrack::HandleMessage(const pp::Var& message) { - if (message.is_resource()) - video_track_ = pp::MediaStreamVideoTrack(message.AsResource()); - event_.Signal(); -} - -std::string TestMediaStreamVideoTrack::TestCreate() { - // Create a track. - instance_->EvalScript(kJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(video_track_.is_null()); - ASSERT_FALSE(video_track_.HasEnded()); - ASSERT_FALSE(video_track_.GetId().empty()); - - // Close the track. - video_track_.Close(); - ASSERT_TRUE(video_track_.HasEnded()); - video_track_ = pp::MediaStreamVideoTrack(); - PASS(); -} - -std::string TestMediaStreamVideoTrack::TestGetFrame() { - // Create a track. - instance_->EvalScript(kJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(video_track_.is_null()); - ASSERT_FALSE(video_track_.HasEnded()); - ASSERT_FALSE(video_track_.GetId().empty()); - - PP_TimeDelta timestamp = 0.0; - - // Get |kTimes| frames. - for (int i = 0; i < kTimes; ++i) { - TestCompletionCallbackWithOutput<pp::VideoFrame> cc( - instance_->pp_instance(), false); - cc.WaitForResult(video_track_.GetFrame(cc.GetCallback())); - ASSERT_EQ(PP_OK, cc.result()); - pp::VideoFrame frame = cc.output(); - ASSERT_FALSE(frame.is_null()); - ASSERT_TRUE(frame.GetFormat() == PP_VIDEOFRAME_FORMAT_YV12 || - frame.GetFormat() == PP_VIDEOFRAME_FORMAT_I420); - - pp::Size size; - ASSERT_TRUE(frame.GetSize(&size)); - ASSERT_EQ(size.width(), kDefaultWidth); - ASSERT_EQ(size.height(), kDefaultHeight); - - ASSERT_GE(frame.GetTimestamp(), timestamp); - timestamp = frame.GetTimestamp(); - - ASSERT_GT(frame.GetDataBufferSize(), 0U); - ASSERT_TRUE(frame.GetDataBuffer() != NULL); - - video_track_.RecycleFrame(frame); - - // A recycled frame should be invalidated. - ASSERT_EQ(frame.GetFormat(), PP_VIDEOFRAME_FORMAT_UNKNOWN); - ASSERT_FALSE(frame.GetSize(&size)); - ASSERT_EQ(frame.GetDataBufferSize(), 0U); - ASSERT_TRUE(frame.GetDataBuffer() == NULL); - } - - // Close the track. - video_track_.Close(); - ASSERT_TRUE(video_track_.HasEnded()); - video_track_ = pp::MediaStreamVideoTrack(); - PASS(); -} - -std::string TestMediaStreamVideoTrack::TestConfigure() { - // Create a track. - instance_->EvalScript(kJSCode); - event_.Wait(); - event_.Reset(); - - ASSERT_FALSE(video_track_.is_null()); - ASSERT_FALSE(video_track_.HasEnded()); - ASSERT_FALSE(video_track_.GetId().empty()); - - // Configure format. - struct { - int32_t format; - int32_t expected_format; - } formats[] = { - { PP_VIDEOFRAME_FORMAT_BGRA, PP_VIDEOFRAME_FORMAT_BGRA }, // To RGBA. - { PP_VIDEOFRAME_FORMAT_I420, PP_VIDEOFRAME_FORMAT_I420 }, // To I420. - { PP_VIDEOFRAME_FORMAT_YV12, PP_VIDEOFRAME_FORMAT_YV12 }, // To YV12. - { PP_VIDEOFRAME_FORMAT_BGRA, PP_VIDEOFRAME_FORMAT_BGRA }, // To RGBA. - { PP_VIDEOFRAME_FORMAT_UNKNOWN, PP_VIDEOFRAME_FORMAT_YV12 }, // To default. - }; - for (size_t i = 0; i < sizeof(formats) / sizeof(formats[0]); ++i) { - TestCompletionCallback cc1(instance_->pp_instance(), false); - int32_t attrib_list[] = { - PP_MEDIASTREAMVIDEOTRACK_ATTRIB_FORMAT, formats[i].format, - PP_MEDIASTREAMVIDEOTRACK_ATTRIB_NONE, - }; - cc1.WaitForResult(video_track_.Configure(attrib_list, cc1.GetCallback())); - ASSERT_EQ(PP_OK, cc1.result()); - - for (int j = 0; j < kTimes; ++j) { - TestCompletionCallbackWithOutput<pp::VideoFrame> cc2( - instance_->pp_instance(), false); - cc2.WaitForResult(video_track_.GetFrame(cc2.GetCallback())); - ASSERT_EQ(PP_OK, cc2.result()); - pp::VideoFrame frame = cc2.output(); - ASSERT_FALSE(frame.is_null()); - if (formats[i].format != PP_VIDEOFRAME_FORMAT_UNKNOWN) { - ASSERT_EQ(frame.GetFormat(), formats[i].expected_format); - } else { - // Both YV12 and I420 are acceptable as default YUV formats. - ASSERT_TRUE(frame.GetFormat() == PP_VIDEOFRAME_FORMAT_YV12 || - frame.GetFormat() == PP_VIDEOFRAME_FORMAT_I420); - } - - pp::Size size; - ASSERT_TRUE(frame.GetSize(&size)); - ASSERT_EQ(size.width(), kDefaultWidth); - ASSERT_EQ(size.height(), kDefaultHeight); - - ASSERT_GT(frame.GetDataBufferSize(), 0U); - ASSERT_TRUE(frame.GetDataBuffer() != NULL); - - video_track_.RecycleFrame(frame); - } - } - - // Configure size. - struct { - int32_t width; - int32_t height; - int32_t expect_width; - int32_t expect_height; - } sizes[] = { - { 72, 72, 72, 72 }, // To 72x27. - { 1024, 768, 1024, 768 }, // To 1024x768. - { 0, 0, kDefaultWidth, kDefaultHeight }, // To default. - }; - for (size_t i = 0; i < sizeof(sizes) / sizeof(sizes[0]); ++i) { - TestCompletionCallback cc1(instance_->pp_instance(), false); - int32_t attrib_list[] = { - PP_MEDIASTREAMVIDEOTRACK_ATTRIB_WIDTH, sizes[i].width, - PP_MEDIASTREAMVIDEOTRACK_ATTRIB_HEIGHT, sizes[i].height, - PP_MEDIASTREAMVIDEOTRACK_ATTRIB_NONE, - }; - cc1.WaitForResult(video_track_.Configure(attrib_list, cc1.GetCallback())); - ASSERT_EQ(PP_OK, cc1.result()); - - for (int j = 0; j < kTimes; ++j) { - TestCompletionCallbackWithOutput<pp::VideoFrame> cc2( - instance_->pp_instance(), false); - cc2.WaitForResult(video_track_.GetFrame(cc2.GetCallback())); - ASSERT_EQ(PP_OK, cc2.result()); - pp::VideoFrame frame = cc2.output(); - ASSERT_FALSE(frame.is_null()); - ASSERT_TRUE(frame.GetFormat() == PP_VIDEOFRAME_FORMAT_YV12 || - frame.GetFormat() == PP_VIDEOFRAME_FORMAT_I420); - - pp::Size size; - ASSERT_TRUE(frame.GetSize(&size)); - ASSERT_EQ(size.width(), sizes[i].expect_width); - ASSERT_EQ(size.height(), sizes[i].expect_height); - - ASSERT_GT(frame.GetDataBufferSize(), 0U); - ASSERT_TRUE(frame.GetDataBuffer() != NULL); - - video_track_.RecycleFrame(frame); - } - } - - // Close the track. - video_track_.Close(); - ASSERT_TRUE(video_track_.HasEnded()); - video_track_ = pp::MediaStreamVideoTrack(); - PASS(); -}
diff --git a/tests/test_media_stream_video_track.h b/tests/test_media_stream_video_track.h deleted file mode 100644 index b6c7a83..0000000 --- a/tests/test_media_stream_video_track.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_MEDIA_STREAM_VIDEO_TRACK_H_ -#define PPAPI_TESTS_TEST_MEDIA_STREAM_VIDEO_TRACK_H_ - -#include <string> - -#include "ppapi/cpp/media_stream_video_track.h" -#include "ppapi/tests/test_case.h" - -class TestMediaStreamVideoTrack : public TestCase { - public: - explicit TestMediaStreamVideoTrack(TestingInstance* instance); - virtual ~TestMediaStreamVideoTrack(); - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - // Overrides. - virtual void HandleMessage(const pp::Var& message_data); - - std::string TestCreate(); - std::string TestGetFrame(); - std::string TestConfigure(); - - pp::MediaStreamVideoTrack video_track_; - - NestedEvent event_; -}; - -#endif // PPAPI_TESTS_TEST_MEDIA_STREAM_VIDEO_TRACK_H_
diff --git a/tests/test_memory.cc b/tests/test_memory.cc deleted file mode 100644 index 40b200a..0000000 --- a/tests/test_memory.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_memory.h" - -#include <stddef.h> -#include <stdint.h> - -#include "ppapi/c/dev/ppb_memory_dev.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -size_t kTestBufferSize = 1000; - -} // namespace - -REGISTER_TEST_CASE(Memory); - -bool TestMemory::Init() { - memory_dev_interface_ = static_cast<const PPB_Memory_Dev*>( - pp::Module::Get()->GetBrowserInterface(PPB_MEMORY_DEV_INTERFACE)); - return memory_dev_interface_ && CheckTestingInterface(); -} - -void TestMemory::RunTests(const std::string& filter) { - RUN_TEST(MemAlloc, filter); - RUN_TEST(NullMemFree, filter); -} - -std::string TestMemory::TestMemAlloc() { - char* buffer = static_cast<char*>( - memory_dev_interface_->MemAlloc(static_cast<uint32_t>(kTestBufferSize))); - // Touch a couple of locations. Failure will crash the test. - buffer[0] = '1'; - buffer[kTestBufferSize - 1] = '1'; - memory_dev_interface_->MemFree(buffer); - - PASS(); -} - -std::string TestMemory::TestNullMemFree() { - // Failure crashes the test. - memory_dev_interface_->MemFree(NULL); - - PASS(); -} -
diff --git a/tests/test_memory.h b/tests/test_memory.h deleted file mode 100644 index 3d48108..0000000 --- a/tests/test_memory.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_MEMORY_H_ -#define PPAPI_TESTS_TEST_MEMORY_H_ - -#include <string> - -#include "ppapi/c/dev/ppb_memory_dev.h" -#include "ppapi/tests/test_case.h" - -class TestMemory : public TestCase { - public: - explicit TestMemory(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestMemAlloc(); - std::string TestNullMemFree(); - - // Used by the tests that access the C API directly. - const PPB_Memory_Dev* memory_dev_interface_; -}; - -#endif // PPAPI_TESTS_TEST_MEMORY_H_
diff --git a/tests/test_message_handler.cc b/tests/test_message_handler.cc deleted file mode 100644 index 577ef90..0000000 --- a/tests/test_message_handler.cc +++ /dev/null
@@ -1,412 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_message_handler.h" - -#include <stddef.h> -#include <stdint.h> -#include <string.h> -#include <algorithm> -#include <map> -#include <sstream> - -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/c/ppb_messaging.h" -#include "ppapi/c/ppp_message_handler.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/message_handler.h" -#include "ppapi/cpp/module_impl.h" -#include "ppapi/cpp/network_list.h" -#include "ppapi/cpp/network_monitor.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/var_array.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/cpp/var_dictionary.h" -#include "ppapi/tests/pp_thread.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -// Windows defines 'PostMessage', so we have to undef it. -#ifdef PostMessage -#undef PostMessage -#endif - -REGISTER_TEST_CASE(MessageHandler); - -namespace { - -// Created and destroyed on the main thread. All public methods should be called -// on the main thread. Most data members are only accessed on the main thread. -// (Though it handles messages on the background thread). -class MyMessageHandler : public pp::MessageHandler { - public: - explicit MyMessageHandler(TestingInstance* instance, - const pp::MessageLoop& loop) - : testing_instance_(instance), - message_handler_loop_(loop), - is_registered_(false), - test_finished_event_(instance->pp_instance()), - destroy_event_(instance->pp_instance()), - async_message_received_(instance->pp_instance()) { - AssertOnMainThread(); - } - void Register() { - AssertOnMainThread(); - assert(!is_registered_); - int32_t result = - testing_instance_->RegisterMessageHandler(this, message_handler_loop_); - if (result == PP_OK) { - is_registered_ = true; - } else { - std::ostringstream stream; - stream << "Failed to register message handler; got error " << result; - AddError(stream.str()); - test_finished_event_.Signal(); - } - // Note, at this point, we can't safely read or write errors_ until we wait - // on destroy_event_. - } - void Unregister() { - AssertOnMainThread(); - assert(is_registered_); - testing_instance_->UnregisterMessageHandler(); - is_registered_ = false; - } - void WaitForTestFinishedMessage() { - test_finished_event_.Wait(); - test_finished_event_.Reset(); - } - // Wait for Destroy() to be called on the MessageHandler thread. When it's - // done, return any errors that occurred during the time the MessageHandler - // was getting messages. - std::string WaitForDestroy() { - AssertOnMainThread(); - // If we haven't called Unregister, we'll be waiting forever. - assert(!is_registered_); - destroy_event_.Wait(); - destroy_event_.Reset(); - // Now that we know Destroy() has been called, we know errors_ isn't being - // written on the MessageHandler thread anymore. So we can safely read it - // here on the main thread (since destroy_event_ gave us a memory barrier). - std::string temp_errors; - errors_.swap(temp_errors); - return temp_errors; - } - pp::Var WaitForAsyncMessage() { - async_message_received_.Wait(); - pp::Var var_to_return = last_async_message_received_; - last_async_message_received_ = pp::Var(); - async_message_received_.Reset(); - return var_to_return; - } - private: - static void AssertOnMainThread() { - assert(pp::MessageLoop::GetForMainThread() == - pp::MessageLoop::GetCurrent()); - } - void AddError(const std::string& error) { - if (!error.empty()) { - if (!errors_.empty()) - errors_ += "<p>"; - errors_ += error; - } - } - virtual void HandleMessage(pp::InstanceHandle instance, const pp::Var& var) { - if (pp::MessageLoop::GetCurrent() != message_handler_loop_) - AddError("HandleMessage was called on the wrong thread!"); - if (instance.pp_instance() != testing_instance_->pp_instance()) - AddError("HandleMessage was passed the wrong instance!"); - if (var.is_string() && var.AsString() == "FINISHED_TEST") { - test_finished_event_.Signal(); - } else { - // Any client causing a message to arrive must wait for the message - // before continuing. See WaitForAsyncMessage(). - assert(last_async_message_received_.is_undefined()); - last_async_message_received_ = var; - async_message_received_.Signal(); - } - } - - virtual pp::Var HandleBlockingMessage(pp::InstanceHandle instance, - const pp::Var& var) { - if (pp::MessageLoop::GetCurrent() != message_handler_loop_) - AddError("HandleBlockingMessage was called on the wrong thread!"); - if (instance.pp_instance() != testing_instance_->pp_instance()) - AddError("HandleBlockingMessage was passed the wrong instance!"); - - // Attempt a blocking operation; make sure it's disallowed. - pp::NetworkMonitor monitor(instance); - PP_Resource out_param = 0; - pp::CompletionCallbackWithOutput<pp::NetworkList> blocking_callback( - &out_param); - int32_t error = monitor.UpdateNetworkList(blocking_callback); - if (error != PP_ERROR_WOULD_BLOCK_THREAD) { - AddError("HandleBlockingMessage was allowed to do a blocking call!"); - pp::Module::Get()->core()->ReleaseResource(out_param); - } - - return var; - } - - virtual void WasUnregistered(pp::InstanceHandle instance) { - if (pp::MessageLoop::GetCurrent() != message_handler_loop_) - AddError("Destroy was called on the wrong thread!"); - if (instance.pp_instance() != testing_instance_->pp_instance()) - AddError("Destroy was passed the wrong instance!"); - destroy_event_.Signal(); - } - - // These data members are initialized on the main thread, but don't change for - // the life of the object, so are safe to access on the background thread, - // because there will be a memory barrier before the the MessageHandler calls - // are invoked. - TestingInstance* const testing_instance_; - const pp::MessageLoop message_handler_loop_; - const pp::MessageLoop main_loop_; - - // is_registered_ is only read/written on the main thread. - bool is_registered_; - - // errors_ is written on the MessageHandler thread. When Destroy() is - // called, we stop writing to errors_ and signal destroy_event_. This causes - // a memory barrier, so it's safe to read errors_ after that. - std::string errors_; - NestedEvent test_finished_event_; - NestedEvent destroy_event_; - - pp::Var last_async_message_received_; - NestedEvent async_message_received_; - - // Undefined & private to disallow copy and assign. - MyMessageHandler(const MyMessageHandler&); - MyMessageHandler& operator=(const MyMessageHandler&); -}; - -void FakeHandleMessage(PP_Instance instance, - void* user_data, - const PP_Var* message_data) {} -void FakeHandleBlockingMessage(PP_Instance instance, - void* user_data, - const PP_Var* message_data, - PP_Var* result) {} -void FakeDestroy(PP_Instance instance, void* user_data) {} - -} // namespace - -TestMessageHandler::TestMessageHandler(TestingInstance* instance) - : TestCase(instance), - message_received_(instance->pp_instance()), - ppb_messaging_if_(NULL), - handler_thread_(instance) { -} - -TestMessageHandler::~TestMessageHandler() { - handler_thread_.Join(); -} - -bool TestMessageHandler::Init() { - ppb_messaging_if_ = static_cast<const PPB_Messaging_1_2*>( - pp::Module::Get()->GetBrowserInterface(PPB_MESSAGING_INTERFACE_1_2)); - return ppb_messaging_if_ && - CheckTestingInterface() && - handler_thread_.Start(); -} - -void TestMessageHandler::RunTests(const std::string& filter) { - RUN_TEST(RegisterErrorConditions, filter); - RUN_TEST(PostMessageAndAwaitResponse, filter); - RUN_TEST(ArrayBuffer, filter); - RUN_TEST(Exceptions, filter); -} - -void TestMessageHandler::HandleMessage(const pp::Var& message_data) { - if (instance()->current_test_name() == "Exceptions") { - // For TestPostMessageAndAwaitResponse(), all messages should go to the - // background thread message handler. - assert(false); - } else { - // Any subtest causing a message to arrive here must wait for it before - // continuing. See WaitForMessage(). - assert(last_message_.is_undefined()); - last_message_ = message_data; - message_received_.Signal(); - } -} - -std::string TestMessageHandler::TestRegisterErrorConditions() { - { - // Test registering with the main thread as the message loop. - PPP_MessageHandler_0_2 fake_ppp_message_handler = { - &FakeHandleMessage, &FakeHandleBlockingMessage, &FakeDestroy - }; - pp::MessageLoop main_loop = pp::MessageLoop::GetForMainThread(); - int32_t result = ppb_messaging_if_->RegisterMessageHandler( - instance()->pp_instance(), - reinterpret_cast<void*>(0xdeadbeef), - &fake_ppp_message_handler, - main_loop.pp_resource()); - ASSERT_EQ(PP_ERROR_WRONG_THREAD, result); - } - { - // Test registering with incomplete PPP_Messaging interface. - PPP_MessageHandler_0_2 bad_ppp_ifs[] = { - { NULL, &FakeHandleBlockingMessage, &FakeDestroy }, - { &FakeHandleMessage, NULL, &FakeDestroy }, - { &FakeHandleMessage, &FakeHandleBlockingMessage, NULL }}; - for (size_t i = 0; i < sizeof(bad_ppp_ifs)/sizeof(bad_ppp_ifs[0]); ++i) { - int32_t result = ppb_messaging_if_->RegisterMessageHandler( - instance()->pp_instance(), - reinterpret_cast<void*>(0xdeadbeef), - &bad_ppp_ifs[i], - handler_thread_.message_loop().pp_resource()); - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - } - } - PASS(); -} - -std::string TestMessageHandler::TestPostMessageAndAwaitResponse() { - MyMessageHandler handler(instance(), - handler_thread_.message_loop()); - handler.Register(); - std::string js_code("var plugin = document.getElementById('plugin');\n"); - js_code += "var result = undefined;\n"; - const char* const values_to_test[] = { - "5", - "undefined", - "1.5", - "'hello'", - "{'key': 'value', 'array_key': [1, 2, 3, 4, 5]}", - NULL - }; - for (size_t i = 0; values_to_test[i]; ++i) { - js_code += "result = plugin.postMessageAndAwaitResponse("; - js_code += values_to_test[i]; - js_code += ");\n"; - js_code += "if (!deepCompare(result, "; - js_code += values_to_test[i]; - js_code += "))\n"; - js_code += " InternalError(\" Failed postMessageAndAwaitResponse for: "; - js_code += values_to_test[i]; - js_code += " result: \" + result);\n"; - } - instance_->EvalScript(js_code); - instance_->EvalScript("plugin.postMessage('FINISHED_TEST');\n"); - handler.WaitForTestFinishedMessage(); - handler.Unregister(); - ASSERT_SUBTEST_SUCCESS(handler.WaitForDestroy()); - - PASS(); -} - -std::string TestMessageHandler::TestArrayBuffer() { - // Set the array buffer shared memory threshold so that some of the - // ArrayBuffer values will be sent as shared memory. - ScopedArrayBufferSizeSetter setter(testing_interface_, - instance_->pp_instance(), - 200); - const char* const sizes[] = { "0", "128", "1024", "4096", NULL }; - MyMessageHandler handler(instance(), - handler_thread_.message_loop()); - handler.Register(); - std::string js_code("var plugin = document.getElementById('plugin');\n"); - js_code += "var result = undefined;\n"; - js_code += "var param = undefined;\n"; - for (size_t i = 0; sizes[i]; ++i) { - js_code += "param = new ArrayBuffer("; - js_code += sizes[i]; - js_code += ");"; - // TODO(dmichael): It would be better to set specific values in param. - js_code += "result = plugin.postMessageAndAwaitResponse(param);"; - js_code += "if (!deepCompare(result, param))\n"; - js_code += " InternalError(\" Failed postMessageAndAwaitResponse for "; - js_code += "ArrayBuffer of size: "; - js_code += sizes[i]; - js_code += " result: \" + result);\n"; - } - instance_->EvalScript(js_code); - instance_->EvalScript("plugin.postMessage('FINISHED_TEST');\n"); - handler.WaitForTestFinishedMessage(); - handler.Unregister(); - ASSERT_SUBTEST_SUCCESS(handler.WaitForDestroy()); - - PASS(); -} - -std::string TestMessageHandler::TestExceptions() { - MyMessageHandler handler(instance(), - handler_thread_.message_loop()); - { - // First, try sending a blocking message when there is no handler - // registered. It should throw an exception. - std::string js_code( - "var plugin = document.getElementById('plugin');\n" - "var caught_exception = false;\n" - "try {\n" - " plugin.postMessageAndAwaitResponse('Hello!');\n" - "} catch (err) {\n" - " caught_exception = true;\n" - "}\n" - "plugin.postMessage(caught_exception ? 'SUCCESS' : 'FAIL');\n"); - instance_->EvalScript(js_code); - // Note that we want to wait for the Instance to get the SUCCESS/FAIL - // message here. |message_handler| is not yet registered, so the message - // goes to the instance instead. - pp::Var msg = WaitForMessage(); - ASSERT_TRUE(msg.is_string()); - ASSERT_EQ("SUCCESS", msg.AsString()); - } - handler.Register(); - { - // Now that a handler is registered, try requesting and sending a - // FileSystem. It should throw an exception. The file system is opened - // asynchronously. What *should* happen is that it opens successfully, then - // we try to send it via postMessageAndAwaitResponse, which fails with an - // exception. The test could fail either because the filesystem doesn't - // open or because postMessageAndAwaitResponse doesn't throw an exception. - std::string js_code( - "var plugin = document.getElementById('plugin');\n" - "function gotFileSystem(fs) {\n" - " var caught_exception = false;\n" - " try {\n" - " plugin.postMessageAndAwaitResponse(fs);\n" - " } catch (err) {\n" - " caught_exception = true;\n" - " }\n" - " plugin.postMessage(caught_exception ? 'SUCCESS' : 'FAIL');\n" - "}\n" - "function fileSystemError() {\n" - " plugin.postMessage('Failed to open filesystem');\n" - "}\n" - "window.webkitRequestFileSystem(\n" - " window.Temporary, 1024, gotFileSystem, fileSystemError)\n"); - instance_->EvalScript(js_code); - pp::Var msg = handler.WaitForAsyncMessage(); - ASSERT_EQ(PP_VARTYPE_STRING, msg.pp_var().type); - ASSERT_EQ("SUCCESS", msg.AsString()); - } - handler.Unregister(); - ASSERT_SUBTEST_SUCCESS(handler.WaitForDestroy()); - - PASS(); -} - -pp::Var TestMessageHandler::WaitForMessage() { - message_received_.Wait(); - pp::Var var_to_return = last_message_; - last_message_ = pp::Var(); - message_received_.Reset(); - return var_to_return; -} -
diff --git a/tests/test_message_handler.h b/tests/test_message_handler.h deleted file mode 100644 index dabea70..0000000 --- a/tests/test_message_handler.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_MESSAGE_HANDLER_H_ -#define PPAPI_TESTS_TEST_MESSAGE_HANDLER_H_ - -#include <string> - -#include "ppapi/c/ppb_messaging.h" -#include "ppapi/tests/test_case.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/utility/threading/simple_thread.h" - -class TestMessageHandler : public TestCase { - public: - explicit TestMessageHandler(TestingInstance* instance); - virtual ~TestMessageHandler(); - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - virtual void HandleMessage(const pp::Var& message_data); - - std::string TestRegisterErrorConditions(); - std::string TestPostMessageAndAwaitResponse(); - std::string TestArrayBuffer(); - std::string TestExceptions(); - - // Wait for HandleMessage to be called, and return the Var it received. - pp::Var WaitForMessage(); - NestedEvent message_received_; - pp::Var last_message_; - - const PPB_Messaging_1_2* ppb_messaging_if_; - pp::SimpleThread handler_thread_; - -}; - -#endif // PPAPI_TESTS_TEST_MESSAGE_HANDLER_H_ -
diff --git a/tests/test_message_loop.cc b/tests/test_message_loop.cc deleted file mode 100644 index 56f3103..0000000 --- a/tests/test_message_loop.cc +++ /dev/null
@@ -1,105 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_message_loop.h" - -#include "ppapi/c/pp_macros.h" -#include "ppapi/cpp/core.h" -#include "ppapi/cpp/logging.h" -#include "ppapi/cpp/message_loop.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" -#include "ppapi/utility/threading/simple_thread.h" - -REGISTER_TEST_CASE(MessageLoop); - -TestMessageLoop::TestMessageLoop(TestingInstance* instance) - : TestCase(instance), - param_(kInvalid), - callback_factory_(this), - main_loop_task_ran_(instance->pp_instance()) { -} - -TestMessageLoop::~TestMessageLoop() { -} - -void TestMessageLoop::RunTests(const std::string& filter) { - RUN_TEST(Basics, filter); - RUN_TEST(Post, filter); -} - -std::string TestMessageLoop::TestBasics() { - // The main thread message loop should be valid, and equal to the "current" - // one. - ASSERT_NE(0, pp::MessageLoop::GetForMainThread().pp_resource()); - ASSERT_EQ(pp::MessageLoop::GetForMainThread().pp_resource(), - pp::MessageLoop::GetCurrent().pp_resource()); - - // We shouldn't be able to attach a new loop to the main thread. - pp::MessageLoop loop(instance_); - ASSERT_EQ(PP_ERROR_INPROGRESS, loop.AttachToCurrentThread()); - - // Nested loops aren't allowed. - ASSERT_EQ(PP_ERROR_INPROGRESS, - pp::MessageLoop::GetForMainThread().Run()); - - // We can't run on a loop that isn't attached to a thread. - ASSERT_EQ(PP_ERROR_WRONG_THREAD, loop.Run()); - - PASS(); -} - -std::string TestMessageLoop::TestPost() { - // Make sure we can post a task from the main thread back to the main thread. - pp::MessageLoop::GetCurrent().PostWork(callback_factory_.NewCallback( - &TestMessageLoop::SetParamAndQuitTask, kMainToMain)); - main_loop_task_ran_.Wait(); - ASSERT_EQ(param_, kMainToMain); - main_loop_task_ran_.Reset(); - - pp::SimpleThread thread(instance_); - // Post a task before the thread is started, to make sure it is run. - // TODO(dmichael): CompletionCallbackFactory is not 100% thread safe for - // posting tasks to a thread other than where the factory was created. It - // should be OK for this test, since we know that the - // CompletionCallbackFactory and its target object outlive all callbacks. But - // developers are likely to misuse CompletionCallbackFactory. Maybe we should - // make it safe to use a callback on another thread? - thread.message_loop().PostWork(callback_factory_.NewCallback( - &TestMessageLoop::EchoParamToMainTask, kBeforeStart)); - ASSERT_TRUE(thread.Start()); - main_loop_task_ran_.Wait(); - ASSERT_EQ(param_, kBeforeStart); - main_loop_task_ran_.Reset(); - - // Now post another one after start. This is the more normal case. - - // Nested loops aren't allowed. - ASSERT_EQ(PP_ERROR_INPROGRESS, - pp::MessageLoop::GetForMainThread().Run()); - thread.message_loop().PostWork(callback_factory_.NewCallback( - &TestMessageLoop::EchoParamToMainTask, kAfterStart)); - main_loop_task_ran_.Wait(); - ASSERT_EQ(param_, kAfterStart); - main_loop_task_ran_.Reset(); - - // Quit and join the thread. - ASSERT_TRUE(thread.Join()); - - PASS(); -} - -void TestMessageLoop::SetParamAndQuitTask(int32_t result, TestParam param) { - PP_DCHECK(result == PP_OK); - param_ = param; - main_loop_task_ran_.Signal(); -} - -void TestMessageLoop::EchoParamToMainTask(int32_t result, TestParam param) { - PP_DCHECK(result == PP_OK); - pp::MessageLoop::GetForMainThread().PostWork( - callback_factory_.NewCallback( - &TestMessageLoop::SetParamAndQuitTask, param)); -} -
diff --git a/tests/test_message_loop.h b/tests/test_message_loop.h deleted file mode 100644 index a39af9a..0000000 --- a/tests/test_message_loop.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_MESSAGE_LOOP_H_ -#define PPAPI_TESTS_TEST_MESSAGE_LOOP_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" -#include "ppapi/utility/completion_callback_factory.h" - -class TestMessageLoop : public TestCase { - public: - explicit TestMessageLoop(TestingInstance* instance); - virtual ~TestMessageLoop(); - - private: - // TestCase implementation. - virtual void RunTests(const std::string& filter); - - std::string TestBasics(); - std::string TestPost(); - - // This just ensures we have a unique number for each little thing we test. - enum TestParam { kInvalid, kMainToMain, kBeforeStart, kAfterStart}; - - // A task to run on the main thread. It sets param_ and quits the main loop. - void SetParamAndQuitTask(int32_t result, TestParam param); - - // A task to run on a background thread. It posts SetResultAndQuitTask to the - // main loop, echoing result. - void EchoParamToMainTask(int32_t result, TestParam param); - - // The last test param we received in SetParamAndQuitTask (or kInvalid if - // none). - TestParam param_; - pp::CompletionCallbackFactory<TestMessageLoop> callback_factory_; - NestedEvent main_loop_task_ran_; -}; - -#endif // PPAPI_TESTS_TEST_MESSAGE_LOOP_H_
diff --git a/tests/test_mouse_cursor.cc b/tests/test_mouse_cursor.cc deleted file mode 100644 index a7f1e9b..0000000 --- a/tests/test_mouse_cursor.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_mouse_cursor.h" - -#include "ppapi/cpp/image_data.h" -#include "ppapi/tests/test_case.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(MouseCursor); - -TestMouseCursor::TestMouseCursor(TestingInstance* instance) - : TestCase(instance) { -} - -bool TestMouseCursor::Init() { - mouse_cursor_interface_ = static_cast<const PPB_MouseCursor*>( - pp::Module::Get()->GetBrowserInterface(PPB_MOUSECURSOR_INTERFACE)); - return !!mouse_cursor_interface_; -} - -void TestMouseCursor::RunTests(const std::string& filter) { - RUN_TEST(Type, filter); - RUN_TEST(Custom, filter); - RUN_TEST(Point, filter); -} - -std::string TestMouseCursor::TestType() { - ASSERT_TRUE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), PP_MOUSECURSOR_TYPE_POINTER, 0, NULL))); - ASSERT_FALSE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), static_cast<PP_MouseCursor_Type>(-2), - 0, NULL))); - PASS(); -} - -std::string TestMouseCursor::TestCustom() { - // First test a valid image. - pp::ImageData valid_image(instance_, - pp::ImageData::GetNativeImageDataFormat(), - pp::Size(16, 16), true); - PP_Point point = { 0, 0 }; - ASSERT_TRUE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), PP_MOUSECURSOR_TYPE_CUSTOM, - valid_image.pp_resource(), &point))); - - // 0 image resource ID. - ASSERT_FALSE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), PP_MOUSECURSOR_TYPE_CUSTOM, 0, NULL))); - - // Image specified for predefined type. - ASSERT_FALSE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), PP_MOUSECURSOR_TYPE_POINTER, - valid_image.pp_resource(), &point))); - - // A too-big image. - pp::ImageData big_image(instance_, pp::ImageData::GetNativeImageDataFormat(), - pp::Size(65, 12), true); - ASSERT_FALSE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), PP_MOUSECURSOR_TYPE_CUSTOM, - big_image.pp_resource(), &point))); - - PASS(); -} - -std::string TestMouseCursor::TestPoint() { - pp::ImageData valid_image(instance_, - pp::ImageData::GetNativeImageDataFormat(), - pp::Size(16, 16), true); - PP_Point point = { -1, 0 }; - ASSERT_FALSE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), PP_MOUSECURSOR_TYPE_CUSTOM, - valid_image.pp_resource(), &point))); - - point.x = 67; - point.y = 5; - ASSERT_FALSE(PP_ToBool(mouse_cursor_interface_->SetCursor( - instance_->pp_instance(), PP_MOUSECURSOR_TYPE_CUSTOM, - valid_image.pp_resource(), &point))); - PASS(); -}
diff --git a/tests/test_mouse_cursor.h b/tests/test_mouse_cursor.h deleted file mode 100644 index 67f3a8e..0000000 --- a/tests/test_mouse_cursor.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_MOUSE_CURSOR_H_ -#define PPAPI_TESTS_TEST_MOUSE_CURSOR_H_ - -#include "ppapi/c/ppb_mouse_cursor.h" -#include "ppapi/tests/test_case.h" - -class TestMouseCursor : public TestCase { - public: - explicit TestMouseCursor(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestType(); - std::string TestCustom(); - std::string TestPoint(); - - const PPB_MouseCursor* mouse_cursor_interface_; -}; - -#endif // PPAPI_TESTS_TEST_MOUSE_CURSOR_H_
diff --git a/tests/test_mouse_lock.cc b/tests/test_mouse_lock.cc deleted file mode 100644 index d85a9e6..0000000 --- a/tests/test_mouse_lock.cc +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_mouse_lock.h" - -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/view.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(MouseLock); - -TestMouseLock::TestMouseLock(TestingInstance* instance) - : TestCase(instance), - MouseLock(instance), - nested_event_(instance->pp_instance()) { -} - -TestMouseLock::~TestMouseLock() { -} - -bool TestMouseLock::Init() { - return CheckTestingInterface(); -} - -void TestMouseLock::RunTests(const std::string& filter) { - RUN_TEST(SucceedWhenAllowed, filter); -} - -void TestMouseLock::DidChangeView(const pp::View& view) { - position_ = view.GetRect(); -} - -void TestMouseLock::MouseLockLost() { - nested_event_.Signal(); -} - -std::string TestMouseLock::TestSucceedWhenAllowed() { - // Content settings are configured to allow mouse lock for any site. - // Please see chrome/test/ppapi/ppapi_interactive_browsertest.cc. - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - SimulateUserGesture(); - callback.WaitForResult(LockMouse(callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - - UnlockMouse(); - // Wait for the MouseLockLost() call. - nested_event_.Wait(); - - PASS(); -} - -void TestMouseLock::SimulateUserGesture() { - pp::Point mouse_movement; - pp::MouseInputEvent input_event( - instance_, - PP_INPUTEVENT_TYPE_MOUSEDOWN, - 0, // time_stamp - 0, // modifiers - PP_INPUTEVENT_MOUSEBUTTON_LEFT, - position_.CenterPoint(), - 1, // click_count - mouse_movement); - - testing_interface_->SimulateInputEvent(instance_->pp_instance(), - input_event.pp_resource()); -}
diff --git a/tests/test_mouse_lock.h b/tests/test_mouse_lock.h deleted file mode 100644 index 97039ef..0000000 --- a/tests/test_mouse_lock.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_MOUSE_LOCK_H_ -#define PPAPI_TESTS_TEST_MOUSE_LOCK_H_ - -#include <string> - -#include "ppapi/cpp/mouse_lock.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/tests/test_case.h" -#include "ppapi/tests/test_utils.h" - -class TestMouseLock: public TestCase, public pp::MouseLock { - public: - explicit TestMouseLock(TestingInstance* instance); - virtual ~TestMouseLock(); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - virtual void DidChangeView(const pp::View& view); - - // pp::MouseLock implementation. - virtual void MouseLockLost(); - - private: - std::string TestSucceedWhenAllowed(); - - void SimulateUserGesture(); - - pp::Rect position_; - - NestedEvent nested_event_; -}; - -#endif // PPAPI_TESTS_TEST_MOUSE_LOCK_H_
diff --git a/tests/test_nacl_irt_stack_alignment.cc b/tests/test_nacl_irt_stack_alignment.cc deleted file mode 100644 index 3938dc4..0000000 --- a/tests/test_nacl_irt_stack_alignment.cc +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_nacl_irt_stack_alignment.h" - -#include <stddef.h> - -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/testing_instance.h" - -// This whole test is really only meant for x86-32 NaCl (not PNaCl). -// -// This is a regression test for the IRT code being sensitive to stack -// alignment. The de jure ABI is that the stack should be aligned to -// 16 bytes at call sites. However, the de facto ABI is that the IRT -// worked in the past when called with misaligned stack. NaCl code is -// now compiled to expect the proper 16-byte alignment, but the IRT -// code must remain compatible with old binaries that failed to do so. - -#if defined(__i386__) - -REGISTER_TEST_CASE(NaClIRTStackAlignment); - -bool TestNaClIRTStackAlignment::Init() { - var_interface_ = static_cast<const PPB_Var*>( - pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE)); - return var_interface_ && CheckTestingInterface(); -} - -void TestNaClIRTStackAlignment::RunTests(const std::string& filter) { - RUN_TEST(MisalignedCallVarAddRef, filter); -} - -// This calls the given function with the stack explicitly misaligned. -// If the function (in the IRT) was compiled wrongly, it will crash. -void MisalignedCall(void (*func)(PP_Var), const PP_Var* arg) - asm("MisalignedCall") __attribute__((regparm(2))); - -// regparm(2) means: First argument in %eax, second argument in %edx. -// Writing this with an inline asm would require explaining all the -// call-clobbers register behavior in the asm clobber list, which is a -// lot with all the SSE and FPU state. It's far simpler just to make -// it a function call the compiler knows is a function call, and then -// write the function itself in pure assembly. -asm("MisalignedCall:\n" - // Use an SSE register to copy the 16 bytes of memory. - // Note this instruction does not care about alignment. - // The pointer is not necessarily aligned to 16 bytes. - "movups (%edx), %xmm0\n" - // Set up a frame so we can recover the stack pointer after alignment. - "push %ebp\n" - "mov %esp, %ebp\n" - // Align the stack properly to 16 bytes. - "andl $-16, %esp\n" - // Now make space for the 16 bytes of argument data, - // plus another 4 bytes so the stack pointer is misaligned. - "subl $20, %esp\n" - // Copy the argument onto the (misaligned) top of stack. - "movups %xmm0, (%esp)\n" - // Now call into the IRT, and hilarity ensues. - "naclcall %eax\n" - // Standard epilogue. - "mov %ebp, %esp\n" - "pop %ebp\n" - "naclret"); - -std::string TestNaClIRTStackAlignment::TestMisalignedCallVarAddRef() { - PP_Var var; - var.type = PP_VARTYPE_INT32; - var.padding = 0; - var.value.as_int = 23; - - ASSERT_EQ(sizeof(var), static_cast<size_t>(16)); - - // This will crash if the test fails. - MisalignedCall(var_interface_->AddRef, &var); - MisalignedCall(var_interface_->Release, &var); - - PASS(); -} - -#endif // defined(__i386__)
diff --git a/tests/test_nacl_irt_stack_alignment.h b/tests/test_nacl_irt_stack_alignment.h deleted file mode 100644 index 841e8a9..0000000 --- a/tests/test_nacl_irt_stack_alignment.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_NACL_IRT_STACK_ALIGNMENT_H_ -#define PPAPI_TESTS_TEST_NACL_IRT_STACK_ALIGNMENT_H_ - -#include <string> - -#include "ppapi/c/ppb_var.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_case.h" - -class TestNaClIRTStackAlignment : public TestCase { - public: - explicit TestNaClIRTStackAlignment(TestingInstance* instance) - : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestMisalignedCallVarAddRef(); - - // Used by the tests that access the C API directly. - const PPB_Var* var_interface_; -}; - -#endif // PPAPI_TESTS_TEST_NACL_IRT_STACK_ALIGNMENT_H_
diff --git a/tests/test_net_address.cc b/tests/test_net_address.cc deleted file mode 100644 index caef016..0000000 --- a/tests/test_net_address.cc +++ /dev/null
@@ -1,181 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_net_address.h" - -#include <stddef.h> -#include <stdint.h> - -#include <cstring> - -#include "ppapi/cpp/net_address.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -using pp::NetAddress; - -REGISTER_TEST_CASE(NetAddress); - -namespace { - -bool EqualIPv4Address(const PP_NetAddress_IPv4& addr1, - const PP_NetAddress_IPv4& addr2) { - return addr1.port == addr2.port && - !memcmp(addr1.addr, addr2.addr, sizeof(addr1.addr)); -} - -bool EqualIPv6Address(const PP_NetAddress_IPv6& addr1, - const PP_NetAddress_IPv6& addr2) { - return addr1.port == addr2.port && - !memcmp(addr1.addr, addr2.addr, sizeof(addr1.addr)); -} - -NetAddress CreateFromHostOrderIPv6Address( - const pp::InstanceHandle& instance, - const uint16_t host_order_addr[8], - uint16_t host_order_port) { - PP_NetAddress_IPv6 ipv6_addr; - ipv6_addr.port = ConvertToNetEndian16(host_order_port); - for (size_t i = 0; i < 8; ++i) { - uint16_t net_order_addr = ConvertToNetEndian16(host_order_addr[i]); - memcpy(&ipv6_addr.addr[2 * i], &net_order_addr, 2); - } - - return NetAddress(instance, ipv6_addr); -} - -} // namespace - -TestNetAddress::TestNetAddress(TestingInstance* instance) : TestCase(instance) { -} - -bool TestNetAddress::Init() { - return NetAddress::IsAvailable(); -} - -void TestNetAddress::RunTests(const std::string& filter) { - RUN_TEST(IPv4Address, filter); - RUN_TEST(IPv6Address, filter); - RUN_TEST(DescribeAsString, filter); -} - -std::string TestNetAddress::TestIPv4Address() { - PP_NetAddress_IPv4 ipv4_addr = { ConvertToNetEndian16(80), { 127, 0, 0, 1 } }; - NetAddress net_addr(instance_, ipv4_addr); - ASSERT_NE(0, net_addr.pp_resource()); - - ASSERT_EQ(PP_NETADDRESS_FAMILY_IPV4, net_addr.GetFamily()); - - PP_NetAddress_IPv4 out_ipv4_addr; - ASSERT_TRUE(net_addr.DescribeAsIPv4Address(&out_ipv4_addr)); - ASSERT_TRUE(EqualIPv4Address(ipv4_addr, out_ipv4_addr)); - - PP_NetAddress_IPv6 out_ipv6_addr; - ASSERT_FALSE(net_addr.DescribeAsIPv6Address(&out_ipv6_addr)); - - PASS(); -} - -std::string TestNetAddress::TestIPv6Address() { - PP_NetAddress_IPv6 ipv6_addr = { - ConvertToNetEndian16(1024), - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } - }; - - NetAddress net_addr(instance_, ipv6_addr); - ASSERT_NE(0, net_addr.pp_resource()); - - ASSERT_EQ(PP_NETADDRESS_FAMILY_IPV6, net_addr.GetFamily()); - - PP_NetAddress_IPv6 out_ipv6_addr; - ASSERT_TRUE(net_addr.DescribeAsIPv6Address(&out_ipv6_addr)); - ASSERT_TRUE(EqualIPv6Address(ipv6_addr, out_ipv6_addr)); - - PP_NetAddress_IPv4 out_ipv4_addr; - ASSERT_FALSE(net_addr.DescribeAsIPv4Address(&out_ipv4_addr)); - - PASS(); -} - -std::string TestNetAddress::TestDescribeAsString() { - { - // Test describing IPv4 addresses. - PP_NetAddress_IPv4 ipv4_addr1 = { ConvertToNetEndian16(1234), - { 127, 0, 0, 1 } }; - NetAddress addr1(instance_, ipv4_addr1); - ASSERT_EQ("127.0.0.1", addr1.DescribeAsString(false).AsString()); - ASSERT_EQ("127.0.0.1:1234", addr1.DescribeAsString(true).AsString()); - - PP_NetAddress_IPv4 ipv4_addr2 = { ConvertToNetEndian16(80), - { 192, 168, 0, 2 } }; - NetAddress addr2(instance_, ipv4_addr2); - ASSERT_EQ("192.168.0.2", addr2.DescribeAsString(false).AsString()); - ASSERT_EQ("192.168.0.2:80", addr2.DescribeAsString(true).AsString()); - } - { - // Test describing IPv6 addresses. - static const struct { - uint16_t host_order_addr[8]; - uint16_t host_order_port; - const char* expected_without_port; - const char* expected_with_port; - } ipv6_test_cases[] = { - { // Generic test case (unique longest run of zeros to collapse). - { 0x12, 0xabcd, 0, 0x0001, 0, 0, 0, 0xcdef }, 12, - "12:abcd:0:1::cdef", "[12:abcd:0:1::cdef]:12" - }, - { // Ignore the first (non-longest) run of zeros. - { 0, 0, 0, 0x0123, 0, 0, 0, 0 }, 123, - "0:0:0:123::", "[0:0:0:123::]:123" - }, - { // Collapse the first (equally-longest) run of zeros. - { 0x1234, 0xabcd, 0, 0, 0xff, 0, 0, 0xcdef }, 123, - "1234:abcd::ff:0:0:cdef", "[1234:abcd::ff:0:0:cdef]:123" - }, - { // Don't collapse "runs" of zeros of length 1. - { 0, 0xa, 1, 2, 3, 0, 5, 0 }, 123, - "0:a:1:2:3:0:5:0", "[0:a:1:2:3:0:5:0]:123" - }, - { // Collapse a run of zeros at the beginning. - { 0, 0, 0, 2, 3, 0, 0, 0 }, 123, - "::2:3:0:0:0", "[::2:3:0:0:0]:123" - }, - { // Collapse a run of zeros at the end. - { 0, 0xa, 1, 2, 3, 0, 0, 0 }, 123, - "0:a:1:2:3::", "[0:a:1:2:3::]:123" - }, - { // IPv4 192.168.1.2 embedded in IPv6 in the deprecated way. - { 0, 0, 0, 0, 0, 0, 0xc0a8, 0x102 }, 123, - "::192.168.1.2", "[::192.168.1.2]:123" - }, - { // IPv4 192.168.1.2 embedded in IPv6. - { 0, 0, 0, 0, 0, 0xffff, 0xc0a8, 0x102 }, 123, - "::ffff:192.168.1.2", "[::ffff:192.168.1.2]:123" - }, - { // *Not* IPv4 embedded in IPv6. - { 0, 0, 0, 0, 0, 0x1234, 0xc0a8, 0x102 }, 123, - "::1234:c0a8:102", "[::1234:c0a8:102]:123" - } - }; - - for (size_t i = 0; - i < sizeof(ipv6_test_cases) / sizeof(ipv6_test_cases[0]); - ++i) { - NetAddress addr = CreateFromHostOrderIPv6Address( - instance_, ipv6_test_cases[i].host_order_addr, - ipv6_test_cases[i].host_order_port); - ASSERT_EQ(ipv6_test_cases[i].expected_without_port, - addr.DescribeAsString(false).AsString()); - ASSERT_EQ(ipv6_test_cases[i].expected_with_port, - addr.DescribeAsString(true).AsString()); - } - } - - PASS(); -}
diff --git a/tests/test_net_address.h b/tests/test_net_address.h deleted file mode 100644 index 2751d04..0000000 --- a/tests/test_net_address.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_NET_ADDRESS_H_ -#define PPAPI_TESTS_TEST_NET_ADDRESS_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -class TestNetAddress : public TestCase { - public: - explicit TestNetAddress(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestIPv4Address(); - std::string TestIPv6Address(); - std::string TestDescribeAsString(); -}; - -#endif // PPAPI_TESTS_TEST_NET_ADDRESS_H_
diff --git a/tests/test_net_address_private.cc b/tests/test_net_address_private.cc deleted file mode 100644 index 6c58c2d..0000000 --- a/tests/test_net_address_private.cc +++ /dev/null
@@ -1,328 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_net_address_private.h" - -#include <stddef.h> -#include <stdint.h> -#include <string.h> - -#include "ppapi/c/private/ppb_net_address_private.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -using pp::NetAddressPrivate; - -namespace { - -PP_NetAddress_Private MakeIPv4NetAddress(const uint8_t host[4], int port) { - PP_NetAddress_Private addr; - NetAddressPrivate::CreateFromIPv4Address(host, port, &addr); - return addr; -} - -PP_NetAddress_Private MakeIPv6NetAddress(const uint16_t host[8], uint16_t port, - uint32_t scope_id) { - PP_NetAddress_Private addr = PP_NetAddress_Private(); - uint8_t ip[16]; - for(int i = 0; i < 8; ++i) { - ip[i * 2] = host[i] >> 8; - ip[i * 2 + 1] = host[i] & 0xff; - } - NetAddressPrivate::CreateFromIPv6Address(ip, scope_id, port, &addr); - return addr; -} - -} // namespace - -REGISTER_TEST_CASE(NetAddressPrivate); - -TestNetAddressPrivate::TestNetAddressPrivate(TestingInstance* instance) - : TestCase(instance) { -} - -bool TestNetAddressPrivate::Init() { - return NetAddressPrivate::IsAvailable(); -} - -void TestNetAddressPrivate::RunTests(const std::string& filter) { - RUN_TEST(AreEqual, filter); - RUN_TEST(AreHostsEqual, filter); - RUN_TEST(Describe, filter); - RUN_TEST(ReplacePort, filter); - RUN_TEST(GetAnyAddress, filter); - RUN_TEST(DescribeIPv6, filter); - RUN_TEST(GetFamily, filter); - RUN_TEST(GetPort, filter); - RUN_TEST(GetAddress, filter); - RUN_TEST(GetScopeID, filter); -} - -std::string TestNetAddressPrivate::TestAreEqual() { - // No comparisons should ever be done with invalid addresses. - PP_NetAddress_Private invalid = PP_NetAddress_Private(); - ASSERT_FALSE(NetAddressPrivate::AreEqual(invalid, invalid)); - - uint8_t localhost_ip[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private localhost_80 = MakeIPv4NetAddress(localhost_ip, 80); - ASSERT_TRUE(NetAddressPrivate::AreEqual(localhost_80, localhost_80)); - ASSERT_FALSE(NetAddressPrivate::AreEqual(localhost_80, invalid)); - - PP_NetAddress_Private localhost_1234 = MakeIPv4NetAddress(localhost_ip, 1234); - ASSERT_FALSE(NetAddressPrivate::AreEqual(localhost_80, localhost_1234)); - - uint8_t other_ip[4] = { 192, 168, 0, 1 }; - PP_NetAddress_Private other_80 = MakeIPv4NetAddress(other_ip, 80); - ASSERT_FALSE(NetAddressPrivate::AreEqual(localhost_80, other_80)); - - PASS(); -} - -std::string TestNetAddressPrivate::TestAreHostsEqual() { - // No comparisons should ever be done with invalid addresses. - PP_NetAddress_Private invalid = PP_NetAddress_Private(); - ASSERT_FALSE(NetAddressPrivate::AreHostsEqual(invalid, invalid)); - - uint8_t localhost_ip[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private localhost_80 = MakeIPv4NetAddress(localhost_ip, 80); - ASSERT_TRUE(NetAddressPrivate::AreHostsEqual(localhost_80, localhost_80)); - ASSERT_FALSE(NetAddressPrivate::AreHostsEqual(localhost_80, invalid)); - - PP_NetAddress_Private localhost_1234 = MakeIPv4NetAddress(localhost_ip, 1234); - ASSERT_TRUE(NetAddressPrivate::AreHostsEqual(localhost_80, localhost_1234)); - - uint8_t other_ip[4] = { 192, 168, 0, 1 }; - PP_NetAddress_Private other_80 = MakeIPv4NetAddress(other_ip, 80); - ASSERT_FALSE(NetAddressPrivate::AreHostsEqual(localhost_80, other_80)); - - PASS(); -} - -std::string TestNetAddressPrivate::TestDescribe() { - PP_NetAddress_Private invalid = PP_NetAddress_Private(); - ASSERT_EQ("", NetAddressPrivate::Describe(invalid, false)); - ASSERT_EQ("", NetAddressPrivate::Describe(invalid, true)); - - uint8_t localhost_ip[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private localhost_80 = MakeIPv4NetAddress(localhost_ip, 80); - ASSERT_EQ("127.0.0.1", NetAddressPrivate::Describe(localhost_80, false)); - ASSERT_EQ("127.0.0.1:80", NetAddressPrivate::Describe(localhost_80, true)); - - PP_NetAddress_Private localhost_1234 = MakeIPv4NetAddress(localhost_ip, 1234); - ASSERT_EQ("127.0.0.1", NetAddressPrivate::Describe(localhost_1234, false)); - ASSERT_EQ("127.0.0.1:1234", NetAddressPrivate::Describe(localhost_1234, - true)); - - uint8_t other_ip[4] = { 192, 168, 0, 1 }; - PP_NetAddress_Private other_80 = MakeIPv4NetAddress(other_ip, 80); - ASSERT_EQ("192.168.0.1", NetAddressPrivate::Describe(other_80, false)); - ASSERT_EQ("192.168.0.1:80", NetAddressPrivate::Describe(other_80, true)); - - PASS(); -} - -std::string TestNetAddressPrivate::TestReplacePort() { - // Assume that |AreEqual()| works correctly. - PP_NetAddress_Private result = PP_NetAddress_Private(); - - PP_NetAddress_Private invalid = PP_NetAddress_Private(); - ASSERT_FALSE(NetAddressPrivate::ReplacePort(invalid, 1234, &result)); - - uint8_t localhost_ip[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private localhost_80 = MakeIPv4NetAddress(localhost_ip, 80); - ASSERT_TRUE(NetAddressPrivate::ReplacePort(localhost_80, 1234, &result)); - PP_NetAddress_Private localhost_1234 = MakeIPv4NetAddress(localhost_ip, 1234); - ASSERT_TRUE(NetAddressPrivate::AreEqual(result, localhost_1234)); - - // Test that having the out param being the same as the in param works - // properly. - ASSERT_TRUE(NetAddressPrivate::ReplacePort(result, 80, &result)); - ASSERT_TRUE(NetAddressPrivate::AreEqual(result, localhost_80)); - - PASS(); -} - -std::string TestNetAddressPrivate::TestGetAnyAddress() { - // Just make sure it doesn't crash and such. - PP_NetAddress_Private result = PP_NetAddress_Private(); - - NetAddressPrivate::GetAnyAddress(false, &result); - ASSERT_TRUE(NetAddressPrivate::AreEqual(result, result)); - - NetAddressPrivate::GetAnyAddress(true, &result); - ASSERT_TRUE(NetAddressPrivate::AreEqual(result, result)); - - PASS(); -} - -// TODO(viettrungluu): More IPv6 tests needed. - -std::string TestNetAddressPrivate::TestDescribeIPv6() { - static const struct { - uint16_t address[8]; - uint16_t port; - uint32_t scope; - const char* expected_without_port; - const char* expected_with_port; - } test_cases[] = { - { // Generic test case (unique longest run of zeros to collapse). - { 0x12, 0xabcd, 0, 0x0001, 0, 0, 0, 0xcdef }, 12, 0, - "12:abcd:0:1::cdef", "[12:abcd:0:1::cdef]:12" - }, - { // Non-zero scope. - { 0x1234, 0xabcd, 0, 0x0001, 0, 0, 0, 0xcdef }, 1234, 789, - "1234:abcd:0:1::cdef%789", "[1234:abcd:0:1::cdef%789]:1234" - }, - { // Ignore the first (non-longest) run of zeros. - { 0, 0, 0, 0x0123, 0, 0, 0, 0 }, 123, 0, - "0:0:0:123::", "[0:0:0:123::]:123" - }, - { // Collapse the first (equally-longest) run of zeros. - { 0x1234, 0xabcd, 0, 0, 0xff, 0, 0, 0xcdef }, 123, 0, - "1234:abcd::ff:0:0:cdef", "[1234:abcd::ff:0:0:cdef]:123" - }, - { // Don't collapse "runs" of zeros of length 1. - { 0, 0xa, 1, 2, 3, 0, 5, 0 }, 123, 0, - "0:a:1:2:3:0:5:0", "[0:a:1:2:3:0:5:0]:123" - }, - { // Collapse a run of zeros at the beginning. - { 0, 0, 0, 2, 3, 0, 0, 0 }, 123, 0, - "::2:3:0:0:0", "[::2:3:0:0:0]:123" - }, - { // Collapse a run of zeros at the end. - { 0, 0xa, 1, 2, 3, 0, 0, 0 }, 123, 0, - "0:a:1:2:3::", "[0:a:1:2:3::]:123" - }, - { // IPv4 192.168.1.2 embedded in IPv6 in the deprecated way. - { 0, 0, 0, 0, 0, 0, 0xc0a8, 0x102 }, 123, 0, - "::192.168.1.2", "[::192.168.1.2]:123" - }, - { // ... with non-zero scope. - { 0, 0, 0, 0, 0, 0, 0xc0a8, 0x102 }, 123, 789, - "::192.168.1.2%789", "[::192.168.1.2%789]:123" - }, - { // IPv4 192.168.1.2 embedded in IPv6. - { 0, 0, 0, 0, 0, 0xffff, 0xc0a8, 0x102 }, 123, 0, - "::ffff:192.168.1.2", "[::ffff:192.168.1.2]:123" - }, - { // ... with non-zero scope. - { 0, 0, 0, 0, 0, 0xffff, 0xc0a8, 0x102 }, 123, 789, - "::ffff:192.168.1.2%789", "[::ffff:192.168.1.2%789]:123" - }, - { // *Not* IPv4 embedded in IPv6. - { 0, 0, 0, 0, 0, 0x1234, 0xc0a8, 0x102 }, 123, 0, - "::1234:c0a8:102", "[::1234:c0a8:102]:123" - } - }; - - for (size_t i = 0; i < sizeof(test_cases)/sizeof(test_cases[0]); i++) { - PP_NetAddress_Private addr = MakeIPv6NetAddress(test_cases[i].address, - test_cases[i].port, - test_cases[i].scope); - ASSERT_EQ(test_cases[i].expected_without_port, - NetAddressPrivate::Describe(addr, false)); - ASSERT_EQ(test_cases[i].expected_with_port, - NetAddressPrivate::Describe(addr, true)); - } - - PASS(); -} - -std::string TestNetAddressPrivate::TestGetFamily() { - uint8_t localhost_ip[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private ipv4 = MakeIPv4NetAddress(localhost_ip, 80); - ASSERT_EQ(NetAddressPrivate::GetFamily(ipv4), - PP_NETADDRESSFAMILY_PRIVATE_IPV4); - - uint16_t ipv6_address[8] = { 0x1234, 0xabcd, 0, 0, 0xff, 0, 0, 0xcdef }; - PP_NetAddress_Private ipv6 = MakeIPv6NetAddress(ipv6_address, 123, 0); - ASSERT_EQ(NetAddressPrivate::GetFamily(ipv6), - PP_NETADDRESSFAMILY_PRIVATE_IPV6); - - PASS(); -} - -std::string TestNetAddressPrivate::TestGetPort() { - uint8_t localhost_ip[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private localhost_80 = MakeIPv4NetAddress(localhost_ip, 80); - ASSERT_EQ(NetAddressPrivate::GetPort(localhost_80), 80); - - uint16_t ipv6_address[8] = { 0x1234, 0xabcd, 0, 0, 0xff, 0, 0, 0xcdef }; - - PP_NetAddress_Private port_123 = MakeIPv6NetAddress(ipv6_address, 123, 0); - ASSERT_EQ(NetAddressPrivate::GetPort(port_123), 123); - - PP_NetAddress_Private port_FFFF = MakeIPv6NetAddress(ipv6_address, - 0xFFFF, - 0); - ASSERT_EQ(NetAddressPrivate::GetPort(port_FFFF), 0xFFFF); - - PASS(); -} - -std::string TestNetAddressPrivate::TestGetAddress() { - const int addr_storage_len = 16; - unsigned char addr_storage[addr_storage_len]; - - const uint8_t ipv4_addr[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private localhost_80 = MakeIPv4NetAddress(ipv4_addr, 80); - memset(addr_storage, 0, addr_storage_len); - ASSERT_TRUE(NetAddressPrivate::GetAddress(localhost_80, - addr_storage, - addr_storage_len)); - ASSERT_EQ(memcmp(addr_storage, &ipv4_addr, 4), 0); - - // Insufficient storage for address. - ASSERT_FALSE(NetAddressPrivate::GetAddress(localhost_80, - addr_storage, - 1)); - - uint16_t ipv6_address[8] = { 0x1234, 0xabcd, 0, 0, 0xff, 0, 0, 0xcdef }; - PP_NetAddress_Private ipv6_addr = MakeIPv6NetAddress(ipv6_address, - 123, - 0); - - // Ensure the ipv6 address is transformed properly into network order. - uint8_t ipv6_bytes[16]; - for(int i = 0; i < 8; ++i) { - ipv6_bytes[i * 2] = ipv6_address[i] >> 8; - ipv6_bytes[i * 2 + 1] = ipv6_address[i] & 0xFF; - } - - memset(addr_storage, 0, addr_storage_len); - ASSERT_TRUE(NetAddressPrivate::GetAddress(ipv6_addr, - addr_storage, - addr_storage_len)); - ASSERT_EQ(memcmp(addr_storage, ipv6_bytes, 16), 0); - - // Insufficient storage for address. - ASSERT_FALSE(NetAddressPrivate::GetAddress(ipv6_addr, - addr_storage, - 1)); - - PASS(); -} - -std::string TestNetAddressPrivate::TestGetScopeID() { - uint8_t localhost_ip[4] = { 127, 0, 0, 1 }; - PP_NetAddress_Private ipv4 = MakeIPv4NetAddress(localhost_ip, 80); - ASSERT_EQ(0, NetAddressPrivate::GetScopeID(ipv4)); - - uint16_t ipv6_address[8] = { 0x1234, 0xabcd, 0, 0, 0xff, 0, 0, 0xcdef }; - - PP_NetAddress_Private ipv6_123 = MakeIPv6NetAddress(ipv6_address, 0, 123); - ASSERT_EQ(123, NetAddressPrivate::GetScopeID(ipv6_123)); - - PP_NetAddress_Private ipv6_max = - MakeIPv6NetAddress(ipv6_address, 0, 0xFFFFFFFF); - ASSERT_EQ(NetAddressPrivate::GetScopeID(ipv6_max), 0xFFFFFFFF); - - PASS(); -}
diff --git a/tests/test_net_address_private.h b/tests/test_net_address_private.h deleted file mode 100644 index c870405..0000000 --- a/tests/test_net_address_private.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_NET_ADDRESS_PRIVATE_H_ -#define PPAPI_TESTS_TEST_NET_ADDRESS_PRIVATE_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -class TestNetAddressPrivate : public TestCase { - public: - explicit TestNetAddressPrivate(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestAreEqual(); - std::string TestAreHostsEqual(); - std::string TestDescribe(); - std::string TestReplacePort(); - std::string TestGetAnyAddress(); - std::string TestDescribeIPv6(); - std::string TestGetFamily(); - std::string TestGetPort(); - std::string TestGetAddress(); - std::string TestGetScopeID(); -}; - -#endif // PPAPI_TESTS_TEST_NET_ADDRESS_PRIVATE_H_
diff --git a/tests/test_net_address_private_untrusted.cc b/tests/test_net_address_private_untrusted.cc deleted file mode 100644 index 9a88bdc..0000000 --- a/tests/test_net_address_private_untrusted.cc +++ /dev/null
@@ -1,204 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_net_address_private_untrusted.h" - -#include <limits> -#include <sstream> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(NetAddressPrivateUntrusted); - -using pp::NetAddressPrivate; -using pp::TCPSocketPrivate; - -TestNetAddressPrivateUntrusted::TestNetAddressPrivateUntrusted( - TestingInstance* instance) : TestCase(instance), port_(0) { -} - -bool TestNetAddressPrivateUntrusted::Init() { - bool net_address_private_is_available = NetAddressPrivate::IsAvailable(); - if (!net_address_private_is_available) - instance_->AppendError("PPB_NetAddress_Private interface not available"); - - bool tcp_socket_private_is_available = TCPSocketPrivate::IsAvailable(); - if (!tcp_socket_private_is_available) - instance_->AppendError("PPB_TCPSocket_Private interface not available"); - - bool init_host_port = - GetLocalHostPort(instance_->pp_instance(), &host_, &port_); - if (!init_host_port) - instance_->AppendError("Can't init host and port"); - - return net_address_private_is_available && - tcp_socket_private_is_available && - init_host_port && - CheckTestingInterface(); -} - -void TestNetAddressPrivateUntrusted::RunTests(const std::string& filter) { - RUN_TEST(AreEqual, filter); - RUN_TEST(AreHostsEqual, filter); - RUN_TEST(Describe, filter); - RUN_TEST(ReplacePort, filter); - RUN_TEST(GetAnyAddress, filter); - RUN_TEST(GetFamily, filter); - RUN_TEST(GetPort, filter); - RUN_TEST(GetAddress, filter); -} - -int32_t TestNetAddressPrivateUntrusted::Connect(TCPSocketPrivate* socket, - const std::string& host, - uint16_t port) { - TestCompletionCallback callback(instance_->pp_instance(), false); - - callback.WaitForResult( - socket->Connect(host.c_str(), port, callback.GetCallback())); - return callback.result(); -} - -std::string TestNetAddressPrivateUntrusted::TestAreEqual() { - pp::TCPSocketPrivate socket(instance_); - int32_t rv = Connect(&socket, host_, port_); - if (rv != PP_OK) - return ReportError("pp::TCPSocketPrivate::Connect", rv); - - PP_NetAddress_Private local_address, remote_address; - ASSERT_TRUE(socket.GetLocalAddress(&local_address)); - ASSERT_TRUE(socket.GetRemoteAddress(&remote_address)); - - ASSERT_TRUE(NetAddressPrivate::AreEqual(local_address, local_address)); - ASSERT_FALSE(NetAddressPrivate::AreEqual(local_address, remote_address)); - - socket.Disconnect(); - PASS(); -} - -std::string TestNetAddressPrivateUntrusted::TestAreHostsEqual() { - pp::TCPSocketPrivate socket(instance_); - int32_t rv = Connect(&socket, host_, port_); - if (rv != PP_OK) - return ReportError("pp::TCPSocketPrivate::Connect", rv); - - PP_NetAddress_Private local_address, remote_address; - ASSERT_TRUE(socket.GetLocalAddress(&local_address)); - ASSERT_TRUE(socket.GetRemoteAddress(&remote_address)); - - ASSERT_TRUE(NetAddressPrivate::AreHostsEqual(local_address, local_address)); - ASSERT_TRUE(NetAddressPrivate::AreHostsEqual(local_address, remote_address)); - - socket.Disconnect(); - PASS(); -} - -std::string TestNetAddressPrivateUntrusted::TestDescribe() { - pp::TCPSocketPrivate socket(instance_); - int32_t rv = Connect(&socket, host_, port_); - if (rv != PP_OK) - return ReportError("pp::TCPSocketPrivate::Connect", rv); - - PP_NetAddress_Private remote_address; - ASSERT_TRUE(socket.GetRemoteAddress(&remote_address)); - - std::ostringstream os; - - os << host_; - ASSERT_EQ(os.str(), NetAddressPrivate::Describe(remote_address, false)); - - os << ':' << port_; - ASSERT_EQ(os.str(), NetAddressPrivate::Describe(remote_address, true)); - - socket.Disconnect(); - PASS(); -} - -std::string TestNetAddressPrivateUntrusted::TestReplacePort() { - pp::TCPSocketPrivate socket(instance_); - int32_t rv = Connect(&socket, host_, port_); - if (rv != PP_OK) - return ReportError("pp::TCPSocketPrivate::Connect", rv); - - PP_NetAddress_Private src_addr, dst_addr; - ASSERT_TRUE(socket.GetRemoteAddress(&src_addr)); - - uint16_t nport = port_; - if (nport == std::numeric_limits<uint16_t>::max()) - --nport; - else - ++nport; - ASSERT_TRUE(NetAddressPrivate::ReplacePort(src_addr, nport, &dst_addr)); - - std::ostringstream os; - os << host_ << ':' << nport; - - ASSERT_EQ(os.str(), NetAddressPrivate::Describe(dst_addr, true)); - - socket.Disconnect(); - PASS(); -} - -std::string TestNetAddressPrivateUntrusted::TestGetAnyAddress() { - PP_NetAddress_Private address; - - NetAddressPrivate::GetAnyAddress(false, &address); - ASSERT_TRUE(NetAddressPrivate::AreEqual(address, address)); - - NetAddressPrivate::GetAnyAddress(true, &address); - ASSERT_TRUE(NetAddressPrivate::AreEqual(address, address)); - - PASS(); -} - -std::string TestNetAddressPrivateUntrusted::TestGetFamily() { - pp::TCPSocketPrivate socket(instance_); - int32_t rv = Connect(&socket, host_, port_); - if (rv != PP_OK) - return ReportError("pp::TCPSocketPrivate::Connect", rv); - - PP_NetAddress_Private remote_address; - ASSERT_TRUE(socket.GetRemoteAddress(&remote_address)); - - ASSERT_EQ(NetAddressPrivate::GetFamily(remote_address), - NetAddressPrivate::GetFamily(remote_address)); - - socket.Disconnect(); - PASS(); -} - -std::string TestNetAddressPrivateUntrusted::TestGetPort() { - pp::TCPSocketPrivate socket(instance_); - int32_t rv = Connect(&socket, host_, port_); - if (rv != PP_OK) - return ReportError("pp::TCPSocketPrivate::Connect", rv); - - PP_NetAddress_Private remote_address; - ASSERT_TRUE(socket.GetRemoteAddress(&remote_address)); - - ASSERT_EQ(NetAddressPrivate::GetPort(remote_address), port_); - - socket.Disconnect(); - PASS(); -} - -std::string TestNetAddressPrivateUntrusted::TestGetAddress() { - pp::TCPSocketPrivate socket(instance_); - int32_t rv = Connect(&socket, host_, port_); - if (rv != PP_OK) - return ReportError("pp::TCPSocketPrivate::Connect", rv); - - PP_NetAddress_Private remote_address; - ASSERT_TRUE(socket.GetRemoteAddress(&remote_address)); - - static const uint16_t buffer_size = sizeof(remote_address.data); - char buffer[buffer_size]; - ASSERT_TRUE(NetAddressPrivate::GetAddress(remote_address, buffer, - buffer_size)); - - socket.Disconnect(); - PASS(); -}
diff --git a/tests/test_net_address_private_untrusted.h b/tests/test_net_address_private_untrusted.h deleted file mode 100644 index e6161a2..0000000 --- a/tests/test_net_address_private_untrusted.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_NET_ADDRESS_PRIVATE_UNTRUSTED_H_ -#define PPAPI_TESTS_TEST_NET_ADDRESS_PRIVATE_UNTRUSTED_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/tests/test_case.h" - -// TestNetAddressPrivate doesn't compile via NaCl toolchain, because -// these tests depend on network API which is not available in -// NaCl. TestNetAddressPrivateUntrusted is written only for check that -// API is correctly exposed to NaCl, not for checking correctness of -// API --- this is a job of TestNetAddressPrivate. -class TestNetAddressPrivateUntrusted : public TestCase { - public: - explicit TestNetAddressPrivateUntrusted(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - int32_t Connect(pp::TCPSocketPrivate* socket, - const std::string& host, - uint16_t port); - - std::string TestAreEqual(); - std::string TestAreHostsEqual(); - std::string TestDescribe(); - std::string TestReplacePort(); - std::string TestGetAnyAddress(); - std::string TestGetFamily(); - std::string TestGetPort(); - std::string TestGetAddress(); - - std::string host_; - uint16_t port_; -}; - -#endif // PPAPI_TESTS_TEST_NET_ADDRESS_PRIVATE_UNTRUSTED_H_
diff --git a/tests/test_network_monitor.cc b/tests/test_network_monitor.cc deleted file mode 100644 index 634d8b2..0000000 --- a/tests/test_network_monitor.cc +++ /dev/null
@@ -1,191 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_network_monitor.h" - -#include <stddef.h> -#include <string.h> - -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/net_address.h" -#include "ppapi/cpp/network_list.h" -#include "ppapi/cpp/network_monitor.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(NetworkMonitor); - -namespace { - -class MonitorDeletionCallbackDelegate - : public TestCompletionCallback::Delegate { - public: - explicit MonitorDeletionCallbackDelegate(pp::NetworkMonitor* monitor) - : monitor_(monitor) { - } - - // TestCompletionCallback::Delegate interface. - virtual void OnCallback(void* user_data, int32_t result) { - delete monitor_; - } - - private: - pp::NetworkMonitor* monitor_; -}; - -} // namespace - -TestNetworkMonitor::TestNetworkMonitor(TestingInstance* instance) - : TestCase(instance) { -} - -bool TestNetworkMonitor::Init() { - if (!pp::NetworkMonitor::IsAvailable()) - return false; - - return CheckTestingInterface(); -} - -void TestNetworkMonitor::RunTests(const std::string& filter) { - RUN_TEST_FORCEASYNC_AND_NOT(Basic, filter); - RUN_TEST_FORCEASYNC_AND_NOT(2Monitors, filter); - RUN_TEST_FORCEASYNC_AND_NOT(DeleteInCallback, filter); -} - -std::string TestNetworkMonitor::VerifyNetworkList( - const pp::NetworkList& network_list) { - // Verify that there is at least one network interface. - size_t count = network_list.GetCount(); - ASSERT_TRUE(count >= 1U); - - // Iterate over all interfaces and verify their properties. - for (size_t iface = 0; iface < count; ++iface) { - // Verify that the first interface has at least one address. - std::vector<pp::NetAddress> addresses; - network_list.GetIpAddresses(static_cast<uint32_t>(iface), &addresses); - ASSERT_TRUE(addresses.size() >= 1U); - // Verify that the addresses are valid. - for (size_t i = 0; i < addresses.size(); ++i) { - PP_NetAddress_Family family = addresses[i].GetFamily(); - - switch (family) { - case PP_NETADDRESS_FAMILY_IPV4: { - PP_NetAddress_IPv4 ipv4; - ASSERT_TRUE(addresses[i].DescribeAsIPv4Address(&ipv4)); - - // Verify that the address is not zero. - bool all_zeros = true; - for (size_t j = 0; j < sizeof(ipv4.addr); ++j) { - if (ipv4.addr[j] != 0) { - all_zeros = false; - break; - } - } - ASSERT_TRUE(!all_zeros); - - // Verify that port is set to 0. - ASSERT_TRUE(ipv4.port == 0); - break; - } - - case PP_NETADDRESS_FAMILY_IPV6: { - PP_NetAddress_IPv6 ipv6; - ASSERT_TRUE(addresses[i].DescribeAsIPv6Address(&ipv6)); - - // Verify that the address is not zero. - bool all_zeros = true; - for (size_t j = 0; j < sizeof(ipv6.addr); ++j) { - if (ipv6.addr[j] != 0) { - all_zeros = false; - break; - } - } - ASSERT_TRUE(!all_zeros); - - // Verify that port is set to 0. - ASSERT_TRUE(ipv6.port == 0); - break; - } - - default: - ASSERT_TRUE(false); - } - } - - // Verify that each interface has a unique name and a display name. - ASSERT_FALSE(network_list.GetName(static_cast<uint32_t>(iface)).empty()); - ASSERT_FALSE(network_list.GetDisplayName( - static_cast<uint32_t>(iface)).empty()); - - PP_NetworkList_Type type = - network_list.GetType(static_cast<uint32_t>(iface)); - ASSERT_TRUE(type >= PP_NETWORKLIST_TYPE_UNKNOWN); - ASSERT_TRUE(type <= PP_NETWORKLIST_TYPE_CELLULAR); - - PP_NetworkList_State state = - network_list.GetState(static_cast<uint32_t>(iface)); - ASSERT_TRUE(state >= PP_NETWORKLIST_STATE_DOWN); - ASSERT_TRUE(state <= PP_NETWORKLIST_STATE_UP); - } - - PASS(); -} - -std::string TestNetworkMonitor::TestBasic() { - TestCompletionCallbackWithOutput<pp::NetworkList> test_callback( - instance_->pp_instance()); - pp::NetworkMonitor network_monitor(instance_); - test_callback.WaitForResult( - network_monitor.UpdateNetworkList(test_callback.GetCallback())); - - ASSERT_EQ(PP_OK, test_callback.result()); - ASSERT_SUBTEST_SUCCESS(VerifyNetworkList(test_callback.output())); - - PASS(); -} - -std::string TestNetworkMonitor::Test2Monitors() { - TestCompletionCallbackWithOutput<pp::NetworkList> test_callback( - instance_->pp_instance()); - pp::NetworkMonitor network_monitor(instance_); - test_callback.WaitForResult( - network_monitor.UpdateNetworkList(test_callback.GetCallback())); - - ASSERT_EQ(PP_OK, test_callback.result()); - ASSERT_SUBTEST_SUCCESS(VerifyNetworkList(test_callback.output())); - - TestCompletionCallbackWithOutput<pp::NetworkList> test_callback_2( - instance_->pp_instance()); - pp::NetworkMonitor network_monitor_2(instance_); - test_callback_2.WaitForResult( - network_monitor_2.UpdateNetworkList(test_callback_2.GetCallback())); - - ASSERT_EQ(PP_OK, test_callback_2.result()); - ASSERT_SUBTEST_SUCCESS(VerifyNetworkList(test_callback_2.output())); - - PASS(); -} - -std::string TestNetworkMonitor::TestDeleteInCallback() { - pp::NetworkMonitor* network_monitor = - new pp::NetworkMonitor(instance_); - MonitorDeletionCallbackDelegate deletion_delegate(network_monitor); - TestCompletionCallbackWithOutput<pp::NetworkList> test_callback( - instance_->pp_instance()); - test_callback.SetDelegate(&deletion_delegate); - test_callback.WaitForResult( - network_monitor->UpdateNetworkList(test_callback.GetCallback())); - - ASSERT_EQ(PP_OK, test_callback.result()); - ASSERT_SUBTEST_SUCCESS(VerifyNetworkList(test_callback.output())); - - PASS(); -}
diff --git a/tests/test_network_monitor.h b/tests/test_network_monitor.h deleted file mode 100644 index c783c2e..0000000 --- a/tests/test_network_monitor.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_NETWORK_MONITOR_H_ -#define PPAPI_TESTS_TEST_NETWORK_MONITOR_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -namespace pp { -class NetworkList; -} // namespace pp - -class TestNetworkMonitor : public TestCase { - public: - explicit TestNetworkMonitor(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestBasic(); - std::string Test2Monitors(); - std::string TestDeleteInCallback(); - - std::string VerifyNetworkListResource(PP_Resource network_resource); - std::string VerifyNetworkList(const pp::NetworkList& network_list); - -}; - -#endif // PPAPI_TESTS_TEST_NETWORK_MONITOR_H_
diff --git a/tests/test_network_proxy.cc b/tests/test_network_proxy.cc deleted file mode 100644 index 9ab06ae..0000000 --- a/tests/test_network_proxy.cc +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_network_proxy.h" - -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/network_proxy.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(NetworkProxy); - -TestNetworkProxy::TestNetworkProxy(TestingInstance* instance) - : TestCase(instance) { -} - -void TestNetworkProxy::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestNetworkProxy, GetProxyForURL, filter); -} - -std::string TestNetworkProxy::TestGetProxyForURL() { - TestCompletionCallbackWithOutput<pp::Var> callback(instance_->pp_instance(), - callback_type()); - callback.WaitForResult( - pp::NetworkProxy::GetProxyForURL(instance_, - pp::Var("http://127.0.0.1/foobar/"), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - pp::Var output = callback.output(); - ASSERT_TRUE(output.is_string()); - // Assume no one configures a proxy for localhost. - ASSERT_EQ("DIRECT", callback.output().AsString()); - - callback.WaitForResult( - pp::NetworkProxy::GetProxyForURL(instance_, - pp::Var("http://www.google.com"), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - output = callback.output(); - // Don't know what the proxy might be, but it should be a valid result. - ASSERT_TRUE(output.is_string()); - - callback.WaitForResult( - pp::NetworkProxy::GetProxyForURL(instance_, - pp::Var("file:///tmp"), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - output = callback.output(); - ASSERT_TRUE(output.is_string()); - // Should get "DIRECT" for file:// URLs. - ASSERT_EQ("DIRECT", output.AsString()); - - callback.WaitForResult( - pp::NetworkProxy::GetProxyForURL(instance_, - pp::Var("this isn't a url"), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - ASSERT_TRUE(callback.output().is_undefined()); - - callback.WaitForResult( - pp::NetworkProxy::GetProxyForURL(instance_, - pp::Var(42), // non-string Var - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - ASSERT_TRUE(callback.output().is_undefined()); - - PASS(); -}
diff --git a/tests/test_network_proxy.h b/tests/test_network_proxy.h deleted file mode 100644 index dcb109a..0000000 --- a/tests/test_network_proxy.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_NETWORK_PROXY_H_ -#define PPAPI_TESTS_TEST_NETWORK_PROXY_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -class TestNetworkProxy : public TestCase { - public: - explicit TestNetworkProxy(TestingInstance* instance); - - private: - // TestCase implementation. - virtual void RunTests(const std::string& filter); - - std::string TestGetProxyForURL(); -}; - -#endif // PPAPI_TESTS_TEST_NETWORK_PROXY_H_
diff --git a/tests/test_page.css b/tests/test_page.css deleted file mode 100644 index de76c41..0000000 --- a/tests/test_page.css +++ /dev/null
@@ -1,67 +0,0 @@ -body { - font-family:Verdana,Arial,sans-serif; - padding: 0; - margin: 0; -} - -p.frame-container { - margin: 0; - margin-top: 1em ! important; - margin-bottom: 1em ! important; - padding: 0; -} - -p.frame-container > h2 { - font-size: 1.1em; - margin: 0; - margin-left: 10% ! important; - padding: 0; -} - -p.frame-container > iframe { - margin: 0; - padding: 0; - border: none; - width: 100%; - height: 30%; -} - -#console { - border:1px solid black; - padding:4px; - background-color:#EEE; - margin-left:10%; - margin-right:10%; -} - -#container { - height: 16px; -} - -#container > object { - width: 100%; - height: 100%; -} - -.test_line { -} - -.test_name { -} - -.pass { - font-weight:bold; - color:#080; -} - -.fail { - font-weight:bold; - color:#800; -} - -.err_msg { -} - -.load_msg { - font-style:italic; -}
diff --git a/tests/test_page.css.mock-http-headers b/tests/test_page.css.mock-http-headers deleted file mode 100644 index 3a9d3fb..0000000 --- a/tests/test_page.css.mock-http-headers +++ /dev/null
@@ -1,3 +0,0 @@ -HTTP/1.1 200 OK -Content-Type: text/css -Access-Control-Allow-Origin: *
diff --git a/tests/test_paint_aggregator.cc b/tests/test_paint_aggregator.cc deleted file mode 100644 index e3d3876..0000000 --- a/tests/test_paint_aggregator.cc +++ /dev/null
@@ -1,426 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_paint_aggregator.h" - -#include "ppapi/tests/testing_instance.h" -#include "ppapi/utility/graphics/paint_aggregator.h" - -REGISTER_TEST_CASE(PaintAggregator); - -bool TestPaintAggregator::Init() { - return true; -} - -void TestPaintAggregator::RunTests(const std::string& filter) { - RUN_TEST(InitialState, filter); - RUN_TEST(SingleInvalidation, filter); - RUN_TEST(DoubleDisjointInvalidation, filter); - RUN_TEST(SingleScroll, filter); - RUN_TEST(DoubleOverlappingScroll, filter); - RUN_TEST(NegatingScroll, filter); - RUN_TEST(DiagonalScroll, filter); - RUN_TEST(ContainedPaintAfterScroll, filter); - RUN_TEST(ContainedPaintBeforeScroll, filter); - RUN_TEST(ContainedPaintsBeforeAndAfterScroll, filter); - RUN_TEST(LargeContainedPaintAfterScroll, filter); - RUN_TEST(LargeContainedPaintBeforeScroll, filter); - RUN_TEST(OverlappingPaintBeforeScroll, filter); - RUN_TEST(OverlappingPaintAfterScroll, filter); - RUN_TEST(DisjointPaintBeforeScroll, filter); - RUN_TEST(DisjointPaintAfterScroll, filter); - RUN_TEST(ContainedPaintTrimmedByScroll, filter); - RUN_TEST(ContainedPaintEliminatedByScroll, filter); - RUN_TEST(ContainedPaintAfterScrollTrimmedByScrollDamage, filter); - RUN_TEST(ContainedPaintAfterScrollEliminatedByScrollDamage, filter); -} - -std::string TestPaintAggregator::TestInitialState() { - pp::PaintAggregator greg; - if (greg.HasPendingUpdate()) - return "Pending update invalid"; - PASS(); -} - -std::string TestPaintAggregator::TestSingleInvalidation() { - pp::PaintAggregator greg; - - pp::Rect rect(2, 4, 10, 16); - greg.InvalidateRect(rect); - - ASSERT_TRUE(greg.HasPendingUpdate()); - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(rect == greg.GetPendingUpdate().paint_rects[0]); - - PASS(); -} - -std::string TestPaintAggregator::TestDoubleDisjointInvalidation() { - pp::PaintAggregator greg; - - pp::Rect r1(2, 4, 2, 4); - pp::Rect r2(4, 2, 4, 2); - - greg.InvalidateRect(r1); - greg.InvalidateRect(r2); - - pp::Rect expected_bounds = r1.Union(r2); - - ASSERT_TRUE(greg.HasPendingUpdate()); - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(expected_bounds == greg.GetPendingUpdate().paint_bounds); - PASS(); -} - -std::string TestPaintAggregator::TestSingleScroll() { - pp::PaintAggregator greg; - - pp::Rect r1(2, 4, 2, 4); - pp::Rect r2(4, 2, 4, 2); - - greg.InvalidateRect(r1); - greg.InvalidateRect(r2); - - pp::Rect expected_bounds = r1.Union(r2); - - ASSERT_TRUE(greg.HasPendingUpdate()); - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(expected_bounds == greg.GetPendingUpdate().paint_bounds); - PASS(); -} - -std::string TestPaintAggregator::TestDoubleOverlappingScroll() { - pp::PaintAggregator greg; - - pp::Rect rect(1, 2, 3, 4); - pp::Point delta1(1, 0); - pp::Point delta2(1, 0); - greg.ScrollRect(rect, delta1); - greg.ScrollRect(rect, delta2); - - ASSERT_TRUE(greg.HasPendingUpdate()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - - ASSERT_TRUE(rect == greg.GetPendingUpdate().scroll_rect); - - pp::Point expected_delta(delta1.x() + delta2.x(), - delta1.y() + delta2.y()); - ASSERT_TRUE(expected_delta.x() == greg.GetPendingUpdate().scroll_delta.x()); - ASSERT_TRUE(expected_delta.y() == greg.GetPendingUpdate().scroll_delta.y()); - - pp::Rect resulting_damage = greg.GetPendingUpdate().paint_rects[0]; - pp::Rect expected_damage(1, 2, 2, 4); - ASSERT_TRUE(expected_damage == resulting_damage); - PASS(); -} - -std::string TestPaintAggregator::TestNegatingScroll() { - pp::PaintAggregator greg; - - // Scroll twice in opposite directions by equal amounts. The result - // should be no scrolling. - - pp::Rect rect(1, 2, 3, 4); - pp::Point delta1(1, 0); - pp::Point delta2(-1, 0); - greg.ScrollRect(rect, delta1); - greg.ScrollRect(rect, delta2); - - ASSERT_FALSE(greg.HasPendingUpdate()); - PASS(); -} - -std::string TestPaintAggregator::TestDiagonalScroll() { - pp::PaintAggregator greg; - - // We don't support optimized diagonal scrolling, so this should result in - // repainting. - - pp::Rect rect(1, 2, 3, 4); - pp::Point delta(1, 1); - greg.ScrollRect(rect, delta); - - ASSERT_TRUE(greg.HasPendingUpdate()); - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestContainedPaintAfterScroll() { - pp::PaintAggregator greg; - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - pp::Rect paint_rect(4, 4, 2, 2); - greg.InvalidateRect(paint_rect); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - // Expecting a paint rect inside the scroll rect. The last paint rect is the - // scroll dirty rect. - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - ASSERT_TRUE(paint_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestContainedPaintBeforeScroll() { - pp::PaintAggregator greg; - - pp::Rect paint_rect(4, 4, 2, 2); - greg.InvalidateRect(paint_rect); - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - // Expecting a paint rect inside the scroll rect. The last paint rect is the - // scroll dirty rect. - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - paint_rect.Offset(2, 0); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - ASSERT_TRUE(paint_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestContainedPaintsBeforeAndAfterScroll() { - pp::PaintAggregator greg; - - pp::Rect paint_rect1(4, 4, 2, 2); - greg.InvalidateRect(paint_rect1); - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - pp::Rect paint_rect2(6, 4, 2, 2); - greg.InvalidateRect(paint_rect2); - - pp::Rect expected_paint_rect = paint_rect2; - - ASSERT_TRUE(greg.HasPendingUpdate()); - - // Expecting a paint rect inside the scroll rect - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - ASSERT_TRUE(expected_paint_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestLargeContainedPaintAfterScroll() { - pp::PaintAggregator greg; - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(0, 1)); - - pp::Rect paint_rect(0, 0, 10, 9); // Repaint 90% - greg.InvalidateRect(paint_rect); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestLargeContainedPaintBeforeScroll() { - pp::PaintAggregator greg; - - pp::Rect paint_rect(0, 0, 10, 9); // Repaint 90% - greg.InvalidateRect(paint_rect); - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(0, 1)); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestOverlappingPaintBeforeScroll() { - pp::PaintAggregator greg; - - pp::Rect paint_rect(4, 4, 10, 2); - greg.InvalidateRect(paint_rect); - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - pp::Rect expected_paint_rect = scroll_rect.Union(paint_rect); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(expected_paint_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestOverlappingPaintAfterScroll() { - pp::PaintAggregator greg; - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - pp::Rect paint_rect(4, 4, 10, 2); - greg.InvalidateRect(paint_rect); - - pp::Rect expected_paint_rect = scroll_rect.Union(paint_rect); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_TRUE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(expected_paint_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string TestPaintAggregator::TestDisjointPaintBeforeScroll() { - pp::PaintAggregator greg; - - pp::Rect paint_rect(4, 4, 10, 2); - greg.InvalidateRect(paint_rect); - - pp::Rect scroll_rect(0, 0, 2, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(paint_rect == greg.GetPendingUpdate().paint_rects[0]); - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - PASS(); -} - -std::string TestPaintAggregator::TestDisjointPaintAfterScroll() { - pp::PaintAggregator greg; - - pp::Rect scroll_rect(0, 0, 2, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - pp::Rect paint_rect(4, 4, 10, 2); - greg.InvalidateRect(paint_rect); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(paint_rect == greg.GetPendingUpdate().paint_rects[0]); - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - PASS(); -} - -std::string TestPaintAggregator::TestContainedPaintTrimmedByScroll() { - pp::PaintAggregator greg; - - pp::Rect paint_rect(4, 4, 6, 6); - greg.InvalidateRect(paint_rect); - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(2, 0)); - - // The paint rect should have become narrower. - pp::Rect expected_paint_rect(6, 4, 4, 6); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(expected_paint_rect == greg.GetPendingUpdate().paint_rects[0]); - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - PASS(); -} - -std::string TestPaintAggregator::TestContainedPaintEliminatedByScroll() { - pp::PaintAggregator greg; - - pp::Rect paint_rect(4, 4, 6, 6); - greg.InvalidateRect(paint_rect); - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(6, 0)); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - PASS(); -} - -std::string -TestPaintAggregator::TestContainedPaintAfterScrollTrimmedByScrollDamage() { - pp::PaintAggregator greg; - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(4, 0)); - - pp::Rect paint_rect(2, 0, 4, 10); - greg.InvalidateRect(paint_rect); - - pp::Rect expected_scroll_damage(0, 0, 4, 10); - pp::Rect expected_paint_rect(4, 0, 2, 10); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(2U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - ASSERT_TRUE(expected_scroll_damage == greg.GetPendingUpdate().paint_rects[1]); - ASSERT_TRUE(expected_paint_rect == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -} - -std::string -TestPaintAggregator::TestContainedPaintAfterScrollEliminatedByScrollDamage() { - pp::PaintAggregator greg; - - pp::Rect scroll_rect(0, 0, 10, 10); - greg.ScrollRect(scroll_rect, pp::Point(4, 0)); - - pp::Rect paint_rect(2, 0, 2, 10); - greg.InvalidateRect(paint_rect); - - pp::Rect expected_scroll_damage(0, 0, 4, 10); - - ASSERT_TRUE(greg.HasPendingUpdate()); - - ASSERT_FALSE(greg.GetPendingUpdate().scroll_rect.IsEmpty()); - ASSERT_TRUE(1U == greg.GetPendingUpdate().paint_rects.size()); - - ASSERT_TRUE(scroll_rect == greg.GetPendingUpdate().scroll_rect); - ASSERT_TRUE(expected_scroll_damage == greg.GetPendingUpdate().paint_rects[0]); - PASS(); -}
diff --git a/tests/test_paint_aggregator.h b/tests/test_paint_aggregator.h deleted file mode 100644 index 1a1ce0e..0000000 --- a/tests/test_paint_aggregator.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_PAINT_AGGREGATOR_H_ -#define PPAPI_TESTS_TEST_PAINT_AGGREGATOR_H_ - -#include "ppapi/tests/test_case.h" - -class TestPaintAggregator : public TestCase { - public: - TestPaintAggregator(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestInitialState(); - std::string TestSingleInvalidation(); - std::string TestDoubleDisjointInvalidation(); - std::string TestSingleScroll(); - std::string TestDoubleOverlappingScroll(); - std::string TestNegatingScroll(); - std::string TestDiagonalScroll(); - std::string TestContainedPaintAfterScroll(); - std::string TestContainedPaintBeforeScroll(); - std::string TestContainedPaintsBeforeAndAfterScroll(); - std::string TestLargeContainedPaintAfterScroll(); - std::string TestLargeContainedPaintBeforeScroll(); - std::string TestOverlappingPaintBeforeScroll(); - std::string TestOverlappingPaintAfterScroll(); - std::string TestDisjointPaintBeforeScroll(); - std::string TestDisjointPaintAfterScroll(); - std::string TestContainedPaintTrimmedByScroll(); - std::string TestContainedPaintEliminatedByScroll(); - std::string TestContainedPaintAfterScrollTrimmedByScrollDamage(); - std::string TestContainedPaintAfterScrollEliminatedByScrollDamage(); -}; - -#endif // PPAPI_TESTS_TEST_PAINT_AGGREGATOR_H_
diff --git a/tests/test_post_message.cc b/tests/test_post_message.cc deleted file mode 100644 index 7dbda9e..0000000 --- a/tests/test_post_message.cc +++ /dev/null
@@ -1,905 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_post_message.h" - -#include <stddef.h> -#include <stdint.h> -#include <string.h> -#include <algorithm> -#include <map> -#include <sstream> - -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/var_array.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/cpp/var_dictionary.h" -#include "ppapi/tests/pp_thread.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -// Windows defines 'PostMessage', so we have to undef it. -#ifdef PostMessage -#undef PostMessage -#endif - -REGISTER_TEST_CASE(PostMessage); - -namespace { - -const char kTestFilename[] = "testfile.txt"; -const char kTestString[] = "Hello world!"; -const bool kTestBool = true; -const int32_t kTestInt = 42; -const double kTestDouble = 42.0; - -// On Windows XP bots, the NonMainThread test can run very slowly. So we dial -// back the number of threads & messages when running on Windows. -#ifdef PPAPI_OS_WIN -const int32_t kThreadsToRun = 2; -const int32_t kMessagesToSendPerThread = 5; -#else -const int32_t kThreadsToRun = 4; -const int32_t kMessagesToSendPerThread = 10; -#endif - -// The struct that invoke_post_message_thread_func expects for its argument. -// It includes the instance on which to invoke PostMessage, and the value to -// pass to PostMessage. -struct InvokePostMessageThreadArg { - InvokePostMessageThreadArg(pp::Instance* i, const pp::Var& v) - : instance(i), value_to_send(v) {} - pp::Instance* instance; - pp::Var value_to_send; -}; - -void InvokePostMessageThreadFunc(void* user_data) { - InvokePostMessageThreadArg* arg = - static_cast<InvokePostMessageThreadArg*>(user_data); - for (int32_t i = 0; i < kMessagesToSendPerThread; ++i) - arg->instance->PostMessage(arg->value_to_send); - delete arg; -} - -// TODO(raymes): Consider putting something like this into pp::Var. -bool VarsEqual(const pp::Var& expected, - const pp::Var& actual, - std::map<int64_t, int64_t>* visited_ids) { - if (expected.pp_var().type != actual.pp_var().type) { - if (!expected.is_number() && !actual.is_number()) - return false; - } - // TODO(raymes): Implement a pp::Var::IsRefCounted() function. - if (expected.pp_var().type > PP_VARTYPE_DOUBLE) { - std::map<int64_t, int64_t>::const_iterator it = - visited_ids->find(expected.pp_var().value.as_id); - if (it != visited_ids->end()) { - if (it->second == actual.pp_var().value.as_id) - return true; - return false; - } - // Round-tripping reference graphs with strings will not necessarily - // result in isomorphic graphs. This is because string vars are converted - // to string primitives in JS which cannot be referenced. - if (!expected.is_string()) { - (*visited_ids)[expected.pp_var().value.as_id] = - actual.pp_var().value.as_id; - } - } - - if (expected.is_number()) { - return fabs(expected.AsDouble() - actual.AsDouble()) < 1.0e-4; - } else if (expected.is_array()) { - pp::VarArray expected_array(expected); - pp::VarArray actual_array(actual); - if (expected_array.GetLength() != actual_array.GetLength()) - return false; - for (uint32_t i = 0; i < expected_array.GetLength(); ++i) { - if (!VarsEqual(expected_array.Get(i), actual_array.Get(i), visited_ids)) - return false; - } - return true; - } else if (expected.is_dictionary()) { - pp::VarDictionary expected_dict(expected); - pp::VarDictionary actual_dict(actual); - if (expected_dict.GetKeys().GetLength() != - actual_dict.GetKeys().GetLength()) { - return false; - } - for (uint32_t i = 0; i < expected_dict.GetKeys().GetLength(); ++i) { - pp::Var key = expected_dict.GetKeys().Get(i); - if (!actual_dict.HasKey(key)) - return false; - if (!VarsEqual(expected_dict.Get(key), actual_dict.Get(key), visited_ids)) - return false; - } - return true; - } else { - return expected == actual; - } -} - -bool VarsEqual(const pp::Var& expected, - const pp::Var& actual) { - std::map<int64_t, int64_t> visited_ids; - return VarsEqual(expected, actual, &visited_ids); -} - -#define FINISHED_WAITING_MESSAGE "TEST_POST_MESSAGE_FINISHED_WAITING" - -} // namespace - -TestPostMessage::TestPostMessage(TestingInstance* instance) - : TestCase(instance) { -} - -TestPostMessage::~TestPostMessage() { - instance_->PostMessage(pp::Var("This isn't guaranteed to be received, but " - "shouldn't cause a crash.")); - - // Remove the special listener that only responds to a FINISHED_WAITING - // string. See Init for where it gets added. - std::string js_code; - js_code += "var plugin = document.getElementById('plugin');" - "plugin.removeEventListener('message'," - " plugin.wait_for_messages_handler);" - "delete plugin.wait_for_messages_handler;"; - instance_->EvalScript(js_code); -} - -bool TestPostMessage::Init() { - bool success = CheckTestingInterface(); - - // Add a post condition to tests which caches the postMessage function and - // then calls it after the instance is destroyed. The ensures that no UAF - // occurs because the MessageChannel may still be alive after the plugin - // instance is destroyed (it will get garbage collected eventually). - instance_->EvalScript("window.pluginPostMessage = " - "document.getElementById('plugin').postMessage"); - instance_->AddPostCondition("window.pluginPostMessage('') === undefined"); - - // Set up a special listener that only responds to a FINISHED_WAITING string. - // This is for use by WaitForMessages. - std::string js_code; - // Note the following code is dependent on some features of test_case.html. - // E.g., it is assumed that the DOM element where the plugin is embedded has - // an id of 'plugin', and there is a function 'IsTestingMessage' that allows - // us to ignore the messages that are intended for use by the testing - // framework itself. - js_code += "var plugin = document.getElementById('plugin');" - "var wait_for_messages_handler = function(message_event) {" - " if (!IsTestingMessage(message_event.data) &&" - " message_event.data === '" FINISHED_WAITING_MESSAGE "') {" - " plugin.postMessage('" FINISHED_WAITING_MESSAGE "');" - " }" - "};" - "plugin.addEventListener('message', wait_for_messages_handler);" - // Stash it on the plugin so we can remove it in the destructor. - "plugin.wait_for_messages_handler = wait_for_messages_handler;"; - instance_->EvalScript(js_code); - - // Set up the JavaScript message event listener to echo the data part of the - // message event back to us. - success = success && AddEchoingListener("message_event.data"); - message_data_.clear(); - // Send a message that the first test will expect to receive. This is to - // verify that we can send messages when the 'Instance::Init' function is on - // the stack. - instance_->PostMessage(pp::Var(kTestString)); - - return success; -} - -void TestPostMessage::RunTests(const std::string& filter) { - // Note: SendInInit must be first, because it expects to receive a message - // that was sent in Init above. - RUN_TEST(SendInInit, filter); - RUN_TEST(SendingData, filter); - RUN_TEST(SendingString, filter); - RUN_TEST(SendingArrayBuffer, filter); - RUN_TEST(SendingArray, filter); - RUN_TEST(SendingDictionary, filter); - RUN_TEST(SendingResource, filter); - RUN_TEST(SendingComplexVar, filter); - RUN_TEST(MessageEvent, filter); - RUN_TEST(NoHandler, filter); - RUN_TEST(ExtraParam, filter); - if (testing_interface_->IsOutOfProcess()) - RUN_TEST(NonMainThread, filter); -} - -void TestPostMessage::HandleMessage(const pp::Var& message_data) { - if (message_data.is_string() && - (message_data.AsString() == FINISHED_WAITING_MESSAGE)) - testing_interface_->QuitMessageLoop(instance_->pp_instance()); - else - message_data_.push_back(message_data); -} - -bool TestPostMessage::AddEchoingListener(const std::string& expression) { - std::string js_code; - // Note the following code is dependent on some features of test_case.html. - // E.g., it is assumed that the DOM element where the plugin is embedded has - // an id of 'plugin', and there is a function 'IsTestingMessage' that allows - // us to ignore the messages that are intended for use by the testing - // framework itself. - js_code += "var plugin = document.getElementById('plugin');" - "var message_handler = function(message_event) {" - " if (!IsTestingMessage(message_event.data) &&" - " !(message_event.data === '" FINISHED_WAITING_MESSAGE "')) {" - " plugin.postMessage("; - js_code += expression; - js_code += " );" - " }" - "};" - "plugin.addEventListener('message', message_handler);" - // Maintain an array of all event listeners, attached to the - // plugin. This is so that we can easily remove them later (see - // ClearListeners()). - "if (!plugin.eventListeners) plugin.eventListeners = [];" - "plugin.eventListeners.push(message_handler);"; - instance_->EvalScript(js_code); - return true; -} - -bool TestPostMessage::PostMessageFromJavaScript(const std::string& func) { - std::string js_code; - js_code += "var plugin = document.getElementById('plugin');" - "plugin.postMessage("; - js_code += func + "()"; - js_code += " );"; - instance_->EvalScript(js_code); - return true; -} - -bool TestPostMessage::ClearListeners() { - std::string js_code; - js_code += "var plugin = document.getElementById('plugin');" - "while (plugin.eventListeners.length) {" - " plugin.removeEventListener('message'," - " plugin.eventListeners.pop());" - "}"; - instance_->EvalScript(js_code); - return true; -} - -int TestPostMessage::WaitForMessages() { - size_t message_size_before = message_data_.size(); - // We first post a FINISHED_WAITING_MESSAGE. This should be guaranteed to - // come back _after_ any other incoming messages that were already pending. - instance_->PostMessage(pp::Var(FINISHED_WAITING_MESSAGE)); - testing_interface_->RunMessageLoop(instance_->pp_instance()); - // Now that the FINISHED_WAITING_MESSAGE has been echoed back to us, we know - // that all pending messages have been slurped up. Return the number we - // received (which may be zero). - return static_cast<int>(message_data_.size() - message_size_before); -} - -std::string TestPostMessage::CheckMessageProperties( - const pp::Var& test_data, - const std::vector<std::string>& properties_to_check) { - typedef std::vector<std::string>::const_iterator Iterator; - for (Iterator iter = properties_to_check.begin(); - iter != properties_to_check.end(); - ++iter) { - ASSERT_TRUE(AddEchoingListener(*iter)); - message_data_.clear(); - instance_->PostMessage(test_data); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_bool()); - if (!message_data_.back().AsBool()) - return std::string("Failed: ") + *iter; - ASSERT_TRUE(message_data_.back().AsBool()); - ASSERT_TRUE(ClearListeners()); - } - PASS(); -} - -std::string TestPostMessage::TestSendInInit() { - // Wait for the messages from Init() to be guaranteed to be sent. - WaitForMessages(); - // This test assumes Init already sent a message. - ASSERT_EQ(1, message_data_.size()); - ASSERT_TRUE(message_data_.back().is_string()); - ASSERT_EQ(kTestString, message_data_.back().AsString()); - message_data_.clear(); - PASS(); -} - -std::string TestPostMessage::TestSendingData() { - // Clean up after previous tests. This also swallows the message sent by Init - // if we didn't run the 'SendInInit' test. All tests other than 'SendInInit' - // should start with these. - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - - // Set up the JavaScript message event listener to echo the data part of the - // message event back to us. - ASSERT_TRUE(AddEchoingListener("message_event.data")); - - // Test sending a message to JavaScript for each supported type. The JS sends - // the data back to us, and we check that they match. - message_data_.clear(); - instance_->PostMessage(pp::Var(kTestBool)); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_bool()); - ASSERT_EQ(message_data_.back().AsBool(), kTestBool); - - message_data_.clear(); - instance_->PostMessage(pp::Var(kTestInt)); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_number()); - ASSERT_DOUBLE_EQ(static_cast<double>(kTestInt), - message_data_.back().AsDouble()); - - message_data_.clear(); - instance_->PostMessage(pp::Var(kTestDouble)); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_number()); - ASSERT_DOUBLE_EQ(message_data_.back().AsDouble(), kTestDouble); - - message_data_.clear(); - instance_->PostMessage(pp::Var()); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_undefined()); - - message_data_.clear(); - instance_->PostMessage(pp::Var(pp::Var::Null())); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_null()); - - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestSendingString() { - // Clean up after previous tests. This also swallows the message sent by Init - // if we didn't run the 'SendInInit' test. All tests other than 'SendInInit' - // should start with these. - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - - // Test that a string var is converted to a primitive JS string. - message_data_.clear(); - std::vector<std::string> properties_to_check; - properties_to_check.push_back( - "typeof message_event.data === 'string'"); - ASSERT_SUBTEST_SUCCESS(CheckMessageProperties(kTestString, - properties_to_check)); - - ASSERT_TRUE(AddEchoingListener("message_event.data")); - message_data_.clear(); - instance_->PostMessage(pp::Var(kTestString)); - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_string()); - ASSERT_EQ(message_data_.back().AsString(), kTestString); - - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestSendingArrayBuffer() { - // Clean up after previous tests. This also swallows the message sent by Init - // if we didn't run the 'SendInInit' test. All tests other than 'SendInInit' - // should start with these. - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - - // TODO(sehr,dmichael): Add testing of longer array buffers when - // crbug.com/110086 is fixed. - ScopedArrayBufferSizeSetter setter(testing_interface_, - instance_->pp_instance(), - 200); - uint32_t sizes[] = { 0, 100, 1000, 10000 }; - for (size_t i = 0; i < sizeof(sizes)/sizeof(sizes[i]); ++i) { - std::ostringstream size_stream; - size_stream << sizes[i]; - const std::string kSizeAsString(size_stream.str()); - - // Create an appropriately sized array buffer with test_data[i] == i. - pp::VarArrayBuffer test_data(sizes[i]); - if (sizes[i] > 0) - ASSERT_NE(NULL, test_data.Map()); - // Make sure we can Unmap/Map successfully (there's not really any way to - // detect if it's unmapped, so we just re-map before getting the pointer to - // the buffer). - test_data.Unmap(); - test_data.Map(); - ASSERT_EQ(sizes[i], test_data.ByteLength()); - unsigned char* buff = static_cast<unsigned char*>(test_data.Map()); - const uint32_t kByteLength = test_data.ByteLength(); - for (size_t j = 0; j < kByteLength; ++j) - buff[j] = static_cast<uint8_t>(j % 256u); - - // Have the listener test some properties of the ArrayBuffer. - std::vector<std::string> properties_to_check; - properties_to_check.push_back( - "message_event.data.constructor.name === 'ArrayBuffer'"); - properties_to_check.push_back( - std::string("message_event.data.byteLength === ") + kSizeAsString); - if (sizes[i] > 0) { - properties_to_check.push_back( - "(new DataView(message_event.data)).getUint8(0) == 0"); - // Checks that the last element has the right value: (byteLength-1)%256. - std::string received_byte("(new DataView(message_event.data)).getUint8(" - " message_event.data.byteLength-1)"); - std::string expected_byte("(message_event.data.byteLength-1)%256"); - properties_to_check.push_back(received_byte + " == " + expected_byte); - } - ASSERT_SUBTEST_SUCCESS(CheckMessageProperties(test_data, - properties_to_check)); - - // Set up the JavaScript message event listener to echo the data part of the - // message event back to us. - ASSERT_TRUE(AddEchoingListener("message_event.data")); - message_data_.clear(); - instance_->PostMessage(test_data); - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_array_buffer()); - pp::VarArrayBuffer received(message_data_.back()); - message_data_.clear(); - ASSERT_EQ(test_data.ByteLength(), received.ByteLength()); - unsigned char* received_buff = static_cast<unsigned char*>(received.Map()); - // The buffer should be copied, so this should be a distinct buffer. When - // 'transferrables' are implemented for PPAPI, we'll also want to test that - // we get the _same_ buffer back when it's transferred. - if (sizes[i] > 0) - ASSERT_NE(buff, received_buff); - for (size_t byte = 0; byte < test_data.ByteLength(); ++byte) - ASSERT_EQ(buff[byte], received_buff[byte]); - - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - } - - PASS(); -} - -std::string TestPostMessage::TestSendingArray() { - // Clean up after previous tests. This also swallows the message sent by Init - // if we didn't run the 'SendInInit' test. All tests other than 'SendInInit' - // should start with these. - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - - pp::VarArray array; - array.Set(0, pp::Var(kTestBool)); - array.Set(1, pp::Var(kTestString)); - // Purposely leave index 2 empty. - array.Set(3, pp::Var(kTestInt)); - array.Set(4, pp::Var(kTestDouble)); - - std::stringstream ss; - ss << array.GetLength(); - std::string length_as_string(ss.str()); - - // Have the listener test some properties of the Array. - std::vector<std::string> properties_to_check; - properties_to_check.push_back( - "message_event.data.constructor.name === 'Array'"); - properties_to_check.push_back( - std::string("message_event.data.length === ") + length_as_string); - // Check that the string is converted to a primitive JS string. - properties_to_check.push_back( - std::string("typeof message_event.data[1] === 'string'")); - ASSERT_SUBTEST_SUCCESS(CheckMessageProperties(array, properties_to_check)); - - // Set up the JavaScript message event listener to echo the data part of the - // message event back to us. - ASSERT_TRUE(AddEchoingListener("message_event.data")); - message_data_.clear(); - instance_->PostMessage(array); - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_array()); - ASSERT_TRUE(VarsEqual(array, message_data_.back())); - - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestSendingDictionary() { - // Clean up after previous tests. This also swallows the message sent by Init - // if we didn't run the 'SendInInit' test. All tests other than 'SendInInit' - // should start with these. - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - - pp::VarDictionary dictionary; - dictionary.Set(pp::Var("foo"), pp::Var(kTestBool)); - dictionary.Set(pp::Var("bar"), pp::Var(kTestString)); - dictionary.Set(pp::Var("abc"), pp::Var(kTestInt)); - dictionary.Set(pp::Var("def"), pp::Var()); - - std::stringstream ss; - ss << dictionary.GetKeys().GetLength(); - std::string length_as_string(ss.str()); - - // Have the listener test some properties of the Dictionary. - std::vector<std::string> properties_to_check; - properties_to_check.push_back( - "message_event.data.constructor.name === 'Object'"); - properties_to_check.push_back( - std::string("Object.keys(message_event.data).length === ") + - length_as_string); - // Check that the string is converted to a primitive JS string. - properties_to_check.push_back( - std::string("typeof message_event.data['bar'] === 'string'")); - ASSERT_SUBTEST_SUCCESS(CheckMessageProperties(dictionary, - properties_to_check)); - - // Set up the JavaScript message event listener to echo the data part of the - // message event back to us. - ASSERT_TRUE(AddEchoingListener("message_event.data")); - message_data_.clear(); - instance_->PostMessage(dictionary); - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_dictionary()); - ASSERT_TRUE(VarsEqual(dictionary, message_data_.back())); - - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestSendingResource() { - // Clean up after previous tests. This also swallows the message sent by Init - // if we didn't run the 'SendInInit' test. All tests other than 'SendInInit' - // should start with these. - WaitForMessages(); - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - std::string file_path("/"); - file_path += kTestFilename; - int content_length = static_cast<int>(strlen(kTestString)); - - // Create a file in the HTML5 temporary file system, in the Pepper plugin. - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - pp::FileRef write_file_ref(file_system, file_path.c_str()); - // Write to the file. - pp::FileIO write_file_io(instance_); - ASSERT_NE(0, write_file_io.pp_resource()); - callback.WaitForResult( - write_file_io.Open(write_file_ref, - PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - callback.WaitForResult(write_file_io.Write( - 0, kTestString, content_length, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(callback.result(), content_length); - write_file_io.Close(); - - // Pass the file system to JavaScript and have the listener test some - // properties of the file system. - pp::Var file_system_var(file_system); - std::vector<std::string> properties_to_check; - properties_to_check.push_back("message_event.data.root.isDirectory"); - properties_to_check.push_back( - "message_event.data.name.indexOf(" - " ':Temporary'," - " message_event.data.name.length - ':Temporary'.length) !== -1"); - ASSERT_SUBTEST_SUCCESS(CheckMessageProperties(file_system_var, - properties_to_check)); - - // Set up the JavaScript message event listener to echo the data part of the - // message event back to us. - ASSERT_TRUE(AddEchoingListener("message_event.data")); - // Send the file system in a message from the Pepper plugin to JavaScript. - message_data_.clear(); - instance_->PostMessage(file_system_var); - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - - // The JavaScript should have posted the file system back to us. Verify that - // it is a file system and read the file contents that we wrote earlier. - pp::Var var = message_data_.back(); - ASSERT_TRUE(var.is_resource()); - pp::Resource result = var.AsResource(); - ASSERT_TRUE(pp::FileSystem::IsFileSystem(result)); - { - pp::FileSystem received_file_system(result); - pp::FileRef file_ref(received_file_system, file_path.c_str()); - ASSERT_NE(0, file_ref.pp_resource()); - - // Ensure that the file can be queried. - TestCompletionCallbackWithOutput<PP_FileInfo> cc(instance_->pp_instance(), - callback_type()); - cc.WaitForResult(file_ref.Query(cc.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cc); - ASSERT_EQ(PP_OK, cc.result()); - ASSERT_EQ(cc.output().size, content_length); - - // Read the file and test that its contents match. - pp::FileIO file_io(instance_); - ASSERT_NE(0, file_io.pp_resource()); - callback.WaitForResult( - file_io.Open(file_ref, PP_FILEOPENFLAG_READ, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - std::vector<char> buffer_vector(content_length); - char* buffer = &buffer_vector[0]; // Note: Not null-terminated! - callback.WaitForResult( - file_io.Read(0, buffer, content_length, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(callback.result(), content_length); - ASSERT_EQ(0, memcmp(buffer, kTestString, content_length)); - } - - WaitForMessages(); - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestSendingComplexVar() { - // Clean up after previous tests. This also swallows the message sent by Init - // if we didn't run the 'SendInInit' test. All tests other than 'SendInInit' - // should start with these. - WaitForMessages(); - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - pp::Var string(kTestString); - pp::VarDictionary dictionary; - dictionary.Set(pp::Var("foo"), pp::Var(kTestBool)); - dictionary.Set(pp::Var("bar"), string); - dictionary.Set(pp::Var("abc"), pp::Var(kTestInt)); - dictionary.Set(pp::Var("def"), pp::Var()); - - // Reference to array. - pp::VarArray array; - array.Set(0, pp::Var(kTestBool)); - array.Set(1, string); - // Purposely leave index 2 empty (which will place an undefined var there). - array.Set(3, pp::Var(kTestInt)); - array.Set(4, pp::Var(kTestDouble)); - - dictionary.Set(pp::Var("array-ref1"), array); - dictionary.Set(pp::Var("array-ref2"), array); - - // Set up the JavaScript message event listener to echo the data part of the - // message event back to us. - ASSERT_TRUE(AddEchoingListener("message_event.data")); - instance_->PostMessage(dictionary); - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_dictionary()); - pp::VarDictionary result(message_data_.back()); - ASSERT_TRUE(VarsEqual(dictionary, message_data_.back())); - - WaitForMessages(); - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - // Set up a (dictionary -> array -> dictionary) cycle. Cycles shouldn't be - // transmitted. - pp::VarArray array2; - array2.Set(0, dictionary); - dictionary.Set(pp::Var("array2"), array2); - - ASSERT_TRUE(AddEchoingListener("message_event.data")); - instance_->PostMessage(dictionary); - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(WaitForMessages(), 0); - - // Break the cycles. - dictionary.Delete(pp::Var("array2")); - - WaitForMessages(); - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - // Test sending a cycle from JavaScript to the plugin. - ASSERT_TRUE(AddEchoingListener("message_event.data")); - PostMessageFromJavaScript("function() { var x = []; x[0] = x; return x; }"); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(WaitForMessages(), 0); - - WaitForMessages(); - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestMessageEvent() { - // Set up the JavaScript message event listener to pass us some values from - // the MessageEvent and make sure they match our expectations. - - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - // Have the listener pass back the class name of message_event and make sure - // it's "MessageEvent". - ASSERT_TRUE(AddEchoingListener("message_event.constructor.name")); - message_data_.clear(); - instance_->PostMessage(pp::Var(kTestInt)); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_string()); - ASSERT_EQ(message_data_.back().AsString(), "MessageEvent"); - ASSERT_TRUE(ClearListeners()); - - // Make sure all the non-data properties have the expected values. - bool success = AddEchoingListener("((message_event.origin === '')" - " && (message_event.lastEventId === '')" - " && (message_event.source === null)" - " && (message_event.ports.length === 0)" - " && (message_event.bubbles === false)" - " && (message_event.cancelable === false)" - ")"); - ASSERT_TRUE(success); - message_data_.clear(); - instance_->PostMessage(pp::Var(kTestInt)); - ASSERT_EQ(0, message_data_.size()); - ASSERT_EQ(1, WaitForMessages()); - ASSERT_TRUE(message_data_.back().is_bool()); - ASSERT_TRUE(message_data_.back().AsBool()); - ASSERT_TRUE(ClearListeners()); - - // Add some event handlers to make sure they receive messages. - ASSERT_TRUE(AddEchoingListener("1")); - ASSERT_TRUE(AddEchoingListener("2")); - ASSERT_TRUE(AddEchoingListener("3")); - - message_data_.clear(); - instance_->PostMessage(pp::Var(kTestInt)); - // Make sure we don't get a response in a re-entrant fashion. - ASSERT_EQ(0, message_data_.size()); - // We should get 3 messages. - ASSERT_EQ(WaitForMessages(), 3); - // Copy to a vector of doubles and sort; w3c does not specify the order for - // event listeners. (Copying is easier than writing an operator< for pp::Var.) - // - // See http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html. - VarVector::iterator iter(message_data_.begin()), the_end(message_data_.end()); - std::vector<double> double_vec; - for (; iter != the_end; ++iter) { - ASSERT_TRUE(iter->is_number()); - double_vec.push_back(iter->AsDouble()); - } - std::sort(double_vec.begin(), double_vec.end()); - ASSERT_DOUBLE_EQ(double_vec[0], 1.0); - ASSERT_DOUBLE_EQ(double_vec[1], 2.0); - ASSERT_DOUBLE_EQ(double_vec[2], 3.0); - - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestNoHandler() { - // Delete any lingering messages and event listeners. - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - - // Now send a message. We shouldn't get a response. - message_data_.clear(); - instance_->PostMessage(pp::Var()); - ASSERT_EQ(WaitForMessages(), 0); - ASSERT_TRUE(message_data_.empty()); - - PASS(); -} - -std::string TestPostMessage::TestExtraParam() { - // Delete any lingering messages and event listeners. - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - // Add a listener that will respond with 1 and an empty array (where the - // message port array would appear if it was Worker postMessage). - ASSERT_TRUE(AddEchoingListener("1, []")); - - // Now send a message. We shouldn't get a response. - message_data_.clear(); - instance_->PostMessage(pp::Var()); - ASSERT_EQ(WaitForMessages(), 0); - ASSERT_TRUE(message_data_.empty()); - - ASSERT_TRUE(ClearListeners()); - - PASS(); -} - -std::string TestPostMessage::TestNonMainThread() { - WaitForMessages(); - ASSERT_TRUE(ClearListeners()); - ASSERT_TRUE(AddEchoingListener("message_event.data")); - message_data_.clear(); - - // Set up a thread for each integer from 0 to (kThreadsToRun - 1). Make each - // thread send the number that matches its index kMessagesToSendPerThread - // times. For good measure, call postMessage from the main thread - // kMessagesToSendPerThread times. At the end, we make sure we got all the - // values we expected. - PP_Thread threads[kThreadsToRun]; - for (int32_t i = 0; i < kThreadsToRun; ++i) { - // Set up a thread to send a value of i. - void* arg = new InvokePostMessageThreadArg(instance_, pp::Var(i)); - PP_CreateThread(&threads[i], &InvokePostMessageThreadFunc, arg); - } - // Invoke PostMessage right now to send a value of (kThreadsToRun). - for (int32_t i = 0; i < kMessagesToSendPerThread; ++i) - instance_->PostMessage(pp::Var(kThreadsToRun)); - - // Now join all threads. - for (int32_t i = 0; i < kThreadsToRun; ++i) - PP_JoinThread(threads[i]); - - // PostMessage is asynchronous, so we should not receive a response yet. - ASSERT_EQ(0, message_data_.size()); - - // Make sure we got all values that we expected. Note that because it's legal - // for the JavaScript engine to treat our integers as floating points, we - // can't just use std::find or equality comparison. So we instead, we convert - // each incoming value to an integer, and count them in received_counts. - int32_t expected_num = (kThreadsToRun + 1) * kMessagesToSendPerThread; - // Count how many we receive per-index. - std::vector<int32_t> expected_counts(kThreadsToRun + 1, - kMessagesToSendPerThread); - std::vector<int32_t> received_counts(kThreadsToRun + 1, 0); - ASSERT_EQ(expected_num, WaitForMessages()); - for (int32_t i = 0; i < expected_num; ++i) { - const pp::Var& latest_var(message_data_[i]); - ASSERT_TRUE(latest_var.is_int() || latest_var.is_double()); - int32_t received_value = -1; - if (latest_var.is_int()) { - received_value = latest_var.AsInt(); - } else if (latest_var.is_double()) { - received_value = static_cast<int32_t>(latest_var.AsDouble() + 0.5); - } - ASSERT_TRUE(received_value >= 0); - ASSERT_TRUE(received_value <= kThreadsToRun); - ++received_counts[received_value]; - } - ASSERT_EQ(expected_counts, received_counts); - - message_data_.clear(); - ASSERT_TRUE(ClearListeners()); - - PASS(); -}
diff --git a/tests/test_post_message.h b/tests/test_post_message.h deleted file mode 100644 index f8e4fbf..0000000 --- a/tests/test_post_message.h +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_POST_MESSAGE_H_ -#define PPAPI_TESTS_TEST_POST_MESSAGE_H_ - -#include <string> -#include <vector> - -#include "ppapi/tests/test_case.h" - -class TestPostMessage : public TestCase { - public: - explicit TestPostMessage(TestingInstance* instance); - virtual ~TestPostMessage(); - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - // A handler for JS->Native calls to postMessage. Simply pushes - // the given value to the back of message_data_ - virtual void HandleMessage(const pp::Var& message_data); - - // Add a listener for message events which will echo back the given - // JavaScript expression by passing it to postMessage. JavaScript Variables - // available to the expression are: - // 'plugin' - the DOM element for the test plugin. - // 'message_event' - the message event parameter to the listener function. - // This also adds the new listener to an array called 'eventListeners' on the - // plugin's DOM element. This is used by ClearListeners(). - // Returns true on success, false on failure. - bool AddEchoingListener(const std::string& expression); - - // Posts a message from JavaScript to the plugin. |func| should be a - // JavaScript function which returns the variable to post. - bool PostMessageFromJavaScript(const std::string& func); - - // Clear any listeners that have been added using AddEchoingListener by - // calling removeEventListener for each. - // Returns true on success, false on failure. - bool ClearListeners(); - - // Wait for pending messages; return the number of messages that were pending - // at the time of invocation. - int WaitForMessages(); - - // Posts a message from JavaScript to the plugin and wait for it to arrive. - // |func| should be a JavaScript function(callback) which calls |callback| - // with the variable to post. This function will block until the message - // arrives on the plugin side (there is no need to use WaitForMessages()). - // Returns the number of messages that were pending at the time of invocation. - int PostAsyncMessageFromJavaScriptAndWait(const std::string& func); - - // Verifies that the given javascript assertions are true of the message - // (|test_data|) passed via PostMessage(). - std::string CheckMessageProperties( - const pp::Var& test_data, - const std::vector<std::string>& properties_to_check); - - // Test that we can send a message from Instance::Init. Note the actual - // message is sent in TestPostMessage::Init, and this test simply makes sure - // we got it. - std::string TestSendInInit(); - - // Test some basic functionality; make sure we can send data successfully - // in both directions. - std::string TestSendingData(); - - // Test sending string vars in both directions. - std::string TestSendingString(); - - // Test sending ArrayBuffer vars in both directions. - std::string TestSendingArrayBuffer(); - - // Test sending Array vars in both directions. - std::string TestSendingArray(); - - // Test sending Dictionary vars in both directions. - std::string TestSendingDictionary(); - - // Test sending Resource vars in both directions. - std::string TestSendingResource(); - - // Test sending a complex var with references and cycles in both directions. - std::string TestSendingComplexVar(); - - // Test the MessageEvent object that JavaScript received to make sure it is - // of the right type and has all the expected fields. - std::string TestMessageEvent(); - - // Test sending a message when no handler exists, make sure nothing happens. - std::string TestNoHandler(); - - // Test sending from JavaScript to the plugin with extra parameters, make sure - // nothing happens. - std::string TestExtraParam(); - - // Test sending messages off of the main thread. - std::string TestNonMainThread(); - - typedef std::vector<pp::Var> VarVector; - - // This is used to store pp::Var objects we receive via a call to - // HandleMessage. - VarVector message_data_; -}; - -#endif // PPAPI_TESTS_TEST_POST_MESSAGE_H_ -
diff --git a/tests/test_printing.cc b/tests/test_printing.cc deleted file mode 100644 index aa28248..0000000 --- a/tests/test_printing.cc +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_printing.h" - -#include "ppapi/cpp/dev/printing_dev.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/tests/testing_instance.h" - -namespace { -bool g_callback_triggered; -int32_t g_callback_result; -PP_PrintSettings_Dev g_print_settings; -} // namespace - -REGISTER_TEST_CASE(Printing); - -class TestPrinting_Dev : public pp::Printing_Dev { - public: - explicit TestPrinting_Dev(pp::Instance* instance) : - pp::Printing_Dev(instance) {} - virtual ~TestPrinting_Dev() {} - virtual uint32_t QuerySupportedPrintOutputFormats() { return 0; } - virtual int32_t PrintBegin( - const PP_PrintSettings_Dev& print_settings) { return 0; } - virtual pp::Resource PrintPages( - const PP_PrintPageNumberRange_Dev* page_ranges, - uint32_t page_range_count) { - return pp::Resource(); - } - virtual void PrintEnd() {} - virtual bool IsPrintScalingDisabled() { return false; } -}; - -TestPrinting::TestPrinting(TestingInstance* instance) - : TestCase(instance), - nested_event_(instance->pp_instance()) { - callback_factory_.Initialize(this); -} - -void TestPrinting::RunTests(const std::string& filter) { - RUN_TEST(GetDefaultPrintSettings, filter); -} - -std::string TestPrinting::TestGetDefaultPrintSettings() { - g_callback_triggered = false; - TestPrinting_Dev test_printing(instance_); - pp::CompletionCallbackWithOutput<PP_PrintSettings_Dev> cb = - callback_factory_.NewCallbackWithOutput(&TestPrinting::Callback); - test_printing.GetDefaultPrintSettings(cb); - nested_event_.Wait(); - - ASSERT_EQ(PP_OK, g_callback_result); - ASSERT_TRUE(g_callback_triggered); - - // Sanity check the |printable_area|, |content_area| and |paper_size| members. - // It is possible these values are outside these ranges but it shouldn't - // happen in practice and probably means there is an error in computing - // the default print settings. These values are in points. - ASSERT_TRUE(g_print_settings.printable_area.point.x < 200); - ASSERT_TRUE(g_print_settings.printable_area.point.y < 200); - ASSERT_TRUE(g_print_settings.printable_area.size.width < 2000); - ASSERT_TRUE(g_print_settings.printable_area.size.height < 2000); - - ASSERT_TRUE(g_print_settings.content_area.point.x < 200); - ASSERT_TRUE(g_print_settings.content_area.point.y < 200); - ASSERT_TRUE(g_print_settings.content_area.size.width < 2000); - ASSERT_TRUE(g_print_settings.content_area.size.height< 2000); - - ASSERT_TRUE(g_print_settings.paper_size.width < 2000); - ASSERT_TRUE(g_print_settings.paper_size.height < 2000); - - PASS(); -} - -void TestPrinting::Callback(int32_t result, - PP_PrintSettings_Dev& print_settings) { - g_callback_triggered = true; - g_callback_result = result; - g_print_settings = print_settings; - nested_event_.Signal(); -}
diff --git a/tests/test_printing.h b/tests/test_printing.h deleted file mode 100644 index 037b9b5..0000000 --- a/tests/test_printing.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_PRINTING_H_ -#define PPAPI_TESTS_TEST_PRINTING_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/tests/test_case.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/utility/completion_callback_factory.h" - -struct PP_PrintSettings_Dev; - -class TestPrinting : public TestCase { - public: - explicit TestPrinting(TestingInstance* instance); - - // TestCase implementation. - virtual void RunTests(const std::string& filter); - - private: - // Tests. - std::string TestGetDefaultPrintSettings(); - - void Callback(int32_t result, - PP_PrintSettings_Dev&); - - NestedEvent nested_event_; - - pp::CompletionCallbackFactory<TestPrinting> callback_factory_; -}; - -#endif // PPAPI_TESTS_TEST_PRINTING_H_
diff --git a/tests/test_struct_sizes.c b/tests/test_struct_sizes.c deleted file mode 100644 index 1e8ccd2..0000000 --- a/tests/test_struct_sizes.c +++ /dev/null
@@ -1,28 +0,0 @@ -/* Copyright 2010 The Chromium Authors - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - * - * This test ensures (at compile time) that some types have the expected size in - * C. The purpose is to ensure that the ABI of PPAPI is known, consistent, and - * stable. Only structs that have architecture-dependent size are checked by - * this test. These structs use at least one type which differs in size between - * 64-bit and 32-bit (e.g. pointers or long). By convention, we require other - * types to be of consistent size on 32-bit and 64-bit architectures. - */ - -#include "ppapi/tests/all_c_includes.h" - -#if !defined(__native_client__) && (defined(_M_X64) || defined(__x86_64__) || defined(__aarch64__) || defined(__mips64)) -/* This section is for 64-bit compilation on Windows, Mac, and Linux. Native - client follows ILP32 even if -m64 is used, so NaCl code is explicitly treated - as 32-bit. This means pointers are always 4 bytes in native client, and it - matches Win32 (see below). - */ -#include "ppapi/tests/arch_dependent_sizes_64.h" -#else -/* This section is for compilation on 32-bit targets plus native client (in both - 32-bit and 64-bit mode, since native client always conforms to ILP32). - */ -#include "ppapi/tests/arch_dependent_sizes_32.h" -#endif -
diff --git a/tests/test_tcp_server_socket_private.cc b/tests/test_tcp_server_socket_private.cc deleted file mode 100644 index df399fc..0000000 --- a/tests/test_tcp_server_socket_private.cc +++ /dev/null
@@ -1,375 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_tcp_server_socket_private.h" - -#include <cstdio> -#include <vector> - -#include "ppapi/cpp/pass_ref.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/cpp/private/tcp_server_socket_private.h" -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -using pp::NetAddressPrivate; -using pp::TCPServerSocketPrivate; -using pp::TCPSocketPrivate; - -namespace { - -// Used by pp::CompletionCallbacks that want to delete a PP_Resource, passed as -// |user_data|, on completion. -void DeleteResource(void* user_data, int32_t flags) { - delete reinterpret_cast<PP_Resource*>(user_data); -} - -} // namespace - -REGISTER_TEST_CASE(TCPServerSocketPrivate); - -TestTCPServerSocketPrivate::TestTCPServerSocketPrivate( - TestingInstance* instance) : TestCase(instance) { -} - -bool TestTCPServerSocketPrivate::Init() { - bool tcp_server_socket_private_is_available = - TCPServerSocketPrivate::IsAvailable(); - if (!tcp_server_socket_private_is_available) { - instance_->AppendError( - "PPB_TCPServerSocket_Private interface not available"); - } - - bool tcp_socket_private_is_available = TCPSocketPrivate::IsAvailable(); - if (!tcp_socket_private_is_available) - instance_->AppendError("PPB_TCPSocket_Private interface not available"); - - bool net_address_private_is_available = NetAddressPrivate::IsAvailable(); - if (!net_address_private_is_available) - instance_->AppendError("PPB_NetAddress_Private interface not available"); - - bool init_host_port = GetLocalHostPort(instance_->pp_instance(), - &host_, &port_); - if (!init_host_port) - instance_->AppendError("Can't init host and port"); - - return tcp_server_socket_private_is_available && - tcp_socket_private_is_available && - net_address_private_is_available && - init_host_port && - CheckTestingInterface() && - EnsureRunningOverHTTP(); -} - -void TestTCPServerSocketPrivate::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestTCPServerSocketPrivate, Listen, filter); - RUN_CALLBACK_TEST(TestTCPServerSocketPrivate, Backlog, filter); - - RUN_CALLBACK_TEST(TestTCPServerSocketPrivate, ListenFails, filter); - RUN_CALLBACK_TEST(TestTCPServerSocketPrivate, ListenHangs, filter); - RUN_CALLBACK_TEST(TestTCPServerSocketPrivate, AcceptFails, filter); - RUN_CALLBACK_TEST(TestTCPServerSocketPrivate, AcceptHangs, filter); -} - -std::string TestTCPServerSocketPrivate::GetLocalAddress( - PP_NetAddress_Private* address) { - TCPSocketPrivate socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket.Connect(host_.c_str(), port_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_TRUE(socket.GetLocalAddress(address)); - socket.Disconnect(); - PASS(); -} - -std::string TestTCPServerSocketPrivate::SyncRead(TCPSocketPrivate* socket, - char* buffer, - size_t num_bytes) { - while (num_bytes > 0) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Read(buffer, static_cast<int32_t>(num_bytes), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_TRUE(callback.result() >= 0); - buffer += callback.result(); - num_bytes -= callback.result(); - } - PASS(); -} - -std::string TestTCPServerSocketPrivate::SyncWrite(TCPSocketPrivate* socket, - const char* buffer, - size_t num_bytes) { - while (num_bytes > 0) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Write(buffer, static_cast<int32_t>(num_bytes), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_TRUE(callback.result() >= 0); - buffer += callback.result(); - num_bytes -= callback.result(); - } - PASS(); -} - -std::string TestTCPServerSocketPrivate::SyncConnect( - TCPSocketPrivate* socket, - PP_NetAddress_Private* address) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->ConnectWithNetAddress(address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -void TestTCPServerSocketPrivate::ForceConnect(TCPSocketPrivate* socket, - PP_NetAddress_Private* address) { - std::string error_message; - do { - error_message = SyncConnect(socket, address); - } while (!error_message.empty()); -} - -std::string TestTCPServerSocketPrivate::SyncListenFails( - pp::TCPServerSocketPrivate* socket) { - uint8_t localhost_ip[4] = {127, 0, 0, 1}; - PP_NetAddress_Private ipv4; - ASSERT_TRUE( - NetAddressPrivate::CreateFromIPv4Address(localhost_ip, 80, &ipv4)); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Listen(&ipv4, 2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - PASS(); -} - -std::string TestTCPServerSocketPrivate::SyncAcceptFails( - pp::TCPServerSocketPrivate* socket) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - PP_Resource resource; - callback.WaitForResult(socket->Accept(&resource, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - PASS(); -} - -std::string TestTCPServerSocketPrivate::SyncListen( - TCPServerSocketPrivate* socket, - PP_NetAddress_Private* address, - int32_t backlog) { - PP_NetAddress_Private base_address; - ASSERT_SUBTEST_SUCCESS(GetLocalAddress(&base_address)); - if (!NetAddressPrivate::ReplacePort(base_address, 0, address)) - return ReportError("PPB_NetAddress_Private::ReplacePort", 0); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Listen(address, backlog, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - int32_t rv = socket->GetLocalAddress(address); - ASSERT_EQ(PP_OK, rv); - ASSERT_TRUE(NetAddressPrivate::GetPort(*address) != 0); - PASS(); -} - -std::string TestTCPServerSocketPrivate::TestListen() { - static const int kBacklog = 2; - - TCPServerSocketPrivate server_socket(instance_); - PP_NetAddress_Private address; - ASSERT_SUBTEST_SUCCESS(SyncListen(&server_socket, &address, kBacklog)); - - // We can't use a blocking callback for Accept, because it will wait forever - // for the client to connect, since the client connects after. - TestCompletionCallback accept_callback(instance_->pp_instance(), PP_REQUIRED); - // We need to make sure there's a message loop to run accept_callback on. - pp::MessageLoop current_thread_loop(pp::MessageLoop::GetCurrent()); - if (current_thread_loop.is_null() && testing_interface_->IsOutOfProcess()) { - current_thread_loop = pp::MessageLoop(instance_); - current_thread_loop.AttachToCurrentThread(); - } - - PP_Resource resource; - int32_t accept_rv = server_socket.Accept(&resource, - accept_callback.GetCallback()); - - TCPSocketPrivate client_socket(instance_); - ForceConnect(&client_socket, &address); - - PP_NetAddress_Private client_local_addr, client_remote_addr; - ASSERT_TRUE(client_socket.GetLocalAddress(&client_local_addr)); - ASSERT_TRUE(client_socket.GetRemoteAddress(&client_remote_addr)); - - accept_callback.WaitForResult(accept_rv); - CHECK_CALLBACK_BEHAVIOR(accept_callback); - ASSERT_EQ(PP_OK, accept_callback.result()); - - ASSERT_TRUE(resource != 0); - TCPSocketPrivate accepted_socket(pp::PassRef(), resource); - PP_NetAddress_Private accepted_local_addr, accepted_remote_addr; - ASSERT_TRUE(accepted_socket.GetLocalAddress(&accepted_local_addr)); - ASSERT_TRUE(accepted_socket.GetRemoteAddress(&accepted_remote_addr)); - ASSERT_TRUE(NetAddressPrivate::AreEqual(client_local_addr, - accepted_remote_addr)); - - const char kSentByte = 'a'; - ASSERT_SUBTEST_SUCCESS(SyncWrite(&client_socket, - &kSentByte, - sizeof(kSentByte))); - - char received_byte; - ASSERT_SUBTEST_SUCCESS(SyncRead(&accepted_socket, - &received_byte, - sizeof(received_byte))); - ASSERT_EQ(kSentByte, received_byte); - - accepted_socket.Disconnect(); - client_socket.Disconnect(); - server_socket.StopListening(); - - PASS(); -} - -std::string TestTCPServerSocketPrivate::TestBacklog() { - static const size_t kBacklog = 5; - - TCPServerSocketPrivate server_socket(instance_); - PP_NetAddress_Private address; - ASSERT_SUBTEST_SUCCESS(SyncListen(&server_socket, &address, 2 * kBacklog)); - - std::vector<TCPSocketPrivate*> client_sockets(kBacklog); - std::vector<TestCompletionCallback*> connect_callbacks(kBacklog); - std::vector<int32_t> connect_rv(kBacklog); - for (size_t i = 0; i < kBacklog; ++i) { - client_sockets[i] = new TCPSocketPrivate(instance_); - connect_callbacks[i] = new TestCompletionCallback(instance_->pp_instance(), - callback_type()); - connect_rv[i] = client_sockets[i]->ConnectWithNetAddress( - &address, - connect_callbacks[i]->GetCallback()); - } - - std::vector<PP_Resource> resources(kBacklog); - std::vector<TCPSocketPrivate*> accepted_sockets(kBacklog); - for (size_t i = 0; i < kBacklog; ++i) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - server_socket.Accept(&resources[i], callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - ASSERT_TRUE(resources[i] != 0); - accepted_sockets[i] = new TCPSocketPrivate(pp::PassRef(), resources[i]); - } - - for (size_t i = 0; i < kBacklog; ++i) { - connect_callbacks[i]->WaitForResult(connect_rv[i]); - CHECK_CALLBACK_BEHAVIOR(*connect_callbacks[i]); - ASSERT_EQ(PP_OK, connect_callbacks[i]->result()); - } - - for (size_t i = 0; i < kBacklog; ++i) { - const char byte = static_cast<char>('a' + i); - ASSERT_SUBTEST_SUCCESS(SyncWrite(client_sockets[i], &byte, sizeof(byte))); - } - - bool byte_received[kBacklog] = {}; - for (size_t i = 0; i < kBacklog; ++i) { - char byte; - ASSERT_SUBTEST_SUCCESS(SyncRead(accepted_sockets[i], &byte, sizeof(byte))); - const size_t index = byte - 'a'; - ASSERT_FALSE(byte_received[index]); - byte_received[index] = true; - } - - for (size_t i = 0; i < kBacklog; ++i) { - client_sockets[i]->Disconnect(); - delete client_sockets[i]; - delete connect_callbacks[i]; - accepted_sockets[i]->Disconnect(); - delete accepted_sockets[i]; - } - - server_socket.StopListening(); - PASS(); -} - -std::string TestTCPServerSocketPrivate::TestListenFails() { - TCPServerSocketPrivate socket(instance_); - ASSERT_SUBTEST_SUCCESS(SyncListenFails(&socket)); - - // After a listen failure, accept should fail, too. - ASSERT_SUBTEST_SUCCESS(SyncAcceptFails(&socket)); - - // Listening again fails, just because of the test fixture simulating another - // failure. - ASSERT_SUBTEST_SUCCESS(SyncListenFails(&socket)); - - PASS(); -} - -std::string TestTCPServerSocketPrivate::TestListenHangs() { - TCPServerSocketPrivate socket(instance_); - - uint8_t localhost_ip[4] = {127, 0, 0, 1}; - PP_NetAddress_Private ipv4; - ASSERT_TRUE( - NetAddressPrivate::CreateFromIPv4Address(localhost_ip, 80, &ipv4)); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - socket.Listen(&ipv4, 2 /* backlog */, DoNothingCallback()); - PASS(); -} - -std::string TestTCPServerSocketPrivate::TestAcceptFails() { - TCPServerSocketPrivate socket(instance_); - uint8_t localhost_ip[4] = {127, 0, 0, 1}; - PP_NetAddress_Private ipv4; - ASSERT_TRUE( - NetAddressPrivate::CreateFromIPv4Address(localhost_ip, 80, &ipv4)); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket.Listen(&ipv4, 2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Accept calls should fail. - ASSERT_SUBTEST_SUCCESS(SyncAcceptFails(&socket)); - ASSERT_SUBTEST_SUCCESS(SyncAcceptFails(&socket)); - - // Listening again fails, since the socket is already listening. - ASSERT_SUBTEST_SUCCESS(SyncListenFails(&socket)); - - PASS(); -} - -std::string TestTCPServerSocketPrivate::TestAcceptHangs() { - TCPServerSocketPrivate socket(instance_); - uint8_t localhost_ip[4] = {127, 0, 0, 1}; - PP_NetAddress_Private ipv4; - ASSERT_TRUE( - NetAddressPrivate::CreateFromIPv4Address(localhost_ip, 80, &ipv4)); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket.Listen(&ipv4, 2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - PP_Resource* resource = new PP_Resource(); - socket.Accept(resource, - pp::CompletionCallback(&DeleteResource, resource, - PP_COMPLETIONCALLBACK_FLAG_OPTIONAL)); - PASS(); -}
diff --git a/tests/test_tcp_server_socket_private.h b/tests/test_tcp_server_socket_private.h deleted file mode 100644 index 7b5b7d0..0000000 --- a/tests/test_tcp_server_socket_private.h +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TCP_SERVER_SOCKET_PRIVATE_H_ -#define PPAPI_TESTS_TEST_TCP_SERVER_SOCKET_PRIVATE_H_ - -#include <stddef.h> - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -struct PP_NetAddress_Private; - -namespace pp { - -class TCPServerSocketPrivate; -class TCPSocketPrivate; - -} // namespace pp - -class TestTCPServerSocketPrivate : public TestCase { - public: - explicit TestTCPServerSocketPrivate(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string GetLocalAddress(PP_NetAddress_Private* address); - std::string SyncRead(pp::TCPSocketPrivate* socket, - char* buffer, - size_t num_bytes); - std::string SyncWrite(pp::TCPSocketPrivate* socket, - const char* buffer, - size_t num_bytes); - std::string SyncConnect(pp::TCPSocketPrivate* socket, - PP_NetAddress_Private* address); - void ForceConnect(pp::TCPSocketPrivate* socket, - PP_NetAddress_Private* address); - std::string SyncListen(pp::TCPServerSocketPrivate* socket, - PP_NetAddress_Private* address, - int32_t backlog); - - // Checks that a listen/accept attempt on |socket| fails. - std::string SyncListenFails(pp::TCPServerSocketPrivate* socket); - std::string SyncAcceptFails(pp::TCPServerSocketPrivate* socket); - - std::string TestListen(); - std::string TestBacklog(); - - // The higher level test fixture is responsible for making socket methods - // behave in the expected manner. The *Fails tests expect the specified event - // to fail with PP_ERROR_FAILED, and the *Hangs tests expect the specified - // operation to never complete, at least until teardown starts. - std::string TestListenFails(); - std::string TestListenHangs(); - std::string TestAcceptFails(); - std::string TestAcceptHangs(); - - std::string host_; - uint16_t port_; -}; - -#endif // PPAPI_TESTS_TEST_TCP_SERVER_SOCKET_PRIVATE_H_
diff --git a/tests/test_tcp_server_socket_private_disallowed.cc b/tests/test_tcp_server_socket_private_disallowed.cc deleted file mode 100644 index 3605684..0000000 --- a/tests/test_tcp_server_socket_private_disallowed.cc +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_tcp_server_socket_private_disallowed.h" - -#include <cstddef> - -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(TCPServerSocketPrivateDisallowed); - -TestTCPServerSocketPrivateDisallowed::TestTCPServerSocketPrivateDisallowed( - TestingInstance* instance) - : TestCase(instance), - core_interface_(NULL), - tcp_server_socket_private_interface_(NULL) { -} - -bool TestTCPServerSocketPrivateDisallowed::Init() { - core_interface_ = static_cast<const PPB_Core*>( - pp::Module::Get()->GetBrowserInterface(PPB_CORE_INTERFACE)); - if (!core_interface_) - instance_->AppendError("PPB_Core interface not available"); - - tcp_server_socket_private_interface_ = - static_cast<const PPB_TCPServerSocket_Private*>( - pp::Module::Get()->GetBrowserInterface( - PPB_TCPSERVERSOCKET_PRIVATE_INTERFACE)); - if (!tcp_server_socket_private_interface_) { - instance_->AppendError( - "PPB_TCPServerSocket_Private interface not available"); - } - - bool net_address_private_is_available = pp::NetAddressPrivate::IsAvailable(); - if (!net_address_private_is_available) - instance_->AppendError("PPB_NetAddress_Private interface not available"); - - return core_interface_ && - tcp_server_socket_private_interface_ && - net_address_private_is_available && - CheckTestingInterface(); -} - -void TestTCPServerSocketPrivateDisallowed::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestTCPServerSocketPrivateDisallowed, Listen, filter); -} - -std::string TestTCPServerSocketPrivateDisallowed::TestListen() { - PP_Resource socket = - tcp_server_socket_private_interface_->Create(instance_->pp_instance()); - ASSERT_TRUE(socket != 0); - ASSERT_TRUE(tcp_server_socket_private_interface_->IsTCPServerSocket(socket)); - - PP_NetAddress_Private base_address, address; - pp::NetAddressPrivate::GetAnyAddress(false, &base_address); - ASSERT_TRUE(pp::NetAddressPrivate::ReplacePort( - base_address, 0, &address)); - TestCompletionCallback callback(instance_->pp_instance()); - callback.WaitForResult(tcp_server_socket_private_interface_->Listen( - socket, - &address, - 1, - callback.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_NE(PP_OK, callback.result()); - PASS(); -}
diff --git a/tests/test_tcp_server_socket_private_disallowed.h b/tests/test_tcp_server_socket_private_disallowed.h deleted file mode 100644 index c0ad3eb..0000000 --- a/tests/test_tcp_server_socket_private_disallowed.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TCP_SERVER_SOCKET_PRIVATE_DISALLOWED_H_ -#define PPAPI_TESTS_TEST_TCP_SERVER_SOCKET_PRIVATE_DISALLOWED_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/private/ppb_tcp_server_socket_private.h" -#include "ppapi/tests/test_case.h" - -class TestTCPServerSocketPrivateDisallowed : public TestCase { - public: - explicit TestTCPServerSocketPrivateDisallowed(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestListen(); - - const PPB_Core* core_interface_; - const PPB_TCPServerSocket_Private* tcp_server_socket_private_interface_; -}; - -#endif // PPAPI_TESTS_TEST_TCP_SERVER_SOCKET_PRIVATE_DISALLOWED_H_
diff --git a/tests/test_tcp_socket.cc b/tests/test_tcp_socket.cc deleted file mode 100644 index 83a2b3e..0000000 --- a/tests/test_tcp_socket.cc +++ /dev/null
@@ -1,1052 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_tcp_socket.h" - -#include <vector> - -#include "ppapi/cpp/message_loop.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -// Validates the first line of an HTTP response. -bool ValidateHttpResponse(const std::string& s) { - // Just check that it begins with "HTTP/" and ends with a "\r\n". - return s.size() >= 5 && - s.substr(0, 5) == "HTTP/" && - s.substr(s.size() - 2) == "\r\n"; -} - -} // namespace - -REGISTER_TEST_CASE(TCPSocket); - -TestTCPSocket::TestTCPSocket(TestingInstance* instance) - : TestCase(instance), - socket_interface_1_0_(NULL) { -} - -bool TestTCPSocket::Init() { - if (!pp::TCPSocket::IsAvailable()) - return false; - socket_interface_1_0_ = - static_cast<const PPB_TCPSocket_1_0*>( - pp::Module::Get()->GetBrowserInterface(PPB_TCPSOCKET_INTERFACE_1_0)); - if (!socket_interface_1_0_) - return false; - - // We need something to connect to, so we connect to the HTTP server whence we - // came. Grab the host and port. - if (!EnsureRunningOverHTTP()) - return false; - - std::string host; - uint16_t port = 0; - if (!GetLocalHostPort(instance_->pp_instance(), &host, &port)) - return false; - - if (!ResolveHost(instance_->pp_instance(), host, port, &test_server_addr_)) - return false; - - return true; -} - -void TestTCPSocket::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestTCPSocket, Connect, filter); - RUN_CALLBACK_TEST(TestTCPSocket, ReadWrite, filter); - RUN_CALLBACK_TEST(TestTCPSocket, SetOption, filter); - RUN_CALLBACK_TEST(TestTCPSocket, Listen, filter); - RUN_CALLBACK_TEST(TestTCPSocket, Backlog, filter); - RUN_CALLBACK_TEST(TestTCPSocket, Interface_1_0, filter); - RUN_CALLBACK_TEST(TestTCPSocket, UnexpectedCalls, filter); - - RUN_CALLBACK_TEST(TestTCPSocket, ConnectFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, ConnectHangs, filter); - RUN_CALLBACK_TEST(TestTCPSocket, WriteFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, ReadFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, SetSendBufferSizeFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, SetReceiveBufferSizeFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, SetNoDelayFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, BindFailsConnectSucceeds, filter); - RUN_CALLBACK_TEST(TestTCPSocket, BindFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, BindHangs, filter); - RUN_CALLBACK_TEST(TestTCPSocket, ListenFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, ListenHangs, filter); - RUN_CALLBACK_TEST(TestTCPSocket, AcceptFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, AcceptHangs, filter); - RUN_CALLBACK_TEST(TestTCPSocket, AcceptedSocketWriteFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, AcceptedSocketReadFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, BindConnectFails, filter); - RUN_CALLBACK_TEST(TestTCPSocket, BindConnectHangs, filter); -} - -std::string TestTCPSocket::TestConnect() { - { - // The basic case. - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - pp::NetAddress local_addr, remote_addr; - local_addr = socket.GetLocalAddress(); - remote_addr = socket.GetRemoteAddress(); - - ASSERT_NE(0, local_addr.pp_resource()); - ASSERT_NE(0, remote_addr.pp_resource()); - ASSERT_TRUE(EqualNetAddress(test_server_addr_, remote_addr)); - - socket.Close(); - } - - { - // Connect a bound socket. - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - pp::NetAddress any_port_address; - ASSERT_SUBTEST_SUCCESS(GetAddressToBind(&any_port_address)); - - cb.WaitForResult(socket.Bind(any_port_address, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - pp::NetAddress local_addr, remote_addr; - local_addr = socket.GetLocalAddress(); - remote_addr = socket.GetRemoteAddress(); - - ASSERT_NE(0, local_addr.pp_resource()); - ASSERT_NE(0, remote_addr.pp_resource()); - ASSERT_TRUE(EqualNetAddress(test_server_addr_, remote_addr)); - ASSERT_NE(0u, GetPort(local_addr)); - - socket.Close(); - } - - PASS(); -} - -std::string TestTCPSocket::TestReadWrite() { - pp::TCPSocket socket(instance_); - { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - } - - ASSERT_SUBTEST_SUCCESS(WriteToSocket(&socket, "GET / HTTP/1.0\r\n\r\n")); - - // Read up to the first \n and check that it looks like valid HTTP response. - std::string s; - ASSERT_SUBTEST_SUCCESS(ReadFirstLineFromSocket(&socket, &s)); - ASSERT_TRUE(ValidateHttpResponse(s)); - - // Read until the server closes the socket. - std::string read_data; - int read_error; - ASSERT_SUBTEST_SUCCESS( - ReadFromSocketUntilError(&socket, &read_data, &read_error)); - ASSERT_EQ(PP_OK, read_error); - - // Reading again from the socket after getting an EOF should result in an - // error. - read_data = ""; - ASSERT_SUBTEST_SUCCESS( - ReadFromSocketUntilError(&socket, &read_data, &read_error)); - ASSERT_EQ(PP_ERROR_FAILED, read_error); - ASSERT_EQ("", read_data); - - char write_data[32 * 1024] = {}; - // Write to the socket until there's an error, just to make sure the error - // handling code works. As with the read case, go through two failures - // (which may or may not fail with the same error code). - int failures = 0; - while (true) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Write(write_data, - static_cast<int32_t>(sizeof(write_data)), - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - if (cb.result() > 0) { - ASSERT_EQ(0, failures); - continue; - } - // While this will most likely be PP_ERROR_CONNECTION_ABORTED, it seems best - // not to rely on that, as write errors can be a bit finicky. - ASSERT_LT(cb.result(), 0); - ASSERT_NE(PP_ERROR_FAILED, cb.result()); - ASSERT_NE(PP_OK_COMPLETIONPENDING, cb.result()); - ++failures; - - if (failures == 2) - break; - } - - PASS(); -} - -std::string TestTCPSocket::TestSetOption() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb_1(instance_->pp_instance(), callback_type()); - TestCompletionCallback cb_2(instance_->pp_instance(), callback_type()); - TestCompletionCallback cb_3(instance_->pp_instance(), callback_type()); - - // These options can be set even before the socket is connected. - int32_t result_1 = socket.SetOption(PP_TCPSOCKET_OPTION_NO_DELAY, - true, cb_1.GetCallback()); - int32_t result_2 = socket.SetOption(PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE, - 256, cb_2.GetCallback()); - int32_t result_3 = socket.SetOption(PP_TCPSOCKET_OPTION_RECV_BUFFER_SIZE, - 512, cb_3.GetCallback()); - - cb_1.WaitForResult(result_1); - CHECK_CALLBACK_BEHAVIOR(cb_1); - ASSERT_EQ(PP_OK, cb_1.result()); - - cb_2.WaitForResult(result_2); - CHECK_CALLBACK_BEHAVIOR(cb_2); - ASSERT_EQ(PP_OK, cb_2.result()); - - cb_3.WaitForResult(result_3); - CHECK_CALLBACK_BEHAVIOR(cb_3); - ASSERT_EQ(PP_OK, cb_3.result()); - - cb_1.WaitForResult(socket.Connect(test_server_addr_, cb_1.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb_1); - ASSERT_EQ(PP_OK, cb_1.result()); - - result_1 = socket.SetOption(PP_TCPSOCKET_OPTION_NO_DELAY, - false, cb_1.GetCallback()); - result_2 = socket.SetOption(PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE, - 512, cb_2.GetCallback()); - result_3 = socket.SetOption(PP_TCPSOCKET_OPTION_RECV_BUFFER_SIZE, - 1024, cb_3.GetCallback()); - - cb_1.WaitForResult(result_1); - CHECK_CALLBACK_BEHAVIOR(cb_1); - ASSERT_EQ(PP_OK, cb_1.result()); - - cb_2.WaitForResult(result_2); - CHECK_CALLBACK_BEHAVIOR(cb_2); - ASSERT_EQ(PP_OK, cb_2.result()); - - cb_3.WaitForResult(result_3); - CHECK_CALLBACK_BEHAVIOR(cb_3); - ASSERT_EQ(PP_OK, cb_3.result()); - - PASS(); -} - -std::string TestTCPSocket::TestListen() { - // TODO(mmenke): Whenever this test is run, the PPAPI process DCHECKs on - // shutdown when a ref count is decremented on the wrong thread. Someone - // should probably look into that. - static const int kBacklog = 2; - - pp::TCPSocket server_socket(instance_); - ASSERT_SUBTEST_SUCCESS(StartListen(&server_socket, kBacklog)); - - // We can't use a blocking callback for Accept, because it will wait forever - // for the client to connect, since the client connects after. - TestCompletionCallbackWithOutput<pp::TCPSocket> - accept_callback(instance_->pp_instance(), PP_REQUIRED); - // We need to make sure there's a message loop to run accept_callback on. - pp::MessageLoop current_thread_loop(pp::MessageLoop::GetCurrent()); - if (current_thread_loop.is_null() && testing_interface_->IsOutOfProcess()) { - current_thread_loop = pp::MessageLoop(instance_); - current_thread_loop.AttachToCurrentThread(); - } - - int32_t accept_rv = server_socket.Accept(accept_callback.GetCallback()); - - pp::TCPSocket client_socket; - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - do { - client_socket = pp::TCPSocket(instance_); - - callback.WaitForResult(client_socket.Connect( - server_socket.GetLocalAddress(), callback.GetCallback())); - } while (callback.result() != PP_OK); - - pp::NetAddress client_local_addr = client_socket.GetLocalAddress(); - pp::NetAddress client_remote_addr = client_socket.GetRemoteAddress(); - ASSERT_FALSE(client_local_addr.is_null()); - ASSERT_FALSE(client_remote_addr.is_null()); - - accept_callback.WaitForResult(accept_rv); - CHECK_CALLBACK_BEHAVIOR(accept_callback); - ASSERT_EQ(PP_OK, accept_callback.result()); - - pp::TCPSocket accepted_socket(accept_callback.output()); - pp::NetAddress accepted_local_addr = accepted_socket.GetLocalAddress(); - pp::NetAddress accepted_remote_addr = accepted_socket.GetRemoteAddress(); - ASSERT_FALSE(accepted_local_addr.is_null()); - ASSERT_FALSE(accepted_remote_addr.is_null()); - - ASSERT_TRUE(EqualNetAddress(client_local_addr, accepted_remote_addr)); - - const std::string kSentData = "a"; - ASSERT_SUBTEST_SUCCESS(WriteToSocket(&client_socket, kSentData)); - - // Close the client socket to be able to read until EOF. - client_socket.Close(); - - std::string read_data; - int read_error; - ASSERT_SUBTEST_SUCCESS( - ReadFromSocketUntilError(&accepted_socket, &read_data, &read_error)); - ASSERT_EQ(kSentData, read_data); - ASSERT_EQ(PP_OK, read_error); - - accepted_socket.Close(); - server_socket.Close(); - - PASS(); -} - -std::string TestTCPSocket::TestBacklog() { - static const size_t kBacklog = 5; - - pp::TCPSocket server_socket(instance_); - ASSERT_SUBTEST_SUCCESS(StartListen(&server_socket, 2 * kBacklog)); - - std::vector<pp::TCPSocket*> client_sockets(kBacklog); - std::vector<TestCompletionCallback*> connect_callbacks(kBacklog); - std::vector<int32_t> connect_rv(kBacklog); - pp::NetAddress address = server_socket.GetLocalAddress(); - for (size_t i = 0; i < kBacklog; ++i) { - client_sockets[i] = new pp::TCPSocket(instance_); - connect_callbacks[i] = new TestCompletionCallback(instance_->pp_instance(), - callback_type()); - connect_rv[i] = client_sockets[i]->Connect( - address, connect_callbacks[i]->GetCallback()); - } - - std::vector<pp::TCPSocket*> accepted_sockets(kBacklog); - for (size_t i = 0; i < kBacklog; ++i) { - TestCompletionCallbackWithOutput<pp::TCPSocket> callback( - instance_->pp_instance(), callback_type()); - callback.WaitForResult(server_socket.Accept(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - accepted_sockets[i] = new pp::TCPSocket(callback.output()); - ASSERT_FALSE(accepted_sockets[i]->is_null()); - } - - for (size_t i = 0; i < kBacklog; ++i) { - connect_callbacks[i]->WaitForResult(connect_rv[i]); - CHECK_CALLBACK_BEHAVIOR(*connect_callbacks[i]); - ASSERT_EQ(PP_OK, connect_callbacks[i]->result()); - } - - for (size_t i = 0; i < kBacklog; ++i) { - const char byte = static_cast<char>('a' + i); - ASSERT_SUBTEST_SUCCESS(WriteToSocket(client_sockets[i], - std::string(1, byte))); - } - - bool byte_received[kBacklog] = {}; - for (size_t i = 0; i < kBacklog; ++i) { - char byte; - ASSERT_SUBTEST_SUCCESS(ReadFromSocket( - accepted_sockets[i], &byte, sizeof(byte))); - const size_t index = byte - 'a'; - ASSERT_GE(index, 0u); - ASSERT_LT(index, kBacklog); - ASSERT_FALSE(byte_received[index]); - byte_received[index] = true; - } - - for (size_t i = 0; i < kBacklog; ++i) { - ASSERT_TRUE(byte_received[i]); - - delete client_sockets[i]; - delete connect_callbacks[i]; - delete accepted_sockets[i]; - } - - PASS(); -} - -std::string TestTCPSocket::TestInterface_1_0() { - PP_Resource socket = socket_interface_1_0_->Create(instance_->pp_instance()); - ASSERT_NE(0, socket); - - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket_interface_1_0_->Connect( - socket, test_server_addr_.pp_resource(), - cb.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - ASSERT_SUBTEST_SUCCESS(WriteToSocket_1_0(socket, "GET / HTTP/1.0\r\n\r\n")); - - // Read up to the first \n and check that it looks like valid HTTP response. - std::string s; - ASSERT_SUBTEST_SUCCESS(ReadFirstLineFromSocket_1_0(socket, &s)); - ASSERT_TRUE(ValidateHttpResponse(s)); - - pp::Module::Get()->core()->ReleaseResource(socket); - PASS(); -} - -std::string TestTCPSocket::TestUnexpectedCalls() { - // Tests that calls that are not expected given a sockets current state fail - // with PP_ERROR_FAILED without breaking future operations on the socket. - - // Test a listen socket. - { - pp::TCPSocket socket(instance_); - ASSERT_SUBTEST_SUCCESS( - RunCommandsExpendingFailures(&socket, kListen | kAccept | kReadWrite)); - - // Connect - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - ASSERT_SUBTEST_SUCCESS( - RunCommandsExpendingFailures(&socket, kListen | kAccept | kConnect)); - - // Write - ASSERT_SUBTEST_SUCCESS(WriteToSocket(&socket, "GET / HTTP/1.0\r\n\r\n")); - ASSERT_SUBTEST_SUCCESS( - RunCommandsExpendingFailures(&socket, kListen | kAccept | kConnect)); - - // Read - std::string s; - ASSERT_SUBTEST_SUCCESS(ReadFirstLineFromSocket(&socket, &s)); - ASSERT_TRUE(ValidateHttpResponse(s)); - ASSERT_SUBTEST_SUCCESS( - RunCommandsExpendingFailures(&socket, kListen | kAccept | kConnect)); - - socket.Close(); - ASSERT_SUBTEST_SUCCESS(RunCommandsExpendingFailures( - &socket, kListen | kAccept | kConnect | kReadWrite)); - } - - // Test a server socket. - { - pp::TCPSocket server_socket(instance_); - - // Bind - pp::NetAddress any_port_address; - ASSERT_SUBTEST_SUCCESS(GetAddressToBind(&any_port_address)); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - server_socket.Bind(any_port_address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_SUBTEST_SUCCESS(RunCommandsExpendingFailures( - &server_socket, kBind | kAccept | kReadWrite)); - - // Listen - callback.WaitForResult( - server_socket.Listen(1 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_SUBTEST_SUCCESS(RunCommandsExpendingFailures( - &server_socket, kBind | kListen | kConnect | kReadWrite)); - - // Accept - pp::TCPSocket client_socket(instance_); - TestCompletionCallback connect_callback(instance_->pp_instance(), - callback_type()); - int connect_result = client_socket.Connect(server_socket.GetLocalAddress(), - connect_callback.GetCallback()); - TestCompletionCallbackWithOutput<pp::TCPSocket> accept_callback( - instance_->pp_instance(), callback_type()); - accept_callback.WaitForResult( - server_socket.Accept(accept_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(accept_callback); - ASSERT_EQ(PP_OK, accept_callback.result()); - connect_callback.WaitForResult(connect_result); - CHECK_CALLBACK_BEHAVIOR(connect_callback); - ASSERT_EQ(PP_OK, connect_callback.result()); - pp::TCPSocket accepted_socket(accept_callback.output()); - ASSERT_SUBTEST_SUCCESS(RunCommandsExpendingFailures( - &server_socket, kBind | kListen | kConnect | kReadWrite)); - - client_socket.Close(); - accepted_socket.Close(); - server_socket.Close(); - } - - PASS(); -} - -std::string TestTCPSocket::TestConnectFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - // All subsequent calls on the socket should fail. - ASSERT_SUBTEST_SUCCESS(RunCommandsExpendingFailures(&socket, kAllCommands)); - - PASS(); -} - -std::string TestTCPSocket::TestConnectHangs() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - socket.Connect(test_server_addr_, DoNothingCallback()); - PASS(); -} - -std::string TestTCPSocket::TestWriteFails() { - pp::TCPSocket socket(instance_); - { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - } - - // Write to the socket until there's an error. Some writes may succeed, since - // Mojo writes complete before the socket tries to send data. As with the read - // case, wait for two errors. - char write_data[32 * 1024] = {}; - int failures = 0; - while (true) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Write(write_data, - static_cast<int32_t>(sizeof(write_data)), - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - if (cb.result() > 0) { - ASSERT_EQ(0, failures); - continue; - } - - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - ++failures; - - if (failures == 2) - break; - } - - PASS(); -} - -std::string TestTCPSocket::TestReadFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - std::string read_data; - int read_error; - // Read should fail with no data received. - ASSERT_SUBTEST_SUCCESS( - ReadFromSocketUntilError(&socket, &read_data, &read_error)); - ASSERT_EQ(PP_ERROR_FAILED, read_error); - ASSERT_EQ(0, read_data.size()); - - // Reading again after the socket has been closed should also fail. - ASSERT_SUBTEST_SUCCESS( - ReadFromSocketUntilError(&socket, &read_data, &read_error)); - ASSERT_EQ(PP_ERROR_FAILED, read_error); - ASSERT_EQ(0, read_data.size()); - - PASS(); -} - -std::string TestTCPSocket::TestSetSendBufferSizeFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult(socket.SetOption(PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE, 256, - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - PASS(); -} - -std::string TestTCPSocket::TestSetReceiveBufferSizeFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult(socket.SetOption(PP_TCPSOCKET_OPTION_RECV_BUFFER_SIZE, 256, - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - PASS(); -} - -std::string TestTCPSocket::TestSetNoDelayFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult( - socket.SetOption(PP_TCPSOCKET_OPTION_NO_DELAY, true, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - PASS(); -} - -std::string TestTCPSocket::TestBindFailsConnectSucceeds() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - callback.WaitForResult( - socket.Connect(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - PASS(); -} - -std::string TestTCPSocket::TestBindFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - PASS(); -} - -std::string TestTCPSocket::TestBindHangs() { - pp::TCPSocket socket(instance_); - socket.Bind(test_server_addr_, DoNothingCallback()); - PASS(); -} - -std::string TestTCPSocket::TestListenFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult( - socket.Listen(2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - // All subsequent calls on the socket should fail. - ASSERT_SUBTEST_SUCCESS(RunCommandsExpendingFailures(&socket, kAllCommands)); - - PASS(); -} - -std::string TestTCPSocket::TestListenHangs() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - socket.Listen(2 /* backlog */, DoNothingCallback()); - PASS(); -} - -std::string TestTCPSocket::TestAcceptFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult( - socket.Listen(2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallbackWithOutput<pp::TCPSocket> accept_callback( - instance_->pp_instance(), callback_type()); - accept_callback.WaitForResult(socket.Accept(accept_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(accept_callback); - ASSERT_EQ(PP_ERROR_FAILED, accept_callback.result()); - - PASS(); -} - -std::string TestTCPSocket::TestAcceptHangs() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult( - socket.Listen(2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - socket.Accept(DoNothingCallbackWithOutput<pp::TCPSocket>()); - PASS(); -} - -std::string TestTCPSocket::TestAcceptedSocketWriteFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult( - socket.Listen(2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallbackWithOutput<pp::TCPSocket> accept_callback( - instance_->pp_instance(), callback_type()); - accept_callback.WaitForResult(socket.Accept(accept_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(accept_callback); - ASSERT_EQ(PP_OK, accept_callback.result()); - - pp::TCPSocket accepted_socket(accept_callback.output()); - - // Write to the socket until there's an error. Some writes may succeed, since - // Mojo writes complete before the socket tries to send data. As with the read - // case, wait for two errors. - char write_data[32 * 1024] = {}; - int failures = 0; - while (true) { - callback.WaitForResult(accepted_socket.Write( - write_data, static_cast<int32_t>(sizeof(write_data)), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - if (callback.result() > 0) { - ASSERT_EQ(0, failures); - continue; - } - - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - ++failures; - - if (failures == 2) - break; - } - - PASS(); -} - -std::string TestTCPSocket::TestAcceptedSocketReadFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - // The address doesn't matter here, other than that it should be valid. - callback.WaitForResult( - socket.Bind(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult( - socket.Listen(2 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - TestCompletionCallbackWithOutput<pp::TCPSocket> accept_callback( - instance_->pp_instance(), callback_type()); - accept_callback.WaitForResult(socket.Accept(accept_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(accept_callback); - ASSERT_EQ(PP_OK, accept_callback.result()); - - pp::TCPSocket accepted_socket(accept_callback.output()); - - std::string read_data; - int read_error; - // Read should fail with no data received. - ASSERT_SUBTEST_SUCCESS( - ReadFromSocketUntilError(&accepted_socket, &read_data, &read_error)); - ASSERT_EQ(PP_ERROR_FAILED, read_error); - ASSERT_EQ(0, read_data.size()); - - // Reading again after the socket has been closed should also fail. - ASSERT_SUBTEST_SUCCESS( - ReadFromSocketUntilError(&accepted_socket, &read_data, &read_error)); - ASSERT_EQ(PP_ERROR_FAILED, read_error); - ASSERT_EQ(0, read_data.size()); - - PASS(); -} - -std::string TestTCPSocket::TestBindConnectFails() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Bind(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult(socket.Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - // All subsequent calls on the socket should fail. - ASSERT_SUBTEST_SUCCESS(RunCommandsExpendingFailures(&socket, kAllCommands)); - - PASS(); -} - -std::string TestTCPSocket::TestBindConnectHangs() { - pp::TCPSocket socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Bind(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - socket.Connect(test_server_addr_, DoNothingCallback()); - PASS(); -} - -std::string TestTCPSocket::ReadFirstLineFromSocket(pp::TCPSocket* socket, - std::string* s) { - char buffer[1000]; - - s->clear(); - // Make sure we don't just hang if |Read()| spews. - while (s->size() < 10000) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket->Read(buffer, sizeof(buffer), cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_GT(cb.result(), 0); - s->reserve(s->size() + cb.result()); - for (int32_t i = 0; i < cb.result(); ++i) { - s->push_back(buffer[i]); - if (buffer[i] == '\n') - PASS(); - } - } - PASS(); -} - -std::string TestTCPSocket::ReadFirstLineFromSocket_1_0(PP_Resource socket, - std::string* s) { - char buffer[1000]; - - s->clear(); - // Make sure we don't just hang if |Read()| spews. - while (s->size() < 10000) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket_interface_1_0_->Read( - socket, buffer, sizeof(buffer), - cb.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_GT(cb.result(), 0); - s->reserve(s->size() + cb.result()); - for (int32_t i = 0; i < cb.result(); ++i) { - s->push_back(buffer[i]); - if (buffer[i] == '\n') - PASS(); - } - } - PASS(); -} - -std::string TestTCPSocket::ReadFromSocket(pp::TCPSocket* socket, - char* buffer, - size_t num_bytes) { - while (num_bytes > 0) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Read(buffer, static_cast<int32_t>(num_bytes), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_GT(callback.result(), 0); - buffer += callback.result(); - num_bytes -= callback.result(); - } - ASSERT_EQ(0u, num_bytes); - PASS(); -} - -// Reads from the socket until an error (Or 0-byte read) occurs. Populates -// |read_data| and |error| with that information. Doesn't return a std::string -// to distinguish it from a subtest. -std::string TestTCPSocket::ReadFromSocketUntilError(pp::TCPSocket* socket, - std::string* read_data, - int* read_error) { - // Set |read_error| to a value that a read should never complete with. - *read_error = PP_OK_COMPLETIONPENDING; - while (true) { - char buffer[1024]; - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Read(buffer, sizeof(buffer), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_LE(callback.result(), static_cast<int32_t>(sizeof(buffer))); - ASSERT_NE(PP_OK_COMPLETIONPENDING, callback.result()); - if (callback.result() <= 0) { - *read_error = callback.result(); - PASS(); - } - read_data->append(buffer, callback.result()); - } -} - -std::string TestTCPSocket::WriteToSocket(pp::TCPSocket* socket, - const std::string& s) { - const char* buffer = s.data(); - size_t written = 0; - while (written < s.size()) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult( - socket->Write(buffer + written, - static_cast<int32_t>(s.size() - written), - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_GT(cb.result(), 0); - written += cb.result(); - } - ASSERT_EQ(written, s.size()); - PASS(); -} - -std::string TestTCPSocket::WriteToSocket_1_0( - PP_Resource socket, - const std::string& s) { - const char* buffer = s.data(); - size_t written = 0; - while (written < s.size()) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket_interface_1_0_->Write( - socket, buffer + written, - static_cast<int32_t>(s.size() - written), - cb.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_GT(cb.result(), 0); - written += cb.result(); - } - ASSERT_EQ(written, s.size()); - PASS(); -} - -std::string TestTCPSocket::GetAddressToBind(pp::NetAddress* address) { - // Connect to |test_server_addr_| and then sets |address| to the local address - // used by that connection, replacing the port with 0 to use a random port. - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket.Connect(test_server_addr_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - ASSERT_TRUE(ReplacePort(instance_->pp_instance(), socket.GetLocalAddress(), 0, - address)); - ASSERT_FALSE(address->is_null()); - PASS(); -} - -std::string TestTCPSocket::StartListen(pp::TCPSocket* socket, int32_t backlog) { - pp::NetAddress any_port_address; - ASSERT_SUBTEST_SUCCESS(GetAddressToBind(&any_port_address)); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Bind(any_port_address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult( - socket->Listen(backlog, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - PASS(); -} - -std::string TestTCPSocket::RunCommandsExpendingFailures(pp::TCPSocket* socket, - int commands) { - ASSERT_NE(0, commands); - - if (commands & kBind) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - pp::NetAddress any_port_address; - ASSERT_TRUE(ReplacePort(instance_->pp_instance(), test_server_addr_, 0, - &any_port_address)); - cb.WaitForResult(socket->Bind(any_port_address, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - } - - if (commands & kListen) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->Listen(1 /* backlog */, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - } - - if (commands & kAccept) { - TestCompletionCallbackWithOutput<pp::TCPSocket> accept_callback( - instance_->pp_instance(), callback_type()); - accept_callback.WaitForResult( - socket->Accept(accept_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(accept_callback); - ASSERT_EQ(PP_ERROR_FAILED, accept_callback.result()); - } - - if (commands & kConnect) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket->Connect(test_server_addr_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - } - - if (commands & kReadWrite) { - // Check that a read on a new socket fails. - char buffer[1] = {'1'}; - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket->Read(buffer, sizeof(buffer), cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - // Check that a write on a new socket fails. - cb.WaitForResult(socket->Write(buffer, sizeof(buffer), cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - } - - PASS(); -}
diff --git a/tests/test_tcp_socket.h b/tests/test_tcp_socket.h deleted file mode 100644 index 0e302c7..0000000 --- a/tests/test_tcp_socket.h +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TCP_SOCKET_H_ -#define PPAPI_TESTS_TEST_TCP_SOCKET_H_ - -#include <stddef.h> - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/ppb_tcp_socket.h" -#include "ppapi/cpp/net_address.h" -#include "ppapi/tests/test_case.h" - -namespace pp { -class TCPSocket; -} - -class TestTCPSocket: public TestCase { - public: - explicit TestTCPSocket(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestConnect(); - std::string TestReadWrite(); - std::string TestSetOption(); - std::string TestListen(); - std::string TestBacklog(); - std::string TestInterface_1_0(); - std::string TestUnexpectedCalls(); - - // The higher level test fixture is responsible for making socket methods - // behave in the expected manner. The *Fails tests expect the specified even - // to fail with PP_ERROR_FAILED, and the *Hangs test expect the specified - // operation to never complete, at least until teardown starts. - std::string TestConnectFails(); - std::string TestConnectHangs(); - std::string TestWriteFails(); - std::string TestReadFails(); - std::string TestSetSendBufferSizeFails(); - std::string TestSetReceiveBufferSizeFails(); - std::string TestSetNoDelayFails(); - // When a bind call fails, normally the socket is reuseable. - std::string TestBindFailsConnectSucceeds(); - // This is needed in addition to the above test in the case where a bind - // failure is simulated in a way that also closes the NetworkContext pipe. - std::string TestBindFails(); - std::string TestBindHangs(); - std::string TestListenFails(); - std::string TestListenHangs(); - std::string TestAcceptFails(); - std::string TestAcceptHangs(); - std::string TestAcceptedSocketWriteFails(); - std::string TestAcceptedSocketReadFails(); - std::string TestBindConnectFails(); - std::string TestBindConnectHangs(); - - std::string ReadFirstLineFromSocket(pp::TCPSocket* socket, std::string* s); - std::string ReadFirstLineFromSocket_1_0(PP_Resource socket, - std::string* s); - // Expects to read exactly |num_bytes| from the socket. Stops once exactly - // |num_bytes| have been read. - std::string ReadFromSocket(pp::TCPSocket* socket, - char* buffer, - size_t num_bytes); - // Reads from |socket| until a read error occurs, and sets |read_data| and - // |error| accordingly. Only fails if a Read() call returns more data than the - // buffer that was passed in to it. - std::string ReadFromSocketUntilError(pp::TCPSocket* socket, - std::string* read_data, - int* error); - std::string WriteToSocket(pp::TCPSocket* socket, const std::string& s); - std::string WriteToSocket_1_0(PP_Resource socket, const std::string& s); - - // Sets |address| to an address usable for Bind(). Returned address uses the - // IP address used to talk to |test_server_addr_| and a port of 0, so Bind() - // calls to it should succeed. - std::string GetAddressToBind(pp::NetAddress* address); - - std::string StartListen(pp::TCPSocket* socket, int32_t backlog); - - enum Command { - kBind = 0x1, - kListen = 0x2, - kAccept = 0x4, - kConnect = 0x8, - kReadWrite = 0x10, - kAllCommands = -1, - }; - // Runs |commands|, consisting of one or more Command values on |socket|, - // expecting all of them to fail with PP_ERROR_FAILED. Useful for testing - // invalid state transitions. - std::string RunCommandsExpendingFailures(pp::TCPSocket* socket, int commands); - - // Address of the EmbeddedTestServer set up by the browser test fixture. - pp::NetAddress test_server_addr_; - - const PPB_TCPSocket_1_0* socket_interface_1_0_; -}; - -#endif // PPAPI_TESTS_TEST_TCP_SOCKET_H_
diff --git a/tests/test_tcp_socket_private.cc b/tests/test_tcp_socket_private.cc deleted file mode 100644 index 9536382..0000000 --- a/tests/test_tcp_socket_private.cc +++ /dev/null
@@ -1,364 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_tcp_socket_private.h" - -#include <stddef.h> -#include <stdlib.h> - -#include <new> - -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -// Validates the first line of an HTTP response. -bool ValidateHttpResponse(const std::string& s) { - // Just check that it begins with "HTTP/" and ends with a "\r\n". - return s.size() >= 5 && - s.substr(0, 5) == "HTTP/" && - s.substr(s.size() - 2) == "\r\n"; -} - -} // namespace - -REGISTER_TEST_CASE(TCPSocketPrivate); - -TestTCPSocketPrivate::TestTCPSocketPrivate(TestingInstance* instance) - : TestCase(instance) { -} - -bool TestTCPSocketPrivate::Init() { - if (!pp::TCPSocketPrivate::IsAvailable()) - return false; - - // We need something to connect to, so we connect to the HTTP server whence we - // came. Grab the host and port. - if (!EnsureRunningOverHTTP()) - return false; - - if (!GetLocalHostPort(instance_->pp_instance(), &host_, &port_)) - return false; - - // Get the port for the SSL server. - ssl_port_ = instance_->ssl_server_port(); - - return true; -} - -void TestTCPSocketPrivate::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestTCPSocketPrivate, Basic, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, ReadWrite, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, ReadWriteSSL, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, ConnectAddress, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, SetOption, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, LargeRead, filter); - - RUN_CALLBACK_TEST(TestTCPSocketPrivate, SSLHandshakeFails, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, SSLHandshakeHangs, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, SSLWriteFails, filter); - RUN_CALLBACK_TEST(TestTCPSocketPrivate, SSLReadFails, filter); -} - -std::string TestTCPSocketPrivate::TestBasic() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect(host_.c_str(), port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - PP_NetAddress_Private unused; - // TODO(viettrungluu): check the values somehow. - ASSERT_TRUE(socket.GetLocalAddress(&unused)); - ASSERT_TRUE(socket.GetRemoteAddress(&unused)); - - socket.Disconnect(); - - PASS(); -} - -std::string TestTCPSocketPrivate::TestReadWrite() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect(host_.c_str(), port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - ASSERT_EQ(PP_OK, WriteStringToSocket(&socket, "GET / HTTP/1.0\r\n\r\n")); - - // Read up to the first \n and check that it looks like valid HTTP response. - std::string s; - ASSERT_EQ(PP_OK, ReadFirstLineFromSocket(&socket, &s)); - ASSERT_TRUE(ValidateHttpResponse(s)); - - socket.Disconnect(); - - PASS(); -} - -std::string TestTCPSocketPrivate::TestReadWriteSSL() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect(host_.c_str(), ssl_port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult( - socket.SSLHandshake(host_.c_str(), ssl_port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - ASSERT_EQ(PP_OK, WriteStringToSocket(&socket, "GET / HTTP/1.0\r\n\r\n")); - - // Read up to the first \n and check that it looks like valid HTTP response. - std::string s; - ASSERT_EQ(PP_OK, ReadFirstLineFromSocket(&socket, &s)); - ASSERT_TRUE(ValidateHttpResponse(s)); - - socket.Disconnect(); - - PASS(); -} - -std::string TestTCPSocketPrivate::TestConnectAddress() { - PP_NetAddress_Private address; - - // First, bring up a connection and grab the address. - { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Connect(host_.c_str(), port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - ASSERT_TRUE(socket.GetRemoteAddress(&address)); - // Omit the |Disconnect()| here to make sure we don't crash if we just let - // the resource be destroyed. - } - - // Connect to that address. - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.ConnectWithNetAddress(&address, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - // Make sure we can read/write to it properly (see |TestReadWrite()|). - ASSERT_EQ(PP_OK, WriteStringToSocket(&socket, "GET / HTTP/1.0\r\n\r\n")); - std::string s; - ASSERT_EQ(PP_OK, ReadFirstLineFromSocket(&socket, &s)); - ASSERT_TRUE(ValidateHttpResponse(s)); - - socket.Disconnect(); - - PASS(); -} - -std::string TestTCPSocketPrivate::TestSetOption() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult( - socket.SetOption(PP_TCPSOCKETOPTION_PRIVATE_NO_DELAY, true, - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - cb.WaitForResult(socket.Connect(host_.c_str(), port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult( - socket.SetOption(PP_TCPSOCKETOPTION_PRIVATE_NO_DELAY, true, - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult( - socket.SetOption(PP_TCPSOCKETOPTION_PRIVATE_INVALID, true, - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_BADARGUMENT, cb.result()); - - socket.Disconnect(); - - PASS(); -} - -std::string TestTCPSocketPrivate::TestLargeRead() { - pp::TCPSocketPrivate socket(instance_); - { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect(host_.c_str(), port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - } - - ASSERT_EQ(PP_OK, WriteStringToSocket(&socket, "GET / HTTP/1.0\r\n\r\n")); - - const size_t kReadSize = 1024 * 1024 + 32; - // Create large buffer in heap to prevent run-time errors related to - // limits on stack size. - char* buffer = new (std::nothrow) char[kReadSize]; - ASSERT_TRUE(buffer != NULL); - - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Read(buffer, kReadSize * sizeof(*buffer), - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_LE(0, cb.result()); - - delete [] buffer; - - PASS(); -} - -std::string TestTCPSocketPrivate::TestSSLHandshakeFails() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect("foo.test", 443, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult(socket.SSLHandshake("foo.test", 443, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - // Writes and reads should both fail after an SSL handshake fails. - - char byte = 'a'; - cb.WaitForResult(socket.Write(&byte, 1, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - cb.WaitForResult(socket.Read(&byte, 1, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - PASS(); -} - -std::string TestTCPSocketPrivate::TestSSLHandshakeHangs() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect("foo.test", 443, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - socket.SSLHandshake("foo.test", 443, DoNothingCallback()); - PASS(); -} - -std::string TestTCPSocketPrivate::TestSSLWriteFails() { - pp::TCPSocketPrivate socket(instance_); - { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect("foo.test", 443, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult(socket.SSLHandshake("foo.test", 443, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - } - - // Write to the socket until there's an error. Some writes may succeed, since - // Mojo writes complete before the socket tries to send data. - char write_data[32 * 1024] = {}; - while (true) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(socket.Write(write_data, - static_cast<int32_t>(sizeof(write_data)), - cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - if (cb.result() > 0) - continue; - - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - PASS(); - } -} - -std::string TestTCPSocketPrivate::TestSSLReadFails() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult(socket.Connect("foo.test", 443, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult(socket.SSLHandshake("foo.test", 443, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - char byte; - cb.WaitForResult(socket.Read(&byte, 1, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - PASS(); -} - -int32_t TestTCPSocketPrivate::ReadFirstLineFromSocket( - pp::TCPSocketPrivate* socket, - std::string* s) { - char buffer[10000]; - - s->clear(); - // Make sure we don't just hang if |Read()| spews. - while (s->size() < 1000000) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - int32_t rv = socket->Read(buffer, sizeof(buffer), cb.GetCallback()); - if (callback_type() == PP_REQUIRED && rv != PP_OK_COMPLETIONPENDING) - return PP_ERROR_FAILED; - cb.WaitForResult(rv); - if (cb.result() < 0) - return cb.result(); - if (cb.result() == 0) - return PP_ERROR_FAILED; // Didn't get a \n-terminated line. - s->reserve(s->size() + cb.result()); - for (int32_t i = 0; i < cb.result(); i++) { - s->push_back(buffer[i]); - if (buffer[i] == '\n') - return PP_OK; - } - } - return PP_ERROR_FAILED; -} - -int32_t TestTCPSocketPrivate::WriteStringToSocket(pp::TCPSocketPrivate* socket, - const std::string& s) { - const char* buffer = s.data(); - size_t written = 0; - while (written < s.size()) { - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - int32_t rv = socket->Write(buffer + written, - static_cast<int32_t>(s.size() - written), - cb.GetCallback()); - if (callback_type() == PP_REQUIRED && rv != PP_OK_COMPLETIONPENDING) - return PP_ERROR_FAILED; - cb.WaitForResult(rv); - if (cb.result() < 0) - return cb.result(); - if (cb.result() == 0) - return PP_ERROR_FAILED; - written += cb.result(); - } - if (written != s.size()) - return PP_ERROR_FAILED; - return PP_OK; -}
diff --git a/tests/test_tcp_socket_private.h b/tests/test_tcp_socket_private.h deleted file mode 100644 index b45229b..0000000 --- a/tests/test_tcp_socket_private.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_H_ -#define PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -namespace pp { -class TCPSocketPrivate; -} - -class TestTCPSocketPrivate : public TestCase { - public: - explicit TestTCPSocketPrivate(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestBasic(); - std::string TestReadWrite(); - std::string TestReadWriteSSL(); - std::string TestConnectAddress(); - std::string TestSetOption(); - std::string TestLargeRead(); - - // The higher level test fixture is responsible for making socket methods - // behave in the expected manner. The *Fails tests expect the specified event - // to fail with PP_ERROR_FAILED, and the *Hangs test expects the specified - // operation to never complete, at least until teardown starts. - std::string TestSSLHandshakeFails(); - std::string TestSSLHandshakeHangs(); - std::string TestSSLWriteFails(); - std::string TestSSLReadFails(); - - int32_t ReadFirstLineFromSocket(pp::TCPSocketPrivate* socket, std::string* s); - int32_t WriteStringToSocket(pp::TCPSocketPrivate* socket, - const std::string& s); - - std::string host_; - uint16_t port_; - uint16_t ssl_port_; -}; - -#endif // PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_H_
diff --git a/tests/test_tcp_socket_private_crash.cc b/tests/test_tcp_socket_private_crash.cc deleted file mode 100644 index cef1d11..0000000 --- a/tests/test_tcp_socket_private_crash.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_tcp_socket_private_crash.h" - -#include <stddef.h> -#include <stdlib.h> - -#include <new> - -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(TCPSocketPrivateCrash); - -TestTCPSocketPrivateCrash::TestTCPSocketPrivateCrash(TestingInstance* instance) - : TestCase(instance) {} - -bool TestTCPSocketPrivateCrash::Init() { - return pp::TCPSocketPrivate::IsAvailable(); -} - -void TestTCPSocketPrivateCrash::RunTests(const std::string& filter) { - // No need to run this test with the various callback types since that's - // orthogonal from the functionality being tested. It would also make the - // test more complicated because it would have to keep watching the network - // process restart and telling it to crash again on crash.com. - RUN_TEST(Resolve, filter); -} - -std::string TestTCPSocketPrivateCrash::TestResolve() { - pp::TCPSocketPrivate socket(instance_); - - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - std::string host("crash.com"); - cb.WaitForResult(socket.Connect(host.c_str(), 80, cb.GetCallback())); - ASSERT_EQ(PP_ERROR_FAILED, cb.result()); - - socket.Disconnect(); - - PASS(); -}
diff --git a/tests/test_tcp_socket_private_crash.h b/tests/test_tcp_socket_private_crash.h deleted file mode 100644 index 1aafb8f..0000000 --- a/tests/test_tcp_socket_private_crash.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2018 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_CRASH_H_ -#define PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_CRASH_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -class TestTCPSocketPrivateCrash : public TestCase { - public: - explicit TestTCPSocketPrivateCrash(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestResolve(); -}; - -#endif // PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_CRASH_H_
diff --git a/tests/test_tcp_socket_private_disallowed.cc b/tests/test_tcp_socket_private_disallowed.cc deleted file mode 100644 index 65a08bc..0000000 --- a/tests/test_tcp_socket_private_disallowed.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_tcp_socket_private_disallowed.h" - -#include "ppapi/cpp/module.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -const char kServerName[] = "www.google.com"; -const int kPort = 80; - -} - -REGISTER_TEST_CASE(TCPSocketPrivateDisallowed); - -TestTCPSocketPrivateDisallowed::TestTCPSocketPrivateDisallowed( - TestingInstance* instance) - : TestCase(instance), tcp_socket_private_interface_(NULL) { -} - -bool TestTCPSocketPrivateDisallowed::Init() { - tcp_socket_private_interface_ = static_cast<const PPB_TCPSocket_Private*>( - pp::Module::Get()->GetBrowserInterface(PPB_TCPSOCKET_PRIVATE_INTERFACE)); - if (!tcp_socket_private_interface_) - instance_->AppendError("TCPSocketPrivate interface not available"); - return tcp_socket_private_interface_ && CheckTestingInterface(); -} - -void TestTCPSocketPrivateDisallowed::RunTests(const std::string& filter) { - RUN_TEST(Connect, filter); -} - -std::string TestTCPSocketPrivateDisallowed::TestConnect() { - PP_Resource socket = - tcp_socket_private_interface_->Create(instance_->pp_instance()); - if (0 != socket) { - TestCompletionCallback callback(instance_->pp_instance()); - callback.WaitForResult(tcp_socket_private_interface_->Connect( - socket, kServerName, kPort, - callback.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - } - PASS(); -}
diff --git a/tests/test_tcp_socket_private_disallowed.h b/tests/test_tcp_socket_private_disallowed.h deleted file mode 100644 index 66020cb..0000000 --- a/tests/test_tcp_socket_private_disallowed.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_DISALLOWED_H_ -#define PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_DISALLOWED_H_ - -#include <string> - -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/tests/test_case.h" - -class TestTCPSocketPrivateDisallowed : public TestCase { - public: - explicit TestTCPSocketPrivateDisallowed(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestConnect(); - - const PPB_TCPSocket_Private* tcp_socket_private_interface_; -}; - -#endif // PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_DISALLOWED_H_
diff --git a/tests/test_tcp_socket_private_trusted.cc b/tests/test_tcp_socket_private_trusted.cc deleted file mode 100644 index b27923b..0000000 --- a/tests/test_tcp_socket_private_trusted.cc +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_tcp_socket_private_trusted.h" - -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/cpp/private/x509_certificate_private.h" -#include "ppapi/tests/testing_instance.h" -#include "ppapi/tests/test_utils.h" - -REGISTER_TEST_CASE(TCPSocketPrivateTrusted); - -TestTCPSocketPrivateTrusted::TestTCPSocketPrivateTrusted( - TestingInstance* instance) - : TestCase(instance) { -} - -bool TestTCPSocketPrivateTrusted::Init() { - if (!pp::TCPSocketPrivate::IsAvailable()) - return false; - - // We need something to connect to, so we connect to the HTTP server whence we - // came. Grab the host and port. - if (!EnsureRunningOverHTTP()) - return false; - - if (!GetLocalHostPort(instance_->pp_instance(), &host_, &port_)) - return false; - - // Get the port for the SSL server. - ssl_port_ = instance_->ssl_server_port(); - - return true; -} - -void TestTCPSocketPrivateTrusted::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestTCPSocketPrivateTrusted, GetServerCertificate, filter); -} - -std::string TestTCPSocketPrivateTrusted::TestGetServerCertificate() { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - - cb.WaitForResult( - socket.Connect(host_.c_str(), ssl_port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - cb.WaitForResult( - socket.SSLHandshake(host_.c_str(), ssl_port_, cb.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(cb); - ASSERT_EQ(PP_OK, cb.result()); - - const pp::X509CertificatePrivate& cert = socket.GetServerCertificate(); - ASSERT_EQ( - cert.GetField(PP_X509CERTIFICATE_PRIVATE_ISSUER_COMMON_NAME).AsString(), - "Test Root CA"); - ASSERT_EQ( - cert.GetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_COMMON_NAME).AsString(), - "127.0.0.1"); - PASS(); -}
diff --git a/tests/test_tcp_socket_private_trusted.h b/tests/test_tcp_socket_private_trusted.h deleted file mode 100644 index 9feb4c5..0000000 --- a/tests/test_tcp_socket_private_trusted.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_TRUSTED_H_ -#define PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_TRUSTED_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -// This class is necessary to test the portions of TCP socket which are -// not exposed to NaCl yet. In particular, functionality related to -// X509 Certificates is tested here. -class TestTCPSocketPrivateTrusted : public TestCase { - public: - explicit TestTCPSocketPrivateTrusted(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestGetServerCertificate(); - - std::string host_; - uint16_t port_; - uint16_t ssl_port_; -}; - -#endif // PPAPI_TESTS_TEST_TCP_SOCKET_PRIVATE_TRUSTED_H_
diff --git a/tests/test_test_internals.cc b/tests/test_test_internals.cc deleted file mode 100644 index 10919a3..0000000 --- a/tests/test_test_internals.cc +++ /dev/null
@@ -1,279 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_test_internals.h" - -#include <stdint.h> - -#include <vector> - -namespace { - -std::string CheckEqual(const std::string& expected, const std::string& actual) { - if (expected != actual) { - return std::string("Expected : \"") + expected + "\", got : \"" + actual + - "\""; - } - PASS(); -} - -std::string Negate(const std::string& result) { - if (result.empty()) - return std::string("FAIL: String was empty."); - return std::string(); -} - -class CallCounter { - public: - CallCounter() : num_calls_(0) {} - - int return_zero() { - ++num_calls_; - return 0; - } - double return_zero_as_double() { - ++num_calls_; - return 0.0; - } - - int num_calls() const { return num_calls_; } - - private: - int num_calls_; -}; - -} - -REGISTER_TEST_CASE(TestInternals); - -bool TestTestInternals::Init() { - return true; -} - -void TestTestInternals::RunTests(const std::string& filter) { - RUN_TEST(ToString, filter); - RUN_TEST(PassingComparisons, filter); - RUN_TEST(FailingComparisons, filter); - RUN_TEST(EvaluateOnce, filter); -} - -#define WRAP_LEFT_PARAM(a) \ - internal::ParameterWrapper<IS_NULL_LITERAL(a)>::WrapValue(a) -std::string TestTestInternals::TestToString() { - // We don't use most ASSERT macros here, because they rely on ToString. - // ASSERT_SUBTEST_SUCCESS does not use ToString. - ASSERT_SUBTEST_SUCCESS(CheckEqual(WRAP_LEFT_PARAM(NULL).ToString(), "0")); - ASSERT_SUBTEST_SUCCESS(CheckEqual(WRAP_LEFT_PARAM(0).ToString(), "0")); - ASSERT_SUBTEST_SUCCESS(CheckEqual(internal::ToString(5), "5")); - int32_t x = 5; - ASSERT_SUBTEST_SUCCESS(CheckEqual(internal::ToString(x + 1), "6")); - std::string str = "blah"; - ASSERT_SUBTEST_SUCCESS(CheckEqual(internal::ToString(str + "blah"), - "blahblah")); - std::vector<int> vec; - ASSERT_SUBTEST_SUCCESS(CheckEqual(internal::ToString(vec), std::string())); - - PASS(); -} - -#define COMPARE_DOUBLE_EQ(a, b) \ - internal::CompareDoubleEq( \ - internal::ParameterWrapper<IS_NULL_LITERAL(a)>::WrapValue(a), \ - (b), #a, #b, __FILE__, __LINE__) -std::string TestTestInternals::TestPassingComparisons() { - // These comparisons should all "pass", meaning they should return the empty - // string. - { - const std::string* const kNull = NULL; - const std::string* const kDeadBeef = - reinterpret_cast<const std::string*>(0xdeadbeef); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, NULL, kNull)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, kDeadBeef, kDeadBeef)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, NULL, kDeadBeef)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, kDeadBeef, kNull)); - } { - const int64_t zero_int32 = 0; - const int64_t zero_int64 = 0; - const int32_t zero_uint32 = 0; - const int64_t zero_uint64 = 0; - const int32_t one_int32 = 1; - const int64_t one_int64 = 1; - const int32_t one_uint32 = 1; - const int64_t one_uint64 = 1; - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 0, zero_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 0, zero_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 0, zero_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 0, zero_uint64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 1, one_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 1, one_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 1, one_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(EQ, 1, one_uint64)); - - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 1, zero_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 1, zero_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 1, zero_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 1, zero_uint64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 0, one_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 0, one_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 0, one_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(NE, 0, one_uint64)); - - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LT, 0, one_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LT, 0, one_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LT, 0, one_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LT, 0, one_uint64)); - - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, zero_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, zero_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, zero_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, zero_uint64)); - - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, one_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, one_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, one_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(LE, 0, one_uint64)); - - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GT, 1, zero_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GT, 1, zero_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GT, 1, zero_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GT, 1, zero_uint64)); - - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, zero_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, zero_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, zero_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, zero_uint64)); - - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, one_int32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, one_uint32)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, one_int64)); - ASSERT_SUBTEST_SUCCESS(COMPARE_BINARY_INTERNAL(GE, 1, one_uint64)); - } { - ASSERT_SUBTEST_SUCCESS( - COMPARE_BINARY_INTERNAL(EQ, "hello", std::string("hello"))); - std::vector<int> int_vector1(10, 10); - std::vector<int> int_vector2(int_vector1); - ASSERT_SUBTEST_SUCCESS( - COMPARE_BINARY_INTERNAL(EQ, int_vector1, int_vector2)); - } { - const double kZeroDouble = 0.0; - const double kPositiveDouble = 1.1; - ASSERT_SUBTEST_SUCCESS( - COMPARE_BINARY_INTERNAL(LT, kZeroDouble, kPositiveDouble)); - ASSERT_SUBTEST_SUCCESS( - COMPARE_BINARY_INTERNAL(GT, kPositiveDouble, kZeroDouble)); - ASSERT_SUBTEST_SUCCESS(COMPARE_DOUBLE_EQ(0.0, kZeroDouble)); - ASSERT_SUBTEST_SUCCESS(COMPARE_DOUBLE_EQ(1.0 + 0.1, kPositiveDouble)); - } - - // TODO: Things that return non-empty string. - // TODO: Test that the parameter is evaluated exactly once. - PASS(); -} - -#define ASSERT_SUBTEST_FAILURE(param) ASSERT_SUBTEST_SUCCESS(Negate(param)) -std::string TestTestInternals::TestFailingComparisons() { - // Note, we don't really worry about the content of failure strings here. - // That's mostly covered by the ToString test above. This test just makes - // sure that comparisons which should return a non-empty string do so. - { - const std::string* const kNull = NULL; - const std::string* const kDeadBeef = - reinterpret_cast<const std::string*>(0xdeadbeef); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, NULL, kNull)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, kDeadBeef, kDeadBeef)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, NULL, kDeadBeef)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, kDeadBeef, kNull)); - } - - // Now, just make sure we get any non-empty string at all, which will indicate - // test failure. We mostly rely on the ToString test to get the formats right. - { - const int64_t zero_int32 = 0; - const int64_t zero_int64 = 0; - const int32_t zero_uint32 = 0; - const int64_t zero_uint64 = 0; - const int32_t one_int32 = 1; - const int64_t one_int64 = 1; - const int32_t one_uint32 = 1; - const int64_t one_uint64 = 1; - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 1, zero_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 1, zero_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 1, zero_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 1, zero_uint64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 0, one_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 0, one_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 0, one_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(EQ, 0, one_uint64)); - - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 0, zero_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 0, zero_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 0, zero_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 0, zero_uint64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 1, one_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 1, one_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 1, one_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(NE, 1, one_uint64)); - - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LT, 1, one_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LT, 1, one_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LT, 1, one_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LT, 1, one_uint64)); - - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LE, 1, zero_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LE, 1, zero_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LE, 1, zero_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(LE, 1, zero_uint64)); - - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GT, 0, zero_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GT, 0, zero_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GT, 0, zero_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GT, 0, zero_uint64)); - - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GE, 0, one_int32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GE, 0, one_uint32)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GE, 0, one_int64)); - ASSERT_SUBTEST_FAILURE(COMPARE_BINARY_INTERNAL(GE, 0, one_uint64)); - } { - ASSERT_SUBTEST_FAILURE( - COMPARE_BINARY_INTERNAL(EQ, "goodbye", std::string("hello"))); - std::vector<int> int_vector1(10, 10); - std::vector<int> int_vector2; - ASSERT_SUBTEST_FAILURE( - COMPARE_BINARY_INTERNAL(EQ, int_vector1, int_vector2)); - } { - const double kZeroDouble = 0.0; - const double kPositiveDouble = 1.1; - ASSERT_SUBTEST_FAILURE( - COMPARE_BINARY_INTERNAL(GT, kZeroDouble, kPositiveDouble)); - ASSERT_SUBTEST_FAILURE( - COMPARE_BINARY_INTERNAL(LT, kPositiveDouble, kZeroDouble)); - ASSERT_SUBTEST_FAILURE(COMPARE_DOUBLE_EQ(1.1, kZeroDouble)); - ASSERT_SUBTEST_FAILURE(COMPARE_DOUBLE_EQ(0.0, kPositiveDouble)); - } - - // TODO: Test that the parameter is evaluated exactly once. - PASS(); -} -#undef COMPARE -#undef COMPARE_DOUBLE_EQ - -std::string TestTestInternals::TestEvaluateOnce() { - // Make sure that the ASSERT macros only evaluate each parameter once. - { - CallCounter call_counter1; - CallCounter call_counter2; - ASSERT_EQ(call_counter1.return_zero(), call_counter2.return_zero()); - assert(call_counter1.num_calls() == 1); - assert(call_counter2.num_calls() == 1); - } { - CallCounter call_counter1; - CallCounter call_counter2; - ASSERT_DOUBLE_EQ(call_counter1.return_zero_as_double(), - call_counter2.return_zero_as_double()); - assert(call_counter1.num_calls() == 1); - assert(call_counter2.num_calls() == 1); - } - PASS(); -} -
diff --git a/tests/test_test_internals.h b/tests/test_test_internals.h deleted file mode 100644 index b6c61d3..0000000 --- a/tests/test_test_internals.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TEST_INTERNALS_H_ -#define PPAPI_TESTS_TEST_TEST_INTERNALS_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -// This class is for testing the test framework itself. -class TestTestInternals : public TestCase { - public: - explicit TestTestInternals(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestToString(); - std::string TestPassingComparisons(); - std::string TestFailingComparisons(); - std::string TestEvaluateOnce(); -}; - -#endif // PPAPI_TESTS_TEST_TEST_INTERNALS_H_
diff --git a/tests/test_trace_event.cc b/tests/test_trace_event.cc deleted file mode 100644 index 0e002bb..0000000 --- a/tests/test_trace_event.cc +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_trace_event.h" - -#include <stdint.h> - -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(TraceEvent); - -TestTraceEvent::TestTraceEvent(TestingInstance* instance) - : TestCase(instance), - interface_(NULL) { -} - -bool TestTraceEvent::Init() { - interface_ = static_cast<const PPB_Trace_Event_Dev*>( - pp::Module::Get()->GetBrowserInterface(PPB_TRACE_EVENT_DEV_INTERFACE)); - return !!interface_; -} - -void TestTraceEvent::RunTests(const std::string& filter) { - RUN_TEST(Smoke, filter); - RUN_TEST(SmokeWithTimestamps, filter); - RUN_TEST(Clock, filter); -} - -std::string TestTraceEvent::TestSmoke() { - // This test does not verify the log message actually reaches dev tracing, but - // it does test that the interface exists and that it can be called without - // crashing. - const void* cat_enabled = interface_->GetCategoryEnabled("ppapi"); - interface_->AddTraceEvent('B', cat_enabled, "foo", 0, 0, NULL, NULL, NULL, 0); - interface_->AddTraceEvent('E', cat_enabled, "foo", 0, 0, NULL, NULL, NULL, 0); - PASS(); -} - -std::string TestTraceEvent::TestSmokeWithTimestamps() { - // This test does not verify the log message actually reaches dev tracing, but - // it does test that the interface exists and that it can be called without - // crashing. - const void* cat_enabled = interface_->GetCategoryEnabled("ppapi"); - interface_->AddTraceEventWithThreadIdAndTimestamp( - 'B', cat_enabled, "foo", 0, 0, 42, 0, NULL, NULL, NULL, 0); - interface_->AddTraceEventWithThreadIdAndTimestamp( - 'B', cat_enabled, "foo", 0, 1, 43, 0, NULL, NULL, NULL, 0); - interface_->AddTraceEventWithThreadIdAndTimestamp( - 'E', cat_enabled, "foo", 0, 0, 44, 0, NULL, NULL, NULL, 0); - interface_->AddTraceEventWithThreadIdAndTimestamp( - 'E', cat_enabled, "foo", 0, 1, 45, 0, NULL, NULL, NULL, 0); - PASS(); -} - -std::string TestTraceEvent::TestClock() { - int64_t last = interface_->Now(); - - for(int i=0; i<5; ++i){ - int64_t next = interface_->Now(); - ASSERT_LE(last, next); - last = next; - } - - PASS(); -}
diff --git a/tests/test_trace_event.h b/tests/test_trace_event.h deleted file mode 100644 index a571883..0000000 --- a/tests/test_trace_event.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_TRACE_EVENT_H_ -#define PPAPI_TESTS_TEST_TRACE_EVENT_H_ - -#include <string> - -#include "ppapi/c/dev/ppb_trace_event_dev.h" -#include "ppapi/tests/test_case.h" - -class TestTraceEvent : public TestCase { - public: - explicit TestTraceEvent(TestingInstance* instance); - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestSmoke(); - std::string TestSmokeWithTimestamps(); - std::string TestClock(); - - const PPB_Trace_Event_Dev* interface_; -}; - -#endif // PPAPI_TESTS_TEST_TRACE_EVENT_H_
diff --git a/tests/test_udp_socket.cc b/tests/test_udp_socket.cc deleted file mode 100644 index eca910a..0000000 --- a/tests/test_udp_socket.cc +++ /dev/null
@@ -1,602 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_udp_socket.h" - -#include <vector> - -#include "ppapi/cpp/pass_ref.h" -#include "ppapi/cpp/tcp_socket.h" -#include "ppapi/cpp/udp_socket.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(UDPSocket); - -namespace { - -const uint16_t kPortScanFrom = 1024; -const uint16_t kPortScanTo = 4096; - -pp::NetAddress ReplacePort(const pp::InstanceHandle& instance, - const pp::NetAddress& addr, - uint16_t port) { - switch (addr.GetFamily()) { - case PP_NETADDRESS_FAMILY_IPV4: { - PP_NetAddress_IPv4 ipv4_addr; - if (!addr.DescribeAsIPv4Address(&ipv4_addr)) - break; - ipv4_addr.port = ConvertToNetEndian16(port); - return pp::NetAddress(instance, ipv4_addr); - } - case PP_NETADDRESS_FAMILY_IPV6: { - PP_NetAddress_IPv6 ipv6_addr; - if (!addr.DescribeAsIPv6Address(&ipv6_addr)) - break; - ipv6_addr.port = ConvertToNetEndian16(port); - return pp::NetAddress(instance, ipv6_addr); - } - default: { - PP_NOTREACHED(); - } - } - return pp::NetAddress(); -} - -} // namespace - -TestUDPSocket::TestUDPSocket(TestingInstance* instance) - : TestCase(instance), - socket_interface_1_0_(NULL), - socket_interface_1_1_(NULL) { -} - -bool TestUDPSocket::Init() { - bool tcp_socket_is_available = pp::TCPSocket::IsAvailable(); - if (!tcp_socket_is_available) - instance_->AppendError("PPB_TCPSocket interface not available"); - - bool udp_socket_is_available = pp::UDPSocket::IsAvailable(); - if (!udp_socket_is_available) - instance_->AppendError("PPB_UDPSocket interface not available"); - - bool net_address_is_available = pp::NetAddress::IsAvailable(); - if (!net_address_is_available) - instance_->AppendError("PPB_NetAddress interface not available"); - - std::string host; - uint16_t port = 0; - bool init_address = - GetLocalHostPort(instance_->pp_instance(), &host, &port) && - ResolveHost(instance_->pp_instance(), host, port, &address_); - if (!init_address) - instance_->AppendError("Can't init address"); - - socket_interface_1_0_ = - static_cast<const PPB_UDPSocket_1_0*>( - pp::Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_INTERFACE_1_0)); - if (!socket_interface_1_0_) - instance_->AppendError("PPB_UDPSocket_1_0 interface not available"); - - socket_interface_1_1_ = - static_cast<const PPB_UDPSocket_1_1*>( - pp::Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_INTERFACE_1_1)); - if (!socket_interface_1_1_) - instance_->AppendError("PPB_UDPSocket_1_1 interface not available"); - - return tcp_socket_is_available && - udp_socket_is_available && - net_address_is_available && - init_address && - CheckTestingInterface() && - EnsureRunningOverHTTP() && - socket_interface_1_0_ != NULL && - socket_interface_1_1_ != NULL; -} - -void TestUDPSocket::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestUDPSocket, ReadWrite, filter); - RUN_CALLBACK_TEST(TestUDPSocket, Broadcast, filter); - RUN_CALLBACK_TEST(TestUDPSocket, SetOption_1_0, filter); - RUN_CALLBACK_TEST(TestUDPSocket, SetOption_1_1, filter); - RUN_CALLBACK_TEST(TestUDPSocket, SetOption, filter); - RUN_CALLBACK_TEST(TestUDPSocket, ParallelSend, filter); - RUN_CALLBACK_TEST(TestUDPSocket, Multicast, filter); - - // Failure tests. Generally can only be run individually, since they require - // specific socket failures to be injected into the UDP code. - RUN_CALLBACK_TEST(TestUDPSocket, BindFails, filter); - RUN_CALLBACK_TEST(TestUDPSocket, SetBroadcastFails, filter); - RUN_CALLBACK_TEST(TestUDPSocket, SendToFails, filter); - RUN_CALLBACK_TEST(TestUDPSocket, ReadFails, filter); -} - -std::string TestUDPSocket::GetLocalAddress(pp::NetAddress* address) { - pp::TCPSocket socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket.Connect(address_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - *address = socket.GetLocalAddress(); - ASSERT_NE(0, address->pp_resource()); - socket.Close(); - PASS(); -} - -std::string TestUDPSocket::SetBroadcastOptions(pp::UDPSocket* socket) { - TestCompletionCallback callback_1(instance_->pp_instance(), callback_type()); - callback_1.WaitForResult(socket->SetOption( - PP_UDPSOCKET_OPTION_ADDRESS_REUSE, pp::Var(true), - callback_1.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_1); - ASSERT_EQ(PP_OK, callback_1.result()); - - TestCompletionCallback callback_2(instance_->pp_instance(), callback_type()); - callback_2.WaitForResult(socket->SetOption( - PP_UDPSOCKET_OPTION_BROADCAST, pp::Var(true), callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_EQ(PP_OK, callback_2.result()); - - PASS(); -} - -std::string TestUDPSocket::BindUDPSocket(pp::UDPSocket* socket, - const pp::NetAddress& address) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket->Bind(address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -std::string TestUDPSocket::LookupPortAndBindUDPSocket( - pp::UDPSocket* socket, - pp::NetAddress* address) { - pp::NetAddress base_address; - ASSERT_SUBTEST_SUCCESS(GetLocalAddress(&base_address)); - - bool is_free_port_found = false; - std::string ret; - for (uint16_t port = kPortScanFrom; port < kPortScanTo; ++port) { - pp::NetAddress new_address = ReplacePort(instance_, base_address, port); - ASSERT_NE(0, new_address.pp_resource()); - ret = BindUDPSocket(socket, new_address); - if (ret.empty()) { - is_free_port_found = true; - break; - } - } - if (!is_free_port_found) - return "Can't find available port (" + ret + ")"; - - *address = socket->GetBoundAddress(); - ASSERT_NE(0, address->pp_resource()); - - PASS(); -} - -std::string TestUDPSocket::ReadSocket(pp::UDPSocket* socket, - pp::NetAddress* address, - size_t size, - std::string* message) { - std::vector<char> buffer(size); - TestCompletionCallbackWithOutput<pp::NetAddress> callback( - instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->RecvFrom(&buffer[0], static_cast<int32_t>(size), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_FALSE(callback.result() < 0); - ASSERT_EQ(size, static_cast<size_t>(callback.result())); - *address = callback.output(); - message->assign(buffer.begin(), buffer.end()); - PASS(); -} - -std::string TestUDPSocket::PassMessage(pp::UDPSocket* target, - pp::UDPSocket* source, - const pp::NetAddress& target_address, - const std::string& message, - pp::NetAddress* recvfrom_address) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - int32_t rv = source->SendTo(message.c_str(), - static_cast<int32_t>(message.size()), - target_address, - callback.GetCallback()); - std::string str; - ASSERT_SUBTEST_SUCCESS(ReadSocket(target, recvfrom_address, message.size(), - &str)); - - callback.WaitForResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_FALSE(callback.result() < 0); - ASSERT_EQ(message.size(), static_cast<size_t>(callback.result())); - ASSERT_EQ(message, str); - PASS(); -} - -std::string TestUDPSocket::SetMulticastOptions(pp::UDPSocket* socket) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket->SetOption( - PP_UDPSOCKET_OPTION_MULTICAST_LOOP, pp::Var(true), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult(socket->SetOption( - PP_UDPSOCKET_OPTION_MULTICAST_TTL, pp::Var(1), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - PASS(); -} - -std::string TestUDPSocket::TestReadWrite() { - pp::UDPSocket server_socket(instance_), client_socket(instance_); - pp::NetAddress server_address, client_address; - - ASSERT_SUBTEST_SUCCESS(LookupPortAndBindUDPSocket(&server_socket, - &server_address)); - ASSERT_SUBTEST_SUCCESS(LookupPortAndBindUDPSocket(&client_socket, - &client_address)); - const std::string message = "Simple message that will be sent via UDP"; - pp::NetAddress recvfrom_address; - ASSERT_SUBTEST_SUCCESS(PassMessage(&server_socket, &client_socket, - server_address, message, - &recvfrom_address)); - ASSERT_TRUE(EqualNetAddress(recvfrom_address, client_address)); - - server_socket.Close(); - client_socket.Close(); - - if (server_socket.GetBoundAddress().pp_resource() != 0) - return "PPB_UDPSocket::GetBoundAddress: expected failure"; - - PASS(); -} - -std::string TestUDPSocket::TestBroadcast() { - pp::UDPSocket server1(instance_), server2(instance_); - - ASSERT_SUBTEST_SUCCESS(SetBroadcastOptions(&server1)); - ASSERT_SUBTEST_SUCCESS(SetBroadcastOptions(&server2)); - - PP_NetAddress_IPv4 any_ipv4_address = { 0, { 0, 0, 0, 0 } }; - pp::NetAddress any_address(instance_, any_ipv4_address); - ASSERT_SUBTEST_SUCCESS(BindUDPSocket(&server1, any_address)); - // Fill port field of |server_address|. - pp::NetAddress server_address = server1.GetBoundAddress(); - ASSERT_NE(0, server_address.pp_resource()); - ASSERT_SUBTEST_SUCCESS(BindUDPSocket(&server2, server_address)); - - PP_NetAddress_IPv4 server_ipv4_address; - ASSERT_TRUE(server_address.DescribeAsIPv4Address(&server_ipv4_address)); - - PP_NetAddress_IPv4 broadcast_ipv4_address = { - server_ipv4_address.port, { 0xff, 0xff, 0xff, 0xff } - }; - pp::NetAddress broadcast_address(instance_, broadcast_ipv4_address); - - std::string message; - const std::string first_message = "first message"; - const std::string second_message = "second_message"; - - pp::NetAddress recvfrom_address; - ASSERT_SUBTEST_SUCCESS(PassMessage(&server1, &server2, broadcast_address, - first_message, &recvfrom_address)); - // |first_message| was also received by |server2|. - ASSERT_SUBTEST_SUCCESS(ReadSocket(&server2, &recvfrom_address, - first_message.size(), &message)); - ASSERT_EQ(first_message, message); - - ASSERT_SUBTEST_SUCCESS(PassMessage(&server2, &server1, broadcast_address, - second_message, &recvfrom_address)); - // |second_message| was also received by |server1|. - ASSERT_SUBTEST_SUCCESS(ReadSocket(&server1, &recvfrom_address, - second_message.size(), &message)); - ASSERT_EQ(second_message, message); - - server1.Close(); - server2.Close(); - PASS(); -} - -int32_t TestUDPSocket::SetOptionValue(UDPSocketSetOption func, - PP_Resource socket, - PP_UDPSocket_Option option, - const PP_Var& value) { - PP_TimeTicks start_time(NowInTimeTicks()); - TestCompletionCallback cb(instance_->pp_instance(), callback_type()); - cb.WaitForResult(func(socket, option, value, - cb.GetCallback().pp_completion_callback())); - - // Expanded from CHECK_CALLBACK_BEHAVIOR macro. - if (cb.failed()) { - std::string msg = MakeFailureMessage(__FILE__, __LINE__, - cb.errors().c_str()); - - instance_->LogTest("SetOptionValue", msg, start_time); - return PP_ERROR_FAILED; - } - return cb.result(); -} - -std::string TestUDPSocket::TestSetOption_1_0() { - PP_Resource socket = socket_interface_1_0_->Create(instance_->pp_instance()); - ASSERT_NE(0, socket); - - // Multicast options are not supported in interface 1.0. - ASSERT_EQ(PP_ERROR_BADARGUMENT, - SetOptionValue(socket_interface_1_0_->SetOption, - socket, - PP_UDPSOCKET_OPTION_MULTICAST_LOOP, - PP_MakeBool(PP_TRUE))); - - ASSERT_EQ(PP_ERROR_BADARGUMENT, - SetOptionValue(socket_interface_1_0_->SetOption, - socket, - PP_UDPSOCKET_OPTION_MULTICAST_TTL, - PP_MakeInt32(1))); - - socket_interface_1_0_->Close(socket); - pp::Module::Get()->core()->ReleaseResource(socket); - - PASS(); -} - -std::string TestUDPSocket::TestSetOption_1_1() { - PP_Resource socket = socket_interface_1_1_->Create(instance_->pp_instance()); - ASSERT_NE(0, socket); - - // Multicast options are not supported in interface 1.1. - ASSERT_EQ(PP_ERROR_BADARGUMENT, - SetOptionValue(socket_interface_1_1_->SetOption, - socket, - PP_UDPSOCKET_OPTION_MULTICAST_LOOP, - PP_MakeBool(PP_TRUE))); - - ASSERT_EQ(PP_ERROR_BADARGUMENT, - SetOptionValue(socket_interface_1_1_->SetOption, - socket, - PP_UDPSOCKET_OPTION_MULTICAST_TTL, - PP_MakeInt32(1))); - - socket_interface_1_1_->Close(socket); - pp::Module::Get()->core()->ReleaseResource(socket); - - PASS(); -} - -std::string TestUDPSocket::TestSetOption() { - pp::UDPSocket socket(instance_); - - ASSERT_SUBTEST_SUCCESS(SetBroadcastOptions(&socket)); - ASSERT_SUBTEST_SUCCESS(SetMulticastOptions(&socket)); - - // Try to pass incorrect option value's type. - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_ADDRESS_REUSE, pp::Var(1), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - - // Invalid multicast TTL values (less than 0 and greater than 255). - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_MULTICAST_TTL, pp::Var(-1), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_MULTICAST_TTL, pp::Var(256), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_BROADCAST, pp::Var(false), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_SEND_BUFFER_SIZE, pp::Var(4096), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_RECV_BUFFER_SIZE, pp::Var(512), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::NetAddress address; - ASSERT_SUBTEST_SUCCESS(LookupPortAndBindUDPSocket(&socket, &address)); - - // ADDRESS_REUSE won't take effect after the socket is bound. - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_ADDRESS_REUSE, pp::Var(true), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - // BROADCAST, SEND_BUFFER_SIZE and RECV_BUFFER_SIZE can be set after the - // socket is bound. - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_BROADCAST, pp::Var(true), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_SEND_BUFFER_SIZE, pp::Var(2048), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_RECV_BUFFER_SIZE, pp::Var(1024), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - PASS(); -} - -std::string TestUDPSocket::TestParallelSend() { - // This test only makes sense when callbacks are optional. - if (callback_type() != PP_OPTIONAL) - PASS(); - - pp::UDPSocket server_socket(instance_), client_socket(instance_); - pp::NetAddress server_address, client_address; - - ASSERT_SUBTEST_SUCCESS( - LookupPortAndBindUDPSocket(&server_socket, &server_address)); - ASSERT_SUBTEST_SUCCESS( - LookupPortAndBindUDPSocket(&client_socket, &client_address)); - const std::string message = "Simple message that will be sent via UDP"; - pp::NetAddress recvfrom_address; - - const size_t kParallelSends = 10; - std::vector<TestCompletionCallback*> sendto_callbacks(kParallelSends); - std::vector<int32_t> sendto_results(kParallelSends); - size_t pending = 0; - for (size_t i = 0; i < kParallelSends; i++) { - sendto_callbacks[i] = - new TestCompletionCallback(instance_->pp_instance(), callback_type()); - sendto_results[i] = - client_socket.SendTo(message.c_str(), - static_cast<int32_t>(message.size()), - server_address, - sendto_callbacks[i]->GetCallback()); - - if (sendto_results[i] == PP_ERROR_INPROGRESS) { - // Run a pending send to completion to free a slot for the current send. - ASSERT_GT(i, pending); - sendto_callbacks[pending]->WaitForResult(sendto_results[pending]); - CHECK_CALLBACK_BEHAVIOR(*sendto_callbacks[pending]); - ASSERT_EQ(message.size(), - static_cast<size_t>(sendto_callbacks[pending]->result())); - pending++; - // Try to send the message again. - sendto_results[i] = - client_socket.SendTo(message.c_str(), - static_cast<int32_t>(message.size()), - server_address, - sendto_callbacks[i]->GetCallback()); - ASSERT_NE(PP_ERROR_INPROGRESS, sendto_results[i]); - } - } - - // Finish all pending sends. - for (size_t i = pending; i < kParallelSends; i++) { - sendto_callbacks[i]->WaitForResult(sendto_results[i]); - CHECK_CALLBACK_BEHAVIOR(*sendto_callbacks[i]); - ASSERT_EQ(message.size(), - static_cast<size_t>(sendto_callbacks[i]->result())); - } - - for (size_t i = 0; i < kParallelSends; ++i) - delete sendto_callbacks[i]; - - for (size_t i = 0; i < kParallelSends; i++) { - std::string str; - ASSERT_SUBTEST_SUCCESS( - ReadSocket(&server_socket, &recvfrom_address, message.size(), &str)); - ASSERT_EQ(message, str); - } - - server_socket.Close(); - client_socket.Close(); - - PASS(); -} - -std::string TestUDPSocket::TestMulticast() { - pp::UDPSocket server1(instance_), server2(instance_); - - ASSERT_SUBTEST_SUCCESS(SetMulticastOptions(&server1)); - ASSERT_SUBTEST_SUCCESS(SetMulticastOptions(&server2)); - - server1.Close(); - server2.Close(); - - PASS(); -} - -std::string TestUDPSocket::TestBindFails() { - pp::UDPSocket socket(instance_); - - PP_NetAddress_IPv4 any_ipv4_address = {0, {0, 0, 0, 0}}; - pp::NetAddress any_address(instance_, any_ipv4_address); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket.Bind(any_address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - PASS(); -} - -std::string TestUDPSocket::TestSetBroadcastFails() { - pp::UDPSocket socket(instance_); - PP_NetAddress_IPv4 any_ipv4_address = {0, {0, 0, 0, 0}}; - pp::NetAddress any_address(instance_, any_ipv4_address); - ASSERT_SUBTEST_SUCCESS(BindUDPSocket(&socket, any_address)); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_BROADCAST, pp::Var(true), callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - // Setting broadcast again should also fail. - TestCompletionCallback callback_2(instance_->pp_instance(), callback_type()); - callback_2.WaitForResult(socket.SetOption( - PP_UDPSOCKET_OPTION_BROADCAST, pp::Var(true), callback_2.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback_2); - ASSERT_EQ(PP_ERROR_FAILED, callback_2.result()); - PASS(); -} - -std::string TestUDPSocket::TestSendToFails() { - pp::UDPSocket socket(instance_); - PP_NetAddress_IPv4 any_ipv4_address = {0, {0, 0, 0, 0}}; - pp::NetAddress any_address(instance_, any_ipv4_address); - ASSERT_SUBTEST_SUCCESS(BindUDPSocket(&socket, any_address)); - - std::vector<char> buffer(1); - buffer[0] = 1; - PP_NetAddress_IPv4 target_ipv4_address = {1024, {127, 0, 0, 1}}; - pp::NetAddress target_address(instance_, target_ipv4_address); - // All writes should fail. - for (int i = 0; i < 10; ++i) { - TestCompletionCallbackWithOutput<pp::NetAddress> callback( - instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket.SendTo(buffer.data(), static_cast<int32_t>(buffer.size()), - target_address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - } - PASS(); -} - -std::string TestUDPSocket::TestReadFails() { - pp::UDPSocket socket(instance_); - PP_NetAddress_IPv4 any_ipv4_address = {0, {0, 0, 0, 0}}; - pp::NetAddress any_address(instance_, any_ipv4_address); - ASSERT_SUBTEST_SUCCESS(BindUDPSocket(&socket, any_address)); - - std::vector<char> buffer(1); - // All reads should fail. Larger number of reads increases the chance that at - // least one read will be synchronous. - for (int i = 0; i < 200; ++i) { - TestCompletionCallbackWithOutput<pp::NetAddress> callback( - instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket.RecvFrom(&buffer[0], - static_cast<int32_t>(buffer.size()), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - } - PASS(); -}
diff --git a/tests/test_udp_socket.h b/tests/test_udp_socket.h deleted file mode 100644 index 6636e4f..0000000 --- a/tests/test_udp_socket.h +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_UDP_SOCKET_H_ -#define PPAPI_TESTS_TEST_UDP_SOCKET_H_ - -#include <stddef.h> - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/ppb_udp_socket.h" -#include "ppapi/cpp/net_address.h" -#include "ppapi/tests/test_case.h" - -namespace { -typedef int32_t (*UDPSocketSetOption)(PP_Resource udp_socket, - PP_UDPSocket_Option name, - struct PP_Var value, - struct PP_CompletionCallback callback); -} - -namespace pp { -class UDPSocket; -} - -class TestUDPSocket: public TestCase { - public: - explicit TestUDPSocket(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string GetLocalAddress(pp::NetAddress* address); - std::string SetBroadcastOptions(pp::UDPSocket* socket); - std::string BindUDPSocket(pp::UDPSocket* socket, - const pp::NetAddress& address); - std::string LookupPortAndBindUDPSocket(pp::UDPSocket* socket, - pp::NetAddress* address); - std::string ReadSocket(pp::UDPSocket* socket, - pp::NetAddress* address, - size_t size, - std::string* message); - std::string PassMessage(pp::UDPSocket* target, - pp::UDPSocket* source, - const pp::NetAddress& target_address, - const std::string& message, - pp::NetAddress* recvfrom_address); - std::string SetMulticastOptions(pp::UDPSocket* socket); - - std::string TestReadWrite(); - std::string TestBroadcast(); - int32_t SetOptionValue(UDPSocketSetOption func, - PP_Resource socket, - PP_UDPSocket_Option option, - const PP_Var& value); - std::string TestSetOption_1_0(); - std::string TestSetOption_1_1(); - std::string TestSetOption(); - std::string TestParallelSend(); - std::string TestMulticast(); - - // Error cases. It's up to the parent test fixture to ensure that these events - // result in errors. - std::string TestBindFails(); - std::string TestSetBroadcastFails(); - std::string TestSendToFails(); - std::string TestReadFails(); - - pp::NetAddress address_; - - const PPB_UDPSocket_1_0* socket_interface_1_0_; - const PPB_UDPSocket_1_1* socket_interface_1_1_; -}; - -#endif // PPAPI_TESTS_TEST_UDP_SOCKET_H_
diff --git a/tests/test_udp_socket_private.cc b/tests/test_udp_socket_private.cc deleted file mode 100644 index 9940b9f..0000000 --- a/tests/test_udp_socket_private.cc +++ /dev/null
@@ -1,261 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <cstring> -#include <vector> - -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/cpp/private/tcp_socket_private.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_udp_socket_private.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(UDPSocketPrivate); - -namespace { - -const uint16_t kPortScanFrom = 1024; -const uint16_t kPortScanTo = 4096; - -} // namespace - -TestUDPSocketPrivate::TestUDPSocketPrivate( - TestingInstance* instance) - : TestCase(instance) { -} - -bool TestUDPSocketPrivate::Init() { - bool tcp_socket_private_is_available = pp::TCPSocketPrivate::IsAvailable(); - if (!tcp_socket_private_is_available) - instance_->AppendError("PPB_TCPSocket_Private interface not available"); - - bool udp_socket_private_is_available = pp::UDPSocketPrivate::IsAvailable(); - if (!udp_socket_private_is_available) - instance_->AppendError("PPB_UDPSocket_Private interface not available"); - - bool net_address_private_is_available = pp::NetAddressPrivate::IsAvailable(); - if (!net_address_private_is_available) - instance_->AppendError("PPB_NetAddress_Private interface not available"); - - bool init_host_port = GetLocalHostPort(instance_->pp_instance(), - &host_, &port_); - if (!init_host_port) - instance_->AppendError("Can't init host and port"); - - return tcp_socket_private_is_available && - udp_socket_private_is_available && - net_address_private_is_available && - init_host_port && - CheckTestingInterface() && - EnsureRunningOverHTTP(); -} - -void TestUDPSocketPrivate::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestUDPSocketPrivate, Connect, filter); - RUN_CALLBACK_TEST(TestUDPSocketPrivate, ConnectFailure, filter); - RUN_CALLBACK_TEST(TestUDPSocketPrivate, Broadcast, filter); - RUN_CALLBACK_TEST(TestUDPSocketPrivate, SetSocketFeatureErrors, filter); -} - -std::string TestUDPSocketPrivate::GetLocalAddress( - PP_NetAddress_Private* address) { - pp::TCPSocketPrivate socket(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket.Connect(host_.c_str(), port_, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_TRUE(socket.GetLocalAddress(address)); - socket.Disconnect(); - PASS(); -} - -std::string TestUDPSocketPrivate::SetBroadcastOptions( - pp::UDPSocketPrivate* socket) { - int32_t rv = socket->SetSocketFeature( - PP_UDPSOCKETFEATURE_PRIVATE_ADDRESS_REUSE, pp::Var(true)); - if (rv != PP_OK) - return ReportError("PPB_UDPSocket_Private::SetSocketFeature", rv); - - rv = socket->SetSocketFeature(PP_UDPSOCKETFEATURE_PRIVATE_BROADCAST, - pp::Var(true)); - if (rv != PP_OK) - return ReportError("PPB_UDPSocket_Private::SetSocketFeature", rv); - - PASS(); -} - -std::string TestUDPSocketPrivate::BindUDPSocket( - pp::UDPSocketPrivate* socket, - PP_NetAddress_Private* address) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket->Bind(address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - PASS(); -} - -std::string TestUDPSocketPrivate::LookupPortAndBindUDPSocket( - pp::UDPSocketPrivate* socket, - PP_NetAddress_Private *address) { - PP_NetAddress_Private base_address; - ASSERT_SUBTEST_SUCCESS(GetLocalAddress(&base_address)); - - bool is_free_port_found = false; - for (uint16_t port = kPortScanFrom; port < kPortScanTo; ++port) { - if (!pp::NetAddressPrivate::ReplacePort(base_address, port, address)) - return "PPB_NetAddress_Private::ReplacePort: Failed"; - if (BindUDPSocket(socket, address).empty()) { - is_free_port_found = true; - break; - } - } - if (!is_free_port_found) - return "Can't find available port"; - if (!socket->GetBoundAddress(address)) - return "PPB_UDPSocket_Private::GetBoundAddress: Failed"; - PASS(); -} - -std::string TestUDPSocketPrivate::BindUDPSocketFailure( - pp::UDPSocketPrivate* socket, - PP_NetAddress_Private *address) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(socket->Bind(address, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_NE(PP_OK, callback.result()); - ASSERT_FALSE(socket->GetBoundAddress(address)); - PASS(); -} - -std::string TestUDPSocketPrivate::ReadSocket(pp::UDPSocketPrivate* socket, - PP_NetAddress_Private* address, - size_t size, - std::string* message) { - std::vector<char> buffer(size); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - socket->RecvFrom(&buffer[0], static_cast<int32_t>(size), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_FALSE(callback.result() < 0); - ASSERT_EQ(size, static_cast<size_t>(callback.result())); - message->assign(buffer.begin(), buffer.end()); - PASS(); -} - -std::string TestUDPSocketPrivate::PassMessage(pp::UDPSocketPrivate* target, - pp::UDPSocketPrivate* source, - PP_NetAddress_Private* address, - const std::string& message) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - int32_t rv = source->SendTo(message.c_str(), - static_cast<int32_t>(message.size()), address, - callback.GetCallback()); - std::string str; - ASSERT_SUBTEST_SUCCESS(ReadSocket(target, address, message.size(), &str)); - - callback.WaitForResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_FALSE(callback.result() < 0); - ASSERT_EQ(message.size(), static_cast<size_t>(callback.result())); - ASSERT_EQ(message, str); - PASS(); -} - -std::string TestUDPSocketPrivate::TestConnect() { - pp::UDPSocketPrivate server_socket(instance_), client_socket(instance_); - PP_NetAddress_Private server_address, client_address; - - ASSERT_SUBTEST_SUCCESS(LookupPortAndBindUDPSocket(&server_socket, - &server_address)); - ASSERT_SUBTEST_SUCCESS(LookupPortAndBindUDPSocket(&client_socket, - &client_address)); - const std::string message = "Simple message that will be sent via UDP"; - ASSERT_SUBTEST_SUCCESS(PassMessage(&server_socket, &client_socket, - &server_address, - message)); - PP_NetAddress_Private recv_from_address; - ASSERT_TRUE(server_socket.GetRecvFromAddress(&recv_from_address)); - ASSERT_TRUE(pp::NetAddressPrivate::AreEqual(recv_from_address, - client_address)); - - server_socket.Close(); - client_socket.Close(); - - if (server_socket.GetBoundAddress(&server_address)) - return "PPB_UDPSocket_Private::GetBoundAddress: expected Failure"; - PASS(); -} - -std::string TestUDPSocketPrivate::TestConnectFailure() { - pp::UDPSocketPrivate socket(instance_); - PP_NetAddress_Private invalid_address = {}; - - std::string error_message = BindUDPSocketFailure(&socket, &invalid_address); - if (!error_message.empty()) - return error_message; - - PASS(); -} - -std::string TestUDPSocketPrivate::TestBroadcast() { - const uint8_t broadcast_ip[4] = { 0xff, 0xff, 0xff, 0xff }; - - pp::UDPSocketPrivate server1(instance_), server2(instance_); - - ASSERT_SUBTEST_SUCCESS(SetBroadcastOptions(&server1)); - ASSERT_SUBTEST_SUCCESS(SetBroadcastOptions(&server2)); - PP_NetAddress_Private server_address; - ASSERT_TRUE(pp::NetAddressPrivate::GetAnyAddress(false, &server_address)); - ASSERT_SUBTEST_SUCCESS(BindUDPSocket(&server1, &server_address)); - // Fill port field of |server_address|. - ASSERT_TRUE(server1.GetBoundAddress(&server_address)); - ASSERT_SUBTEST_SUCCESS(BindUDPSocket(&server2, &server_address)); - - const uint16_t port = pp::NetAddressPrivate::GetPort(server_address); - PP_NetAddress_Private broadcast_address; - ASSERT_TRUE(pp::NetAddressPrivate::CreateFromIPv4Address( - broadcast_ip, port, &broadcast_address)); - - std::string message; - const std::string first_message = "first message"; - const std::string second_message = "second_message"; - - ASSERT_SUBTEST_SUCCESS(PassMessage(&server1, &server2, - &broadcast_address, - first_message)); - // |first_message| also arrived to |server2|. - ASSERT_SUBTEST_SUCCESS(ReadSocket(&server2, &broadcast_address, - first_message.size(), &message)); - ASSERT_EQ(first_message, message); - - ASSERT_SUBTEST_SUCCESS(PassMessage(&server2, &server1, - &broadcast_address, - second_message)); - // |second_message| also arrived to |server1|. - ASSERT_SUBTEST_SUCCESS(ReadSocket(&server1, &broadcast_address, - second_message.size(), &message)); - ASSERT_EQ(second_message, message); - - server1.Close(); - server2.Close(); - PASS(); -} - -std::string TestUDPSocketPrivate::TestSetSocketFeatureErrors() { - pp::UDPSocketPrivate socket(instance_); - // Try to pass incorrect feature name. - int32_t rv = socket.SetSocketFeature(PP_UDPSOCKETFEATURE_PRIVATE_COUNT, - pp::Var(true)); - ASSERT_EQ(PP_ERROR_BADARGUMENT, rv); - - // Try to pass incorrect feature value's type. - rv = socket.SetSocketFeature(PP_UDPSOCKETFEATURE_PRIVATE_ADDRESS_REUSE, - pp::Var(1)); - ASSERT_EQ(PP_ERROR_BADARGUMENT, rv); - PASS(); -}
diff --git a/tests/test_udp_socket_private.h b/tests/test_udp_socket_private.h deleted file mode 100644 index 985fd9b..0000000 --- a/tests/test_udp_socket_private.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_UDP_SOCKET_PRIVATE_H_ -#define PPAPI_TESTS_TEST_UDP_SOCKET_PRIVATE_H_ - -#include <stddef.h> - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/cpp/private/udp_socket_private.h" -#include "ppapi/tests/test_case.h" - -class TestUDPSocketPrivate : public TestCase { - public: - explicit TestUDPSocketPrivate(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string GetLocalAddress(PP_NetAddress_Private* address); - std::string SetBroadcastOptions(pp::UDPSocketPrivate* socket); - std::string BindUDPSocket(pp::UDPSocketPrivate* socket, - PP_NetAddress_Private *address); - std::string LookupPortAndBindUDPSocket(pp::UDPSocketPrivate* socket, - PP_NetAddress_Private* address); - std::string BindUDPSocketFailure(pp::UDPSocketPrivate* socket, - PP_NetAddress_Private *address); - std::string ReadSocket(pp::UDPSocketPrivate* socket, - PP_NetAddress_Private* address, - size_t size, - std::string* message); - std::string PassMessage(pp::UDPSocketPrivate* target, - pp::UDPSocketPrivate* source, - PP_NetAddress_Private* address, - const std::string& message); - - std::string TestConnect(); - std::string TestConnectFailure(); - std::string TestBroadcast(); - std::string TestSetSocketFeatureErrors(); - - std::string host_; - uint16_t port_; -}; - -#endif // PPAPI_TESTS_TEST_UDP_SOCKET_PRIVATE_H_
diff --git a/tests/test_udp_socket_private_disallowed.cc b/tests/test_udp_socket_private_disallowed.cc deleted file mode 100644 index ad98118..0000000 --- a/tests/test_udp_socket_private_disallowed.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_udp_socket_private_disallowed.h" - -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/tests/testing_instance.h" -#include "ppapi/tests/test_utils.h" - -REGISTER_TEST_CASE(UDPSocketPrivateDisallowed); - -TestUDPSocketPrivateDisallowed::TestUDPSocketPrivateDisallowed( - TestingInstance* instance) - : TestCase(instance), udp_socket_private_interface_(NULL) { -} - -bool TestUDPSocketPrivateDisallowed::Init() { - udp_socket_private_interface_ = static_cast<const PPB_UDPSocket_Private*>( - pp::Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE)); - if (!udp_socket_private_interface_) - instance_->AppendError("UDPSocketPrivate interface not available"); - return udp_socket_private_interface_ && CheckTestingInterface(); -} - -void TestUDPSocketPrivateDisallowed::RunTests(const std::string& filter) { - RUN_TEST(Bind, filter); -} - -std::string TestUDPSocketPrivateDisallowed::TestBind() { - PP_Resource socket = - udp_socket_private_interface_->Create(instance_->pp_instance()); - if (0 != socket) { - PP_NetAddress_Private addr; - pp::NetAddressPrivate::GetAnyAddress(false, &addr); - - TestCompletionCallback callback(instance_->pp_instance()); - callback.WaitForResult(udp_socket_private_interface_->Bind(socket, &addr, - callback.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - } - PASS(); -}
diff --git a/tests/test_udp_socket_private_disallowed.h b/tests/test_udp_socket_private_disallowed.h deleted file mode 100644 index 86f04cf..0000000 --- a/tests/test_udp_socket_private_disallowed.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_UDP_SOCKET_PRIVATE_DISALLOWED_H_ -#define PPAPI_TESTS_TEST_UDP_SOCKET_PRIVATE_DISALLOWED_H_ - -#include <string> - -#include "ppapi/cpp/private/udp_socket_private.h" -#include "ppapi/tests/test_case.h" - -class TestUDPSocketPrivateDisallowed : public TestCase { - public: - explicit TestUDPSocketPrivateDisallowed(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestBind(); - - const PPB_UDPSocket_Private* udp_socket_private_interface_; -}; - -#endif // PPAPI_TESTS_TEST_UDP_SOCKET_PRIVATE_DISALLOWED_H_
diff --git a/tests/test_uma.cc b/tests/test_uma.cc deleted file mode 100644 index 8638945..0000000 --- a/tests/test_uma.cc +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_uma.h" - -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(UMA); - -bool TestUMA::Init() { - uma_interface_ = static_cast<const PPB_UMA_Private*>( - pp::Module::Get()->GetBrowserInterface(PPB_UMA_PRIVATE_INTERFACE)); - return !!uma_interface_; -} - -void TestUMA::RunTests(const std::string& filter) { - RUN_TEST(Count, filter); - RUN_TEST(Time, filter); - RUN_TEST(Enum, filter); -} - -std::string TestUMA::TestCount() { - pp::Var name_var = pp::Var("Test.CountHistogram"); - PP_Var name = name_var.pp_var(); - PP_Instance instance = instance_->pp_instance(); - uma_interface_->HistogramCustomCounts(instance, name, 10, 1, 100, 50); - uma_interface_->HistogramCustomCounts(instance, name, 30, 1, 100, 50); - uma_interface_->HistogramCustomCounts(instance, name, 20, 1, 100, 50); - uma_interface_->HistogramCustomCounts(instance, name, 40, 1, 100, 50); - // Test that passing in different construction arguments for the same - // histogram name does not crash. - uma_interface_->HistogramCustomCounts(instance, name, 40, 1, 100, 100); - uma_interface_->HistogramCustomCounts(instance, name, 40, 1, 90, 50); - uma_interface_->HistogramCustomCounts(instance, name, 40, 10, 100, 50); - PASS(); -} - -std::string TestUMA::TestTime() { - pp::Var name_var = pp::Var("Test.TimeHistogram"); - PP_Var name = name_var.pp_var(); - PP_Instance instance = instance_->pp_instance(); - uma_interface_->HistogramCustomTimes(instance, name, 100, 1, 10000, 50); - uma_interface_->HistogramCustomTimes(instance, name, 1000, 1, 10000, 50); - uma_interface_->HistogramCustomTimes(instance, name, 5000, 1, 10000, 50); - uma_interface_->HistogramCustomTimes(instance, name, 10, 1, 10000, 50); - // Test that passing in different construction arguments for the same - // histogram name does not crash. - uma_interface_->HistogramCustomTimes(instance, name, 10, 1, 10000, 100); - uma_interface_->HistogramCustomTimes(instance, name, 10, 1, 9000, 50); - uma_interface_->HistogramCustomTimes(instance, name, 10, 100, 10000, 50); - PASS(); -} - -std::string TestUMA::TestEnum() { - pp::Var name_var = pp::Var("Test.EnumHistogram"); - PP_Var name = name_var.pp_var(); - PP_Instance instance = instance_->pp_instance(); - uma_interface_->HistogramEnumeration(instance, name, 0, 5); - uma_interface_->HistogramEnumeration(instance, name, 3, 5); - uma_interface_->HistogramEnumeration(instance, name, 3, 5); - uma_interface_->HistogramEnumeration(instance, name, 1, 5); - uma_interface_->HistogramEnumeration(instance, name, 2, 5); - // Test that passing in different construction arguments for the same - // histogram name does not crash. - uma_interface_->HistogramEnumeration(instance, name, 2, 6); - PASS(); -} -
diff --git a/tests/test_uma.h b/tests/test_uma.h deleted file mode 100644 index 4924f29..0000000 --- a/tests/test_uma.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_UMA_H_ -#define PPAPI_TESTS_TEST_UMA_H_ - -#include <string> - -#include "ppapi/c/private/ppb_uma_private.h" -#include "ppapi/tests/test_case.h" - -class TestUMA : public TestCase { - public: - explicit TestUMA(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestCount(); - std::string TestTime(); - std::string TestEnum(); - - // Used by the tests that access the C API directly. - const PPB_UMA_Private* uma_interface_; -}; - -#endif // PPAPI_TESTS_TEST_UMA_H_
diff --git a/tests/test_url_loader.cc b/tests/test_url_loader.cc deleted file mode 100644 index 6e4653d..0000000 --- a/tests/test_url_loader.cc +++ /dev/null
@@ -1,1098 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_url_loader.h" - -#include <stddef.h> -#include <stdio.h> -#include <string.h> -#include <string> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/c/ppb_url_loader.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" -#include "ppapi/cpp/dev/url_util_dev.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/file_io_private.h" -#include "ppapi/cpp/url_loader.h" -#include "ppapi/cpp/url_request_info.h" -#include "ppapi/cpp/url_response_info.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(URLLoader); - -namespace { - -int32_t WriteEntireBuffer(PP_Instance instance, - pp::FileIO* file_io, - int32_t offset, - const std::string& data, - CallbackType callback_type) { - TestCompletionCallback callback(instance, callback_type); - int32_t write_offset = offset; - const char* buf = data.c_str(); - int32_t size = static_cast<int32_t>(data.size()); - - while (write_offset < offset + size) { - callback.WaitForResult(file_io->Write(write_offset, - &buf[write_offset - offset], - size - write_offset + offset, - callback.GetCallback())); - if (callback.result() < 0) - return callback.result(); - if (callback.result() == 0) - return PP_ERROR_FAILED; - write_offset += callback.result(); - } - - return PP_OK; -} - -} // namespace - -TestURLLoader::TestURLLoader(TestingInstance* instance) - : TestCase(instance), - file_io_private_interface_(NULL), - url_loader_trusted_interface_(NULL) { -} - -bool TestURLLoader::Init() { - if (!CheckTestingInterface()) { - instance_->AppendError("Testing interface not available"); - return false; - } - - const PPB_FileIO* file_io_interface = static_cast<const PPB_FileIO*>( - pp::Module::Get()->GetBrowserInterface(PPB_FILEIO_INTERFACE)); - if (!file_io_interface) - instance_->AppendError("FileIO interface not available"); - - file_io_private_interface_ = static_cast<const PPB_FileIO_Private*>( - pp::Module::Get()->GetBrowserInterface(PPB_FILEIO_PRIVATE_INTERFACE)); - if (!file_io_private_interface_) - instance_->AppendError("FileIO_Private interface not available"); - url_loader_trusted_interface_ = static_cast<const PPB_URLLoaderTrusted*>( - pp::Module::Get()->GetBrowserInterface(PPB_URLLOADERTRUSTED_INTERFACE)); - if (!testing_interface_->IsOutOfProcess()) { - // Trusted interfaces are not supported under NaCl. -#if !(defined __native_client__) - if (!url_loader_trusted_interface_) - instance_->AppendError("URLLoaderTrusted interface not available"); -#else - if (url_loader_trusted_interface_) - instance_->AppendError("URLLoaderTrusted interface is supported by NaCl"); -#endif - } - return EnsureRunningOverHTTP(); -} - -/* - * The test order is important here, as running tests out of order may cause - * test timeout. - * - * Here is the environment: - * - * 1. net::EmbeddedTestServer only accepts one open connection at the time. - * 2. HTTP socket pool keeps sockets open for several seconds after last use - * (hoping that there will be another request that could reuse the connection). - * 3. HTTP socket pool is separated by host/port and privacy mode (which is - * based on cookies set/get permissions). So, connections to 127.0.0.1, - * localhost and localhost in privacy mode cannot reuse existing socket and will - * try to open another connection. - * - * Here is the problem: - * - * Original test order was repeatedly accessing 127.0.0.1, localhost and - * localhost in privacy mode, causing new sockets to open and try to connect to - * testserver, which they couldn't until previous connection is closed by socket - * pool idle socket timeout (10 seconds). - * - * Because of this the test run was taking around 45 seconds, and test was - * reported as 'timed out' by trybot. - * - * Re-ordering of tests provides more sequential access to 127.0.0.1, localhost - * and localhost in privacy mode. It decreases the number of times when socket - * pool doesn't have existing connection to host and has to wait, therefore - * reducing total test time and ensuring its completion under 30 seconds. - */ -void TestURLLoader::RunTests(const std::string& filter) { - // These tests connect to 127.0.0.1: - RUN_CALLBACK_TEST(TestURLLoader, BasicGET, filter); - RUN_CALLBACK_TEST(TestURLLoader, BasicPOST, filter); - RUN_CALLBACK_TEST(TestURLLoader, BasicFilePOST, filter); - RUN_CALLBACK_TEST(TestURLLoader, BasicFileRangePOST, filter); - RUN_CALLBACK_TEST(TestURLLoader, CompoundBodyPOST, filter); - RUN_CALLBACK_TEST(TestURLLoader, EmptyDataPOST, filter); - RUN_CALLBACK_TEST(TestURLLoader, BinaryDataPOST, filter); - RUN_CALLBACK_TEST(TestURLLoader, CustomRequestHeader, filter); - RUN_CALLBACK_TEST(TestURLLoader, FailsBogusContentLength, filter); - RUN_CALLBACK_TEST(TestURLLoader, StreamToFile, filter); - RUN_CALLBACK_TEST(TestURLLoader, UntrustedJavascriptURLRestriction, filter); - RUN_CALLBACK_TEST(TestURLLoader, TrustedJavascriptURLRestriction, filter); - RUN_CALLBACK_TEST(TestURLLoader, UntrustedHttpRequests, filter); - RUN_CALLBACK_TEST(TestURLLoader, TrustedHttpRequests, filter); - RUN_CALLBACK_TEST(TestURLLoader, FollowURLRedirect, filter); - RUN_CALLBACK_TEST(TestURLLoader, AuditURLRedirect, filter); - RUN_CALLBACK_TEST(TestURLLoader, RestrictURLRedirectCommon, filter); - RUN_CALLBACK_TEST(TestURLLoader, RestrictURLRedirectEnabled, filter); - RUN_CALLBACK_TEST(TestURLLoader, RestrictURLRedirectDisabled, filter); - RUN_CALLBACK_TEST(TestURLLoader, AbortCalls, filter); - RUN_CALLBACK_TEST(TestURLLoader, UntendedLoad, filter); - RUN_CALLBACK_TEST(TestURLLoader, PrefetchBufferThreshold, filter); - RUN_CALLBACK_TEST(TestURLLoader, XRequestedWithHeader, filter); - // These tests connect to localhost with privacy mode enabled: - RUN_CALLBACK_TEST(TestURLLoader, UntrustedSameOriginRestriction, filter); - RUN_CALLBACK_TEST(TestURLLoader, UntrustedCrossOriginRequest, filter); - RUN_CALLBACK_TEST(TestURLLoader, UntrustedCorbEligibleRequest, filter); - // These tests connect to localhost with privacy mode disabled: - RUN_CALLBACK_TEST(TestURLLoader, TrustedSameOriginRestriction, filter); - RUN_CALLBACK_TEST(TestURLLoader, TrustedCrossOriginRequest, filter); - RUN_CALLBACK_TEST(TestURLLoader, TrustedCorbEligibleRequest, filter); -} - -std::string TestURLLoader::ReadEntireFile(pp::FileIO* file_io, - std::string* data) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - char buf[256]; - int64_t offset = 0; - - for (;;) { - callback.WaitForResult(file_io->Read(offset, buf, sizeof(buf), - callback.GetCallback())); - if (callback.result() < 0) - return ReportError("FileIO::Read", callback.result()); - if (callback.result() == 0) - break; - offset += callback.result(); - data->append(buf, callback.result()); - } - - PASS(); -} - -std::string TestURLLoader::ReadEntireResponseBody(pp::URLLoader* loader, - std::string* body) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - char buf[2]; // Small so that multiple reads are needed. - - for (;;) { - callback.WaitForResult( - loader->ReadResponseBody(buf, sizeof(buf), callback.GetCallback())); - if (callback.result() < 0) - return ReportError("URLLoader::ReadResponseBody", callback.result()); - if (callback.result() == 0) - break; - body->append(buf, callback.result()); - } - - PASS(); -} - -std::string TestURLLoader::LoadAndCompareBody( - const pp::URLRequestInfo& request, - const std::string& expected_body) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::URLLoader loader(instance_); - callback.WaitForResult(loader.Open(request, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::URLResponseInfo response_info(loader.GetResponseInfo()); - if (response_info.is_null()) - return "URLLoader::GetResponseInfo returned null"; - int32_t status_code = response_info.GetStatusCode(); - if (status_code != 200) - return "Unexpected HTTP status code"; - - std::string body; - std::string error = ReadEntireResponseBody(&loader, &body); - if (!error.empty()) - return error; - - if (body.size() != expected_body.size()) - return "URLLoader::ReadResponseBody returned unexpected content length"; - if (body != expected_body) - return "URLLoader::ReadResponseBody returned unexpected content"; - - PASS(); -} - -std::string TestURLLoader::LoadAndFail(const pp::URLRequestInfo& request) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::URLLoader loader(instance_); - callback.WaitForResult(loader.Open(request, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - - PASS(); -} - -int32_t TestURLLoader::OpenFileSystem(pp::FileSystem* file_system, - std::string* message) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(file_system->Open(1024, callback.GetCallback())); - if (callback.failed()) { - message->assign(callback.errors()); - return callback.result(); - } - if (callback.result() != PP_OK) { - message->assign("FileSystem::Open"); - return callback.result(); - } - return callback.result(); -} - -int32_t TestURLLoader::PrepareFileForPost( - const pp::FileRef& file_ref, - const std::string& data, - std::string* message) { - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::FileIO file_io(instance_); - callback.WaitForResult(file_io.Open(file_ref, - PP_FILEOPENFLAG_CREATE | - PP_FILEOPENFLAG_TRUNCATE | - PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - if (callback.failed()) { - message->assign(callback.errors()); - return callback.result(); - } - if (callback.result() != PP_OK) { - message->assign("FileIO::Open failed."); - return callback.result(); - } - - int32_t rv = WriteEntireBuffer(instance_->pp_instance(), &file_io, 0, data, - callback_type()); - if (rv != PP_OK) { - message->assign("FileIO::Write failed."); - return rv; - } - - return rv; -} - -std::string TestURLLoader::GetReachableAbsoluteURL( - const std::string& file_name) { - // Get the absolute page URL and replace the test case file name - // with the given one. - pp::Var document_url( - pp::PASS_REF, - testing_interface_->GetDocumentURL(instance_->pp_instance(), - NULL)); - std::string url(document_url.AsString()); - std::string old_name("test_case.html"); - size_t index = url.find(old_name); - ASSERT_NE(index, std::string::npos); - url.replace(index, old_name.length(), file_name); - return url; -} - -std::string TestURLLoader::GetReachableCrossOriginURL( - const std::string& file_name) { - // Get an absolute URL and use it to construct a URL that will be - // considered cross-origin by the CORS access control code, and yet be - // reachable by the test server. - std::string url = GetReachableAbsoluteURL(file_name); - // Replace '127.0.0.1' with 'localhost'. - std::string host("127.0.0.1"); - size_t index = url.find(host); - ASSERT_NE(index, std::string::npos); - url.replace(index, host.length(), "localhost"); - return url; -} - -int32_t TestURLLoader::OpenUntrusted(const std::string& method, - const std::string& header) { - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod(method); - request.SetHeaders(header); - - return OpenUntrusted(request, NULL); -} - -int32_t TestURLLoader::OpenTrusted(const std::string& method, - const std::string& header) { - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod(method); - request.SetHeaders(header); - - return OpenTrusted(request, NULL); -} - -int32_t TestURLLoader::OpenUntrusted(const pp::URLRequestInfo& request, - std::string* response_body) { - return Open(request, false, response_body); -} - -int32_t TestURLLoader::OpenTrusted(const pp::URLRequestInfo& request, - std::string* response_body) { - return Open(request, true, response_body); -} - -int32_t TestURLLoader::Open(const pp::URLRequestInfo& request, - bool trusted, - std::string* response_body) { - pp::URLLoader loader(instance_); - if (trusted) - url_loader_trusted_interface_->GrantUniversalAccess(loader.pp_resource()); - - return OpenURLRequest(instance_->pp_instance(), &loader, request, - callback_type(), response_body); -} - -std::string TestURLLoader::TestBasicGET() { - pp::URLRequestInfo request(instance_); - request.SetURL("test_url_loader_data/hello.txt"); - return LoadAndCompareBody(request, "hello\n"); -} - -std::string TestURLLoader::TestBasicPOST() { - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod("POST"); - std::string postdata("postdata"); - request.AppendDataToBody(postdata.data(), - static_cast<uint32_t>(postdata.length())); - return LoadAndCompareBody(request, postdata); -} - -std::string TestURLLoader::TestBasicFilePOST() { - std::string message; - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - int32_t rv = OpenFileSystem(&file_system, &message); - if (rv != PP_OK) - return ReportError(message.c_str(), rv); - - pp::FileRef file_ref(file_system, "/file_post_test"); - std::string postdata("postdata"); - rv = PrepareFileForPost(file_ref, postdata, &message); - if (rv != PP_OK) - return ReportError(message.c_str(), rv); - - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod("POST"); - request.AppendFileToBody(file_ref, 0); - return LoadAndCompareBody(request, postdata); -} - -std::string TestURLLoader::TestBasicFileRangePOST() { - std::string message; - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - int32_t rv = OpenFileSystem(&file_system, &message); - if (rv != PP_OK) - return ReportError(message.c_str(), rv); - - pp::FileRef file_ref(file_system, "/file_range_post_test"); - std::string postdata("postdatapostdata"); - rv = PrepareFileForPost(file_ref, postdata, &message); - if (rv != PP_OK) - return ReportError(message.c_str(), rv); - - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod("POST"); - request.AppendFileRangeToBody(file_ref, 4, 12, 0); - return LoadAndCompareBody(request, postdata.substr(4, 12)); -} - -std::string TestURLLoader::TestCompoundBodyPOST() { - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod("POST"); - std::string postdata1("post"); - request.AppendDataToBody(postdata1.data(), - static_cast<uint32_t>(postdata1.length())); - std::string postdata2("data"); - request.AppendDataToBody(postdata2.data(), - static_cast<uint32_t>(postdata2.length())); - return LoadAndCompareBody(request, postdata1 + postdata2); -} - -std::string TestURLLoader::TestEmptyDataPOST() { - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod("POST"); - request.AppendDataToBody("", 0); - return LoadAndCompareBody(request, std::string()); -} - -std::string TestURLLoader::TestBinaryDataPOST() { - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod("POST"); - const char postdata_chars[] = - "\x00\x01\x02\x03\x04\x05postdata\xfa\xfb\xfc\xfd\xfe\xff"; - std::string postdata(postdata_chars, - sizeof(postdata_chars) / sizeof(postdata_chars[0])); - request.AppendDataToBody(postdata.data(), - static_cast<uint32_t>(postdata.length())); - return LoadAndCompareBody(request, postdata); -} - -std::string TestURLLoader::TestCustomRequestHeader() { - pp::URLRequestInfo request(instance_); - request.SetURL("/echoheader?Foo"); - request.SetHeaders("Foo: 1"); - return LoadAndCompareBody(request, "1"); -} - -std::string TestURLLoader::TestFailsBogusContentLength() { - pp::URLRequestInfo request(instance_); - request.SetURL("/echo"); - request.SetMethod("POST"); - request.SetHeaders("Content-Length: 400"); - std::string postdata("postdata"); - request.AppendDataToBody(postdata.data(), - static_cast<uint32_t>(postdata.length())); - - int32_t rv; - rv = OpenUntrusted(request, NULL); - if (rv != PP_ERROR_NOACCESS) - return ReportError( - "Untrusted request with bogus Content-Length restriction", rv); - - PASS(); -} - -std::string TestURLLoader::TestStreamToFile() { - pp::URLRequestInfo request(instance_); - request.SetURL("test_url_loader_data/hello.txt"); - ASSERT_FALSE(request.SetStreamToFile(true)); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::URLLoader loader(instance_); - callback.WaitForResult(loader.Open(request, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::URLResponseInfo response_info(loader.GetResponseInfo()); - if (response_info.is_null()) - return "URLLoader::GetResponseInfo returned null"; - int32_t status_code = response_info.GetStatusCode(); - if (status_code != 200) - return "Unexpected HTTP status code"; - - pp::FileRef body(response_info.GetBodyAsFileRef()); - ASSERT_TRUE(body.is_null()); - - callback.WaitForResult(loader.FinishStreamingToFile(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_ERROR_NOTSUPPORTED, callback.result()); - - PASS(); -} - -// Untrusted, unintended cross-origin requests should fail. -std::string TestURLLoader::TestUntrustedSameOriginRestriction() { - pp::URLRequestInfo request(instance_); - std::string cross_origin_url = GetReachableCrossOriginURL("test_case.html"); - request.SetURL(cross_origin_url); - - int32_t rv = OpenUntrusted(request, NULL); - if (rv != PP_ERROR_NOACCESS) - return ReportError( - "Untrusted, unintended cross-origin request restriction", rv); - - PASS(); -} - -// Trusted, unintended cross-origin requests should succeed. -// Use a CORB/ORB-passing resource, so ORB doesn't interfere with the test. -std::string TestURLLoader::TestTrustedSameOriginRestriction() { - pp::URLRequestInfo request(instance_); - std::string cross_origin_url = GetReachableCrossOriginURL("test_image.png"); - request.SetURL(cross_origin_url); - - int32_t rv = OpenTrusted(request, NULL); - if (rv != PP_OK) - return ReportError("Trusted cross-origin request failed", rv); - - PASS(); -} - -// Untrusted, intended cross-origin requests should use CORS and succeed. -std::string TestURLLoader::TestUntrustedCrossOriginRequest() { - pp::URLRequestInfo request(instance_); - std::string cross_origin_url = GetReachableCrossOriginURL("test_case.html"); - request.SetURL(cross_origin_url); - request.SetAllowCrossOriginRequests(true); - - int32_t rv = OpenUntrusted(request, NULL); - if (rv != PP_OK) - return ReportError( - "Untrusted, intended cross-origin request failed", rv); - - PASS(); -} - -// Trusted, intended cross-origin requests should use CORS and succeed. -// Use a CORB/ORB-passing resource, so ORB doesn't interfere with the test. -std::string TestURLLoader::TestTrustedCrossOriginRequest() { - pp::URLRequestInfo request(instance_); - std::string cross_origin_url = GetReachableCrossOriginURL("test_image.png"); - request.SetURL(cross_origin_url); - request.SetAllowCrossOriginRequests(true); - - int32_t rv = OpenTrusted(request, NULL); - if (rv != PP_OK) - return ReportError("Trusted cross-origin request failed", rv); - - PASS(); -} - -// CORB (Cross-Origin Read Blocking) should apply to plugins without universal -// access. This test is very similar to TestUntrustedSameOriginRestriction, but -// explicitly uses a CORB-eligible response (test/json + nosniff). -std::string TestURLLoader::TestUntrustedCorbEligibleRequest() { - // It is important to use a CORB-eligible response here: text/json + nosniff. - std::string cross_origin_url = - GetReachableCrossOriginURL("corb_eligible_resource.json"); - - pp::URLRequestInfo request(instance_); - request.SetURL(cross_origin_url); - request.SetAllowCrossOriginRequests(true); - - std::string response_body; - int32_t rv = OpenUntrusted(request, &response_body); - - // Main verification - the response should be blocked. Ideally the blocking - // should be done before the data leaves the browser and/or network-service - // process (the test doesn't verify this though). - if (rv != PP_ERROR_NOACCESS) { - return ReportError("Untrusted Javascript URL request restriction failed", - rv); - } - ASSERT_EQ("", response_body); - PASS(); -} - -// CORB (Cross-Origin Read Blocking) should apply, even to plugins with -// universal access like the PDF plugin. -// -// This test is quite similar to TestTrustedSameOriginRestriction, but it -// explicitly uses a CORB-eligible response (test/json + nosniff) and also -// explicitly verifies that the response body was not blocked. -std::string TestURLLoader::TestTrustedCorbEligibleRequest() { - // It is important to use a CORB-eligible response here: text/json + nosniff. - std::string cross_origin_url = - GetReachableCrossOriginURL("corb_eligible_resource.json"); - - pp::URLRequestInfo request(instance_); - request.SetURL(cross_origin_url); - request.SetAllowCrossOriginRequests(true); - - // The test code below (similarly to the PDF plugin) sets the referrer - this - // will propagate into network::ResourceRequest::request_initiator and should - // match the NetworkService::AddAllowedRequestInitiatorForPlugin exemption. - // This will pass `request_initiator_origin_lock` verification. - std::string referrer = GetReachableAbsoluteURL(""); - request.SetCustomReferrerURL(referrer); - request.SetHeaders(referrer); - - std::string response_body; - int32_t rv = OpenTrusted(request, &response_body); - // CORB + ORB "v0.1" return an empty response; ORB "v0.2" returns an error - // code for CORB/ORB-blocked requests. This test needs to work with both. - if (rv != PP_OK && rv != PP_ERROR_FAILED) { - return ReportError("Trusted CORB-eligible request failed unexpectedly ", - rv); - } - - // Main verification - CORB should block the response where the - // `request_initiator` is cross-origin wrt the target URL. - // - // Note that this case (and CORB blocking) does never apply to the PDF plugin, - // because the PDF plugin only triggers requests where both - // `request_initiator` and the target URL are based on the URL of the PDF - // document (i.e. they are same-origin wrt each other). - ASSERT_EQ("", response_body); - PASS(); -} - -// Untrusted Javascript URLs requests should fail. -std::string TestURLLoader::TestUntrustedJavascriptURLRestriction() { - pp::URLRequestInfo request(instance_); - request.SetURL("javascript:foo = bar"); - - int32_t rv = OpenUntrusted(request, NULL); - if (rv != PP_ERROR_NOACCESS) - return ReportError( - "Untrusted Javascript URL request restriction failed", rv); - - PASS(); -} - -// Trusted Javascript URLs requests should succeed. -std::string TestURLLoader::TestTrustedJavascriptURLRestriction() { - pp::URLRequestInfo request(instance_); - request.SetURL("javascript:foo = bar"); - - int32_t rv = OpenTrusted(request, NULL); - if (rv == PP_ERROR_NOACCESS) - return ReportError( - "Trusted Javascript URL request", rv); - - PASS(); -} - -std::string TestURLLoader::TestUntrustedHttpRequests() { - // HTTP methods are restricted only for untrusted loaders. Forbidden - // methods are CONNECT, TRACE, and TRACK, and any string that is not a - // valid token (containing special characters like CR, LF). - // http://www.w3.org/TR/XMLHttpRequest/ - { - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("cOnNeCt", std::string())); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("tRaCk", std::string())); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("tRaCe", std::string())); - ASSERT_EQ(PP_ERROR_NOACCESS, - OpenUntrusted("POST\x0d\x0ax-csrf-token:\x20test1234", std::string())); - } - // HTTP methods are restricted only for untrusted loaders. Try all headers - // that are forbidden by http://www.w3.org/TR/XMLHttpRequest/. - { - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Accept-Charset:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Accept-Encoding:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Connection:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Content-Length:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Cookie:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Cookie2:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Date:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Dnt:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Expect:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Host:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Keep-Alive:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Referer:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "TE:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Trailer:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, - OpenUntrusted("GET", "Transfer-Encoding:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Upgrade:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "User-Agent:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Via:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted( - "GET", "Proxy-Authorization: Basic dXNlcjpwYXNzd29yZA==:\n")); - ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted("GET", "Sec-foo:\n")); - } - // Untrusted requests with custom referrer should fail. - { - pp::URLRequestInfo request(instance_); - request.SetCustomReferrerURL("http://www.google.com/"); - - int32_t rv = OpenUntrusted(request, NULL); - if (rv != PP_ERROR_NOACCESS) - return ReportError( - "Untrusted request with custom referrer restriction", rv); - } - // Untrusted requests with custom transfer encodings should fail. - { - pp::URLRequestInfo request(instance_); - request.SetCustomContentTransferEncoding("foo"); - - int32_t rv = OpenUntrusted(request, NULL); - if (rv != PP_ERROR_NOACCESS) - return ReportError( - "Untrusted request with content-transfer-encoding restriction", rv); - } - - PASS(); -} - -std::string TestURLLoader::TestTrustedHttpRequests() { - // Trusted requests can use restricted methods, other than CONNECT, which gets - // sockets into a problematic state. - { - ASSERT_EQ(PP_OK, OpenTrusted("tRaCk", std::string())); - ASSERT_EQ(PP_OK, OpenTrusted("tRaCe", std::string())); - } - // Trusted requests can use restricted headers. - { - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Accept-Charset:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Accept-Encoding:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Connection:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Cookie:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Date:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "DNT:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Expect:\n")); - - // Host header is still forbidden because it can conflict with specific URL. - - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Referer:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "User-Agent:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Via:\n")); - ASSERT_EQ(PP_OK, OpenTrusted("GET", "Sec-foo:\n")); - } - // Trusted requests with custom referrer should succeed. Note that the - // referrer has to be from the same origin as the plugin (this matches the - // behavior of the PDF plugin, which after Flash removal is the only plugin - // that depends on custom referrers). - // Use a CORB/ORB-passing resource, so ORB doesn't interfere with the test. - { - pp::URLRequestInfo request(instance_); - std::string url = GetReachableAbsoluteURL("test_image.png"); - std::string referrer = GetReachableAbsoluteURL(""); - request.SetURL(url); - request.SetCustomReferrerURL(referrer); - request.SetHeaders(referrer); - - int32_t rv = OpenTrusted(request, NULL); - if (rv != PP_OK) - return ReportError("Trusted request with custom referrer", rv); - } - // Trusted requests with custom transfer encodings should succeed. - { - pp::URLRequestInfo request(instance_); - std::string url = GetReachableAbsoluteURL("test_image.png"); - request.SetURL(url); - request.SetCustomContentTransferEncoding("foo"); - - int32_t rv = OpenTrusted(request, NULL); - if (rv != PP_OK) - return ReportError( - "Trusted request with content-transfer-encoding failed", rv); - } - - PASS(); -} - -// This test should cause a redirect and ensure that the loader follows it. -std::string TestURLLoader::TestFollowURLRedirect() { - pp::URLRequestInfo request(instance_); - // This prefix causes the test server to return a 301 redirect. - std::string redirect_prefix("/server-redirect?"); - // We need an absolute path for the redirect to actually work. - std::string redirect_url = - GetReachableAbsoluteURL("test_url_loader_data/hello.txt"); - request.SetURL(redirect_prefix.append(redirect_url)); - return LoadAndCompareBody(request, "hello\n"); -} - -// This test should cause a redirect and ensure that the loader runs -// the callback, rather than following the redirect. -std::string TestURLLoader::TestAuditURLRedirect() { - pp::URLRequestInfo request(instance_); - // This path will cause the server to return a 301 redirect. - // This prefix causes the test server to return a 301 redirect. - std::string redirect_prefix("/server-redirect?"); - // We need an absolute path for the redirect to actually work. - std::string redirect_url = - GetReachableAbsoluteURL("test_url_loader_data/hello.txt"); - request.SetURL(redirect_prefix.append(redirect_url)); - request.SetFollowRedirects(false); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::URLLoader loader(instance_); - callback.WaitForResult(loader.Open(request, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // Checks that the response indicates a redirect, and that the URL - // is correct. - pp::URLResponseInfo response_info(loader.GetResponseInfo()); - if (response_info.is_null()) - return "URLLoader::GetResponseInfo returned null"; - int32_t status_code = response_info.GetStatusCode(); - if (status_code != 301) - return "Response status should be 301"; - - // Test that the paused loader can be resumed. - callback.WaitForResult(loader.FollowRedirect(callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - std::string body; - std::string error = ReadEntireResponseBody(&loader, &body); - if (!error.empty()) - return error; - - if (body != "hello\n") - return "URLLoader::FollowRedirect failed"; - - PASS(); -} - -// This test checks if the redirect restriction does not block acceptable cases -// of 307/308 GET and HEAD. -std::string TestURLLoader::TestRestrictURLRedirectCommon() { - std::string url = GetReachableAbsoluteURL("test_url_loader_data/hello.txt"); - std::string redirect_307_prefix("/server-redirect-307?"); - - { - // Default method is GET and will follow the redirect. - pp::URLRequestInfo request_for_default_307(instance_); - request_for_default_307.SetURL(redirect_307_prefix.append(url)); - std::string result_for_default_307 = - LoadAndCompareBody(request_for_default_307, "hello\n"); - if (!result_for_default_307.empty()) - return result_for_default_307; - } - - { - // GET will follow the redirect. - pp::URLRequestInfo request_for_get_307(instance_); - request_for_get_307.SetURL(redirect_307_prefix.append(url)); - request_for_get_307.SetMethod("GET"); - std::string result_for_get_307 = - LoadAndCompareBody(request_for_get_307, "hello\n"); - if (!result_for_get_307.empty()) - return result_for_get_307; - } - - { - // HEAD will follow the redirect. - pp::URLRequestInfo request_for_head_307(instance_); - request_for_head_307.SetURL(redirect_307_prefix.append(url)); - request_for_head_307.SetMethod("HEAD"); - std::string result_for_head_307 = - LoadAndCompareBody(request_for_head_307, ""); - if (!result_for_head_307.empty()) - return result_for_head_307; - } - - std::string redirect_308_prefix("/server-redirect-308?"); - { - // Default method is GET and will follow the redirect. - pp::URLRequestInfo request_for_default_308(instance_); - request_for_default_308.SetURL(redirect_308_prefix.append(url)); - std::string result_for_default_308 = - LoadAndCompareBody(request_for_default_308, "hello\n"); - if (!result_for_default_308.empty()) - return result_for_default_308; - } - - { - // GET will follow the redirect. - pp::URLRequestInfo request_for_get_308(instance_); - request_for_get_308.SetURL(redirect_308_prefix.append(url)); - request_for_get_308.SetMethod("GET"); - std::string result_for_get_308 = - LoadAndCompareBody(request_for_get_308, "hello\n"); - if (!result_for_get_308.empty()) - return result_for_get_308; - } - - { - // HEAD will follow the redirect. - pp::URLRequestInfo request_for_head_308(instance_); - request_for_head_308.SetURL(redirect_308_prefix.append(url)); - request_for_head_308.SetMethod("HEAD"); - std::string result_for_head_308 = - LoadAndCompareBody(request_for_head_308, ""); - if (!result_for_head_308.empty()) - return result_for_head_308; - } - - PASS(); -} - -// This test checks if the redirect restriction blocks the restricted cases of -// 307/308 POST. -std::string TestURLLoader::TestRestrictURLRedirectEnabled() { - std::string url = GetReachableAbsoluteURL("test_url_loader_data/hello.txt"); - - { - // POST will be blocked and fail. - std::string redirect_307_prefix("/server-redirect-307?"); - pp::URLRequestInfo request_for_post_307(instance_); - request_for_post_307.SetURL(redirect_307_prefix.append(url)); - request_for_post_307.SetMethod("POST"); - std::string result_for_post_307 = LoadAndFail(request_for_post_307); - if (!result_for_post_307.empty()) - return result_for_post_307; - } - - { - // POST will be blocked and fail. - pp::URLRequestInfo request_for_post_308(instance_); - std::string redirect_308_prefix("/server-redirect-308?"); - request_for_post_308.SetURL(redirect_308_prefix.append(url)); - request_for_post_308.SetMethod("POST"); - std::string result_for_post_308 = LoadAndFail(request_for_post_308); - if (!result_for_post_308.empty()) - return result_for_post_308; - } - - PASS(); -} - -// This test checks if the redirect restriction does not block the restricted -// cases if the restriction is disabled. -std::string TestURLLoader::TestRestrictURLRedirectDisabled() { - std::string url = GetReachableAbsoluteURL("test_url_loader_data/hello.txt"); - - { - // POST will not be blocked, but follow the redirect. - std::string redirect_307_prefix("/server-redirect-307?"); - pp::URLRequestInfo request_for_post_307(instance_); - request_for_post_307.SetURL(redirect_307_prefix.append(url)); - request_for_post_307.SetMethod("POST"); - std::string result_for_post_307 = - LoadAndCompareBody(request_for_post_307, "hello\n"); - if (!result_for_post_307.empty()) - return result_for_post_307; - } - - { - // POST will not be blocked, but follow the redirect. - pp::URLRequestInfo request_for_post_308(instance_); - std::string redirect_308_prefix("/server-redirect-308?"); - request_for_post_308.SetURL(redirect_308_prefix.append(url)); - request_for_post_308.SetMethod("POST"); - std::string result_for_post_308 = - LoadAndCompareBody(request_for_post_308, "hello\n"); - if (!result_for_post_308.empty()) - return result_for_post_308; - } - - PASS(); -} - -std::string TestURLLoader::TestAbortCalls() { - pp::URLRequestInfo request(instance_); - request.SetURL("test_url_loader_data/hello.txt"); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - int32_t rv; - - // Abort |Open()|. - { - rv = pp::URLLoader(instance_).Open(request, callback.GetCallback()); - } - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - - // Abort |ReadResponseBody()|. - { - char buf[2] = { 0 }; - { - pp::URLLoader loader(instance_); - callback.WaitForResult(loader.Open(request, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - rv = loader.ReadResponseBody(buf, sizeof(buf), callback.GetCallback()); - } // Destroy |loader|. - callback.WaitForAbortResult(rv); - CHECK_CALLBACK_BEHAVIOR(callback); - if (rv == PP_OK_COMPLETIONPENDING) { - if (buf[0] || buf[1]) { - return "URLLoader::ReadResponseBody wrote data after resource " - "destruction."; - } - } - } - - // TODO(viettrungluu): More abort tests (but add basic tests first). - // Also test that Close() aborts properly. crbug.com/69457 - - PASS(); -} - -std::string TestURLLoader::TestUntendedLoad() { - pp::URLRequestInfo request(instance_); - request.SetURL("test_url_loader_data/hello.txt"); - request.SetRecordDownloadProgress(true); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::URLLoader loader(instance_); - callback.WaitForResult(loader.Open(request, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - // We received the response callback. Yield until the network code has called - // the loader's didReceiveData and didFinishLoading methods before we give it - // another callback function, to make sure the loader works with no callback. - int64_t bytes_received = 0; - int64_t total_bytes_to_be_received = 0; - while (true) { - loader.GetDownloadProgress(&bytes_received, &total_bytes_to_be_received); - if (total_bytes_to_be_received <= 0) - return ReportError("URLLoader::GetDownloadProgress total size", - static_cast<int32_t>(total_bytes_to_be_received)); - if (bytes_received == total_bytes_to_be_received) - break; - // Yield if we're on the main thread, so that URLLoader can receive more - // data. - if (pp::Module::Get()->core()->IsMainThread()) { - NestedEvent event(instance_->pp_instance()); - event.PostSignal(10); - event.Wait(); - } - } - // The loader should now have the data and have finished successfully. - std::string body; - std::string error = ReadEntireResponseBody(&loader, &body); - if (!error.empty()) - return error; - if (body != "hello\n") - return ReportError("Couldn't read data", callback.result()); - - PASS(); -} - -int32_t TestURLLoader::OpenWithPrefetchBufferThreshold(int32_t lower, - int32_t upper) { - pp::URLRequestInfo request(instance_); - request.SetURL("test_url_loader_data/hello.txt"); - request.SetPrefetchBufferLowerThreshold(lower); - request.SetPrefetchBufferUpperThreshold(upper); - - return OpenUntrusted(request, NULL); -} - -std::string TestURLLoader::TestPrefetchBufferThreshold() { - int32_t rv = OpenWithPrefetchBufferThreshold(-1, 1); - if (rv != PP_ERROR_FAILED) { - return ReportError("The prefetch limits contained a negative value but " - "the URLLoader did not fail.", rv); - } - - rv = OpenWithPrefetchBufferThreshold(0, 1); - if (rv != PP_OK) { - return ReportError("The prefetch buffer limits were legal values but " - "the URLLoader failed.", rv); - } - - rv = OpenWithPrefetchBufferThreshold(1000, 1); - if (rv != PP_ERROR_FAILED) { - return ReportError("The lower buffer value was higher than the upper but " - "the URLLoader did not fail.", rv); - } - - PASS(); -} - -// TODO(viettrungluu): This test properly belongs elsewhere. It tests that -// Chrome properly tags URL requests made on behalf of Pepper plugins (with an -// X-Requested-With header), but this isn't, strictly speaking, a PPAPI -// behavior. -std::string TestURLLoader::TestXRequestedWithHeader() { - pp::URLRequestInfo request(instance_); - request.SetURL("/echoheader?X-Requested-With"); - // The name and version of the plugin is set from the command-line (see - // chrome/test/ppapi/ppapi_test.cc. - return LoadAndCompareBody(request, "PPAPITests/1.2.3"); -} - -// TODO(viettrungluu): Add tests for Get{Upload,Download}Progress, Close -// (including abort tests if applicable).
diff --git a/tests/test_url_loader.h b/tests/test_url_loader.h deleted file mode 100644 index 3fd0a37..0000000 --- a/tests/test_url_loader.h +++ /dev/null
@@ -1,92 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_URL_LOADER_H_ -#define PPAPI_TESTS_TEST_URL_LOADER_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/c/private/ppb_file_io_private.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" -#include "ppapi/tests/test_case.h" - -namespace pp { -class FileIO; -class FileRef; -class FileSystem; -class URLLoader; -class URLRequestInfo; -} - -class TestURLLoader : public TestCase { - public: - explicit TestURLLoader(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string ReadEntireFile(pp::FileIO* file_io, std::string* data); - std::string ReadEntireResponseBody(pp::URLLoader* loader, - std::string* body); - std::string LoadAndCompareBody(const pp::URLRequestInfo& request, - const std::string& expected_body); - std::string LoadAndFail(const pp::URLRequestInfo& request); - int32_t OpenFileSystem(pp::FileSystem* file_system, std::string* message); - int32_t PrepareFileForPost(const pp::FileRef& file_ref, - const std::string& data, - std::string* message); - std::string GetReachableAbsoluteURL(const std::string& file_name); - std::string GetReachableCrossOriginURL(const std::string& file_name); - int32_t OpenUntrusted(const pp::URLRequestInfo& request, - std::string* response_body); - int32_t OpenTrusted(const pp::URLRequestInfo& request, - std::string* response_body); - int32_t OpenUntrusted(const std::string& method, - const std::string& header); - int32_t OpenTrusted(const std::string& method, - const std::string& header); - int32_t Open(const pp::URLRequestInfo& request, - bool with_universal_access, - std::string* response_body); - int32_t OpenWithPrefetchBufferThreshold(int32_t lower, int32_t upper); - - std::string TestBasicGET(); - std::string TestBasicPOST(); - std::string TestBasicFilePOST(); - std::string TestBasicFileRangePOST(); - std::string TestCompoundBodyPOST(); - std::string TestEmptyDataPOST(); - std::string TestBinaryDataPOST(); - std::string TestCustomRequestHeader(); - std::string TestFailsBogusContentLength(); - std::string TestStreamToFile(); - std::string TestUntrustedSameOriginRestriction(); - std::string TestTrustedSameOriginRestriction(); - std::string TestUntrustedCrossOriginRequest(); - std::string TestTrustedCrossOriginRequest(); - std::string TestUntrustedCorbEligibleRequest(); - std::string TestTrustedCorbEligibleRequest(); - std::string TestUntrustedJavascriptURLRestriction(); - std::string TestTrustedJavascriptURLRestriction(); - std::string TestUntrustedHttpRequests(); - std::string TestTrustedHttpRequests(); - std::string TestFollowURLRedirect(); - std::string TestAuditURLRedirect(); - std::string TestRestrictURLRedirectCommon(); - std::string TestRestrictURLRedirectEnabled(); - std::string TestRestrictURLRedirectDisabled(); - std::string TestAbortCalls(); - std::string TestUntendedLoad(); - std::string TestPrefetchBufferThreshold(); - std::string TestXRequestedWithHeader(); - - const PPB_FileIO_Private* file_io_private_interface_; - const PPB_URLLoaderTrusted* url_loader_trusted_interface_; -}; - -#endif // PPAPI_TESTS_TEST_URL_LOADER_H_
diff --git a/tests/test_url_loader_data/hello.txt b/tests/test_url_loader_data/hello.txt deleted file mode 100644 index ce01362..0000000 --- a/tests/test_url_loader_data/hello.txt +++ /dev/null
@@ -1 +0,0 @@ -hello
diff --git a/tests/test_url_request.cc b/tests/test_url_request.cc deleted file mode 100644 index 7e19e6e..0000000 --- a/tests/test_url_request.cc +++ /dev/null
@@ -1,475 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Tests PPB_URLRequestInfo interface. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_url_request.h" - -#include <stddef.h> -#include <stdint.h> -#include <string.h> -#include <string> - -#include "ppapi/c/ppb_file_io.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/file_io.h" -#include "ppapi/cpp/file_ref.h" -#include "ppapi/cpp/file_system.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(URLRequest); - -namespace { -// TODO(polina): move these to test_case.h/cc since other NaCl tests use them? - -const PP_Resource kInvalidResource = 0; -const PP_Instance kInvalidInstance = 0; - -// These should not exist. -// The bottom 2 bits are used to differentiate between different id types. -// 00 - module, 01 - instance, 10 - resource, 11 - var. -const PP_Instance kNotAnInstance = 0xFFFFF0; -const PP_Resource kNotAResource = 0xAAAAA0; -} - -TestURLRequest::TestURLRequest(TestingInstance* instance) - : TestCase(instance), - ppb_url_request_interface_(NULL), - ppb_url_loader_interface_(NULL), - ppb_url_response_interface_(NULL), - ppb_core_interface_(NULL), - ppb_var_interface_(NULL) { -} - -bool TestURLRequest::Init() { - ppb_url_request_interface_ = static_cast<const PPB_URLRequestInfo*>( - pp::Module::Get()->GetBrowserInterface(PPB_URLREQUESTINFO_INTERFACE)); - ppb_url_loader_interface_ = static_cast<const PPB_URLLoader*>( - pp::Module::Get()->GetBrowserInterface(PPB_URLLOADER_INTERFACE)); - ppb_url_response_interface_ = static_cast<const PPB_URLResponseInfo*>( - pp::Module::Get()->GetBrowserInterface(PPB_URLRESPONSEINFO_INTERFACE)); - ppb_core_interface_ = static_cast<const PPB_Core*>( - pp::Module::Get()->GetBrowserInterface(PPB_CORE_INTERFACE)); - ppb_var_interface_ = static_cast<const PPB_Var*>( - pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE)); - if (!ppb_url_request_interface_) - instance_->AppendError("PPB_URLRequestInfo interface not available"); - if (!ppb_url_response_interface_) - instance_->AppendError("PPB_URLResponseInfo interface not available"); - if (!ppb_core_interface_) - instance_->AppendError("PPB_Core interface not available"); - if (!ppb_var_interface_) - instance_->AppendError("PPB_Var interface not available"); - if (!ppb_url_loader_interface_) { - instance_->AppendError("PPB_URLLoader interface not available"); - } - return EnsureRunningOverHTTP(); -} - -void TestURLRequest::RunTests(const std::string& filter) { - RUN_TEST(CreateAndIsURLRequestInfo, filter); - RUN_TEST(SetProperty, filter); - RUN_TEST(AppendDataToBody, filter); - RUN_TEST(AppendFileToBody, filter); - RUN_TEST(Stress, filter); -} - -PP_Var TestURLRequest::PP_MakeString(const char* s) { - return ppb_var_interface_->VarFromUtf8(s, static_cast<int32_t>(strlen(s))); -} - -// Tests -// PP_Resource Create(PP_Instance instance) -// PP_Bool IsURLRequestInfo(PP_Resource resource) -std::string TestURLRequest::TestCreateAndIsURLRequestInfo() { - // Create: Invalid / non-existent instance -> invalid resource. - ASSERT_EQ(ppb_url_request_interface_->Create(kInvalidInstance), - kInvalidResource); - ASSERT_EQ(ppb_url_request_interface_->Create(kNotAnInstance), - kInvalidResource); - - // Create: Valid instance -> valid resource. - PP_Resource url_request = ppb_url_request_interface_->Create( - instance_->pp_instance()); - ASSERT_NE(url_request, kInvalidResource); - - // IsURLRequestInfo: - // Invalid / non-existent / non-URLRequestInfo resource -> false. - ASSERT_NE(PP_TRUE, - ppb_url_request_interface_->IsURLRequestInfo(kInvalidResource)); - ASSERT_NE(PP_TRUE, - ppb_url_request_interface_->IsURLRequestInfo(kNotAResource)); - - PP_Resource url_loader = - ppb_url_loader_interface_->Create(instance_->pp_instance()); - ASSERT_NE(kInvalidResource, url_loader); - - ASSERT_NE(PP_TRUE, ppb_url_request_interface_->IsURLRequestInfo(url_loader)); - ppb_url_loader_interface_->Close(url_loader); - ppb_core_interface_->ReleaseResource(url_loader); - - // IsURLRequestInfo: Current URLRequestInfo resource -> true. - std::string error; - if (PP_FALSE == ppb_url_request_interface_->IsURLRequestInfo(url_request)) - error = "IsURLRequestInfo() failed with a current URLRequestInfo resource"; - - // IsURLRequestInfo: Released URLRequestInfo resource -> false. - ppb_core_interface_->ReleaseResource(url_request); - ASSERT_NE(PP_TRUE, ppb_url_request_interface_->IsURLRequestInfo(url_request)); - - return error; // == PASS() if empty. -} - -// Tests -// PP_Bool SetProperty(PP_Resource request, -// PP_URLRequestProperty property, -// struct PP_Var value); -std::string TestURLRequest::TestSetProperty() { - struct PropertyTestData { - PropertyTestData(PP_URLRequestProperty prop, - const std::string& name, - PP_Var value, PP_Bool expected) : - property(prop), property_name(name), - var(value), expected_value(expected) { - // var has ref count of 1 on creation. - } - PP_URLRequestProperty property; - std::string property_name; - PP_Var var; // Instance owner is responsible for releasing this var. - PP_Bool expected_value; - }; - - // All bool properties should accept PP_TRUE and PP_FALSE, while rejecting - // all other variable types. -#define TEST_BOOL(_name) \ - PropertyTestData(ID_STR(_name), PP_MakeBool(PP_TRUE), PP_TRUE), \ - PropertyTestData(ID_STR(_name), PP_MakeBool(PP_FALSE), PP_TRUE), \ - PropertyTestData(ID_STR(_name), PP_MakeUndefined(), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeNull(), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeInt32(0), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeDouble(0.0), PP_FALSE) - - // These property types are always invalid for string properties. -#define TEST_STRING_INVALID(_name) \ - PropertyTestData(ID_STR(_name), PP_MakeNull(), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeBool(PP_FALSE), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeInt32(0), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeDouble(0.0), PP_FALSE) - -#define TEST_INT_INVALID(_name) \ - PropertyTestData(ID_STR(_name), PP_MakeUndefined(), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeNull(), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeBool(PP_FALSE), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeString("notint"), PP_FALSE), \ - PropertyTestData(ID_STR(_name), PP_MakeDouble(0.0), PP_FALSE) - - // SetProperty accepts plenty of invalid values (malformed urls, negative - // thresholds, etc). Error checking is delayed until request opening (aka url - // loading). -#define ID_STR(arg) arg, #arg - PropertyTestData test_data[] = { - TEST_INT_INVALID(PP_URLREQUESTPROPERTY_STREAMTOFILE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_STREAMTOFILE), - PP_MakeBool(PP_TRUE), PP_FALSE), - TEST_BOOL(PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS), - TEST_BOOL(PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS), - TEST_BOOL(PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS), - TEST_BOOL(PP_URLREQUESTPROPERTY_ALLOWCROSSORIGINREQUESTS), - TEST_BOOL(PP_URLREQUESTPROPERTY_ALLOWCREDENTIALS), - TEST_STRING_INVALID(PP_URLREQUESTPROPERTY_URL), - TEST_STRING_INVALID(PP_URLREQUESTPROPERTY_METHOD), - TEST_STRING_INVALID(PP_URLREQUESTPROPERTY_HEADERS), - TEST_STRING_INVALID(PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL), - TEST_STRING_INVALID(PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING), - TEST_STRING_INVALID(PP_URLREQUESTPROPERTY_CUSTOMUSERAGENT), - TEST_INT_INVALID(PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD), - TEST_INT_INVALID(PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_URL), - PP_MakeString("http://www.google.com"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_URL), - PP_MakeString("foo.jpg"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_METHOD), - PP_MakeString("GET"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_METHOD), - PP_MakeString("POST"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_HEADERS), - PP_MakeString("Accept: text/plain"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_HEADERS), PP_MakeString(""), - PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL), - PP_MakeString("http://www.google.com"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL), - PP_MakeString(""), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_CUSTOMREFERRERURL), - PP_MakeUndefined(), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING), - PP_MakeString("base64"), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING), - PP_MakeString(""), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING), - PP_MakeUndefined(), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_CUSTOMUSERAGENT), - PP_MakeString("My Crazy Plugin"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_CUSTOMUSERAGENT), - PP_MakeString(""), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_CUSTOMUSERAGENT), - PP_MakeUndefined(), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_URL), PP_MakeUndefined(), - PP_FALSE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_METHOD), PP_MakeUndefined(), - PP_FALSE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_HEADERS), - PP_MakeString("Proxy-Authorization: Basic dXNlcjpwYXNzd29yZA=="), - PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_HEADERS), - PP_MakeString("Accept-Encoding: *\n" - "Accept-Charset: iso-8859-5, unicode-1-1;q=0.8"), - PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD), - PP_MakeInt32(0), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD), - PP_MakeInt32(100), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD), - PP_MakeInt32(0), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD), - PP_MakeInt32(100), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_URL), - PP_MakeString("::::::::::::"), PP_TRUE), - PropertyTestData(ID_STR(PP_URLREQUESTPROPERTY_METHOD), - PP_MakeString("INVALID"), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_CUSTOMCONTENTTRANSFERENCODING), - PP_MakeString("invalid"), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_PREFETCHBUFFERUPPERTHRESHOLD), - PP_MakeInt32(-100), PP_TRUE), - PropertyTestData( - ID_STR(PP_URLREQUESTPROPERTY_PREFETCHBUFFERLOWERTHRESHOLD), - PP_MakeInt32(-100), PP_TRUE), - - }; - std::string error; - - PP_Resource url_request = ppb_url_request_interface_->Create( - instance_->pp_instance()); - if (url_request == kInvalidResource) - error = "Failed to create a URLRequestInfo"; - - // Loop over all test data even if we encountered an error to release vars. - for (size_t i = 0; - i < sizeof(test_data) / sizeof(test_data[0]); - ++i) { - if (error.empty() && test_data[i].expected_value != - ppb_url_request_interface_->SetProperty(url_request, - test_data[i].property, - test_data[i].var)) { - pp::Var var(pp::Var::DontManage(), test_data[i].var); - error = std::string("Setting property ") + - test_data[i].property_name + " to " + var.DebugString() + - " did not return " + (test_data[i].expected_value ? "True" : "False"); - } - ppb_var_interface_->Release(test_data[i].var); - } - - ppb_core_interface_->ReleaseResource(url_request); - return error; // == PASS() if empty. -} - -std::string TestURLRequest::LoadAndCompareBody( - PP_Resource url_request, const std::string& expected_body) { - TestCompletionCallback callback(instance_->pp_instance(), PP_REQUIRED); - - PP_Resource url_loader = - ppb_url_loader_interface_->Create(instance_->pp_instance()); - ASSERT_NE(kInvalidResource, url_loader); - - callback.WaitForResult(ppb_url_loader_interface_->Open( - url_loader, url_request, - callback.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - std::string error; - PP_Resource url_response = - ppb_url_loader_interface_->GetResponseInfo(url_loader); - if (url_response == kInvalidResource) { - error = "PPB_URLLoader::GetResponseInfo() returned invalid resource"; - } else { - PP_Var status = ppb_url_response_interface_->GetProperty( - url_response, PP_URLRESPONSEPROPERTY_STATUSCODE); - if (status.type != PP_VARTYPE_INT32 && status.value.as_int != 200) - error = ReportError("PPB_URLLoader::Open() status", status.value.as_int); - - std::string actual_body; - for (; error.empty();) { // Read the entire body in this loop. - const size_t kBufferSize = 32; - char buf[kBufferSize]; - callback.WaitForResult(ppb_url_loader_interface_->ReadResponseBody( - url_loader, buf, kBufferSize, - callback.GetCallback().pp_completion_callback())); - if (callback.failed()) - error.assign(callback.errors()); - else if (callback.result() < PP_OK) - error.assign(ReportError("PPB_URLLoader::ReadResponseBody()", - callback.result())); - if (callback.result() <= PP_OK || callback.failed()) - break; - actual_body.append(buf, callback.result()); - } - if (actual_body != expected_body) - error = "PPB_URLLoader::ReadResponseBody() read unexpected response."; - } - ppb_core_interface_->ReleaseResource(url_response); - - ppb_url_loader_interface_->Close(url_loader); - ppb_core_interface_->ReleaseResource(url_loader); - return error; -} - -// Tests -// PP_Bool AppendDataToBody( -// PP_Resource request, const void* data, uint32_t len); -std::string TestURLRequest::TestAppendDataToBody() { - PP_Resource url_request = ppb_url_request_interface_->Create( - instance_->pp_instance()); - ASSERT_NE(url_request, kInvalidResource); - - std::string postdata("sample postdata"); - PP_Var post_string_var = PP_MakeString("POST"); - PP_Var echo_string_var = PP_MakeString("/echo"); - - // NULL pointer causes a crash. In general PPAPI implementation does not - // test for NULL because they are just a special case of bad pointers that - // are not detectable if set to point to an object that does not exist. - - // Invalid resource should fail. - ASSERT_EQ(PP_FALSE, ppb_url_request_interface_->AppendDataToBody( - kInvalidResource, postdata.data(), - static_cast<uint32_t>(postdata.length()))); - - // Append data and POST to echoing web server. - ASSERT_EQ(PP_TRUE, ppb_url_request_interface_->SetProperty( - url_request, PP_URLREQUESTPROPERTY_METHOD, post_string_var)); - ASSERT_EQ(PP_TRUE, ppb_url_request_interface_->SetProperty( - url_request, PP_URLREQUESTPROPERTY_URL, echo_string_var)); - - // Append data to body and verify the body is what we expect. - ASSERT_EQ(PP_TRUE, ppb_url_request_interface_->AppendDataToBody( - url_request, postdata.data(), - static_cast<uint32_t>(postdata.length()))); - std::string error = LoadAndCompareBody(url_request, postdata); - - ppb_var_interface_->Release(post_string_var); - ppb_var_interface_->Release(echo_string_var); - ppb_core_interface_->ReleaseResource(url_request); - return error; // == PASS() if empty. -} - -std::string TestURLRequest::TestAppendFileToBody() { - PP_Resource url_request = ppb_url_request_interface_->Create( - instance_->pp_instance()); - ASSERT_NE(url_request, kInvalidResource); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - - pp::FileSystem file_system(instance_, PP_FILESYSTEMTYPE_LOCALTEMPORARY); - callback.WaitForResult(file_system.Open(1024, callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - pp::FileRef ref(file_system, "/test_file"); - pp::FileIO io(instance_); - callback.WaitForResult(io.Open(ref, - PP_FILEOPENFLAG_CREATE | PP_FILEOPENFLAG_WRITE, - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - - std::string append_data = "hello\n"; - callback.WaitForResult(io.Write(0, - append_data.c_str(), - static_cast<int32_t>(append_data.size()), - callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(static_cast<int32_t>(append_data.size()), callback.result()); - - PP_Var post_string_var = PP_MakeString("POST"); - PP_Var echo_string_var = PP_MakeString("/echo"); - - // NULL pointer causes a crash. In general PPAPI implementation does not - // test for NULL because they are just a special case of bad pointers that - // are not detectable if set to point to an object that does not exist. - - // Invalid resource should fail. - ASSERT_EQ(PP_FALSE, ppb_url_request_interface_->AppendFileToBody( - kInvalidResource, ref.pp_resource(), 0, -1, 0)); - - // Append data and POST to echoing web server. - ASSERT_EQ(PP_TRUE, ppb_url_request_interface_->SetProperty( - url_request, PP_URLREQUESTPROPERTY_METHOD, post_string_var)); - ASSERT_EQ(PP_TRUE, ppb_url_request_interface_->SetProperty( - url_request, PP_URLREQUESTPROPERTY_URL, echo_string_var)); - - // Append file to body and verify the body is what we expect. - ASSERT_EQ(PP_TRUE, ppb_url_request_interface_->AppendFileToBody( - url_request, ref.pp_resource(), 0, -1, 0)); - std::string error = LoadAndCompareBody(url_request, append_data); - - ppb_var_interface_->Release(post_string_var); - ppb_var_interface_->Release(echo_string_var); - ppb_core_interface_->ReleaseResource(url_request); - return error; // == PASS() if empty. -} - -// Allocates and manipulates a large number of resources. -std::string TestURLRequest::TestStress() { - const int kManyResources = 500; - PP_Resource url_request_info[kManyResources]; - - std::string error; - int num_created = kManyResources; - for (int i = 0; i < kManyResources; i++) { - url_request_info[i] = ppb_url_request_interface_->Create( - instance_->pp_instance()); - if (url_request_info[i] == kInvalidResource) { - error = "Create() failed"; - } else if (PP_FALSE == ppb_url_request_interface_->IsURLRequestInfo( - url_request_info[i])) { - error = "IsURLRequestInfo() failed"; - } else if (PP_FALSE == ppb_url_request_interface_->SetProperty( - url_request_info[i], - PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS, - PP_MakeBool(PP_TRUE))) { - error = "SetProperty() failed"; - } - if (!error.empty()) { - num_created = i + 1; - break; - } - } - for (int i = 0; i < num_created; i++) { - ppb_core_interface_->ReleaseResource(url_request_info[i]); - if (PP_TRUE == - ppb_url_request_interface_->IsURLRequestInfo(url_request_info[i])) - error = "IsURLREquestInfo() succeeded after release"; - } - return error; // == PASS() if empty. -}
diff --git a/tests/test_url_request.h b/tests/test_url_request.h deleted file mode 100644 index fdb41be..0000000 --- a/tests/test_url_request.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_URL_REQUEST_H_ -#define PPAPI_TESTS_TEST_URL_REQUEST_H_ - -#include <string> - -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/ppb_url_loader.h" -#include "ppapi/c/ppb_url_request_info.h" -#include "ppapi/c/ppb_url_response_info.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/tests/test_case.h" - -class TestURLRequest : public TestCase { - public: - explicit TestURLRequest(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestCreateAndIsURLRequestInfo(); - std::string TestSetProperty(); - std::string TestAppendDataToBody(); - std::string TestAppendFileToBody(); - std::string TestStress(); - - // Helpers. - PP_Var PP_MakeString(const char* s); - std::string LoadAndCompareBody(PP_Resource url_request, - const std::string& expected_body); - - const PPB_URLRequestInfo* ppb_url_request_interface_; - const PPB_URLLoader* ppb_url_loader_interface_; - const PPB_URLResponseInfo* ppb_url_response_interface_; - const PPB_Core* ppb_core_interface_; - const PPB_Var* ppb_var_interface_; -}; - -#endif // PPAPI_TESTS_TEST_URL_REQUEST_H_
diff --git a/tests/test_url_util.cc b/tests/test_url_util.cc deleted file mode 100644 index 3219884..0000000 --- a/tests/test_url_util.cc +++ /dev/null
@@ -1,155 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_url_util.h" - -#include "ppapi/c/dev/ppb_url_util_dev.h" -#include "ppapi/cpp/dev/url_util_dev.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(URLUtil); - -static bool ComponentEquals(const PP_URLComponent_Dev& component, - int begin, int len) { - return component.begin == begin && component.len == len; -} - -bool TestURLUtil::Init() { - util_ = pp::URLUtil_Dev::Get(); - return !!util_; -} - -void TestURLUtil::RunTests(const std::string& filter) { - RUN_TEST(Canonicalize, filter); - RUN_TEST(ResolveRelative, filter); - RUN_TEST(IsSameSecurityOrigin, filter); - RUN_TEST(DocumentCanRequest, filter); - RUN_TEST(DocumentCanAccessDocument, filter); - RUN_TEST(GetDocumentURL, filter); - RUN_TEST(GetPluginInstanceURL, filter); - RUN_TEST(GetPluginReferrerURL, filter); -} - -std::string TestURLUtil::TestCanonicalize() { - // Test no canonicalize output. - pp::Var result = util_->Canonicalize("http://Google.com"); - ASSERT_TRUE(result.AsString() == "http://google.com/"); - - // Test all the components - PP_URLComponents_Dev c; - result = util_->Canonicalize( - "http://me:pw@Google.com:1234/path?query#ref ", - &c); - ASSERT_TRUE(result.AsString() == - // 0 1 2 3 4 - // 0123456789012345678901234567890123456789012 - "http://me:pw@google.com:1234/path?query#ref"); - ASSERT_TRUE(ComponentEquals(c.scheme, 0, 4)); - ASSERT_TRUE(ComponentEquals(c.username, 7, 2)); - ASSERT_TRUE(ComponentEquals(c.password, 10, 2)); - ASSERT_TRUE(ComponentEquals(c.host, 13, 10)); - ASSERT_TRUE(ComponentEquals(c.port, 24, 4)); - ASSERT_TRUE(ComponentEquals(c.path, 28, 5)); - ASSERT_TRUE(ComponentEquals(c.query, 34, 5)); - ASSERT_TRUE(ComponentEquals(c.ref, 40, 3)); - - // Test minimal components. - result = util_->Canonicalize("http://google.com/", &c); - // 0 1 - // 0123456789012345678 - ASSERT_TRUE(result.AsString() == "http://google.com/"); - ASSERT_TRUE(ComponentEquals(c.scheme, 0, 4)); - ASSERT_TRUE(ComponentEquals(c.username, 0, -1)); - ASSERT_TRUE(ComponentEquals(c.password, 0, -1)); - ASSERT_TRUE(ComponentEquals(c.host, 7, 10)); - ASSERT_TRUE(ComponentEquals(c.port, 0, -1)); - ASSERT_TRUE(ComponentEquals(c.path, 17, 1)); - ASSERT_TRUE(ComponentEquals(c.query, 0, -1)); - ASSERT_TRUE(ComponentEquals(c.ref, 0, -1)); - - PASS(); -} - -std::string TestURLUtil::TestResolveRelative() { - const int kTestCount = 6; - struct TestCase { - const char* base; - const char* relative; - const char* expected; // NULL if - } test_cases[kTestCount] = { - {"http://google.com/", "foo", "http://google.com/foo"}, - {"http://google.com/foo", "/bar", "http://google.com/bar"}, - {"http://foo/", "http://bar", "http://bar/"}, - {"data:foo", "/bar", NULL}, - {"data:foo", "http://foo/", "http://foo/"}, - {"http://foo/", "", "http://foo/"}, - }; - - for (int i = 0; i < kTestCount; i++) { - pp::Var result = util_->ResolveRelativeToURL(test_cases[i].base, - test_cases[i].relative); - if (test_cases[i].expected == NULL) { - ASSERT_TRUE(result.is_null()); - } else { - ASSERT_TRUE(result.AsString() == test_cases[i].expected); - } - } - PASS(); -} - -std::string TestURLUtil::TestIsSameSecurityOrigin() { - ASSERT_FALSE(util_->IsSameSecurityOrigin("http://google.com/", - "http://example.com/")); - ASSERT_TRUE(util_->IsSameSecurityOrigin("http://google.com/foo", - "http://google.com/bar")); - PASS(); -} - -std::string TestURLUtil::TestDocumentCanRequest() { - // This is hard to test, but we can at least verify we can't request - // some random domain. - ASSERT_FALSE(util_->DocumentCanRequest(instance_, "http://evil.com/")); - PASS(); -} - -std::string TestURLUtil::TestDocumentCanAccessDocument() { - // This is hard to test, but we can at least verify we can access ourselves. - ASSERT_TRUE(util_->DocumentCanAccessDocument(instance_, instance_)); - PASS(); -} - -std::string TestURLUtil::TestGetDocumentURL() { - pp::Var url = util_->GetDocumentURL(instance_); - ASSERT_TRUE(url.is_string()); - pp::VarPrivate window = instance_->GetWindowObject(); - pp::Var href = window.GetProperty("location").GetProperty("href"); - ASSERT_TRUE(href.is_string()); - // In the test framework, they should be the same. - ASSERT_EQ(url.AsString(), href.AsString()); - PASS(); -} - -std::string TestURLUtil::TestGetPluginInstanceURL() { - pp::Var url = util_->GetPluginInstanceURL(instance_); - ASSERT_TRUE(url.is_string()); - // see test_case.html - ASSERT_EQ(url.AsString(), "http://a.b.c/test"); - PASS(); -} - -std::string TestURLUtil::TestGetPluginReferrerURL() { - pp::Var url = util_->GetPluginReferrerURL(instance_); - ASSERT_TRUE(url.is_string()); - pp::VarPrivate window = instance_->GetWindowObject(); - pp::Var href = window.GetProperty("location").GetProperty("href"); - ASSERT_TRUE(href.is_string()); - ASSERT_EQ(url.AsString(), href.AsString()); - PASS(); -} -
diff --git a/tests/test_url_util.h b/tests/test_url_util.h deleted file mode 100644 index 0bd24e1..0000000 --- a/tests/test_url_util.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_URL_UTIL_H_ -#define PPAPI_TESTS_TEST_URL_UTIL_H_ - -#include "ppapi/cpp/dev/url_util_dev.h" -#include "ppapi/tests/test_case.h" - -class TestURLUtil : public TestCase { - public: - TestURLUtil(TestingInstance* instance) : TestCase(instance), util_(NULL) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestCanonicalize(); - std::string TestResolveRelative(); - std::string TestIsSameSecurityOrigin(); - std::string TestDocumentCanRequest(); - std::string TestDocumentCanAccessDocument(); - std::string TestGetDocumentURL(); - std::string TestGetPluginInstanceURL(); - std::string TestGetPluginReferrerURL(); - - const pp::URLUtil_Dev* util_; -}; - -#endif // PPAPI_TESTS_TEST_URL_UTIL_H_
diff --git a/tests/test_utils.cc b/tests/test_utils.cc deleted file mode 100644 index f24b124..0000000 --- a/tests/test_utils.cc +++ /dev/null
@@ -1,464 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_utils.h" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#if defined(_MSC_VER) -#include <windows.h> -#else -#include <unistd.h> -#endif - -#include "ppapi/c/pp_errors.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/net_address.h" -#include "ppapi/cpp/private/host_resolver_private.h" -#include "ppapi/cpp/private/net_address_private.h" -#include "ppapi/cpp/url_loader.h" -#include "ppapi/cpp/var.h" - -namespace { - -bool IsBigEndian() { - union { - uint32_t integer32; - uint8_t integer8[4]; - } data = { 0x01020304 }; - - return data.integer8[0] == 1; -} - -void DoNothing(void* user_data, int32_t result) {} - -} // namespace - -const int kActionTimeoutMs = 10000; - -const PPB_Testing_Private* GetTestingInterface() { - static const PPB_Testing_Private* g_testing_interface = - static_cast<const PPB_Testing_Private*>( - pp::Module::Get()->GetBrowserInterface( - PPB_TESTING_PRIVATE_INTERFACE)); - return g_testing_interface; -} - -std::string ReportError(const char* method, int32_t error) { - char error_as_string[12]; - snprintf(error_as_string, sizeof(error_as_string), "%d", - static_cast<int>(error)); - std::string result = method + std::string(" failed with error: ") + - error_as_string; - return result; -} - -void PlatformSleep(int duration_ms) { -#if defined(_MSC_VER) - ::Sleep(duration_ms); -#else - usleep(duration_ms * 1000); -#endif -} - -bool GetLocalHostPort(PP_Instance instance, std::string* host, uint16_t* port) { - if (!host || !port) - return false; - - const PPB_Testing_Private* testing = GetTestingInterface(); - if (!testing) - return false; - - PP_URLComponents_Dev components; - pp::Var pp_url(pp::PASS_REF, - testing->GetDocumentURL(instance, &components)); - if (!pp_url.is_string()) - return false; - std::string url = pp_url.AsString(); - - if (components.host.len < 0) - return false; - host->assign(url.substr(components.host.begin, components.host.len)); - - if (components.port.len <= 0) - return false; - - int i = atoi(url.substr(components.port.begin, components.port.len).c_str()); - if (i < 0 || i > 65535) - return false; - *port = static_cast<uint16_t>(i); - - return true; -} - -uint16_t ConvertFromNetEndian16(uint16_t x) { - if (IsBigEndian()) - return x; - else - return (x << 8) | (x >> 8); -} - -uint16_t ConvertToNetEndian16(uint16_t x) { - if (IsBigEndian()) - return x; - else - return (x << 8) | (x >> 8); -} - -bool EqualNetAddress(const pp::NetAddress& addr1, const pp::NetAddress& addr2) { - if (addr1.GetFamily() == PP_NETADDRESS_FAMILY_UNSPECIFIED || - addr2.GetFamily() == PP_NETADDRESS_FAMILY_UNSPECIFIED) { - return false; - } - - if (addr1.GetFamily() == PP_NETADDRESS_FAMILY_IPV4) { - PP_NetAddress_IPv4 ipv4_addr1, ipv4_addr2; - if (!addr1.DescribeAsIPv4Address(&ipv4_addr1) || - !addr2.DescribeAsIPv4Address(&ipv4_addr2)) { - return false; - } - - return ipv4_addr1.port == ipv4_addr2.port && - !memcmp(ipv4_addr1.addr, ipv4_addr2.addr, sizeof(ipv4_addr1.addr)); - } else { - PP_NetAddress_IPv6 ipv6_addr1, ipv6_addr2; - if (!addr1.DescribeAsIPv6Address(&ipv6_addr1) || - !addr2.DescribeAsIPv6Address(&ipv6_addr2)) { - return false; - } - - return ipv6_addr1.port == ipv6_addr2.port && - !memcmp(ipv6_addr1.addr, ipv6_addr2.addr, sizeof(ipv6_addr1.addr)); - } -} - -bool ResolveHost(PP_Instance instance, - const std::string& host, - uint16_t port, - pp::NetAddress* addr) { - // TODO(yzshen): Change to use the public host resolver once it is supported. - pp::InstanceHandle instance_handle(instance); - pp::HostResolverPrivate host_resolver(instance_handle); - PP_HostResolver_Private_Hint hint = - { PP_NETADDRESSFAMILY_PRIVATE_UNSPECIFIED, 0 }; - - TestCompletionCallback callback(instance); - callback.WaitForResult( - host_resolver.Resolve(host, port, hint, callback.GetCallback())); - - PP_NetAddress_Private addr_private; - if (callback.result() != PP_OK || host_resolver.GetSize() == 0 || - !host_resolver.GetNetAddress(0, &addr_private)) { - return false; - } - - switch (pp::NetAddressPrivate::GetFamily(addr_private)) { - case PP_NETADDRESSFAMILY_PRIVATE_IPV4: { - PP_NetAddress_IPv4 ipv4_addr; - ipv4_addr.port = ConvertToNetEndian16( - pp::NetAddressPrivate::GetPort(addr_private)); - if (!pp::NetAddressPrivate::GetAddress(addr_private, ipv4_addr.addr, - sizeof(ipv4_addr.addr))) { - return false; - } - *addr = pp::NetAddress(instance_handle, ipv4_addr); - return true; - } - case PP_NETADDRESSFAMILY_PRIVATE_IPV6: { - PP_NetAddress_IPv6 ipv6_addr; - ipv6_addr.port = ConvertToNetEndian16( - pp::NetAddressPrivate::GetPort(addr_private)); - if (!pp::NetAddressPrivate::GetAddress(addr_private, ipv6_addr.addr, - sizeof(ipv6_addr.addr))) { - return false; - } - *addr = pp::NetAddress(instance_handle, ipv6_addr); - return true; - } - default: { - return false; - } - } -} - -bool ReplacePort(PP_Instance instance, - const pp::NetAddress& input_addr, - uint16_t port, - pp::NetAddress* output_addr) { - switch (input_addr.GetFamily()) { - case PP_NETADDRESS_FAMILY_IPV4: { - PP_NetAddress_IPv4 ipv4_addr; - if (!input_addr.DescribeAsIPv4Address(&ipv4_addr)) - return false; - ipv4_addr.port = ConvertToNetEndian16(port); - *output_addr = pp::NetAddress(pp::InstanceHandle(instance), ipv4_addr); - return true; - } - case PP_NETADDRESS_FAMILY_IPV6: { - PP_NetAddress_IPv6 ipv6_addr; - if (!input_addr.DescribeAsIPv6Address(&ipv6_addr)) - return false; - ipv6_addr.port = ConvertToNetEndian16(port); - *output_addr = pp::NetAddress(pp::InstanceHandle(instance), ipv6_addr); - return true; - } - default: { - return false; - } - } -} - -uint16_t GetPort(const pp::NetAddress& addr) { - switch (addr.GetFamily()) { - case PP_NETADDRESS_FAMILY_IPV4: { - PP_NetAddress_IPv4 ipv4_addr; - if (!addr.DescribeAsIPv4Address(&ipv4_addr)) - return 0; - return ConvertFromNetEndian16(ipv4_addr.port); - } - case PP_NETADDRESS_FAMILY_IPV6: { - PP_NetAddress_IPv6 ipv6_addr; - if (!addr.DescribeAsIPv6Address(&ipv6_addr)) - return 0; - return ConvertFromNetEndian16(ipv6_addr.port); - } - default: { - return 0; - } - } -} - -void NestedEvent::Wait() { - PP_DCHECK(pp::Module::Get()->core()->IsMainThread()); - // Don't allow nesting more than once; it doesn't work with the code as-is, - // and probably is a bad idea most of the time anyway. - PP_DCHECK(!waiting_); - if (signalled_) - return; - waiting_ = true; - while (!signalled_) - GetTestingInterface()->RunMessageLoop(instance_); - waiting_ = false; -} - -void NestedEvent::Signal() { - if (pp::Module::Get()->core()->IsMainThread()) - SignalOnMainThread(); - else - PostSignal(0); -} - -void NestedEvent::PostSignal(int32_t wait_ms) { - pp::Module::Get()->core()->CallOnMainThread( - wait_ms, - pp::CompletionCallback(&SignalThunk, this), - 0); -} - -void NestedEvent::Reset() { - PP_DCHECK(pp::Module::Get()->core()->IsMainThread()); - // It doesn't make sense to reset when we're still waiting. - PP_DCHECK(!waiting_); - signalled_ = false; -} - -void NestedEvent::SignalOnMainThread() { - PP_DCHECK(pp::Module::Get()->core()->IsMainThread()); - signalled_ = true; - if (waiting_) - GetTestingInterface()->QuitMessageLoop(instance_); -} - -void NestedEvent::SignalThunk(void* event, int32_t /* result */) { - static_cast<NestedEvent*>(event)->SignalOnMainThread(); -} - -pp::CompletionCallback DoNothingCallback() { - return pp::CompletionCallback(&DoNothing, NULL, - PP_COMPLETIONCALLBACK_FLAG_OPTIONAL); -} - -TestCompletionCallback::TestCompletionCallback(PP_Instance instance) - : wait_for_result_called_(false), - have_result_(false), - result_(PP_OK_COMPLETIONPENDING), - // TODO(dmichael): The default should probably be PP_REQUIRED, but this is - // what the tests currently expect. - callback_type_(PP_OPTIONAL), - post_quit_task_(false), - instance_(instance), - delegate_(NULL) { -} - -TestCompletionCallback::TestCompletionCallback(PP_Instance instance, - bool force_async) - : wait_for_result_called_(false), - have_result_(false), - result_(PP_OK_COMPLETIONPENDING), - callback_type_(force_async ? PP_REQUIRED : PP_OPTIONAL), - post_quit_task_(false), - instance_(instance), - delegate_(NULL) { -} - -TestCompletionCallback::TestCompletionCallback(PP_Instance instance, - CallbackType callback_type) - : wait_for_result_called_(false), - have_result_(false), - result_(PP_OK_COMPLETIONPENDING), - callback_type_(callback_type), - post_quit_task_(false), - instance_(instance), - delegate_(NULL) { -} - -void TestCompletionCallback::WaitForResult(int32_t result) { - PP_DCHECK(!wait_for_result_called_); - wait_for_result_called_ = true; - errors_.clear(); - if (result == PP_OK_COMPLETIONPENDING) { - if (!have_result_) { - post_quit_task_ = true; - RunMessageLoop(); - } - if (callback_type_ == PP_BLOCKING) { - errors_.assign( - ReportError("TestCompletionCallback: Call did not run synchronously " - "when passed a blocking completion callback!", - result_)); - return; - } - } else { - result_ = result; - have_result_ = true; - if (callback_type_ == PP_REQUIRED) { - errors_.assign( - ReportError("TestCompletionCallback: Call ran synchronously when " - "passed a required completion callback!", - result_)); - return; - } - } - PP_DCHECK(have_result_ == true); -} - -void TestCompletionCallback::WaitForAbortResult(int32_t result) { - WaitForResult(result); - int32_t final_result = result_; - if (result == PP_OK_COMPLETIONPENDING) { - if (final_result != PP_ERROR_ABORTED) { - errors_.assign( - ReportError("TestCompletionCallback: Expected PP_ERROR_ABORTED or " - "PP_OK. Ran asynchronously.", - final_result)); - return; - } - } else if (result < PP_OK) { - errors_.assign( - ReportError("TestCompletionCallback: Expected PP_ERROR_ABORTED or " - "non-error response. Ran synchronously.", - result)); - return; - } -} - -pp::CompletionCallback TestCompletionCallback::GetCallback() { - Reset(); - int32_t flags = 0; - if (callback_type_ == PP_BLOCKING) - return pp::CompletionCallback(); - else if (callback_type_ == PP_OPTIONAL) - flags = PP_COMPLETIONCALLBACK_FLAG_OPTIONAL; - target_loop_ = pp::MessageLoop::GetCurrent(); - return pp::CompletionCallback(&TestCompletionCallback::Handler, - const_cast<TestCompletionCallback*>(this), - flags); -} - -void TestCompletionCallback::Reset() { - wait_for_result_called_ = false; - result_ = PP_OK_COMPLETIONPENDING; - have_result_ = false; - post_quit_task_ = false; - delegate_ = NULL; - errors_.clear(); -} - -// static -void TestCompletionCallback::Handler(void* user_data, int32_t result) { - TestCompletionCallback* callback = - static_cast<TestCompletionCallback*>(user_data); - // If this check fails, it means that the callback was invoked twice or that - // the PPAPI call completed synchronously, but also ran the callback. - PP_DCHECK(!callback->have_result_); - callback->result_ = result; - callback->have_result_ = true; - if (callback->delegate_) - callback->delegate_->OnCallback(user_data, result); - if (callback->post_quit_task_) { - callback->post_quit_task_ = false; - callback->QuitMessageLoop(); - } - if (callback->target_loop_ != pp::MessageLoop::GetCurrent()) { - // Note, in-process, loop_ and GetCurrent() will both be NULL, so should - // still be equal. - callback->errors_.assign( - ReportError("TestCompletionCallback: Callback ran on the wrong message " - "loop!", - result)); - } -} - -void TestCompletionCallback::RunMessageLoop() { - pp::MessageLoop loop(pp::MessageLoop::GetCurrent()); - // If we don't have a message loop, we're probably running in process, where - // PPB_MessageLoop is not supported. Just use the Testing message loop. - if (loop.is_null() || loop == pp::MessageLoop::GetForMainThread()) - GetTestingInterface()->RunMessageLoop(instance_); - else - loop.Run(); -} - -void TestCompletionCallback::QuitMessageLoop() { - pp::MessageLoop loop(pp::MessageLoop::GetCurrent()); - // If we don't have a message loop, we're probably running in process, where - // PPB_MessageLoop is not supported. Just use the Testing message loop. - if (loop.is_null() || loop == pp::MessageLoop::GetForMainThread()) { - GetTestingInterface()->QuitMessageLoop(instance_); - } else { - const bool should_quit = false; - loop.PostQuit(should_quit); - } -} - -int32_t OpenURLRequest(PP_Instance instance, - pp::URLLoader* loader, - const pp::URLRequestInfo& request, - CallbackType callback_type, - std::string* response_body) { - { - TestCompletionCallback open_callback(instance, callback_type); - open_callback.WaitForResult( - loader->Open(request, open_callback.GetCallback())); - if (open_callback.result() != PP_OK) - return open_callback.result(); - } - - int32_t bytes_read = 0; - do { - char buffer[1024]; - TestCompletionCallback read_callback(instance, callback_type); - read_callback.WaitForResult(loader->ReadResponseBody( - &buffer, sizeof(buffer), read_callback.GetCallback())); - bytes_read = read_callback.result(); - if (bytes_read < 0) - return bytes_read; - if (response_body) - response_body->append(std::string(buffer, bytes_read)); - } while (bytes_read > 0); - - return PP_OK; -}
diff --git a/tests/test_utils.h b/tests/test_utils.h deleted file mode 100644 index 52a0c81..0000000 --- a/tests/test_utils.h +++ /dev/null
@@ -1,362 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_UTILS_H_ -#define PPAPI_TESTS_TEST_UTILS_H_ - -#include <string> - -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/message_loop.h" -#include "ppapi/utility/completion_callback_factory.h" - -namespace pp { -class NetAddress; -class URLLoader; -class URLRequestInfo; -} - -// Timeout to wait for some action to complete. -extern const int kActionTimeoutMs; - -const PPB_Testing_Private* GetTestingInterface(); -std::string ReportError(const char* method, int32_t error); -void PlatformSleep(int duration_ms); - -// Returns the host and port of the current document's URL (Which is generally -// served by an EmbeddedTestServer). Returns false on failure. -bool GetLocalHostPort(PP_Instance instance, std::string* host, uint16_t* port); - -uint16_t ConvertFromNetEndian16(uint16_t x); -uint16_t ConvertToNetEndian16(uint16_t x); -bool EqualNetAddress(const pp::NetAddress& addr1, const pp::NetAddress& addr2); -// Only returns the first address if there are more than one available. -bool ResolveHost(PP_Instance instance, - const std::string& host, - uint16_t port, - pp::NetAddress* addr); -bool ReplacePort(PP_Instance instance, - const pp::NetAddress& input_addr, - uint16_t port, - pp::NetAddress* output_addr); -uint16_t GetPort(const pp::NetAddress& addr); - -// NestedEvent allows you to run a nested MessageLoop and wait for a particular -// event to complete. For example, you can use it to wait for a callback on a -// PPP interface, which will "Signal" the event and make the loop quit. -// "Wait()" will return immediately if it has already been signalled. Otherwise, -// it will run a nested run loop (using PPB_Testing.RunMessageLoop) and will -// return only after it has been signalled. -// Example: -// std::string TestFullscreen::TestNormalToFullscreen() { -// pp::Fullscreen screen_mode(instance); -// screen_mode.SetFullscreen(true); -// SimulateUserGesture(); -// // Let DidChangeView run in a nested run loop. -// nested_event_.Wait(); -// Pass(); -// } -// -// void TestFullscreen::DidChangeView(const pp::View& view) { -// nested_event_.Signal(); -// } -// -// All methods except Signal and PostSignal must be invoked on the main thread. -// It's OK to signal from a background thread, so you can (for example) Signal() -// from the Audio thread. -class NestedEvent { - public: - explicit NestedEvent(PP_Instance instance) - : instance_(instance), waiting_(false), signalled_(false) { - } - // Run a nested run loop and wait until Signal() is called. If Signal() - // has already been called, return immediately without running a nested loop. - void Wait(); - // Signal the NestedEvent. If Wait() has been called, quit the message loop. - // This can be called from any thread. - void Signal(); - // Signal the NestedEvent in |wait_ms| milliseconds. This can be called from - // any thread. - void PostSignal(int32_t wait_ms); - - // Reset the NestedEvent so it can be used again. - void Reset(); - - private: - void SignalOnMainThread(); - static void SignalThunk(void* async_event, int32_t result); - - PP_Instance instance_; - bool waiting_; - bool signalled_; - // Disable copy and assign. - NestedEvent(const NestedEvent&); - NestedEvent& operator=(const NestedEvent&); -}; - -// Returns a callback that does nothing, so can be invoked when the current -// function is out of scope, unlike TestCompletionCallback. -pp::CompletionCallback DoNothingCallback(); - -template <typename OutputT> -void DeleteStorage(void* user_data, int32_t flags) { - typename pp::CompletionCallbackWithOutput<OutputT>::OutputStorageType* - storage = reinterpret_cast<typename pp::CompletionCallbackWithOutput< - OutputT>::OutputStorageType*>(user_data); - delete storage; -} - -// Same as DoNothingCallback(), but with an OutputStorageType, which it deletes -// when the callback is invoked. -template <typename OutputT> -pp::CompletionCallbackWithOutput<OutputT> DoNothingCallbackWithOutput() { - typename pp::CompletionCallbackWithOutput<OutputT>::OutputStorageType* - storage = new - typename pp::CompletionCallbackWithOutput<OutputT>::OutputStorageType(); - return pp::CompletionCallbackWithOutput<OutputT>( - &DeleteStorage<OutputT>, storage, PP_COMPLETIONCALLBACK_FLAG_OPTIONAL, - storage); -} - -enum CallbackType { PP_REQUIRED, PP_OPTIONAL, PP_BLOCKING }; -class TestCompletionCallback { - public: - class Delegate { - public: - virtual ~Delegate() {} - virtual void OnCallback(void* user_data, int32_t result) = 0; - }; - explicit TestCompletionCallback(PP_Instance instance); - // TODO(dmichael): Remove this constructor. - TestCompletionCallback(PP_Instance instance, bool force_async); - - TestCompletionCallback(PP_Instance instance, CallbackType callback_type); - - // Sets a Delegate instance. OnCallback() of this instance will be invoked - // when the completion callback is invoked. - // The delegate will be reset when Reset() or GetCallback() is called. - void SetDelegate(Delegate* delegate) { delegate_ = delegate; } - - // Wait for a result, given the return from the call which took this callback - // as a parameter. If |result| is PP_OK_COMPLETIONPENDING, WaitForResult will - // block until its callback has been invoked (in some cases, this will already - // have happened, and WaitForCallback can return immediately). - // For any other values, WaitForResult will simply set its internal "result_" - // field. To retrieve the final result of the operation (i.e., the result - // the callback has run, if necessary), call result(). You can call result() - // as many times as necessary until a new pp::CompletionCallback is retrieved. - // - // In some cases, you may want to check that the callback was invoked in the - // expected way (i.e., if the callback was "Required", then it should be - // invoked asynchronously). Within the body of a test (where returning a non- - // empty string indicates test failure), you can use the - // CHECK_CALLBACK_BEHAVIOR(callback) macro. From within a helper function, - // you can use failed() and errors(). - // - // Example usage within a test: - // callback.WaitForResult(foo.DoSomething(callback)); - // CHECK_CALLBACK_BEHAVIOR(callback); - // ASSERT_EQ(PP_OK, callback.result()); - // - // Example usage within a helper function: - // void HelperFunction(std::string* error_message) { - // callback.WaitForResult(foo.DoSomething(callback)); - // if (callback.failed()) - // error_message->assign(callback.errors()); - // } - void WaitForResult(int32_t result); - - // Used when you expect to receive either synchronous completion with PP_OK - // or a PP_ERROR_ABORTED asynchronously. - // Example usage: - // int32_t result = 0; - // { - // pp::URLLoader temp(instance_); - // result = temp.Open(request, callback); - // } - // callback.WaitForAbortResult(result); - // CHECK_CALLBACK_BEHAVIOR(callback); - void WaitForAbortResult(int32_t result); - - // Retrieve a pp::CompletionCallback for use in testing. This Reset()s the - // TestCompletionCallback. - pp::CompletionCallback GetCallback(); - - bool failed() { return !errors_.empty(); } - const std::string& errors() { return errors_; } - - int32_t result() const { return result_; } - - // Reset so that this callback can be used again. - void Reset(); - - CallbackType callback_type() { return callback_type_; } - void set_target_loop(const pp::MessageLoop& loop) { target_loop_ = loop; } - static void Handler(void* user_data, int32_t result); - - protected: - void RunMessageLoop(); - void QuitMessageLoop(); - - // Used to check that WaitForResult is only called once for each usage of the - // callback. - bool wait_for_result_called_; - // Indicates whether we have already been invoked. - bool have_result_; - // The last result received (or PP_OK_COMPLETIONCALLBACK if none). - int32_t result_; - CallbackType callback_type_; - bool post_quit_task_; - std::string errors_; - PP_Instance instance_; - Delegate* delegate_; - pp::MessageLoop target_loop_; -}; - -template <typename OutputT> -class TestCompletionCallbackWithOutput { - public: - explicit TestCompletionCallbackWithOutput(PP_Instance instance) - : callback_(instance), - output_storage_() { - pp::internal::CallbackOutputTraits<OutputT>::Initialize(&output_storage_); - } - - TestCompletionCallbackWithOutput(PP_Instance instance, bool force_async) - : callback_(instance, force_async), - output_storage_() { - pp::internal::CallbackOutputTraits<OutputT>::Initialize(&output_storage_); - } - - TestCompletionCallbackWithOutput(PP_Instance instance, - CallbackType callback_type) - : callback_(instance, callback_type), - output_storage_() { - pp::internal::CallbackOutputTraits<OutputT>::Initialize(&output_storage_); - } - - pp::CompletionCallbackWithOutput<OutputT> GetCallback(); - OutputT output() { - return pp::internal::CallbackOutputTraits<OutputT>::StorageToPluginArg( - output_storage_); - } - - // Delegate functions to TestCompletionCallback - void SetDelegate(TestCompletionCallback::Delegate* delegate) { - callback_.SetDelegate(delegate); - } - void WaitForResult(int32_t result) { callback_.WaitForResult(result); } - void WaitForAbortResult(int32_t result) { - callback_.WaitForAbortResult(result); - } - bool failed() { return callback_.failed(); } - const std::string& errors() { return callback_.errors(); } - int32_t result() const { return callback_.result(); } - void Reset() { - pp::internal::CallbackOutputTraits<OutputT>::Initialize(&output_storage_); - return callback_.Reset(); - } - - private: - TestCompletionCallback callback_; - typename pp::CompletionCallbackWithOutput<OutputT>::OutputStorageType - output_storage_; -}; - -template <typename OutputT> -pp::CompletionCallbackWithOutput<OutputT> -TestCompletionCallbackWithOutput<OutputT>::GetCallback() { - this->Reset(); - if (callback_.callback_type() == PP_BLOCKING) { - pp::CompletionCallbackWithOutput<OutputT> cc(&output_storage_); - return cc; - } - - callback_.set_target_loop(pp::MessageLoop::GetCurrent()); - pp::CompletionCallbackWithOutput<OutputT> cc( - &TestCompletionCallback::Handler, - this, - &output_storage_); - if (callback_.callback_type() == PP_OPTIONAL) - cc.set_flags(PP_COMPLETIONCALLBACK_FLAG_OPTIONAL); - return cc; -} - -// Verifies that the callback didn't record any errors. If the callback is run -// in an unexpected way (e.g., if it's invoked asynchronously when the call -// should have blocked), this returns an appropriate error string. -#define CHECK_CALLBACK_BEHAVIOR(callback) \ -do { \ - if ((callback).failed()) \ - return MakeFailureMessage(__FILE__, __LINE__, \ - (callback).errors().c_str()); \ -} while (false) - -/* - * A set of macros to use for platform detection. These were largely copied - * from chromium's build_config.h. - */ -#if defined(__APPLE__) -#define PPAPI_OS_MACOSX 1 -#elif defined(ANDROID) -#define PPAPI_OS_ANDROID 1 -#elif defined(__native_client__) -#define PPAPI_OS_NACL 1 -#elif defined(__linux__) -#define PPAPI_OS_LINUX 1 -#elif defined(_WIN32) -#define PPAPI_OS_WIN 1 -#elif defined(__FreeBSD__) -#define PPAPI_OS_FREEBSD 1 -#elif defined(__OpenBSD__) -#define PPAPI_OS_OPENBSD 1 -#elif defined(__sun) -#define PPAPI_OS_SOLARIS 1 -#else -#error Please add support for your platform in ppapi/tests/test_utils.h -#endif - -/* These are used to determine POSIX-like implementations vs Windows. */ -#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \ - defined(__OpenBSD__) || defined(__sun) || defined(__native_client__) -#define PPAPI_POSIX 1 -#endif - -// By default, ArrayBuffers over a certain size are sent via shared memory. In -// order to test for this without sending huge buffers, tests can use this -// class to set the minimum array buffer size used for shared memory temporarily -// lower. -class ScopedArrayBufferSizeSetter { - public: - ScopedArrayBufferSizeSetter(const PPB_Testing_Private* interface, - PP_Instance instance, - uint32_t threshold) - : interface_(interface), - instance_(instance) { - interface_->SetMinimumArrayBufferSizeForShmem(instance_, threshold); - } - ~ScopedArrayBufferSizeSetter() { - interface_->SetMinimumArrayBufferSizeForShmem(instance_, 0); - } - - private: - const PPB_Testing_Private* interface_; - PP_Instance instance_; -}; - -// Opens |request| in |loader| and returns the results of the URLRequest. The -// caller may provide the optional |response_body| argument to get the contents -// of the body of the response to the URLRequest. -// -// Returns PP_OK upon success. -int32_t OpenURLRequest(PP_Instance instance, - pp::URLLoader* loader, - const pp::URLRequestInfo& request, - CallbackType callback_type, - std::string* response_body); - -#endif // PPAPI_TESTS_TEST_UTILS_H_
diff --git a/tests/test_var.cc b/tests/test_var.cc deleted file mode 100644 index 7a0e723..0000000 --- a/tests/test_var.cc +++ /dev/null
@@ -1,252 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_var.h" - -#include <stdint.h> -#include <string.h> - -#include <limits> - -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -uint32_t kInvalidLength = static_cast<uint32_t>(-1); - -} // namespace - -REGISTER_TEST_CASE(Var); - -bool TestVar::Init() { - var_interface_ = static_cast<const PPB_Var*>( - pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE)); - return var_interface_ && CheckTestingInterface(); -} - -void TestVar::RunTests(const std::string& filter) { - RUN_TEST(BasicString, filter); - RUN_TEST(InvalidAndEmpty, filter); - RUN_TEST(InvalidUtf8, filter); - RUN_TEST(NullInputInUtf8Conversion, filter); - RUN_TEST(ValidUtf8, filter); - RUN_TEST(Utf8WithEmbeddedNulls, filter); - RUN_TEST(VarToUtf8ForWrongType, filter); -} - -std::string TestVar::TestBasicString() { - uint32_t before_object = testing_interface_->GetLiveObjectsForInstance( - instance_->pp_instance()); - { - const char kStr[] = "Hello"; - const uint32_t kStrLen(sizeof(kStr) - 1); - PP_Var str = var_interface_->VarFromUtf8(kStr, kStrLen); - ASSERT_EQ(PP_VARTYPE_STRING, str.type); - - // Reading back the string should work. - uint32_t len = 0; - const char* result = var_interface_->VarToUtf8(str, &len); - ASSERT_EQ(kStrLen, len); - ASSERT_EQ(0, strncmp(kStr, result, kStrLen)); - - // Destroy the string, readback should now fail. - var_interface_->Release(str); - result = var_interface_->VarToUtf8(str, &len); - ASSERT_EQ(0, len); - ASSERT_EQ(NULL, result); - } - - // Make sure we can assign a C++ object to itself and it stays alive. - { - pp::Var a("test"); - a = *&a; // The *& defeats Clang's -Wself-assign warning. - ASSERT_TRUE(a.AsString() == "test"); - } - - // Make sure nothing leaked. - ASSERT_TRUE(testing_interface_->GetLiveObjectsForInstance( - instance_->pp_instance()) == before_object); - - PASS(); -} - -std::string TestVar::TestInvalidAndEmpty() { - PP_Var invalid_string; - invalid_string.type = PP_VARTYPE_STRING; - invalid_string.value.as_id = 31415926; - - // Invalid strings should give NULL as the return value. - uint32_t len = std::numeric_limits<uint32_t>::max(); - const char* result = var_interface_->VarToUtf8(invalid_string, &len); - ASSERT_EQ(0, len); - ASSERT_EQ(NULL, result); - - // Same with vars that are not strings. - len = std::numeric_limits<uint32_t>::max(); - pp::Var int_var(42); - result = var_interface_->VarToUtf8(int_var.pp_var(), &len); - ASSERT_EQ(0, len); - ASSERT_EQ(NULL, result); - - // Empty strings should return non-NULL. - pp::Var empty_string(""); - len = std::numeric_limits<uint32_t>::max(); - result = var_interface_->VarToUtf8(empty_string.pp_var(), &len); - ASSERT_EQ(0, len); - ASSERT_NE(NULL, result); - - PASS(); -} - -std::string TestVar::TestInvalidUtf8() { - // utf8じゃない (japanese for "is not utf8") in shift-jis encoding. - static const char kSjisString[] = "utf8\x82\xb6\x82\xe1\x82\xc8\x82\xa2"; - pp::Var sjis(kSjisString); - if (!sjis.is_null()) - return "Non-UTF8 string was permitted erroneously."; - - PASS(); -} - -std::string TestVar::TestNullInputInUtf8Conversion() { - // This test talks directly to the C interface to access edge cases that - // cannot be exercised via the C++ interface. - PP_Var converted_string; - - // 0-length string should not dereference input string, and should produce - // an empty string. - converted_string = var_interface_->VarFromUtf8(NULL, 0); - if (converted_string.type != PP_VARTYPE_STRING) { - return "Expected 0 length to return empty string."; - } - - // Now convert it back. - uint32_t length = kInvalidLength; - const char* result = NULL; - result = var_interface_->VarToUtf8(converted_string, &length); - if (length != 0) { - return "Expected 0 length string on conversion."; - } - if (result == NULL) { - return "Expected a non-null result for 0-lengthed string from VarToUtf8."; - } - var_interface_->Release(converted_string); - - // Should not crash, and make an empty string. - const char* null_string = NULL; - pp::Var null_var(null_string); - if (!null_var.is_string() || !null_var.AsString().empty()) { - return "Expected NULL input to make an empty string Var."; - } - - PASS(); -} - -std::string TestVar::TestValidUtf8() { - // From UTF8 string -> PP_Var. - // Chinese for "I am utf8." - static const char kValidUtf8[] = "\xe6\x88\x91\xe6\x98\xafutf8."; - pp::Var converted_string(kValidUtf8); - - if (converted_string.is_null()) - return "Unable to convert valid utf8 to var."; - - // Since we're already here, test PP_Var back to UTF8 string. - std::string returned_string = converted_string.AsString(); - - // We need to check against 1 less than sizeof because the resulting string - // is technically not NULL terminated by API design. - if (returned_string.size() != sizeof(kValidUtf8) - 1) { - return "Unable to convert utf8 string back from var."; - } - if (returned_string != kValidUtf8) { - return "String mismatches on conversion back from PP_Var."; - } - - PASS(); -} - -std::string TestVar::TestUtf8WithEmbeddedNulls() { - // From UTF8 string with embedded nulls -> PP_Var. - // Chinese for "also utf8." - static const char kUtf8WithEmbededNull[] = "\xe6\xb9\x9f\xe6\x98\xaf\0utf8."; - std::string orig_string(kUtf8WithEmbededNull, - sizeof(kUtf8WithEmbededNull) -1); - pp::Var converted_string(orig_string); - - if (converted_string.is_null()) - return "Unable to convert utf8 with embedded nulls to var."; - - // Since we're already here, test PP_Var back to UTF8 string. - std::string returned_string = converted_string.AsString(); - - if (returned_string.size() != orig_string.size()) { - return "Unable to convert utf8 with embedded nulls back from var."; - } - if (returned_string != orig_string) { - return "String mismatches on conversion back from PP_Var."; - } - - PASS(); -} - -std::string TestVar::TestVarToUtf8ForWrongType() { - uint32_t length = kInvalidLength; - const char* result = NULL; - result = var_interface_->VarToUtf8(PP_MakeUndefined(), &length); - if (length != 0) { - return "Expected 0 on string conversion from Void var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Void var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeNull(), &length); - if (length != 0) { - return "Expected 0 on string conversion from Null var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Null var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeBool(PP_TRUE), &length); - if (length != 0) { - return "Expected 0 on string conversion from Bool var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Bool var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeInt32(1), &length); - if (length != 0) { - return "Expected 0 on string conversion from Int32 var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Int32 var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeDouble(1.0), &length); - if (length != 0) { - return "Expected 0 on string conversion from Double var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Double var."; - } - - PASS(); -} -
diff --git a/tests/test_var.h b/tests/test_var.h deleted file mode 100644 index e88e033..0000000 --- a/tests/test_var.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_VAR_H_ -#define PPAPI_TESTS_TEST_VAR_H_ - -#include <string> - -#include "ppapi/c/ppb_var.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/test_case.h" - -class TestVar : public TestCase { - public: - explicit TestVar(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestBasicString(); - std::string TestInvalidAndEmpty(); - std::string TestInvalidUtf8(); - std::string TestNullInputInUtf8Conversion(); - std::string TestValidUtf8(); - std::string TestUtf8WithEmbeddedNulls(); - std::string TestVarToUtf8ForWrongType(); - std::string TestHasPropertyAndMethod(); - - // Used by the tests that access the C API directly. - const PPB_Var* var_interface_; -}; - -#endif // PPAPI_TESTS_TEST_VAR_H_
diff --git a/tests/test_var_deprecated.cc b/tests/test_var_deprecated.cc deleted file mode 100644 index 1a8e82d..0000000 --- a/tests/test_var_deprecated.cc +++ /dev/null
@@ -1,396 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_var_deprecated.h" - -#include <stdint.h> -#include <string.h> - -#include <limits> - -#include "ppapi/c/dev/ppb_var_deprecated.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/cpp/dev/scriptable_object_deprecated.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/var_private.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -uint32_t kInvalidLength = static_cast<uint32_t>(-1); - -static const char kSetValueFunction[] = "SetValue"; - -// ScriptableObject used by the var tests. -class VarScriptableObject : public pp::deprecated::ScriptableObject { - public: - explicit VarScriptableObject(TestVarDeprecated* v) - : test_var_deprecated_(v) {} - - // pp::deprecated::ScriptableObject overrides. - bool HasMethod(const pp::Var& name, pp::Var* exception); - pp::Var Call(const pp::Var& name, - const std::vector<pp::Var>& args, - pp::Var* exception); - - private: - TestVarDeprecated* test_var_deprecated_; -}; - -bool VarScriptableObject::HasMethod(const pp::Var& name, pp::Var* exception) { - if (!name.is_string()) - return false; - return name.AsString() == kSetValueFunction; -} - -pp::Var VarScriptableObject::Call(const pp::Var& method_name, - const std::vector<pp::Var>& args, - pp::Var* exception) { - if (!method_name.is_string()) - return false; - std::string name = method_name.AsString(); - - if (name == kSetValueFunction) { - if (args.size() != 1) - *exception = pp::Var("Bad argument to SetValue(<value>)"); - else - test_var_deprecated_->set_var_from_page(pp::VarPrivate(args[0])); - } - - return pp::Var(); -} - -} // namespace - -REGISTER_TEST_CASE(VarDeprecated); - -bool TestVarDeprecated::Init() { - var_interface_ = static_cast<const PPB_Var_Deprecated*>( - pp::Module::Get()->GetBrowserInterface(PPB_VAR_DEPRECATED_INTERFACE)); - return var_interface_ && CheckTestingInterface(); -} - -void TestVarDeprecated::RunTests(const std::string& filter) { - RUN_TEST(BasicString, filter); - RUN_TEST(InvalidAndEmpty, filter); - RUN_TEST(InvalidUtf8, filter); - RUN_TEST(NullInputInUtf8Conversion, filter); - RUN_TEST(ValidUtf8, filter); - RUN_TEST(Utf8WithEmbeddedNulls, filter); - RUN_TEST(VarToUtf8ForWrongType, filter); - RUN_TEST(HasPropertyAndMethod, filter); - RUN_TEST(PassReference, filter); -} - -pp::deprecated::ScriptableObject* TestVarDeprecated::CreateTestObject() { - return new VarScriptableObject(this); -} - -std::string TestVarDeprecated::TestBasicString() { - uint32_t before_object = testing_interface_->GetLiveObjectsForInstance( - instance_->pp_instance()); - { - const char kStr[] = "Hello"; - const uint32_t kStrLen(sizeof(kStr) - 1); - PP_Var str = var_interface_->VarFromUtf8(pp::Module::Get()->pp_module(), - kStr, kStrLen); - ASSERT_EQ(PP_VARTYPE_STRING, str.type); - - // Reading back the string should work. - uint32_t len = 0; - const char* result = var_interface_->VarToUtf8(str, &len); - ASSERT_EQ(kStrLen, len); - ASSERT_EQ(0, strncmp(kStr, result, kStrLen)); - - // Destroy the string, readback should now fail. - var_interface_->Release(str); - result = var_interface_->VarToUtf8(str, &len); - ASSERT_EQ(0, len); - ASSERT_EQ(NULL, result); - } - - // Make sure nothing leaked. - ASSERT_TRUE(testing_interface_->GetLiveObjectsForInstance( - instance_->pp_instance()) == before_object); - - PASS(); -} - -std::string TestVarDeprecated::TestInvalidAndEmpty() { - PP_Var invalid_string; - invalid_string.type = PP_VARTYPE_STRING; - invalid_string.value.as_id = 31415926; - - // Invalid strings should give NULL as the return value. - uint32_t len = std::numeric_limits<uint32_t>::max(); - const char* result = var_interface_->VarToUtf8(invalid_string, &len); - ASSERT_EQ(0, len); - ASSERT_EQ(NULL, result); - - // Same with vars that are not strings. - len = std::numeric_limits<uint32_t>::max(); - pp::Var int_var(42); - result = var_interface_->VarToUtf8(int_var.pp_var(), &len); - ASSERT_EQ(0, len); - ASSERT_EQ(NULL, result); - - // Empty strings should return non-NULL. - pp::Var empty_string(""); - len = std::numeric_limits<uint32_t>::max(); - result = var_interface_->VarToUtf8(empty_string.pp_var(), &len); - ASSERT_EQ(0, len); - ASSERT_NE(NULL, result); - - PASS(); -} - -std::string TestVarDeprecated::TestInvalidUtf8() { - // utf8じゃない (japanese for "is not utf8") in shift-jis encoding. - static const char kSjisString[] = "utf8\x82\xb6\x82\xe1\x82\xc8\x82\xa2"; - pp::Var sjis(kSjisString); - if (!sjis.is_null()) - return "Non-UTF8 string was permitted erroneously."; - - PASS(); -} - -std::string TestVarDeprecated::TestNullInputInUtf8Conversion() { - // This test talks directly to the C interface to access edge cases that - // cannot be exercised via the C++ interface. - PP_Var converted_string; - - // 0-length string should not dereference input string, and should produce - // an empty string. - converted_string = var_interface_->VarFromUtf8( - pp::Module::Get()->pp_module(), NULL, 0); - if (converted_string.type != PP_VARTYPE_STRING) { - return "Expected 0 length to return empty string."; - } - - // Now convert it back. - uint32_t length = kInvalidLength; - const char* result = NULL; - result = var_interface_->VarToUtf8(converted_string, &length); - if (length != 0) { - return "Expected 0 length string on conversion."; - } - if (result == NULL) { - return "Expected a non-null result for 0-lengthed string from VarToUtf8."; - } - var_interface_->Release(converted_string); - - // Should not crash, and make an empty string. - const char* null_string = NULL; - pp::Var null_var(null_string); - if (!null_var.is_string() || !null_var.AsString().empty()) { - return "Expected NULL input to make an empty string Var."; - } - - PASS(); -} - -std::string TestVarDeprecated::TestValidUtf8() { - // From UTF8 string -> PP_Var. - // Chinese for "I am utf8." - static const char kValidUtf8[] = "\xe6\x88\x91\xe6\x98\xafutf8."; - pp::Var converted_string(kValidUtf8); - - if (converted_string.is_null()) - return "Unable to convert valid utf8 to var."; - - // Since we're already here, test PP_Var back to UTF8 string. - std::string returned_string = converted_string.AsString(); - - // We need to check against 1 less than sizeof because the resulting string - // is technically not NULL terminated by API design. - if (returned_string.size() != sizeof(kValidUtf8) - 1) { - return "Unable to convert utf8 string back from var."; - } - if (returned_string != kValidUtf8) { - return "String mismatches on conversion back from PP_Var."; - } - - PASS(); -} - -std::string TestVarDeprecated::TestUtf8WithEmbeddedNulls() { - // From UTF8 string with embedded nulls -> PP_Var. - // Chinese for "also utf8." - static const char kUtf8WithEmbededNull[] = "\xe6\xb9\x9f\xe6\x98\xaf\0utf8."; - std::string orig_string(kUtf8WithEmbededNull, - sizeof(kUtf8WithEmbededNull) -1); - pp::Var converted_string(orig_string); - - if (converted_string.is_null()) - return "Unable to convert utf8 with embedded nulls to var."; - - // Since we're already here, test PP_Var back to UTF8 string. - std::string returned_string = converted_string.AsString(); - - if (returned_string.size() != orig_string.size()) { - return "Unable to convert utf8 with embedded nulls back from var."; - } - if (returned_string != orig_string) { - return "String mismatches on conversion back from PP_Var."; - } - - PASS(); -} - -std::string TestVarDeprecated::TestVarToUtf8ForWrongType() { - uint32_t length = kInvalidLength; - const char* result = NULL; - result = var_interface_->VarToUtf8(PP_MakeUndefined(), &length); - if (length != 0) { - return "Expected 0 on string conversion from Void var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Void var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeNull(), &length); - if (length != 0) { - return "Expected 0 on string conversion from Null var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Null var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeBool(PP_TRUE), &length); - if (length != 0) { - return "Expected 0 on string conversion from Bool var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Bool var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeInt32(1), &length); - if (length != 0) { - return "Expected 0 on string conversion from Int32 var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Int32 var."; - } - - length = kInvalidLength; - result = NULL; - result = var_interface_->VarToUtf8(PP_MakeDouble(1.0), &length); - if (length != 0) { - return "Expected 0 on string conversion from Double var."; - } - if (result != NULL) { - return "Expected NULL on string conversion from Double var."; - } - - PASS(); -} - -std::string TestVarDeprecated::TestHasPropertyAndMethod() { - pp::VarPrivate window = instance_->GetWindowObject(); - ASSERT_TRUE(window.is_object()); - - // Regular property. - pp::Var exception; - ASSERT_TRUE(window.HasProperty("scrollX", &exception)); - ASSERT_TRUE(exception.is_undefined()); - ASSERT_FALSE(window.HasMethod("scrollX", &exception)); - ASSERT_TRUE(exception.is_undefined()); - - // Regular method (also counts as HasProperty). - ASSERT_TRUE(window.HasProperty("find", &exception)); - ASSERT_TRUE(exception.is_undefined()); - ASSERT_TRUE(window.HasMethod("find", &exception)); - ASSERT_TRUE(exception.is_undefined()); - - // Nonexistant ones should return false and not set the exception. - ASSERT_FALSE(window.HasProperty("superEvilBit", &exception)); - ASSERT_TRUE(exception.is_undefined()); - ASSERT_FALSE(window.HasMethod("superEvilBit", &exception)); - ASSERT_TRUE(exception.is_undefined()); - - // Check exception and return false on invalid property name. - ASSERT_FALSE(window.HasProperty(3.14159, &exception)); - ASSERT_FALSE(exception.is_undefined()); - - exception = pp::Var(); - ASSERT_FALSE(window.HasMethod(3.14159, &exception)); - ASSERT_FALSE(exception.is_undefined()); - - // Try to use something not an object. - exception = pp::Var(); - pp::VarPrivate string_object("asdf"); - ASSERT_FALSE(string_object.HasProperty("find", &exception)); - ASSERT_FALSE(exception.is_undefined()); - exception = pp::Var(); - ASSERT_FALSE(string_object.HasMethod("find", &exception)); - ASSERT_FALSE(exception.is_undefined()); - - // Try to use an invalid object (need to use the C API). - PP_Var invalid_object; - invalid_object.type = PP_VARTYPE_OBJECT; - invalid_object.value.as_id = static_cast<int64_t>(-1234567); - PP_Var exception2 = PP_MakeUndefined(); - ASSERT_FALSE(var_interface_->HasProperty(invalid_object, - pp::Var("find").pp_var(), - &exception2)); - ASSERT_NE(PP_VARTYPE_UNDEFINED, exception2.type); - var_interface_->Release(exception2); - - exception2 = PP_MakeUndefined(); - ASSERT_FALSE(var_interface_->HasMethod(invalid_object, - pp::Var("find").pp_var(), - &exception2)); - ASSERT_NE(PP_VARTYPE_UNDEFINED, exception2.type); - var_interface_->Release(exception2); - - // Getting a valid property/method when the exception is set returns false. - exception = pp::Var("Bad something-or-other exception"); - ASSERT_FALSE(window.HasProperty("find", &exception)); - ASSERT_FALSE(exception.is_undefined()); - ASSERT_FALSE(window.HasMethod("find", &exception)); - ASSERT_FALSE(exception.is_undefined()); - - PASS(); -} - -// Tests that when the page sends an object to the plugin via a function call, -// that the refcounting works properly (bug 79813). -std::string TestVarDeprecated::TestPassReference() { - var_from_page_ = pp::Var(); - - // Send a JS object from the page to the plugin. - pp::Var exception; - pp::Var ret = instance_->ExecuteScript( - "document.getElementById('plugin').SetValue(function(arg) {" - "return 'works' + arg;" - "})", - &exception); - ASSERT_TRUE(exception.is_undefined()); - - // We should have gotten an object set for our var_from_page. - ASSERT_TRUE(var_from_page_.is_object()); - - // If the reference counting works, the object should be valid. We can test - // this by executing it (it was a function we defined above) and it should - // return "works" concatenated with the argument. - pp::VarPrivate function(var_from_page_); - pp::Var result = var_from_page_.Call(pp::Var(), "nice"); - ASSERT_TRUE(result.is_string()); - ASSERT_TRUE(result.AsString() == "worksnice"); - - // Reset var_from_page_ so it doesn't seem like a leak to the var leak - // checking code. - var_from_page_ = pp::Var(); - - PASS(); -} -
diff --git a/tests/test_var_deprecated.h b/tests/test_var_deprecated.h deleted file mode 100644 index 4cb581c..0000000 --- a/tests/test_var_deprecated.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_VAR_DEPRECATED_H_ -#define PPAPI_TESTS_TEST_VAR_DEPRECATED_H_ - -#include <string> - -#include "ppapi/c/dev/ppb_var_deprecated.h" -#include "ppapi/cpp/private/var_private.h" -#include "ppapi/tests/test_case.h" - -class TestVarDeprecated : public TestCase { - public: - explicit TestVarDeprecated(TestingInstance* instance) : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - void set_var_from_page(const pp::VarPrivate& v) { var_from_page_ = v; } - - protected: - // Test case protected overrides. - virtual pp::deprecated::ScriptableObject* CreateTestObject(); - - private: - std::string TestBasicString(); - std::string TestInvalidAndEmpty(); - std::string TestInvalidUtf8(); - std::string TestNullInputInUtf8Conversion(); - std::string TestValidUtf8(); - std::string TestUtf8WithEmbeddedNulls(); - std::string TestVarToUtf8ForWrongType(); - std::string TestHasPropertyAndMethod(); - std::string TestPassReference(); - - // Used by the tests that access the C API directly. - const PPB_Var_Deprecated* var_interface_; - - // Saves the var from when a value is set on the test from the page. - pp::VarPrivate var_from_page_; -}; - -#endif // PPAPI_TESTS_TEST_VAR_DEPRECATED_H_
diff --git a/tests/test_var_resource.cc b/tests/test_var_resource.cc deleted file mode 100644 index 9d0a293..0000000 --- a/tests/test_var_resource.cc +++ /dev/null
@@ -1,133 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_var_resource.h" - -#include <stdint.h> - -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(VarResource); - -bool TestVarResource::Init() { - core_interface_ = static_cast<const PPB_Core*>( - pp::Module::Get()->GetBrowserInterface(PPB_CORE_INTERFACE)); - file_system_interface_ = static_cast<const PPB_FileSystem*>( - pp::Module::Get()->GetBrowserInterface(PPB_FILESYSTEM_INTERFACE)); - var_interface_ = static_cast<const PPB_Var*>( - pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE)); - return core_interface_ && file_system_interface_ && var_interface_ && - CheckTestingInterface(); -} - -void TestVarResource::RunTests(const std::string& filter) { - RUN_TEST(BasicResource, filter); - RUN_TEST(InvalidAndEmpty, filter); - RUN_TEST(WrongType, filter); -} - -std::string TestVarResource::TestBasicResource() { - uint32_t before_object = testing_interface_->GetLiveObjectsForInstance( - instance_->pp_instance()); - { - // Create an unopened FileSystem resource. - PP_Resource file_system = file_system_interface_->Create( - instance_->pp_instance(), PP_FILESYSTEMTYPE_LOCALTEMPORARY); - ASSERT_NE(0, file_system); - - // Build a var to wrap the resource. - PP_Var var = var_interface_->VarFromResource(file_system); - ASSERT_EQ(PP_VARTYPE_RESOURCE, var.type); - - // Reading back the resource should work. This will increment the reference - // on the resource, so we must release it afterwards. - PP_Resource result = var_interface_->VarToResource(var); - ASSERT_EQ(file_system, result); - core_interface_->ReleaseResource(result); - - // Destroy the var, readback should now fail. - var_interface_->Release(var); - result = var_interface_->VarToResource(var); - ASSERT_EQ(0, result); - - // Release the resource. There should be no more references to it. - core_interface_->ReleaseResource(file_system); - } - - // Make sure nothing leaked. This checks for both var and resource leaks. - ASSERT_EQ( - before_object, - testing_interface_->GetLiveObjectsForInstance(instance_->pp_instance())); - - PASS(); -} - -std::string TestVarResource::TestInvalidAndEmpty() { - uint32_t before_object = testing_interface_->GetLiveObjectsForInstance( - instance_->pp_instance()); - { - PP_Var invalid_resource; - invalid_resource.type = PP_VARTYPE_RESOURCE; - invalid_resource.value.as_id = 31415926; - - // Invalid resource vars should give 0 as the return value. - PP_Resource result = var_interface_->VarToResource(invalid_resource); - ASSERT_EQ(0, result); - - // Test writing and reading a non-existant resource. - PP_Resource fake_resource = 27182818; - PP_Var var = var_interface_->VarFromResource(fake_resource); - if (testing_interface()->IsOutOfProcess()) { - // An out-of-process plugin is expected to generate null in this case. - ASSERT_EQ(PP_VARTYPE_NULL, var.type); - result = var_interface_->VarToResource(var); - ASSERT_EQ(0, result); - } else { - // An in-process plugin is expected to generate a valid resource var - // (because it does not validate the resource). - ASSERT_EQ(PP_VARTYPE_RESOURCE, var.type); - result = var_interface_->VarToResource(var); - ASSERT_EQ(fake_resource, result); - var_interface_->Release(var); - } - // Note: Not necessary to release the resource, since it does not exist. - - // Write the resource 0; expect a valid resource var with 0. - var = var_interface_->VarFromResource(0); - ASSERT_EQ(PP_VARTYPE_RESOURCE, var.type); - result = var_interface_->VarToResource(var); - ASSERT_EQ(0, result); - var_interface_->Release(var); - } - - // Make sure nothing leaked. This checks for both var and resource leaks. - ASSERT_EQ( - before_object, - testing_interface_->GetLiveObjectsForInstance(instance_->pp_instance())); - - PASS(); -} - -std::string TestVarResource::TestWrongType() { - PP_Resource result = var_interface_->VarToResource(PP_MakeUndefined()); - ASSERT_EQ(0, result); - - result = var_interface_->VarToResource(PP_MakeNull()); - ASSERT_EQ(0, result); - - result = var_interface_->VarToResource(PP_MakeBool(PP_TRUE)); - ASSERT_EQ(0, result); - - result = var_interface_->VarToResource(PP_MakeInt32(42)); - ASSERT_EQ(0, result); - - result = var_interface_->VarToResource(PP_MakeDouble(1.0)); - ASSERT_EQ(0, result); - - PASS(); -}
diff --git a/tests/test_var_resource.h b/tests/test_var_resource.h deleted file mode 100644 index 6a619d4..0000000 --- a/tests/test_var_resource.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2013 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_VAR_RESOURCE_H_ -#define PPAPI_TESTS_TEST_VAR_RESOURCE_H_ - -#include <string> - -#include "ppapi/c/ppb_file_system.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/tests/test_case.h" - -class TestVarResource : public TestCase { - public: - explicit TestVarResource(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestBasicResource(); - std::string TestInvalidAndEmpty(); - std::string TestWrongType(); - - // Used by the tests that access the C APIs directly. - const PPB_Core* core_interface_; - const PPB_FileSystem* file_system_interface_; - const PPB_Var* var_interface_; -}; - -#endif // PPAPI_TESTS_TEST_VAR_RESOURCE_H_
diff --git a/tests/test_video_decoder.cc b/tests/test_video_decoder.cc deleted file mode 100644 index bee71ed..0000000 --- a/tests/test_video_decoder.cc +++ /dev/null
@@ -1,110 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_video_decoder.h" - -#include "ppapi/c/pp_errors.h" -#include "ppapi/cpp/video_decoder.h" -#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h" -#include "ppapi/tests/testing_instance.h" - -namespace { - -// The maximum number of pictures that the client can pass in for -// min_picture_count, just as a sanity check on the argument. -// This should match the value of kMaximumPictureCount in -// video_decoder_resource.cc. -const uint32_t kMaximumPictureCount = 100; - -} // namespace - -REGISTER_TEST_CASE(VideoDecoder); - -bool TestVideoDecoder::Init() { - const int width = 16; - const int height = 16; - const int32_t attribs[] = {PP_GRAPHICS3DATTRIB_WIDTH, width, - PP_GRAPHICS3DATTRIB_HEIGHT, height, - PP_GRAPHICS3DATTRIB_NONE}; - graphics_3d_ = pp::Graphics3D(instance_, attribs); - return (pp::Module::Get()->GetBrowserInterface(PPB_VIDEODECODER_INTERFACE) && - CheckTestingInterface()); -} - -void TestVideoDecoder::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestVideoDecoder, Create, filter); -} - -std::string TestVideoDecoder::TestCreate() { - // Test that Initialize fails with a bad Graphics3D resource. - { - pp::VideoDecoder video_decoder(instance_); - ASSERT_FALSE(video_decoder.is_null()); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - pp::Graphics3D null_graphics_3d; - callback.WaitForResult( - video_decoder.Initialize(null_graphics_3d, - PP_VIDEOPROFILE_VP8_ANY, - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - callback.GetCallback())); - ASSERT_EQ(PP_ERROR_BADRESOURCE, callback.result()); - } - // Test that Initialize fails with a bad profile enum value. - { - pp::VideoDecoder video_decoder(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - const PP_VideoProfile kInvalidProfile = static_cast<PP_VideoProfile>(-1); - callback.WaitForResult( - video_decoder.Initialize(graphics_3d_, - kInvalidProfile, - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - callback.GetCallback())); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - } - // Test that Initialize succeeds if we can create a Graphics3D resources and - // if we allow software fallback to VP8, which should always be supported. - if (!graphics_3d_.is_null()) { - pp::VideoDecoder video_decoder(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - video_decoder.Initialize(graphics_3d_, - PP_VIDEOPROFILE_VP8_ANY, - PP_HARDWAREACCELERATION_WITHFALLBACK, - 0, - callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - } - // Test that Initialize succeeds with a larger than normal number of requested - // picture buffers, if we can create a Graphics3D resource and if we allow - // software fallback to VP8, which should always be supported. - if (!graphics_3d_.is_null()) { - pp::VideoDecoder video_decoder(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - video_decoder.Initialize(graphics_3d_, - PP_VIDEOPROFILE_VP8_ANY, - PP_HARDWAREACCELERATION_WITHFALLBACK, - kMaximumPictureCount, - callback.GetCallback())); - ASSERT_EQ(PP_OK, callback.result()); - } - // Test that Initialize fails if we request an unreasonable number of picture - // buffers. - if (!graphics_3d_.is_null()) { - pp::VideoDecoder video_decoder(instance_); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult( - video_decoder.Initialize(graphics_3d_, - PP_VIDEOPROFILE_VP8_ANY, - PP_HARDWAREACCELERATION_WITHFALLBACK, - kMaximumPictureCount + 1, - callback.GetCallback())); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - } - - PASS(); -}
diff --git a/tests/test_video_decoder.h b/tests/test_video_decoder.h deleted file mode 100644 index 3179462..0000000 --- a/tests/test_video_decoder.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_VIDEO_DECODER_H_ -#define PPAPI_TESTS_TEST_VIDEO_DECODER_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/ppb_video_decoder.h" -#include "ppapi/cpp/graphics_3d.h" -#include "ppapi/tests/test_case.h" - -class TestVideoDecoder : public TestCase { - public: - explicit TestVideoDecoder(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestCreate(); - - pp::Graphics3D graphics_3d_; -}; - -#endif // PPAPI_TESTS_TEST_VIDEO_DECODER_H_
diff --git a/tests/test_video_decoder_dev.cc b/tests/test_video_decoder_dev.cc deleted file mode 100644 index 398a193..0000000 --- a/tests/test_video_decoder_dev.cc +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_video_decoder_dev.h" - -#include "ppapi/c/dev/ppb_video_decoder_dev.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(VideoDecoderDev); - -bool TestVideoDecoderDev::Init() { - video_decoder_interface_ = static_cast<const PPB_VideoDecoder_Dev*>( - pp::Module::Get()->GetBrowserInterface(PPB_VIDEODECODER_DEV_INTERFACE)); - return video_decoder_interface_ && CheckTestingInterface(); -} - -void TestVideoDecoderDev::RunTests(const std::string& filter) { - RUN_TEST(CreateFailure, filter); -} - -void TestVideoDecoderDev::QuitMessageLoop() { - testing_interface_->QuitMessageLoop(instance_->pp_instance()); -} - -std::string TestVideoDecoderDev::TestCreateFailure() { - PP_Resource decoder = video_decoder_interface_->Create( - instance_->pp_instance(), 0, static_cast<PP_VideoDecoder_Profile>(-1)); - if (decoder != 0) - return "Create: error detecting invalid context & configs"; - - PASS(); -}
diff --git a/tests/test_video_decoder_dev.h b/tests/test_video_decoder_dev.h deleted file mode 100644 index 4cb1bab..0000000 --- a/tests/test_video_decoder_dev.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_VIDEO_DECODER_DEV_H_ -#define PPAPI_TESTS_TEST_VIDEO_DECODER_DEV_H_ - -#include <string> - -#include "ppapi/c/dev/ppb_video_decoder_dev.h" -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -class TestVideoDecoderDev : public TestCase { - public: - explicit TestVideoDecoderDev(TestingInstance* instance) - : TestCase(instance) {} - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - void QuitMessageLoop(); - - private: - std::string TestCreateFailure(); - - // Used by the tests that access the C API directly. - const PPB_VideoDecoder_Dev* video_decoder_interface_; -}; - -#endif // PPAPI_TESTS_TEST_VIDEO_DECODER_DEV_H_
diff --git a/tests/test_video_encoder.cc b/tests/test_video_encoder.cc deleted file mode 100644 index f86f319..0000000 --- a/tests/test_video_encoder.cc +++ /dev/null
@@ -1,115 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_video_encoder.h" - -#include "ppapi/c/pp_codecs.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/cpp/video_encoder.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(VideoEncoder); - -bool TestVideoEncoder::Init() { - video_encoder_interface_ = static_cast<const PPB_VideoEncoder_0_1*>( - pp::Module::Get()->GetBrowserInterface(PPB_VIDEOENCODER_INTERFACE_0_1)); - return video_encoder_interface_ && CheckTestingInterface(); -} - -void TestVideoEncoder::RunTests(const std::string& filter) { - RUN_CALLBACK_TEST(TestVideoEncoder, AvailableCodecs, filter); - RUN_CALLBACK_TEST(TestVideoEncoder, IncorrectSizeFails, filter); - RUN_CALLBACK_TEST(TestVideoEncoder, InitializeVP8, filter); - RUN_CALLBACK_TEST(TestVideoEncoder, InitializeVP9, filter); -} - -std::string TestVideoEncoder::TestAvailableCodecs() { - // Test that we get results for supported formats. We should at - // least get the software supported formats. - pp::VideoEncoder video_encoder(instance_); - ASSERT_FALSE(video_encoder.is_null()); - - TestCompletionCallbackWithOutput<std::vector<PP_VideoProfileDescription> > - callback(instance_->pp_instance(), false); - callback.WaitForResult( - video_encoder.GetSupportedProfiles(callback.GetCallback())); - - ASSERT_GE(callback.result(), 1U); - - const std::vector<PP_VideoProfileDescription> video_profiles = - callback.output(); - ASSERT_GE(video_profiles.size(), 1U); - - bool found_vp8 = false, found_vp9 = false; - for (uint32_t i = 0; i < video_profiles.size(); ++i) { - const PP_VideoProfileDescription& description = video_profiles[i]; - if (description.hardware_accelerated == PP_FALSE) { - ASSERT_GE(description.max_framerate_numerator / - description.max_framerate_denominator, - 30U); - if (description.profile == PP_VIDEOPROFILE_VP8_ANY) - found_vp8 = true; - else if (description.profile == PP_VIDEOPROFILE_VP9_ANY) - found_vp9 = true; - } - } - ASSERT_TRUE(found_vp8); - ASSERT_TRUE(found_vp9); - - PASS(); -} - -std::string TestVideoEncoder::TestIncorrectSizeFails() { - // Test that initializing the encoder with incorrect size fails. - pp::VideoEncoder video_encoder(instance_); - ASSERT_FALSE(video_encoder.is_null()); - pp::Size video_size(0, 0); - - TestCompletionCallback callback(instance_->pp_instance(), false); - callback.WaitForResult(video_encoder.Initialize( - PP_VIDEOFRAME_FORMAT_I420, video_size, PP_VIDEOPROFILE_VP8_ANY, 1000000, - PP_HARDWAREACCELERATION_WITHFALLBACK, callback.GetCallback())); - - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - - PASS(); -} - -std::string TestVideoEncoder::TestInitializeVP8() { - return TestInitializeCodec(PP_VIDEOPROFILE_VP8_ANY); -} - -std::string TestVideoEncoder::TestInitializeVP9() { - return TestInitializeCodec(PP_VIDEOPROFILE_VP9_ANY); -} - -std::string TestVideoEncoder::TestInitializeCodec(PP_VideoProfile profile) { - pp::VideoEncoder video_encoder(instance_); - ASSERT_FALSE(video_encoder.is_null()); - pp::Size video_size(640, 480); - - TestCompletionCallback callback(instance_->pp_instance(), false); - callback.WaitForResult(video_encoder.Initialize( - PP_VIDEOFRAME_FORMAT_I420, video_size, profile, 1000000, - PP_HARDWAREACCELERATION_WITHFALLBACK, callback.GetCallback())); - - ASSERT_EQ(PP_OK, callback.result()); - - pp::Size coded_size; - ASSERT_EQ(PP_OK, video_encoder.GetFrameCodedSize(&coded_size)); - ASSERT_GE(coded_size.GetArea(), video_size.GetArea()); - ASSERT_GE(video_encoder.GetFramesRequired(), 1); - - TestCompletionCallbackWithOutput<pp::VideoFrame> get_video_frame( - instance_->pp_instance(), false); - get_video_frame.WaitForResult( - video_encoder.GetVideoFrame(get_video_frame.GetCallback())); - ASSERT_EQ(PP_OK, get_video_frame.result()); - - pp::Size video_frame_size; - ASSERT_TRUE(get_video_frame.output().GetSize(&video_frame_size)); - ASSERT_EQ(coded_size.GetArea(), video_frame_size.GetArea()); - - PASS(); -}
diff --git a/tests/test_video_encoder.h b/tests/test_video_encoder.h deleted file mode 100644 index 10843ec..0000000 --- a/tests/test_video_encoder.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2015 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_VIDEO_ENCODER_H_ -#define PPAPI_TESTS_TEST_VIDEO_ENCODER_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/ppb_video_encoder.h" -#include "ppapi/tests/test_case.h" - -class TestVideoEncoder : public TestCase { - public: - explicit TestVideoEncoder(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string TestAvailableCodecs(); - std::string TestIncorrectSizeFails(); - std::string TestInitializeVP8(); - std::string TestInitializeVP9(); - - std::string TestInitializeCodec(PP_VideoProfile profile); - - // Used by the tests that access the C API directly. - const PPB_VideoEncoder_0_1* video_encoder_interface_; -}; - -#endif // PPAPI_TESTS_TEST_VIDEO_ENCODER_H_
diff --git a/tests/test_view.cc b/tests/test_view.cc deleted file mode 100644 index 2fc0327..0000000 --- a/tests/test_view.cc +++ /dev/null
@@ -1,195 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_view.h" - -#include <stddef.h> - -#include <sstream> - -#include "ppapi/c/pp_time.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(View); - -TestView::TestView(TestingInstance* instance) - : TestCase(instance), - post_quit_on_view_changed_(false) { -} - -void TestView::DidChangeView(const pp::View& view) { - last_view_ = view; - page_visibility_log_.push_back(view.IsPageVisible()); - - if (post_quit_on_view_changed_) { - post_quit_on_view_changed_ = false; - testing_interface_->QuitMessageLoop(instance_->pp_instance()); - } -} - -bool TestView::Init() { - return CheckTestingInterface(); -} - -void TestView::RunTests(const std::string& filter) { - RUN_TEST(CreatedVisible, filter); - RUN_TEST(CreatedInvisible, filter); - RUN_TEST(PageHideShow, filter); - RUN_TEST(SizeChange, filter); - RUN_TEST(ClipChange, filter); - RUN_TEST(ScrollOffsetChange, filter); -} - -bool TestView::WaitUntilViewChanged() { - size_t old_page_visibility_change_count = page_visibility_log_.size(); - - // Run a nested run loop. It will exit either on ViewChanged or if the - // timeout happens. - post_quit_on_view_changed_ = true; - testing_interface_->RunMessageLoop(instance_->pp_instance()); - post_quit_on_view_changed_ = false; - - // We know we got a view changed event if something was appended to the log. - return page_visibility_log_.size() > old_page_visibility_change_count; -} - -void TestView::QuitMessageLoop(int32_t result) { - testing_interface_->QuitMessageLoop(instance_->pp_instance()); -} - -std::string TestView::TestCreatedVisible() { - ASSERT_FALSE(page_visibility_log_.empty()); - ASSERT_TRUE(page_visibility_log_[0]); - PASS(); -} - -std::string TestView::TestCreatedInvisible() { - ASSERT_FALSE(page_visibility_log_.empty()); - - if (page_visibility_log_[0]) { - // Add more error message since this test has some extra requirements. - instance_->AppendError("Initial page is set to visible. NOTE: " - "This test must be run in a background tab. " - "Either run in the UI test which does this, or you can middle-click " - "on the test link to run manually."); - } - ASSERT_FALSE(page_visibility_log_[0]); - PASS(); -} - -std::string TestView::TestPageHideShow() { - // Initial state should be visible. - ASSERT_FALSE(page_visibility_log_.empty()); - ASSERT_TRUE(page_visibility_log_[0]); - - // Now that we're alive, tell the test knows it can change our visibility. - instance_->ReportProgress("TestPageHideShow:Created"); - - // Wait until we get a hide event, being careful to handle spurious - // notifications of ViewChanged. - while (WaitUntilViewChanged() && page_visibility_log_.back()) { - } - if (page_visibility_log_.back()) { - // Didn't get a view changed event that changed visibility (though there - // may have been some that didn't change visibility). - // Add more error message since this test has some extra requirements. - return "Didn't receive a hide event in timeout. NOTE: " - "This test requires tab visibility to change and won't pass if you " - "just run it in a browser. Normally the UI test should handle " - "this. You can also run manually by waiting 2 secs, creating a new " - "tab, waiting 2 more secs, and closing the new tab."; - } - - // Tell the test so it can show us again. - instance_->ReportProgress("TestPageHideShow:Hidden"); - - // Wait until we get a show event. - while (WaitUntilViewChanged() && !page_visibility_log_.back()) { - } - ASSERT_TRUE(page_visibility_log_.back()); - - PASS(); -} - -std::string TestView::TestSizeChange() { - pp::Rect original_rect = last_view_.GetRect(); - - pp::Rect desired_rect = original_rect; - desired_rect.set_width(original_rect.width() + 10); - desired_rect.set_height(original_rect.height() + 12); - - std::ostringstream script_stream; - script_stream << "var plugin = document.getElementById('plugin');"; - script_stream << "plugin.setAttribute('width', " - << desired_rect.width() << ");"; - script_stream << "plugin.setAttribute('height', " - << desired_rect.height() << ");"; - - instance_->EvalScript(script_stream.str()); - - while (WaitUntilViewChanged() && last_view_.GetRect() != desired_rect) { - } - ASSERT_TRUE(last_view_.GetRect() == desired_rect); - - PASS(); -} - -std::string TestView::TestClipChange() { - pp::Rect original_rect = last_view_.GetRect(); - - // Original clip should be the full frame. - pp::Rect original_clip = last_view_.GetClipRect(); - ASSERT_TRUE(original_clip.x() == 1); - ASSERT_TRUE(original_clip.y() == 1); - ASSERT_TRUE(original_clip.width() == original_rect.width()); - ASSERT_TRUE(original_clip.height() == original_rect.height()); - - int clip_amount = original_rect.height() / 2; - - // It might be nice to set the position to be absolute and set the location, - // but this will cause WebKit to actually tear down the plugin and recreate - // it. So instead we add a big div to cause the document to be scrollable, - // and scroll it down. - std::ostringstream script_stream; - script_stream - << "var big = document.createElement('div');" - << "big.setAttribute('style', 'position:absolute; left:100px; " - "top:0px; width:1px; height:5000px;');" - << "document.body.appendChild(big);" - << "window.scrollBy(0, " << original_rect.y() + clip_amount << ");"; - - instance_->EvalScript(script_stream.str()); - - pp::Rect desired_clip = original_clip; - desired_clip.set_y(clip_amount + original_clip.y()); - desired_clip.set_height( - desired_clip.height() - desired_clip.y() + original_clip.y()); - - while (WaitUntilViewChanged() && last_view_.GetClipRect() != desired_clip) { - } - ASSERT_TRUE(last_view_.GetClipRect() == desired_clip); - PASS(); -} - -std::string TestView::TestScrollOffsetChange() { - instance_->EvalScript("document.body.style.width = '5000px';" - "document.body.style.height = '5000px';"); - instance_->EvalScript("window.scrollTo(5, 1);"); - - while (WaitUntilViewChanged() && - last_view_.GetScrollOffset() != pp::Point(5, 1)) { - } - ASSERT_EQ(pp::Point(5, 1), last_view_.GetScrollOffset()); - - instance_->EvalScript("window.scrollTo(0, 0);"); - - while (WaitUntilViewChanged() && - last_view_.GetScrollOffset() != pp::Point(0, 0)) { - } - ASSERT_EQ(pp::Point(0, 0), last_view_.GetScrollOffset()); - - PASS(); -}
diff --git a/tests/test_view.h b/tests/test_view.h deleted file mode 100644 index 85332d6..0000000 --- a/tests/test_view.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2011 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_VIEW_H_ -#define PPAPI_TESTS_TEST_VIEW_H_ - -#include <stdint.h> - -#include "ppapi/cpp/view.h" -#include "ppapi/tests/test_case.h" - -class TestView : public TestCase { - public: - TestView(TestingInstance* instance); - - virtual void DidChangeView(const pp::View& view); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& test_filter); - - private: - // Waits until we get a view changed event. Note that the browser may give - // us any number of view changed events, so tests that use this should - // expect that there may be spurious events and handle them accordingly. - // Note also that view changed sequencing can change between different - // versions of WebKit. - // - // Returns true if we got a view changed, false if it timed out. - bool WaitUntilViewChanged(); - - void QuitMessageLoop(int32_t result); - - std::string TestCreatedVisible(); - std::string TestCreatedInvisible(); - std::string TestPageHideShow(); - std::string TestSizeChange(); - std::string TestClipChange(); - std::string TestScrollOffsetChange(); - - pp::View last_view_; - - // DidChangeView stores the page visibility in this vector on each - // invocation so tests can check it. - std::vector<bool> page_visibility_log_; - - // Set to true to request that the next invocation of DidChangeView should - // post a quit to the message loop. DidChangeView will also reset the flag so - // this will only happen once. - bool post_quit_on_view_changed_; -}; - -#endif // PPAPI_TESTS_TEST_VIEW_H_
diff --git a/tests/test_websocket.cc b/tests/test_websocket.cc deleted file mode 100644 index de11611..0000000 --- a/tests/test_websocket.cc +++ /dev/null
@@ -1,1622 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_websocket.h" - -#include <stddef.h> -#include <stdio.h> -#include <string.h> - -#include <algorithm> -#include <memory> -#include <string> -#include <vector> - -#include "ppapi/c/pp_bool.h" -#include "ppapi/c/pp_completion_callback.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/ppb_var_array_buffer.h" -#include "ppapi/c/ppb_websocket.h" -#include "ppapi/c/private/ppb_testing_private.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/cpp/websocket.h" -#include "ppapi/tests/test_utils.h" -#include "ppapi/tests/testing_instance.h" -#include "ppapi/utility/websocket/websocket_api.h" - -// net::SpawnedTestServer serves WebSocket service for testing. -// Following URLs are handled by pywebsocket handlers in -// net/data/websocket/*_wsh.py. -const char kEchoServerURL[] = "echo-with-no-extension"; -const char kCloseServerURL[] = "close"; -const char kCloseWithCodeAndReasonServerURL[] = "close-code-and-reason"; -const char kProtocolTestServerURL[] = "protocol-test?protocol="; - -const char* const kInvalidURLs[] = {"http://www.google.com/invalid_scheme", - "ws://www.google.com/invalid#fragment", - "ws://www.google.com:7/invalid_port", - NULL}; - -// Internal packet sizes. -const uint64_t kMessageFrameOverhead = 6; - -namespace { - -struct WebSocketEvent { - enum EventType { - EVENT_OPEN, - EVENT_MESSAGE, - EVENT_ERROR, - EVENT_CLOSE - }; - - WebSocketEvent(EventType type, - bool was_clean, - uint16_t close_code, - const pp::Var& var) - : event_type(type), - was_clean(was_clean), - close_code(close_code), - var(var) { - } - EventType event_type; - bool was_clean; - uint16_t close_code; - pp::Var var; -}; - -class ReleaseResourceDelegate : public TestCompletionCallback::Delegate { - public: - explicit ReleaseResourceDelegate(const PPB_Core* core_interface, - PP_Resource resource) - : core_interface_(core_interface), - resource_(resource) { - } - - // TestCompletionCallback::Delegate implementation. - virtual void OnCallback(void* user_data, int32_t result) { - if (resource_) - core_interface_->ReleaseResource(resource_); - } - - private: - const PPB_Core* core_interface_; - PP_Resource resource_; -}; - -class TestWebSocketAPI : public pp::WebSocketAPI { - public: - explicit TestWebSocketAPI(pp::Instance* instance) - : pp::WebSocketAPI(instance), - connected_(false), - received_(false), - closed_(false), - wait_for_connected_(false), - wait_for_received_(false), - wait_for_closed_(false), - instance_(instance->pp_instance()) { - } - - virtual void WebSocketDidOpen() { - events_.push_back( - WebSocketEvent(WebSocketEvent::EVENT_OPEN, true, 0U, pp::Var())); - connected_ = true; - if (wait_for_connected_) { - GetTestingInterface()->QuitMessageLoop(instance_); - wait_for_connected_ = false; - } - } - - virtual void WebSocketDidClose( - bool was_clean, uint16_t code, const pp::Var& reason) { - events_.push_back( - WebSocketEvent(WebSocketEvent::EVENT_CLOSE, was_clean, code, reason)); - connected_ = true; - closed_ = true; - if (wait_for_connected_ || wait_for_closed_) { - GetTestingInterface()->QuitMessageLoop(instance_); - wait_for_connected_ = false; - wait_for_closed_ = false; - } - } - - virtual void HandleWebSocketMessage(const pp::Var &message) { - events_.push_back( - WebSocketEvent(WebSocketEvent::EVENT_MESSAGE, true, 0U, message)); - received_ = true; - if (wait_for_received_) { - GetTestingInterface()->QuitMessageLoop(instance_); - wait_for_received_ = false; - received_ = false; - } - } - - virtual void HandleWebSocketError() { - events_.push_back( - WebSocketEvent(WebSocketEvent::EVENT_ERROR, true, 0U, pp::Var())); - } - - void WaitForConnected() { - if (!connected_) { - wait_for_connected_ = true; - GetTestingInterface()->RunMessageLoop(instance_); - } - } - - void WaitForReceived() { - if (!received_) { - wait_for_received_ = true; - GetTestingInterface()->RunMessageLoop(instance_); - } - } - - void WaitForClosed() { - if (!closed_) { - wait_for_closed_ = true; - GetTestingInterface()->RunMessageLoop(instance_); - } - } - - const std::vector<WebSocketEvent>& GetSeenEvents() const { - return events_; - } - - private: - std::vector<WebSocketEvent> events_; - bool connected_; - bool received_; - bool closed_; - bool wait_for_connected_; - bool wait_for_received_; - bool wait_for_closed_; - PP_Instance instance_; -}; - -} // namespace - -REGISTER_TEST_CASE(WebSocket); - -bool TestWebSocket::Init() { - websocket_interface_ = static_cast<const PPB_WebSocket*>( - pp::Module::Get()->GetBrowserInterface(PPB_WEBSOCKET_INTERFACE)); - var_interface_ = static_cast<const PPB_Var*>( - pp::Module::Get()->GetBrowserInterface(PPB_VAR_INTERFACE)); - arraybuffer_interface_ = static_cast<const PPB_VarArrayBuffer*>( - pp::Module::Get()->GetBrowserInterface( - PPB_VAR_ARRAY_BUFFER_INTERFACE)); - core_interface_ = static_cast<const PPB_Core*>( - pp::Module::Get()->GetBrowserInterface(PPB_CORE_INTERFACE)); - if (!websocket_interface_ || !var_interface_ || !arraybuffer_interface_ || - !core_interface_) - return false; - - return CheckTestingInterface(); -} - -void TestWebSocket::RunTests(const std::string& filter) { - RUN_TEST_WITH_REFERENCE_CHECK(IsWebSocket, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UninitializedPropertiesAccess, filter); - RUN_TEST_WITH_REFERENCE_CHECK(InvalidConnect, filter); - RUN_TEST_WITH_REFERENCE_CHECK(Protocols, filter); - RUN_TEST_WITH_REFERENCE_CHECK(GetURL, filter); - RUN_TEST_WITH_REFERENCE_CHECK(ValidConnect, filter); - RUN_TEST_WITH_REFERENCE_CHECK(InvalidClose, filter); - RUN_TEST_WITH_REFERENCE_CHECK(ValidClose, filter); - RUN_TEST_WITH_REFERENCE_CHECK(GetProtocol, filter); - RUN_TEST_WITH_REFERENCE_CHECK(TextSendReceive, filter); - RUN_TEST_BACKGROUND(TestWebSocket, TextSendReceiveTwice, filter); - RUN_TEST_WITH_REFERENCE_CHECK(BinarySendReceive, filter); - RUN_TEST_WITH_REFERENCE_CHECK(StressedSendReceive, filter); - RUN_TEST_WITH_REFERENCE_CHECK(BufferedAmount, filter); - // PP_Resource for WebSocket may be released later because of an internal - // reference for asynchronous IPC handling. So, suppress reference check on - // the following AbortCallsWithCallback test. - RUN_TEST(AbortCallsWithCallback, filter); - RUN_TEST_WITH_REFERENCE_CHECK(AbortSendMessageCall, filter); - RUN_TEST_WITH_REFERENCE_CHECK(AbortCloseCall, filter); - RUN_TEST_WITH_REFERENCE_CHECK(AbortReceiveMessageCall, filter); - RUN_TEST_WITH_REFERENCE_CHECK(ClosedFromServerWhileSending, filter); - - RUN_TEST_WITH_REFERENCE_CHECK(CcInterfaces, filter); - - RUN_TEST_WITH_REFERENCE_CHECK(UtilityInvalidConnect, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityProtocols, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityGetURL, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityValidConnect, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityInvalidClose, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityValidClose, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityGetProtocol, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityTextSendReceive, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityBinarySendReceive, filter); - RUN_TEST_WITH_REFERENCE_CHECK(UtilityBufferedAmount, filter); -} - -std::string TestWebSocket::GetFullURL(const char* url) { - std::string rv = "ws://"; - // Some WebSocket tests don't start the server so there'll be no host and - // port. - if (instance_->websocket_host().empty()) - rv += "127.0.0.1"; - else - rv += instance_->websocket_host(); - if (instance_->websocket_port() != -1) { - char buffer[10]; - snprintf(buffer, sizeof(buffer), ":%d", instance_->websocket_port()); - rv += std::string(buffer); - } - rv += "/"; - rv += url; - return rv; -} - -PP_Var TestWebSocket::CreateVarString(const std::string& string) { - return var_interface_->VarFromUtf8(string.c_str(), - static_cast<uint32_t>(string.size())); -} - -PP_Var TestWebSocket::CreateVarBinary(const std::vector<uint8_t>& binary) { - PP_Var var = - arraybuffer_interface_->Create(static_cast<uint32_t>(binary.size())); - uint8_t* var_data = static_cast<uint8_t*>(arraybuffer_interface_->Map(var)); - std::copy(binary.begin(), binary.end(), var_data); - return var; -} - -void TestWebSocket::ReleaseVar(const PP_Var& var) { - var_interface_->Release(var); -} - -bool TestWebSocket::AreEqualWithString(const PP_Var& var, - const std::string& string) { - if (var.type != PP_VARTYPE_STRING) - return false; - uint32_t utf8_length; - const char* utf8 = var_interface_->VarToUtf8(var, &utf8_length); - if (utf8_length != string.size()) - return false; - if (string.compare(utf8)) - return false; - return true; -} - -bool TestWebSocket::AreEqualWithBinary(const PP_Var& var, - const std::vector<uint8_t>& binary) { - uint32_t buffer_size = 0; - PP_Bool success = arraybuffer_interface_->ByteLength(var, &buffer_size); - if (!success || buffer_size != binary.size()) - return false; - if (!std::equal(binary.begin(), binary.end(), - static_cast<uint8_t*>(arraybuffer_interface_->Map(var)))) - return false; - return true; -} - -PP_Resource TestWebSocket::Connect(const std::string& url, - int32_t* result, - const std::string& protocol) { - PP_Var protocols[] = { PP_MakeUndefined() }; - PP_Resource ws = websocket_interface_->Create(instance_->pp_instance()); - if (!ws) - return 0; - PP_Var url_var = CreateVarString(url); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - uint32_t protocol_count = 0U; - if (protocol.size()) { - protocols[0] = CreateVarString(protocol); - protocol_count = 1U; - } - callback.WaitForResult(websocket_interface_->Connect( - ws, url_var, protocols, protocol_count, - callback.GetCallback().pp_completion_callback())); - ReleaseVar(url_var); - if (protocol.size()) - ReleaseVar(protocols[0]); - *result = callback.result(); - return ws; -} - -void TestWebSocket::Send(int32_t /* result */, PP_Resource ws, - const std::string& message) { - PP_Var message_var = CreateVarString(message); - websocket_interface_->SendMessage(ws, message_var); - ReleaseVar(message_var); -} - -std::string TestWebSocket::TestIsWebSocket() { - // Test that a NULL resource isn't a websocket. - pp::Resource null_resource; - PP_Bool result = - websocket_interface_->IsWebSocket(null_resource.pp_resource()); - ASSERT_FALSE(result); - - PP_Resource ws = websocket_interface_->Create(instance_->pp_instance()); - ASSERT_TRUE(ws); - - result = websocket_interface_->IsWebSocket(ws); - ASSERT_TRUE(result); - - core_interface_->ReleaseResource(ws); - - PASS(); -} - -std::string TestWebSocket::TestUninitializedPropertiesAccess() { - PP_Resource ws = websocket_interface_->Create(instance_->pp_instance()); - ASSERT_TRUE(ws); - - uint64_t bufferedAmount = websocket_interface_->GetBufferedAmount(ws); - ASSERT_EQ(0U, bufferedAmount); - - uint16_t close_code = websocket_interface_->GetCloseCode(ws); - ASSERT_EQ(0U, close_code); - - PP_Var close_reason = websocket_interface_->GetCloseReason(ws); - ASSERT_TRUE(AreEqualWithString(close_reason, std::string())); - ReleaseVar(close_reason); - - PP_Bool close_was_clean = websocket_interface_->GetCloseWasClean(ws); - ASSERT_EQ(PP_FALSE, close_was_clean); - - PP_Var extensions = websocket_interface_->GetExtensions(ws); - ASSERT_TRUE(AreEqualWithString(extensions, std::string())); - ReleaseVar(extensions); - - PP_Var protocol = websocket_interface_->GetProtocol(ws); - ASSERT_TRUE(AreEqualWithString(protocol, std::string())); - ReleaseVar(protocol); - - PP_WebSocketReadyState ready_state = - websocket_interface_->GetReadyState(ws); - ASSERT_EQ(PP_WEBSOCKETREADYSTATE_INVALID, ready_state); - - PP_Var url = websocket_interface_->GetURL(ws); - ASSERT_TRUE(AreEqualWithString(url, std::string())); - ReleaseVar(url); - - core_interface_->ReleaseResource(ws); - - PASS(); -} - -std::string TestWebSocket::TestInvalidConnect() { - PP_Var protocols[] = { PP_MakeUndefined() }; - - PP_Resource ws = websocket_interface_->Create(instance_->pp_instance()); - ASSERT_TRUE(ws); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(websocket_interface_->Connect( - ws, PP_MakeUndefined(), protocols, 1U, - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - - callback.WaitForResult(websocket_interface_->Connect( - ws, PP_MakeUndefined(), protocols, 1U, - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_INPROGRESS, callback.result()); - - core_interface_->ReleaseResource(ws); - - for (int i = 0; kInvalidURLs[i]; ++i) { - int32_t result; - ws = Connect(kInvalidURLs[i], &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - - core_interface_->ReleaseResource(ws); - } - - PASS(); -} - -std::string TestWebSocket::TestProtocols() { - PP_Var url = CreateVarString(GetFullURL(kEchoServerURL).c_str()); - PP_Var bad_protocols[] = { - CreateVarString("x-test"), - CreateVarString("x-test") - }; - PP_Var good_protocols[] = { - CreateVarString("x-test"), - CreateVarString("x-yatest") - }; - - PP_Resource ws = websocket_interface_->Create(instance_->pp_instance()); - ASSERT_TRUE(ws); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - callback.WaitForResult(websocket_interface_->Connect( - ws, url, bad_protocols, 2U, - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - core_interface_->ReleaseResource(ws); - - ws = websocket_interface_->Create(instance_->pp_instance()); - ASSERT_TRUE(ws); - int32_t result = websocket_interface_->Connect( - ws, url, good_protocols, 2U, PP_BlockUntilComplete()); - ASSERT_EQ(PP_ERROR_BLOCKS_MAIN_THREAD, result); - core_interface_->ReleaseResource(ws); - - ReleaseVar(url); - for (int i = 0; i < 2; ++i) { - ReleaseVar(bad_protocols[i]); - ReleaseVar(good_protocols[i]); - } - core_interface_->ReleaseResource(ws); - - PASS(); -} - -std::string TestWebSocket::TestGetURL() { - for (int i = 0; kInvalidURLs[i]; ++i) { - int32_t result; - PP_Resource ws = Connect(kInvalidURLs[i], &result, std::string()); - ASSERT_TRUE(ws); - PP_Var url = websocket_interface_->GetURL(ws); - ASSERT_TRUE(AreEqualWithString(url, kInvalidURLs[i])); - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - - ReleaseVar(url); - core_interface_->ReleaseResource(ws); - } - - PASS(); -} - -std::string TestWebSocket::TestValidConnect() { - int32_t result; - PP_Resource ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - PP_Var extensions = websocket_interface_->GetExtensions(ws); - ASSERT_TRUE(AreEqualWithString(extensions, std::string())); - core_interface_->ReleaseResource(ws); - ReleaseVar(extensions); - - PASS(); -} - -std::string TestWebSocket::TestInvalidClose() { - PP_Var reason = CreateVarString("close for test"); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - TestCompletionCallback async_callback(instance_->pp_instance(), PP_REQUIRED); - - // Close before connect. - PP_Resource ws = websocket_interface_->Create(instance_->pp_instance()); - callback.WaitForResult(websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - core_interface_->ReleaseResource(ws); - - // Close with bad arguments. - int32_t result; - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - callback.WaitForResult(websocket_interface_->Close( - ws, 1U, reason, callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_NOACCESS, callback.result()); - core_interface_->ReleaseResource(ws); - - // Close with PP_VARTYPE_NULL. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - callback.WaitForResult(websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, PP_MakeNull(), - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - core_interface_->ReleaseResource(ws); - - // Close with PP_VARTYPE_NULL and ongoing receive message. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - PP_Var receive_message_var; - result = websocket_interface_->ReceiveMessage( - ws, &receive_message_var, - async_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - callback.WaitForResult(websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, PP_MakeNull(), - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_BADARGUMENT, callback.result()); - const char* send_message = "hi"; - PP_Var send_message_var = CreateVarString(send_message); - result = websocket_interface_->SendMessage(ws, send_message_var); - ReleaseVar(send_message_var); - ASSERT_EQ(PP_OK, result); - async_callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_OK, async_callback.result()); - ASSERT_TRUE(AreEqualWithString(receive_message_var, send_message)); - ReleaseVar(receive_message_var); - core_interface_->ReleaseResource(ws); - - // Close twice. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - async_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - // Call another Close() before previous one is in progress. - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_ERROR_INPROGRESS, result); - async_callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_OK, async_callback.result()); - // Call another Close() after previous one is completed. - // This Close() must do nothing and reports no error. - callback.WaitForResult(websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_OK, callback.result()); - core_interface_->ReleaseResource(ws); - - ReleaseVar(reason); - - PASS(); -} - -// TODO(tyoshino): Consider splitting this test into smaller ones. -// http://crbug.com/397035 -std::string TestWebSocket::TestValidClose() { - PP_Var reason = CreateVarString("close for test"); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - TestCompletionCallback another_callback( - instance_->pp_instance(), callback_type()); - - // Close. - int32_t result; - PP_Resource ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - callback.WaitForResult(websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - callback.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - core_interface_->ReleaseResource(ws); - - // Close without code and reason. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - callback.WaitForResult(websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NOT_SPECIFIED, reason, - callback.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - core_interface_->ReleaseResource(ws); - - // Close with PP_VARTYPE_UNDEFINED. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - callback.WaitForResult(websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, PP_MakeUndefined(), - callback.GetCallback().pp_completion_callback())); - CHECK_CALLBACK_BEHAVIOR(callback); - ASSERT_EQ(PP_OK, callback.result()); - core_interface_->ReleaseResource(ws); - - // Close in CONNECTING state. - // The ongoing Connect() fails with PP_ERROR_ABORTED, then the Close() - // completes successfully. - ws = websocket_interface_->Create(instance_->pp_instance()); - PP_Var url = CreateVarString(GetFullURL(kEchoServerURL).c_str()); - PP_Var protocols[] = { PP_MakeUndefined() }; - result = websocket_interface_->Connect( - ws, url, protocols, 0U, callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - another_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - another_callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_OK, another_callback.result()); - core_interface_->ReleaseResource(ws); - ReleaseVar(url); - - // Close while already closing. - // The first Close will succeed, and the second one will synchronously fail - // with PP_ERROR_INPROGRESS. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - another_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_ERROR_INPROGRESS, result); - callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_OK, callback.result()); - core_interface_->ReleaseResource(ws); - - // Close with ongoing ReceiveMessage. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - PP_Var receive_message_var; - result = websocket_interface_->ReceiveMessage( - ws, &receive_message_var, - callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - another_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - another_callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_OK, another_callback.result()); - core_interface_->ReleaseResource(ws); - - // Close with PP_VARTYPE_UNDEFINED for reason and ongoing ReceiveMessage. - ws = Connect(GetFullURL(kEchoServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - result = websocket_interface_->ReceiveMessage( - ws, &receive_message_var, - callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, PP_MakeUndefined(), - another_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - another_callback.WaitForResult(PP_OK_COMPLETIONPENDING); - ASSERT_EQ(PP_OK, another_callback.result()); - core_interface_->ReleaseResource(ws); - - // Server initiated closing handshake. - ws = Connect( - GetFullURL(kCloseWithCodeAndReasonServerURL), &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - // Text messsage "1000 bye" requests the server to initiate closing handshake - // with code being 1000 and reason being "bye". - PP_Var close_request_var = CreateVarString("1000 bye"); - result = websocket_interface_->SendMessage(ws, close_request_var); - ReleaseVar(close_request_var); - callback.WaitForResult(websocket_interface_->ReceiveMessage( - ws, &receive_message_var, - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_ERROR_FAILED, callback.result()); - core_interface_->ReleaseResource(ws); - - ReleaseVar(reason); - - PASS(); -} - -std::string TestWebSocket::TestGetProtocol() { - const char* expected_protocols[] = { - "x-chat", - "hoehoe", - NULL - }; - for (int i = 0; expected_protocols[i]; ++i) { - std::string url(GetFullURL(kProtocolTestServerURL)); - url += expected_protocols[i]; - int32_t result; - PP_Resource ws = Connect(url.c_str(), &result, expected_protocols[i]); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - - PP_Var protocol = websocket_interface_->GetProtocol(ws); - ASSERT_TRUE(AreEqualWithString(protocol, expected_protocols[i])); - - ReleaseVar(protocol); - core_interface_->ReleaseResource(ws); - } - - PASS(); -} - -std::string TestWebSocket::TestTextSendReceive() { - // Connect to test echo server. - int32_t connect_result; - PP_Resource ws = - Connect(GetFullURL(kEchoServerURL), &connect_result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, connect_result); - - // Send 'hello pepper' text message. - const char* message = "hello pepper"; - PP_Var message_var = CreateVarString(message); - int32_t result = websocket_interface_->SendMessage(ws, message_var); - ReleaseVar(message_var); - ASSERT_EQ(PP_OK, result); - - // Receive echoed 'hello pepper'. - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - PP_Var received_message; - callback.WaitForResult(websocket_interface_->ReceiveMessage( - ws, &received_message, callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_TRUE(AreEqualWithString(received_message, message)); - ReleaseVar(received_message); - core_interface_->ReleaseResource(ws); - - PASS(); -} - -// Run as a BACKGROUND test. -std::string TestWebSocket::TestTextSendReceiveTwice() { - // Connect to test echo server. - int32_t connect_result; - PP_Resource ws = - Connect(GetFullURL(kEchoServerURL), &connect_result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, connect_result); - pp::MessageLoop message_loop = pp::MessageLoop::GetCurrent(); - pp::CompletionCallbackFactory<TestWebSocket> factory(this); - - message_loop.PostWork(factory.NewCallback(&TestWebSocket::Send, - ws, std::string("hello"))); - // When the server receives 'Goodbye', it closes the session. - message_loop.PostWork(factory.NewCallback(&TestWebSocket::Send, - ws, std::string("Goodbye"))); - message_loop.PostQuit(false); - message_loop.Run(); - - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - PP_Var received_message; - int32_t result = websocket_interface_->ReceiveMessage( - ws, &received_message, callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK, result); - // Since we don't run the message loop, the callback will stay - // "pending and scheduled to run" state. - - // Waiting for the connection close which will be done by the server. - while (true) { - PP_WebSocketReadyState ready_state = - websocket_interface_->GetReadyState(ws); - if (ready_state != PP_WEBSOCKETREADYSTATE_CONNECTING && - ready_state != PP_WEBSOCKETREADYSTATE_OPEN) { - break; - } - PlatformSleep(100); // 100ms - } - - // Cleanup the message loop - message_loop.PostQuit(false); - message_loop.Run(); - - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_TRUE(AreEqualWithString(received_message, "hello")); - ReleaseVar(received_message); - core_interface_->ReleaseResource(ws); - PASS(); -} - -std::string TestWebSocket::TestBinarySendReceive() { - // Connect to test echo server. - int32_t connect_result; - PP_Resource ws = - Connect(GetFullURL(kEchoServerURL), &connect_result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, connect_result); - - // Send binary message. - std::vector<uint8_t> binary(256); - for (uint32_t i = 0; i < binary.size(); ++i) - binary[i] = i; - PP_Var message_var = CreateVarBinary(binary); - int32_t result = websocket_interface_->SendMessage(ws, message_var); - ReleaseVar(message_var); - ASSERT_EQ(PP_OK, result); - - // Receive echoed binary. - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - PP_Var received_message; - callback.WaitForResult(websocket_interface_->ReceiveMessage( - ws, &received_message, callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_TRUE(AreEqualWithBinary(received_message, binary)); - ReleaseVar(received_message); - core_interface_->ReleaseResource(ws); - - PASS(); -} - -std::string TestWebSocket::TestStressedSendReceive() { - // Connect to test echo server. - int32_t connect_result; - PP_Resource ws = - Connect(GetFullURL(kEchoServerURL), &connect_result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, connect_result); - - // Prepare PP_Var objects to send. - const char* text = "hello pepper"; - PP_Var text_var = CreateVarString(text); - std::vector<uint8_t> binary(256); - for (uint32_t i = 0; i < binary.size(); ++i) - binary[i] = i; - PP_Var binary_var = CreateVarBinary(binary); - // Prepare very large binary data over 64KiB. Object serializer in - // ppapi_proxy has a limitation of 64KiB as maximum return PP_Var data size - // to SRPC. In case received data over 64KiB exists, a specific code handles - // this large data via asynchronous callback from main thread. This data - // intends to test the code. - std::vector<uint8_t> large_binary(65 * 1024); - for (uint32_t i = 0; i < large_binary.size(); ++i) - large_binary[i] = i & 0xff; - PP_Var large_binary_var = CreateVarBinary(large_binary); - - // Send many messages. - int32_t result; - for (int i = 0; i < 256; ++i) { - result = websocket_interface_->SendMessage(ws, text_var); - ASSERT_EQ(PP_OK, result); - result = websocket_interface_->SendMessage(ws, binary_var); - ASSERT_EQ(PP_OK, result); - } - result = websocket_interface_->SendMessage(ws, large_binary_var); - ASSERT_EQ(PP_OK, result); - ReleaseVar(text_var); - ReleaseVar(binary_var); - ReleaseVar(large_binary_var); - - // Receive echoed data. - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - for (int i = 0; i <= 512; ++i) { - PP_Var received_message; - callback.WaitForResult(websocket_interface_->ReceiveMessage( - ws, &received_message, - callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_OK, callback.result()); - if (i == 512) { - ASSERT_TRUE(AreEqualWithBinary(received_message, large_binary)); - } else if (i & 1) { - ASSERT_TRUE(AreEqualWithBinary(received_message, binary)); - } else { - ASSERT_TRUE(AreEqualWithString(received_message, text)); - } - ReleaseVar(received_message); - } - core_interface_->ReleaseResource(ws); - - PASS(); -} - -std::string TestWebSocket::TestBufferedAmount() { - // Connect to test echo server. - int32_t connect_result; - PP_Resource ws = - Connect(GetFullURL(kEchoServerURL), &connect_result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, connect_result); - - // Prepare a large message that is not aligned with the internal buffer - // sizes. - std::string message(8193, 'x'); - PP_Var message_var = CreateVarString(message); - - uint64_t buffered_amount = 0; - int32_t result; - for (int i = 0; i < 100; i++) { - result = websocket_interface_->SendMessage(ws, message_var); - ASSERT_EQ(PP_OK, result); - buffered_amount = websocket_interface_->GetBufferedAmount(ws); - // Buffered amount size 262144 is too big for the internal buffer size. - if (buffered_amount > 262144) - break; - } - - // Close connection. - std::string reason_str = "close while busy"; - PP_Var reason = CreateVarString(reason_str.c_str()); - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason, - callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - ASSERT_EQ(PP_WEBSOCKETREADYSTATE_CLOSING, - websocket_interface_->GetReadyState(ws)); - - callback.WaitForResult(result); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_EQ(PP_WEBSOCKETREADYSTATE_CLOSED, - websocket_interface_->GetReadyState(ws)); - - uint64_t base_buffered_amount = websocket_interface_->GetBufferedAmount(ws); - - // After connection closure, all sending requests fail and just increase - // the bufferedAmount property. - PP_Var empty_string = CreateVarString(std::string()); - result = websocket_interface_->SendMessage(ws, empty_string); - ASSERT_EQ(PP_ERROR_FAILED, result); - buffered_amount = websocket_interface_->GetBufferedAmount(ws); - ASSERT_EQ(base_buffered_amount + kMessageFrameOverhead, buffered_amount); - base_buffered_amount = buffered_amount; - - result = websocket_interface_->SendMessage(ws, reason); - ASSERT_EQ(PP_ERROR_FAILED, result); - buffered_amount = websocket_interface_->GetBufferedAmount(ws); - uint64_t reason_frame_size = kMessageFrameOverhead + reason_str.length(); - ASSERT_EQ(base_buffered_amount + reason_frame_size, buffered_amount); - - ReleaseVar(message_var); - ReleaseVar(reason); - ReleaseVar(empty_string); - core_interface_->ReleaseResource(ws); - - PASS(); -} - -// Test abort behaviors where a WebSocket PP_Resource is released while each -// function is in-flight on the WebSocket PP_Resource. -std::string TestWebSocket::TestAbortCallsWithCallback() { - // Following tests make sure the behavior for functions which require a - // callback. The callback must get a PP_ERROR_ABORTED. - - // Test the behavior for Connect(). - PP_Resource ws = websocket_interface_->Create(instance_->pp_instance()); - ASSERT_TRUE(ws); - std::string url = GetFullURL(kEchoServerURL); - PP_Var url_var = CreateVarString(url); - TestCompletionCallback connect_callback( - instance_->pp_instance(), callback_type()); - int32_t result = websocket_interface_->Connect( - ws, url_var, NULL, 0, - connect_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - core_interface_->ReleaseResource(ws); - connect_callback.WaitForResult(result); - ASSERT_EQ(PP_ERROR_ABORTED, connect_callback.result()); - - // Test the behavior for Close(). - ws = Connect(url, &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - PP_Var reason_var = CreateVarString("abort"); - TestCompletionCallback close_callback( - instance_->pp_instance(), callback_type()); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason_var, - close_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - core_interface_->ReleaseResource(ws); - close_callback.WaitForResult(result); - ASSERT_EQ(PP_ERROR_ABORTED, close_callback.result()); - ReleaseVar(reason_var); - - // Test the behavior for ReceiveMessage(). - // Make sure the simplest case to wait for data which never arrives, here. - ws = Connect(url, &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - PP_Var receive_var; - TestCompletionCallback receive_callback( - instance_->pp_instance(), callback_type()); - result = websocket_interface_->ReceiveMessage( - ws, &receive_var, - receive_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - core_interface_->ReleaseResource(ws); - receive_callback.WaitForResult(result); - ASSERT_EQ(PP_ERROR_ABORTED, receive_callback.result()); - - // Release the resource in the aborting receive completion callback which is - // introduced by calling Close(). - ws = Connect(url, &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - result = websocket_interface_->ReceiveMessage( - ws, &receive_var, - receive_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - ReleaseResourceDelegate receive_delegate(core_interface_, ws); - receive_callback.SetDelegate(&receive_delegate); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, PP_MakeUndefined(), - close_callback.GetCallback().pp_completion_callback()); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - receive_callback.WaitForResult(result); - CHECK_CALLBACK_BEHAVIOR(receive_callback); - ASSERT_EQ(PP_ERROR_ABORTED, receive_callback.result()); - close_callback.WaitForResult(result); - CHECK_CALLBACK_BEHAVIOR(close_callback); - ASSERT_EQ(PP_ERROR_ABORTED, close_callback.result()); - - ReleaseVar(url_var); - - PASS(); -} - -std::string TestWebSocket::TestAbortSendMessageCall() { - // Test the behavior for SendMessage(). - // This function doesn't require a callback, but operation will be done - // asynchronously in WebKit and browser process. - std::vector<uint8_t> large_binary(65 * 1024); - PP_Var large_var = CreateVarBinary(large_binary); - - int32_t result; - std::string url = GetFullURL(kEchoServerURL); - PP_Resource ws = Connect(url, &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - result = websocket_interface_->SendMessage(ws, large_var); - ASSERT_EQ(PP_OK, result); - core_interface_->ReleaseResource(ws); - ReleaseVar(large_var); - - PASS(); -} - -std::string TestWebSocket::TestAbortCloseCall() { - // Release the resource in the close completion callback. - int32_t result; - std::string url = GetFullURL(kEchoServerURL); - PP_Resource ws = Connect(url, &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - TestCompletionCallback close_callback( - instance_->pp_instance(), callback_type()); - result = websocket_interface_->Close( - ws, PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, PP_MakeUndefined(), - close_callback.GetCallback().pp_completion_callback()); - ReleaseResourceDelegate close_delegate(core_interface_, ws); - close_callback.SetDelegate(&close_delegate); - close_callback.WaitForResult(result); - CHECK_CALLBACK_BEHAVIOR(close_callback); - ASSERT_EQ(PP_OK, close_callback.result()); - - PASS(); -} - -std::string TestWebSocket::TestAbortReceiveMessageCall() { - // Test the behavior where receive process might be in-flight. - std::vector<uint8_t> large_binary(65 * 1024); - PP_Var large_var = CreateVarBinary(large_binary); - const char* text = "yukarin"; - PP_Var text_var = CreateVarString(text); - - std::string url = GetFullURL(kEchoServerURL); - int32_t result; - PP_Resource ws; - - // Each trial sends |trial_count| + 1 messages and receives just |trial| - // number of message(s) before releasing the WebSocket. The WebSocket is - // released while the next message is going to be received. - const int trial_count = 8; - for (int trial = 1; trial <= trial_count; trial++) { - ws = Connect(url, &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - for (int i = 0; i <= trial_count; ++i) { - result = websocket_interface_->SendMessage(ws, text_var); - ASSERT_EQ(PP_OK, result); - } - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - PP_Var var; - for (int i = 0; i < trial; ++i) { - callback.WaitForResult(websocket_interface_->ReceiveMessage( - ws, &var, callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_TRUE(AreEqualWithString(var, text)); - ReleaseVar(var); - } - result = websocket_interface_->ReceiveMessage( - ws, &var, callback.GetCallback().pp_completion_callback()); - core_interface_->ReleaseResource(ws); - if (result != PP_OK) { - callback.WaitForResult(result); - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - } - } - // Same test, but the last receiving message is large message over 64KiB. - for (int trial = 1; trial <= trial_count; trial++) { - ws = Connect(url, &result, std::string()); - ASSERT_TRUE(ws); - ASSERT_EQ(PP_OK, result); - for (int i = 0; i <= trial_count; ++i) { - if (i == trial) - result = websocket_interface_->SendMessage(ws, large_var); - else - result = websocket_interface_->SendMessage(ws, text_var); - ASSERT_EQ(PP_OK, result); - } - TestCompletionCallback callback(instance_->pp_instance(), callback_type()); - PP_Var var; - for (int i = 0; i < trial; ++i) { - callback.WaitForResult(websocket_interface_->ReceiveMessage( - ws, &var, callback.GetCallback().pp_completion_callback())); - ASSERT_EQ(PP_OK, callback.result()); - ASSERT_TRUE(AreEqualWithString(var, text)); - ReleaseVar(var); - } - result = websocket_interface_->ReceiveMessage( - ws, &var, callback.GetCallback().pp_completion_callback()); - core_interface_->ReleaseResource(ws); - if (result != PP_OK) { - callback.WaitForResult(result); - ASSERT_EQ(PP_ERROR_ABORTED, callback.result()); - } - } - - ReleaseVar(large_var); - ReleaseVar(text_var); - - PASS(); -} - -std::string TestWebSocket::TestClosedFromServerWhileSending() { - // Connect to test echo server. - const pp::Var protocols[] = { pp::Var() }; - TestWebSocketAPI websocket(instance_); - int32_t result = - websocket.Connect(pp::Var(GetFullURL(kEchoServerURL)), protocols, 0U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - - result = websocket.Send(pp::Var("hello")); - ASSERT_EQ(PP_OK, result); - result = websocket.Send(pp::Var("Goodbye")); - // We send many messages so that PepperWebSocketHost::SendText is called - // after PepperWebSocketHost::didClose is called. - // Note: We must not wait for CLOSED event here because - // WebSocketResource::SendMessage doesn't call PepperWebSocketHost::SendText - // when its internal state is CLOSING or CLOSED. We want to test if the - // pepper WebSocket works well when WebSocketResource is OPEN and - // PepperWebSocketHost is CLOSED. - for (size_t i = 0; i < 10000; ++i) { - result = websocket.Send(pp::Var("")); - ASSERT_EQ(PP_OK, result); - } - - PASS(); -} - -std::string TestWebSocket::TestCcInterfaces() { - // C++ bindings is simple straightforward, then just verifies interfaces work - // as a interface bridge fine. - pp::WebSocket ws(instance_); - - // Check uninitialized properties access. - ASSERT_EQ(0, ws.GetBufferedAmount()); - ASSERT_EQ(0, ws.GetCloseCode()); - ASSERT_TRUE(AreEqualWithString(ws.GetCloseReason().pp_var(), std::string())); - ASSERT_FALSE(ws.GetCloseWasClean()); - ASSERT_TRUE(AreEqualWithString(ws.GetExtensions().pp_var(), std::string())); - ASSERT_TRUE(AreEqualWithString(ws.GetProtocol().pp_var(), std::string())); - ASSERT_EQ(PP_WEBSOCKETREADYSTATE_INVALID, ws.GetReadyState()); - ASSERT_TRUE(AreEqualWithString(ws.GetURL().pp_var(), std::string())); - - // Check communication interfaces (connect, send, receive, and close). - TestCompletionCallback connect_callback( - instance_->pp_instance(), callback_type()); - connect_callback.WaitForResult(ws.Connect( - pp::Var(GetFullURL(kCloseServerURL)), NULL, 0U, - connect_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(connect_callback); - ASSERT_EQ(PP_OK, connect_callback.result()); - - std::string text_message("hello C++"); - int32_t result = ws.SendMessage(pp::Var(text_message)); - ASSERT_EQ(PP_OK, result); - - std::vector<uint8_t> binary(256); - for (uint32_t i = 0; i < binary.size(); ++i) - binary[i] = i; - result = ws.SendMessage( - pp::Var(pp::PASS_REF, CreateVarBinary(binary))); - ASSERT_EQ(PP_OK, result); - - pp::Var text_receive_var; - TestCompletionCallback text_receive_callback( - instance_->pp_instance(), callback_type()); - text_receive_callback.WaitForResult( - ws.ReceiveMessage(&text_receive_var, - text_receive_callback.GetCallback())); - ASSERT_EQ(PP_OK, text_receive_callback.result()); - ASSERT_TRUE( - AreEqualWithString(text_receive_var.pp_var(), text_message.c_str())); - - pp::Var binary_receive_var; - TestCompletionCallback binary_receive_callback( - instance_->pp_instance(), callback_type()); - binary_receive_callback.WaitForResult( - ws.ReceiveMessage(&binary_receive_var, - binary_receive_callback.GetCallback())); - ASSERT_EQ(PP_OK, binary_receive_callback.result()); - ASSERT_TRUE(AreEqualWithBinary(binary_receive_var.pp_var(), binary)); - - TestCompletionCallback close_callback( - instance_->pp_instance(), callback_type()); - std::string reason("bye"); - close_callback.WaitForResult(ws.Close( - PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, pp::Var(reason), - close_callback.GetCallback())); - CHECK_CALLBACK_BEHAVIOR(close_callback); - ASSERT_EQ(PP_OK, close_callback.result()); - - // Check initialized properties access. - ASSERT_EQ(0, ws.GetBufferedAmount()); - ASSERT_EQ(PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, ws.GetCloseCode()); - ASSERT_TRUE( - AreEqualWithString(ws.GetCloseReason().pp_var(), reason.c_str())); - ASSERT_EQ(true, ws.GetCloseWasClean()); - ASSERT_TRUE(AreEqualWithString(ws.GetProtocol().pp_var(), std::string())); - ASSERT_EQ(PP_WEBSOCKETREADYSTATE_CLOSED, ws.GetReadyState()); - ASSERT_TRUE(AreEqualWithString( - ws.GetURL().pp_var(), GetFullURL(kCloseServerURL).c_str())); - - PASS(); -} - -std::string TestWebSocket::TestUtilityInvalidConnect() { - const pp::Var protocols[] = { pp::Var() }; - - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect(pp::Var(), protocols, 1U); - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - ASSERT_EQ(0U, websocket.GetSeenEvents().size()); - - result = websocket.Connect(pp::Var(), protocols, 1U); - ASSERT_EQ(PP_ERROR_INPROGRESS, result); - ASSERT_EQ(0U, websocket.GetSeenEvents().size()); - - for (int i = 0; kInvalidURLs[i]; ++i) { - TestWebSocketAPI ws(instance_); - result = ws.Connect(pp::Var(std::string(kInvalidURLs[i])), protocols, 0U); - if (result == PP_OK_COMPLETIONPENDING) { - ws.WaitForClosed(); - const std::vector<WebSocketEvent>& events = ws.GetSeenEvents(); - ASSERT_EQ(WebSocketEvent::EVENT_ERROR, events[0].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_CLOSE, events[1].event_type); - ASSERT_EQ(2U, ws.GetSeenEvents().size()); - } else { - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - ASSERT_EQ(0U, ws.GetSeenEvents().size()); - } - } - - PASS(); -} - -std::string TestWebSocket::TestUtilityProtocols() { - const pp::Var bad_protocols[] = { - pp::Var(std::string("x-test")), pp::Var(std::string("x-test")) }; - const pp::Var good_protocols[] = { - pp::Var(std::string("x-test")), pp::Var(std::string("x-yatest")) }; - - { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect( - pp::Var(GetFullURL(kEchoServerURL)), bad_protocols, 2U); - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - ASSERT_EQ(0U, websocket.GetSeenEvents().size()); - } - - { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect( - pp::Var(GetFullURL(kEchoServerURL)), good_protocols, 2U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - // Protocol arguments are valid, but this test run without a WebSocket - // server. As a result, OnError() and OnClose() are invoked because of - // a connection establishment failure. - ASSERT_EQ(2U, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_ERROR, events[0].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_CLOSE, events[1].event_type); - ASSERT_FALSE(events[1].was_clean); - } - - PASS(); -} - -std::string TestWebSocket::TestUtilityGetURL() { - const pp::Var protocols[] = { pp::Var() }; - - for (int i = 0; kInvalidURLs[i]; ++i) { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect( - pp::Var(std::string(kInvalidURLs[i])), protocols, 0U); - if (result == PP_OK_COMPLETIONPENDING) { - websocket.WaitForClosed(); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_EQ(WebSocketEvent::EVENT_ERROR, events[0].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_CLOSE, events[1].event_type); - ASSERT_EQ(2U, events.size()); - } else { - ASSERT_EQ(PP_ERROR_BADARGUMENT, result); - ASSERT_EQ(0U, websocket.GetSeenEvents().size()); - } - pp::Var url = websocket.GetURL(); - ASSERT_TRUE(AreEqualWithString(url.pp_var(), kInvalidURLs[i])); - } - - PASS(); -} - -std::string TestWebSocket::TestUtilityValidConnect() { - const pp::Var protocols[] = { pp::Var() }; - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect( - pp::Var(GetFullURL(kEchoServerURL)), protocols, 0U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_EQ(1U, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type); - ASSERT_TRUE( - AreEqualWithString(websocket.GetExtensions().pp_var(), std::string())); - - PASS(); -} - -std::string TestWebSocket::TestUtilityInvalidClose() { - const pp::Var reason = pp::Var(std::string("close for test")); - - // Close before connect. - { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Close( - PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, reason); - ASSERT_EQ(PP_ERROR_FAILED, result); - ASSERT_EQ(0U, websocket.GetSeenEvents().size()); - } - - // Close with bad arguments. - { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect(pp::Var(GetFullURL(kEchoServerURL)), - NULL, 0); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - result = websocket.Close(1U, reason); - ASSERT_EQ(PP_ERROR_NOACCESS, result); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_EQ(1U, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type); - } - - PASS(); -} - -std::string TestWebSocket::TestUtilityValidClose() { - std::string reason("close for test"); - pp::Var url = pp::Var(GetFullURL(kCloseServerURL)); - - // Close. - { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect(url, NULL, 0U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - result = websocket.Close( - PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, pp::Var(reason)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForClosed(); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_EQ(2U, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_CLOSE, events[1].event_type); - ASSERT_TRUE(events[1].was_clean); - ASSERT_EQ(PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, events[1].close_code); - ASSERT_TRUE(AreEqualWithString(events[1].var.pp_var(), reason.c_str())); - } - - // Close in connecting. - // The ongoing connect failed with PP_ERROR_ABORTED, then the close is done - // successfully. - { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect(url, NULL, 0U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = websocket.Close( - PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, pp::Var(reason)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForClosed(); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_TRUE(events.size() == 2 || events.size() == 3); - int index = 0; - if (events.size() == 3) - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[index++].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_ERROR, events[index++].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_CLOSE, events[index].event_type); - ASSERT_FALSE(events[index].was_clean); - } - - // Close in closing. - // The first close will be done successfully, then the second one failed with - // with PP_ERROR_INPROGRESS immediately. - { - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect(url, NULL, 0U); - result = websocket.Close( - PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, pp::Var(reason)); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - result = websocket.Close( - PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, pp::Var(reason)); - ASSERT_EQ(PP_ERROR_INPROGRESS, result); - websocket.WaitForClosed(); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_TRUE(events.size() == 2 || events.size() == 3); - int index = 0; - if (events.size() == 3) - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[index++].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_ERROR, events[index++].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_CLOSE, events[index].event_type); - ASSERT_FALSE(events[index].was_clean); - } - - PASS(); -} - -std::string TestWebSocket::TestUtilityGetProtocol() { - const std::string protocol("x-chat"); - const pp::Var protocols[] = { pp::Var(protocol) }; - std::string url(GetFullURL(kProtocolTestServerURL)); - url += protocol; - TestWebSocketAPI websocket(instance_); - int32_t result = websocket.Connect(pp::Var(url), protocols, 1U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForReceived(); - ASSERT_TRUE(AreEqualWithString( - websocket.GetProtocol().pp_var(), protocol.c_str())); - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - // The server to which this test connect returns the decided protocol as a - // text frame message. So the WebSocketEvent records EVENT_MESSAGE event - // after EVENT_OPEN event. - ASSERT_EQ(2U, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_MESSAGE, events[1].event_type); - ASSERT_TRUE(AreEqualWithString(events[1].var.pp_var(), protocol.c_str())); - - PASS(); -} - -std::string TestWebSocket::TestUtilityTextSendReceive() { - const pp::Var protocols[] = { pp::Var() }; - TestWebSocketAPI websocket(instance_); - int32_t result = - websocket.Connect(pp::Var(GetFullURL(kEchoServerURL)), protocols, 0U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - - // Send 'hello pepper'. - std::string message1("hello pepper"); - result = websocket.Send(pp::Var(std::string(message1))); - ASSERT_EQ(PP_OK, result); - - // Receive echoed 'hello pepper'. - websocket.WaitForReceived(); - - // Send 'goodbye pepper'. - std::string message2("goodbye pepper"); - result = websocket.Send(pp::Var(std::string(message2))); - - // Receive echoed 'goodbye pepper'. - websocket.WaitForReceived(); - - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_EQ(3U, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_MESSAGE, events[1].event_type); - ASSERT_TRUE(AreEqualWithString(events[1].var.pp_var(), message1.c_str())); - ASSERT_EQ(WebSocketEvent::EVENT_MESSAGE, events[2].event_type); - ASSERT_TRUE(AreEqualWithString(events[2].var.pp_var(), message2.c_str())); - - PASS(); -} - -std::string TestWebSocket::TestUtilityBinarySendReceive() { - const pp::Var protocols[] = { pp::Var() }; - TestWebSocketAPI websocket(instance_); - int32_t result = - websocket.Connect(pp::Var(GetFullURL(kEchoServerURL)), protocols, 0U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - - // Send binary message. - uint32_t len = 256; - std::vector<uint8_t> binary(len); - for (uint32_t i = 0; i < len; ++i) - binary[i] = i; - pp::VarArrayBuffer message(len); - uint8_t* var_data = static_cast<uint8_t*>(message.Map()); - std::copy(binary.begin(), binary.end(), var_data); - result = websocket.Send(message); - ASSERT_EQ(PP_OK, result); - - // Receive echoed binary message. - websocket.WaitForReceived(); - - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_EQ(2U, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type); - ASSERT_EQ(WebSocketEvent::EVENT_MESSAGE, events[1].event_type); - ASSERT_TRUE(AreEqualWithBinary(events[1].var.pp_var(), binary)); - - PASS(); -} - -std::string TestWebSocket::TestUtilityBufferedAmount() { - // Connect to test echo server. - const pp::Var protocols[] = { pp::Var() }; - TestWebSocketAPI websocket(instance_); - int32_t result = - websocket.Connect(pp::Var(GetFullURL(kEchoServerURL)), protocols, 0U); - ASSERT_EQ(PP_OK_COMPLETIONPENDING, result); - websocket.WaitForConnected(); - - // Prepare a large message that is not aligned with the internal buffer - // sizes. - std::string message(8193, 'x'); - uint64_t buffered_amount = 0; - uint32_t sent; - for (sent = 0; sent < 100; sent++) { - result = websocket.Send(pp::Var(message)); - ASSERT_EQ(PP_OK, result); - buffered_amount = websocket.GetBufferedAmount(); - // Buffered amount size 262144 is too big for the internal buffer size. - if (buffered_amount > 262144) - break; - } - - // Close connection. - std::string reason = "close while busy"; - result = websocket.Close( - PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, pp::Var(reason)); - ASSERT_EQ(PP_WEBSOCKETREADYSTATE_CLOSING, websocket.GetReadyState()); - websocket.WaitForClosed(); - ASSERT_EQ(PP_WEBSOCKETREADYSTATE_CLOSED, websocket.GetReadyState()); - - uint64_t base_buffered_amount = websocket.GetBufferedAmount(); - size_t events_on_closed = websocket.GetSeenEvents().size(); - - // After connection closure, all sending requests fail and just increase - // the bufferedAmount property. - result = websocket.Send(pp::Var(std::string())); - ASSERT_EQ(PP_ERROR_FAILED, result); - buffered_amount = websocket.GetBufferedAmount(); - ASSERT_EQ(base_buffered_amount + kMessageFrameOverhead, buffered_amount); - base_buffered_amount = buffered_amount; - - result = websocket.Send(pp::Var(reason)); - ASSERT_EQ(PP_ERROR_FAILED, result); - buffered_amount = websocket.GetBufferedAmount(); - uint64_t reason_frame_size = kMessageFrameOverhead + reason.length(); - ASSERT_EQ(base_buffered_amount + reason_frame_size, buffered_amount); - - const std::vector<WebSocketEvent>& events = websocket.GetSeenEvents(); - ASSERT_EQ(events_on_closed, events.size()); - ASSERT_EQ(WebSocketEvent::EVENT_OPEN, events[0].event_type); - size_t last_event = events_on_closed - 1; - for (uint32_t i = 1; i < last_event; ++i) { - ASSERT_EQ(WebSocketEvent::EVENT_MESSAGE, events[i].event_type); - ASSERT_TRUE(AreEqualWithString(events[i].var.pp_var(), message)); - } - ASSERT_EQ(WebSocketEvent::EVENT_CLOSE, events[last_event].event_type); - ASSERT_TRUE(events[last_event].was_clean); - - PASS(); -}
diff --git a/tests/test_websocket.h b/tests/test_websocket.h deleted file mode 100644 index 3c5080d..0000000 --- a/tests/test_websocket.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_WEBSOCKET_H_ -#define PPAPI_TESTS_TEST_WEBSOCKET_H_ - -#include <stdint.h> - -#include <string> -#include <vector> - -#include "ppapi/c/ppb_core.h" -#include "ppapi/c/ppb_var.h" -#include "ppapi/c/ppb_var_array_buffer.h" -#include "ppapi/c/ppb_websocket.h" -#include "ppapi/tests/test_case.h" - -class TestWebSocket : public TestCase { - public: - explicit TestWebSocket(TestingInstance* instance) : TestCase(instance) {} - - private: - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - std::string GetFullURL(const char* url); - PP_Var CreateVarString(const std::string& string); - PP_Var CreateVarBinary(const std::vector<uint8_t>& binary); - void ReleaseVar(const PP_Var& var); - bool AreEqualWithString(const PP_Var& var, const std::string& string); - bool AreEqualWithBinary(const PP_Var& var, - const std::vector<uint8_t>& binary); - - PP_Resource Connect(const std::string& url, - int32_t* result, - const std::string& protocol); - - void Send(int32_t result, PP_Resource ws, const std::string& message); - - std::string TestIsWebSocket(); - std::string TestUninitializedPropertiesAccess(); - std::string TestInvalidConnect(); - std::string TestProtocols(); - std::string TestGetURL(); - std::string TestValidConnect(); - std::string TestInvalidClose(); - std::string TestValidClose(); - std::string TestGetProtocol(); - std::string TestTextSendReceive(); - std::string TestTextSendReceiveTwice(); - std::string TestBinarySendReceive(); - std::string TestStressedSendReceive(); - std::string TestBufferedAmount(); - std::string TestAbortCallsWithCallback(); - std::string TestAbortSendMessageCall(); - std::string TestAbortCloseCall(); - std::string TestAbortReceiveMessageCall(); - std::string TestClosedFromServerWhileSending(); - - std::string TestCcInterfaces(); - - std::string TestUtilityInvalidConnect(); - std::string TestUtilityProtocols(); - std::string TestUtilityGetURL(); - std::string TestUtilityValidConnect(); - std::string TestUtilityInvalidClose(); - std::string TestUtilityValidClose(); - std::string TestUtilityGetProtocol(); - std::string TestUtilityTextSendReceive(); - std::string TestUtilityBinarySendReceive(); - std::string TestUtilityBufferedAmount(); - - // Keeps Pepper API interfaces. These are used by the tests that access the C - // API directly. - const PPB_WebSocket* websocket_interface_; - const PPB_Var* var_interface_; - const PPB_VarArrayBuffer* arraybuffer_interface_; - const PPB_Core* core_interface_; -}; - -#endif // PPAPI_TESTS_TEST_WEBSOCKET_H_
diff --git a/tests/test_x509_certificate_private.cc b/tests/test_x509_certificate_private.cc deleted file mode 100644 index 31966d2..0000000 --- a/tests/test_x509_certificate_private.cc +++ /dev/null
@@ -1,243 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/test_x509_certificate_private.h" - -#include <stdint.h> - -#include <cmath> -#include <limits> - -#include "ppapi/cpp/private/x509_certificate_private.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(X509CertificatePrivate); - -namespace { - -bool FieldMatchesString( - const pp::X509CertificatePrivate& certificate, - PP_X509Certificate_Private_Field field, - const std::string& expected) { - pp::Var field_value = certificate.GetField(field); - if (!field_value.is_string()) - return false; - return field_value.AsString() == expected; -} - -bool FieldMatchesDouble( - const pp::X509CertificatePrivate& certificate, - PP_X509Certificate_Private_Field field, - double expected) { - pp::Var field_value = certificate.GetField(field); - if (!field_value.is_double()) - return false; - return std::fabs(field_value.AsDouble() - expected) <= - std::numeric_limits<double>::epsilon(); -} - -bool FieldMatchesBuffer( - const pp::X509CertificatePrivate& certificate, - PP_X509Certificate_Private_Field field, - const char* expected, - uint32_t expected_length) { - pp::Var field_value = certificate.GetField(field); - if (!field_value.is_array_buffer()) - return false; - pp::VarArrayBuffer array_buffer(field_value); - char* bytes = static_cast<char*>(array_buffer.Map()); - uint32_t length = array_buffer.ByteLength(); - if (length != expected_length) - return false; - return std::equal(expected, expected + expected_length, bytes); -} - -bool FieldIsNull( - const pp::X509CertificatePrivate& certificate, - PP_X509Certificate_Private_Field field) { - return certificate.GetField(field).is_null(); -} - -// Google's cert. -const unsigned char kGoogleDer[] = { - 0x30, 0x82, 0x03, 0x21, 0x30, 0x82, 0x02, 0x8a, 0xa0, 0x03, 0x02, 0x01, - 0x02, 0x02, 0x10, 0x01, 0x2a, 0x39, 0x76, 0x0d, 0x3f, 0x4f, 0xc9, 0x0b, - 0xe7, 0xbd, 0x2b, 0xcf, 0x95, 0x2e, 0x7a, 0x30, 0x0d, 0x06, 0x09, 0x2a, - 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x4c, - 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x5a, - 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x1c, - 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e, 0x73, 0x75, - 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79, 0x29, 0x20, - 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, - 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x53, 0x47, - 0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x30, 0x39, 0x30, 0x33, - 0x32, 0x37, 0x32, 0x32, 0x32, 0x30, 0x30, 0x37, 0x5a, 0x17, 0x0d, 0x31, - 0x30, 0x30, 0x33, 0x32, 0x37, 0x32, 0x32, 0x32, 0x30, 0x30, 0x37, 0x5a, - 0x30, 0x68, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, - 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, - 0x13, 0x0a, 0x43, 0x61, 0x6c, 0x69, 0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, - 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0d, 0x4d, - 0x6f, 0x75, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x20, 0x56, 0x69, 0x65, 0x77, - 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x0a, 0x47, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x20, 0x49, 0x6e, 0x63, 0x31, 0x17, 0x30, - 0x15, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x0e, 0x77, 0x77, 0x77, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x81, - 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, - 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, - 0x81, 0x81, 0x00, 0xd6, 0xb9, 0xe1, 0xad, 0xb8, 0x61, 0x0b, 0x1f, 0x4e, - 0xb6, 0x3c, 0x09, 0x3d, 0xab, 0xe8, 0xe3, 0x2b, 0xb6, 0xe8, 0xa4, 0x3a, - 0x78, 0x2f, 0xd3, 0x51, 0x20, 0x22, 0x45, 0x95, 0xd8, 0x00, 0x91, 0x33, - 0x9a, 0xa7, 0xa2, 0x48, 0xea, 0x30, 0x57, 0x26, 0x97, 0x66, 0xc7, 0x5a, - 0xef, 0xf1, 0x9b, 0x0c, 0x3f, 0xe1, 0xb9, 0x7f, 0x7b, 0xc3, 0xc7, 0xcc, - 0xaf, 0x9c, 0xd0, 0x1f, 0x3c, 0x81, 0x15, 0x10, 0x58, 0xfc, 0x06, 0xb3, - 0xbf, 0xbc, 0x9c, 0x02, 0xb9, 0x51, 0xdc, 0xfb, 0xa6, 0xb9, 0x17, 0x42, - 0xe6, 0x46, 0xe7, 0x22, 0xcf, 0x6c, 0x27, 0x10, 0xfe, 0x54, 0xe6, 0x92, - 0x6c, 0x0c, 0x60, 0x76, 0x9a, 0xce, 0xf8, 0x7f, 0xac, 0xb8, 0x5a, 0x08, - 0x4a, 0xdc, 0xb1, 0x64, 0xbd, 0xa0, 0x74, 0x41, 0xb2, 0xac, 0x8f, 0x86, - 0x9d, 0x1a, 0xde, 0x58, 0x09, 0xfd, 0x6c, 0x0a, 0x25, 0xe0, 0x79, 0x02, - 0x03, 0x01, 0x00, 0x01, 0xa3, 0x81, 0xe7, 0x30, 0x81, 0xe4, 0x30, 0x28, - 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x21, 0x30, 0x1f, 0x06, 0x08, 0x2b, - 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2b, 0x06, 0x01, - 0x05, 0x05, 0x07, 0x03, 0x02, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, - 0xf8, 0x42, 0x04, 0x01, 0x30, 0x36, 0x06, 0x03, 0x55, 0x1d, 0x1f, 0x04, - 0x2f, 0x30, 0x2d, 0x30, 0x2b, 0xa0, 0x29, 0xa0, 0x27, 0x86, 0x25, 0x68, - 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x72, 0x6c, 0x2e, 0x74, 0x68, - 0x61, 0x77, 0x74, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x54, 0x68, 0x61, - 0x77, 0x74, 0x65, 0x53, 0x47, 0x43, 0x43, 0x41, 0x2e, 0x63, 0x72, 0x6c, - 0x30, 0x72, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01, - 0x04, 0x66, 0x30, 0x64, 0x30, 0x22, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, - 0x05, 0x07, 0x30, 0x01, 0x86, 0x16, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, - 0x2f, 0x6f, 0x63, 0x73, 0x70, 0x2e, 0x74, 0x68, 0x61, 0x77, 0x74, 0x65, - 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x3e, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, - 0x05, 0x07, 0x30, 0x02, 0x86, 0x32, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, - 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x74, 0x68, 0x61, 0x77, 0x74, 0x65, 0x2e, - 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, - 0x72, 0x79, 0x2f, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x5f, 0x53, 0x47, - 0x43, 0x5f, 0x43, 0x41, 0x2e, 0x63, 0x72, 0x74, 0x30, 0x0c, 0x06, 0x03, - 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0d, - 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, - 0x00, 0x03, 0x81, 0x81, 0x00, 0x39, 0xb6, 0xfb, 0x11, 0xbc, 0x33, 0x2c, - 0xc3, 0x90, 0x48, 0xe3, 0x6e, 0xc3, 0x9b, 0x38, 0xb1, 0x42, 0xd1, 0x00, - 0x09, 0x58, 0x63, 0xa0, 0xe1, 0x98, 0x1c, 0x85, 0xf2, 0xef, 0x10, 0x1d, - 0x60, 0x4e, 0x51, 0x09, 0x62, 0xf5, 0x05, 0xbd, 0x9d, 0x4f, 0x87, 0x6c, - 0x98, 0x72, 0x07, 0x80, 0xc3, 0x59, 0x48, 0x14, 0xe2, 0xd6, 0xef, 0xd0, - 0x8f, 0x33, 0x6a, 0x68, 0x31, 0xfa, 0xb7, 0xbb, 0x85, 0xcc, 0xf7, 0xc7, - 0x47, 0x7b, 0x67, 0x93, 0x3c, 0xc3, 0x16, 0x51, 0x9b, 0x6f, 0x87, 0x20, - 0xfd, 0x67, 0x4c, 0x2b, 0xea, 0x6a, 0x49, 0xdb, 0x11, 0xd1, 0xbd, 0xd7, - 0x95, 0x22, 0x43, 0x7a, 0x06, 0x7b, 0x4e, 0xf6, 0x37, 0x8e, 0xa2, 0xb9, - 0xcf, 0x1f, 0xa5, 0xd2, 0xbd, 0x3b, 0x04, 0x97, 0x39, 0xb3, 0x0f, 0xfa, - 0x38, 0xb5, 0xaf, 0x55, 0x20, 0x88, 0x60, 0x93, 0xf2, 0xde, 0xdb, 0xff, - 0xdf -}; - -} // namespace - -TestX509CertificatePrivate::TestX509CertificatePrivate( - TestingInstance* instance) - : TestCase(instance) { -} - -bool TestX509CertificatePrivate::Init() { - if (!pp::X509CertificatePrivate::IsAvailable()) - return false; - - return true; -} - -void TestX509CertificatePrivate::RunTests(const std::string& filter) { - RUN_TEST_FORCEASYNC_AND_NOT(ValidCertificate, filter); - RUN_TEST_FORCEASYNC_AND_NOT(InvalidCertificate, filter); -} - -std::string TestX509CertificatePrivate::TestValidCertificate() { - pp::X509CertificatePrivate certificate(instance_); - bool successful = certificate.Initialize( - reinterpret_cast<const char*>(kGoogleDer), sizeof(kGoogleDer)); - ASSERT_TRUE(successful); - - ASSERT_TRUE(FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_COMMON_NAME, "www.google.com")); - ASSERT_TRUE(FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_LOCALITY_NAME, "Mountain View")); - ASSERT_TRUE(FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_STATE_OR_PROVINCE_NAME, "California")); - ASSERT_TRUE(FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_COUNTRY_NAME, "US")); - ASSERT_TRUE(FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_ORGANIZATION_NAME, "Google Inc")); - ASSERT_TRUE(FieldMatchesString( - certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_ORGANIZATION_UNIT_NAME, - std::string())); - - ASSERT_TRUE(FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_ISSUER_COMMON_NAME, "Thawte SGC CA")); - ASSERT_TRUE( - FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_ISSUER_LOCALITY_NAME, - std::string())); - ASSERT_TRUE(FieldMatchesString( - certificate, - PP_X509CERTIFICATE_PRIVATE_ISSUER_STATE_OR_PROVINCE_NAME, - std::string())); - ASSERT_TRUE(FieldMatchesString( - certificate, PP_X509CERTIFICATE_PRIVATE_ISSUER_COUNTRY_NAME, "ZA")); - ASSERT_TRUE(FieldMatchesString(certificate, - PP_X509CERTIFICATE_PRIVATE_ISSUER_ORGANIZATION_NAME, - "Thawte Consulting (Pty) Ltd.")); - ASSERT_TRUE(FieldMatchesString( - certificate, - PP_X509CERTIFICATE_PRIVATE_ISSUER_ORGANIZATION_UNIT_NAME, - std::string())); - - ASSERT_FALSE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_SERIAL_NUMBER)); - ASSERT_TRUE(FieldMatchesDouble(certificate, - PP_X509CERTIFICATE_PRIVATE_VALIDITY_NOT_BEFORE, 1238192407)); - ASSERT_TRUE(FieldMatchesDouble(certificate, - PP_X509CERTIFICATE_PRIVATE_VALIDITY_NOT_AFTER, 1269728407)); - ASSERT_TRUE(FieldMatchesBuffer(certificate, - PP_X509CERTIFICATE_PRIVATE_RAW, - reinterpret_cast<const char*>(kGoogleDer), sizeof(kGoogleDer))); - - // Check unimplemented fields return null. - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_UNIQUE_ID)); - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_ISSUER_UNIQUE_ID)); - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_DISTINGUISHED_NAME)); - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_ISSUER_DISTINGUISHED_NAME)); - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_VERSION)); - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_SIGNATURE_ALGORITHM_OID)); - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_SIGNATURE_ALGORITHM_PARAMATERS_RAW)); - ASSERT_TRUE(FieldIsNull(certificate, - PP_X509CERTIFICATE_PRIVATE_SUBJECT_PUBLIC_KEY)); - - PASS(); -} - -std::string TestX509CertificatePrivate::TestInvalidCertificate() { - bool successful; - pp::X509CertificatePrivate null_certificate(instance_); - successful = null_certificate.Initialize(NULL, 0); - ASSERT_FALSE(successful); - - pp::X509CertificatePrivate bad_certificate(instance_); - successful = bad_certificate.Initialize("acbde", 0); - ASSERT_FALSE(successful); - - PASS(); -}
diff --git a/tests/test_x509_certificate_private.h b/tests/test_x509_certificate_private.h deleted file mode 100644 index 8da7725..0000000 --- a/tests/test_x509_certificate_private.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TEST_X509_CERTIFICATE_PRIVATE_H_ -#define PPAPI_TESTS_TEST_X509_CERTIFICATE_PRIVATE_H_ - -#include <string> - -#include "ppapi/tests/test_case.h" - -class TestX509CertificatePrivate : public TestCase { - public: - explicit TestX509CertificatePrivate(TestingInstance* instance); - - // TestCase implementation. - virtual bool Init(); - virtual void RunTests(const std::string& filter); - - private: - std::string TestValidCertificate(); - std::string TestInvalidCertificate(); -}; - -#endif // PPAPI_TESTS_TEST_X509_CERTIFICATE_PRIVATE_H_
diff --git a/tests/testing_instance.cc b/tests/testing_instance.cc deleted file mode 100644 index 2cf7ffd..0000000 --- a/tests/testing_instance.cc +++ /dev/null
@@ -1,343 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/351564777): Remove this and convert code to safer constructs. -#pragma allow_unsafe_buffers -#endif - -#include "ppapi/tests/testing_instance.h" - -#include <stddef.h> - -#include <algorithm> -#include <cstring> -#include <iomanip> -#include <sstream> -#include <vector> - -#include "ppapi/cpp/core.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/view.h" -#include "ppapi/tests/test_case.h" - -TestCaseFactory* TestCaseFactory::head_ = NULL; - -// Cookie value we use to signal "we're still working." See the comment above -// the class declaration for how this works. -static const char kProgressSignal[] = "..."; - -// Returns a new heap-allocated test case for the given test, or NULL on -// failure. -TestingInstance::TestingInstance(PP_Instance instance) -#if (defined __native_client__) - : pp::Instance(instance), -#else - : pp::InstancePrivate(instance), -#endif - current_case_(NULL), - executed_tests_(false), - number_tests_executed_(0), - nacl_mode_(false), - ssl_server_port_(-1), - websocket_port_(-1), - remove_plugin_(true) { - callback_factory_.Initialize(this); -} - -TestingInstance::~TestingInstance() { - if (current_case_) - delete current_case_; -} - -bool TestingInstance::Init(uint32_t argc, - const char* argn[], - const char* argv[]) { - for (uint32_t i = 0; i < argc; i++) { - if (std::strcmp(argn[i], "mode") == 0) { - if (std::strcmp(argv[i], "nacl") == 0) - nacl_mode_ = true; - } else if (std::strcmp(argn[i], "protocol") == 0) { - protocol_ = argv[i]; - } else if (std::strcmp(argn[i], "websocket_host") == 0) { - websocket_host_ = argv[i]; - } else if (std::strcmp(argn[i], "websocket_port") == 0) { - websocket_port_ = atoi(argv[i]); - } else if (std::strcmp(argn[i], "ssl_server_port") == 0) { - ssl_server_port_ = atoi(argv[i]); - } - } - // Create the proper test case from the argument. - for (uint32_t i = 0; i < argc; i++) { - if (std::strcmp(argn[i], "testcase") == 0) { - if (argv[i][0] == '\0') - break; - current_case_ = CaseForTestName(argv[i]); - test_filter_ = argv[i]; - if (!current_case_) - errors_.append(std::string("Unknown test case ") + argv[i]); - else if (!current_case_->Init()) - errors_.append(" Test case could not initialize."); - return true; - } - } - - // In DidChangeView, we'll dump out a list of all available tests. - return true; -} - -#if !(defined __native_client__) -pp::Var TestingInstance::GetInstanceObject() { - if (current_case_) - return current_case_->GetTestObject(); - - return pp::VarPrivate(); -} -#endif - -void TestingInstance::HandleMessage(const pp::Var& message_data) { - if (current_case_) - current_case_->HandleMessage(message_data); -} - -void TestingInstance::DidChangeView(const pp::View& view) { - if (!executed_tests_) { - executed_tests_ = true; - pp::Module::Get()->core()->CallOnMainThread( - 0, - callback_factory_.NewCallback(&TestingInstance::ExecuteTests)); - } - if (current_case_) - current_case_->DidChangeView(view); -} - -bool TestingInstance::HandleInputEvent(const pp::InputEvent& event) { - if (current_case_) - return current_case_->HandleInputEvent(event); - return false; -} - -void TestingInstance::EvalScript(const std::string& script) { - SendTestCommand("EvalScript", script); -} - -void TestingInstance::SetCookie(const std::string& name, - const std::string& value) { - SendTestCommand("SetCookie", name + "=" + value); -} - -void TestingInstance::LogTest(const std::string& test_name, - const std::string& error_message, - PP_TimeTicks start_time) { - current_test_name_ = test_name; - - // Compute the time to run the test and save it in a string for logging: - PP_TimeTicks end_time(pp::Module::Get()->core()->GetTimeTicks()); - std::ostringstream number_stream; - PP_TimeTicks elapsed_time(end_time - start_time); - number_stream << std::fixed << std::setprecision(3) << elapsed_time; - std::string time_string(number_stream.str()); - - // Tell the browser we're still working. - ReportProgress(kProgressSignal); - - number_tests_executed_++; - - std::string html; - html.append("<div class=\"test_line\"><span class=\"test_name\">"); - html.append(test_name); - html.append("</span> "); - if (error_message.empty()) { - html.append("<span class=\"pass\">PASS</span>"); - } else { - html.append("<span class=\"fail\">FAIL</span>: <span class=\"err_msg\">"); - html.append(error_message); - html.append("</span>"); - - if (!errors_.empty()) - errors_.append(", "); // Separator for different error messages. - errors_.append(test_name + " FAIL: " + error_message); - } - html.append(" <span class=\"time\">("); - html.append(time_string); - html.append("s)</span>"); - - html.append("</div>"); - LogHTML(html); - - std::string test_time; - test_time.append(test_name); - test_time.append(" finished in "); - test_time.append(time_string); - test_time.append(" seconds."); - LogTestTime(test_time); - - current_test_name_.clear(); -} - -void TestingInstance::AppendError(const std::string& message) { - if (!errors_.empty()) - errors_.append(", "); - errors_.append(message); -} - -void TestingInstance::ExecuteTests(int32_t unused) { - ReportProgress(kProgressSignal); - - // Clear the console. - SendTestCommand("ClearConsole"); - - if (!errors_.empty()) { - // Catch initialization errors and output the current error string to - // the console. - LogError("Plugin initialization failed: " + errors_); - } else if (!current_case_) { - LogAvailableTests(); - errors_.append("FAIL: Only listed tests"); - } else { - current_case_->RunTests(test_filter_); - - if (number_tests_executed_ == 0) { - errors_.append("No tests executed. The test filter might be too " - "restrictive: '" + test_filter_ + "'."); - LogError(errors_); - } - if (current_case_->skipped_tests().size()) { - // TODO(dmichael): Convert all TestCases to run all tests in one fixture, - // and enable this check. Currently, a lot of our tests - // run 1 test per fixture, which is slow. - /* - errors_.append("Some tests were not listed and thus were not run. Make " - "sure all tests are passed in the test_case URL (even if " - "they are marked DISABLED_). Forgotten tests: "); - std::set<std::string>::const_iterator iter = - current_case_->skipped_tests().begin(); - for (; iter != current_case_->skipped_tests().end(); ++iter) { - errors_.append(*iter); - errors_.append(" "); - } - LogError(errors_); - */ - } - if (current_case_->remaining_tests().size()) { - errors_.append("Some listed tests were not found in the TestCase. Check " - "the test names that were passed to make sure they match " - "tests in the TestCase. Unknown tests: "); - std::map<std::string, bool>::const_iterator iter = - current_case_->remaining_tests().begin(); - for (; iter != current_case_->remaining_tests().end(); ++iter) { - errors_.append(iter->first); - errors_.append(" "); - } - LogError(errors_); - } - } - - if (remove_plugin_) - SendTestCommand("RemovePluginWhenFinished"); - std::string result(errors_); - if (result.empty()) - result = "PASS"; - SendTestCommand("DidExecuteTests", result); - // Note, DidExecuteTests may unload the plugin. We can't really do anything - // after this point. -} - -TestCase* TestingInstance::CaseForTestName(const std::string& name) { - std::string case_name = name.substr(0, name.find_first_of('_')); - TestCaseFactory* iter = TestCaseFactory::head_; - while (iter != NULL) { - if (case_name == iter->name_) - return iter->method_(this); - iter = iter->next_; - } - return NULL; -} - -void TestingInstance::SendTestCommand(const std::string& command) { - std::string msg("TESTING_MESSAGE:"); - msg += command; - PostMessage(pp::Var(msg)); -} - -void TestingInstance::SendTestCommand(const std::string& command, - const std::string& params) { - SendTestCommand(command + ":" + params); -} - - -void TestingInstance::LogAvailableTests() { - // Print out a listing of all tests. - std::vector<std::string> test_cases; - TestCaseFactory* iter = TestCaseFactory::head_; - while (iter != NULL) { - test_cases.push_back(iter->name_); - iter = iter->next_; - } - std::sort(test_cases.begin(), test_cases.end()); - - std::string html; - html.append("Available test cases: <dl>"); - for (size_t i = 0; i < test_cases.size(); ++i) { - html.append("<dd><a href='?testcase="); - html.append(test_cases[i]); - if (nacl_mode_) - html.append("&mode=nacl"); - html.append("'>"); - html.append(test_cases[i]); - html.append("</a></dd>"); - } - html.append("</dl>"); - html.append("<button onclick='RunAll()'>Run All Tests</button>"); - - LogHTML(html); -} - -void TestingInstance::LogError(const std::string& text) { - std::string html; - html.append("<span class=\"fail\">FAIL</span>: <span class=\"err_msg\">"); - html.append(text); - html.append("</span>"); - LogHTML(html); -} - -void TestingInstance::LogHTML(const std::string& html) { - SendTestCommand("LogHTML", html); -} - -void TestingInstance::ReportProgress(const std::string& progress_value) { - SendTestCommand("ReportProgress", progress_value); -} - -void TestingInstance::AddPostCondition(const std::string& script) { - SendTestCommand("AddPostCondition", script); -} - -void TestingInstance::LogTestTime(const std::string& test_time) { - SendTestCommand("LogTestTime", test_time); -} - -class Module : public pp::Module { - public: - Module() : pp::Module() {} - virtual ~Module() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new TestingInstance(instance); - } -}; - -namespace pp { - -#if defined(WIN32) -__declspec(dllexport) -#else -__attribute__((visibility("default"))) -#endif -Module* CreateModule() { - return new ::Module(); -} - -} // namespace pp
diff --git a/tests/testing_instance.h b/tests/testing_instance.h deleted file mode 100644 index cce511e..0000000 --- a/tests/testing_instance.h +++ /dev/null
@@ -1,193 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_TESTS_TESTING_INSTANCE_H_ -#define PPAPI_TESTS_TESTING_INSTANCE_H_ - -#include <stdint.h> - -#include <string> - -#include "ppapi/utility/completion_callback_factory.h" - -#if defined(__native_client__) -#include "ppapi/cpp/instance.h" -#else -#include "ppapi/cpp/private/instance_private.h" -#endif - -// Windows defines 'PostMessage', so we have to undef it. -#ifdef PostMessage -#undef PostMessage -#endif - -class TestCase; - -// How signaling works: -// -// We want to signal to the Chrome browser test harness -// (chrome/test/ppapi/ppapi_browsertest.cc) that we're making progress and when -// we're done. This is done using the DOM controlller. The browser test waits -// for a message from it. We don't want to have a big wait for all tests in a -// TestCase since they can take a while and it might timeout. So we send it -// pings between each test to tell it that we're still running tests and aren't -// stuck. -// -// If the value of the message is "..." then that tells the test runner that -// the test is progressing. It then waits for the next message until it either -// times out or the value is something other than "...". In this case, the value -// will be either "PASS" or "FAIL [optional message]" corresponding to the -// outcome of the entire test case. Timeout will be treated just like a failure -// of the entire test case and the test will be terminated. -// -// In trusted builds, we use InstancePrivate and allow tests that use -// synchronous scripting. NaCl does not support synchronous scripting. -class TestingInstance : public -#if defined(__native_client__) -pp::Instance { -#else -pp::InstancePrivate { -#endif - public: - explicit TestingInstance(PP_Instance instance); - virtual ~TestingInstance(); - - // pp::Instance override. - virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]); - virtual void DidChangeView(const pp::View& view); - virtual bool HandleInputEvent(const pp::InputEvent& event); - -#if !(defined __native_client__) - virtual pp::Var GetInstanceObject(); -#endif - - // Outputs the information from one test run, using the format - // <test_name> [PASS|FAIL <error_message>] - // - // You should generally use one of the RUN_TEST* macros in test_case.h - // instead. - // - // If error_message is empty, we say the test passed and emit PASS. If - // error_message is nonempty, the test failed with that message as the error - // string. - // - // Intended usage: - // PP_TimeTicks start_time(core.GetTimeTicks()); - // LogTest("Foo", FooTest(), start_time); - // - // Where FooTest is defined as: - // std::string FooTest() { - // if (something_horrible_happened) - // return "Something horrible happened"; - // return ""; - // } - // - // NOTE: It's important to get the start time in the previous line, rather - // than calling GetTimeTicks in the LogTestLine. There's no guarantee - // that GetTimeTicks will be evaluated before FooTest(). - void LogTest(const std::string& test_name, - const std::string& error_message, - PP_TimeTicks start_time); - const std::string& current_test_name() { return current_test_name_; } - - // Appends an error message to the log. - void AppendError(const std::string& message); - - // Passes the message_data through to the HandleMessage method on the - // TestClass object that's associated with this instance. - virtual void HandleMessage(const pp::Var& message_data); - - const std::string& protocol() { - return protocol_; - } - - int ssl_server_port() { return ssl_server_port_; } - - const std::string& websocket_host() { return websocket_host_; } - int websocket_port() { return websocket_port_; } - - // Posts a message to the test page to eval() the script. - void EvalScript(const std::string& script); - - // Sets the given cookie in the current document. - void SetCookie(const std::string& name, const std::string& value); - - void ReportProgress(const std::string& progress_value); - - // Logs the amount of time that a given test took to run. This is to help - // debug test timeouts that occur in automated testing. - void LogTestTime(const std::string& test_time); - - // Add a post-condition to the JavaScript on the test_case.html page. This - // JavaScript code will be run after the instance is shut down and must - // evaluate to |true| or the test will fail. - void AddPostCondition(const std::string& script); - - // See doc for |remove_plugin_|. - void set_remove_plugin(bool remove) { remove_plugin_ = remove; } - - private: - void ExecuteTests(int32_t unused); - - // Creates a new TestCase for the give test name, or NULL if there is no such - // test. Ownership is passed to the caller. The given string is split by '_'. - // The test case name is the first part. - TestCase* CaseForTestName(const std::string& name); - - // Sends a test command to the page using PostMessage. - void SendTestCommand(const std::string& command); - void SendTestCommand(const std::string& command, const std::string& params); - - // Appends a list of available tests to the console in the document. - void LogAvailableTests(); - - // Appends the given error test to the console in the document. - void LogError(const std::string& text); - - // Appends the given HTML string to the console in the document. - void LogHTML(const std::string& html); - - pp::CompletionCallbackFactory<TestingInstance> callback_factory_; - - // Owning pointer to the current test case. Valid after Init has been called. - TestCase* current_case_; - - std::string current_test_name_; - - // A filter to use when running tests. This is passed to 'RunTests', which - // runs only tests whose name contains test_filter_ as a substring. - std::string test_filter_; - - // Set once the tests are run so we know not to re-run when the view is sized. - bool executed_tests_; - - // The number of tests executed so far. - int32_t number_tests_executed_; - - // Collects all errors to send the the browser. Empty indicates no error yet. - std::string errors_; - - // True if running in Native Client. - bool nacl_mode_; - - // String representing the protocol. Used for detecting whether we're running - // with http. - std::string protocol_; - - // SSL server port. - int ssl_server_port_; - - // WebSocket host. - std::string websocket_host_; - - // WebSocket port. - int websocket_port_; - - // At the end of each set of tests, the plugin is removed from the web-page. - // However, for some tests, it is desirable to not remove the plguin from the - // page. - bool remove_plugin_; -}; - -#endif // PPAPI_TESTS_TESTING_INSTANCE_H_