chrome.bluetoothSocket: clean-up Listen functions
[chromium-blink-merge.git] / content / renderer / pepper / v8_var_converter_unittest.cc
blob95d5843a29c23746bed13829e0f020fb6a5b652d
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/pepper/v8_var_converter.h"
7 #include <cmath>
9 #include "base/logging.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/run_loop.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "base/values.h"
16 #include "content/renderer/pepper/resource_converter.h"
17 #include "ppapi/c/pp_bool.h"
18 #include "ppapi/c/pp_var.h"
19 #include "ppapi/shared_impl/array_var.h"
20 #include "ppapi/shared_impl/dictionary_var.h"
21 #include "ppapi/shared_impl/ppapi_globals.h"
22 #include "ppapi/shared_impl/proxy_lock.h"
23 #include "ppapi/shared_impl/scoped_pp_var.h"
24 #include "ppapi/shared_impl/test_globals.h"
25 #include "ppapi/shared_impl/unittest_utils.h"
26 #include "ppapi/shared_impl/var.h"
27 #include "ppapi/shared_impl/var_tracker.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29 #include "v8/include/v8.h"
31 using ppapi::ArrayBufferVar;
32 using ppapi::ArrayVar;
33 using ppapi::DictionaryVar;
34 using ppapi::PpapiGlobals;
35 using ppapi::ProxyLock;
36 using ppapi::ScopedPPVar;
37 using ppapi::StringVar;
38 using ppapi::TestGlobals;
39 using ppapi::TestEqual;
40 using ppapi::VarTracker;
42 namespace content {
44 namespace {
46 class MockResourceConverter : public content::ResourceConverter {
47 public:
48 virtual ~MockResourceConverter() {}
49 virtual void Flush(const base::Callback<void(bool)>& callback) OVERRIDE {
50 callback.Run(true);
52 virtual bool FromV8Value(v8::Handle<v8::Object> val,
53 v8::Handle<v8::Context> context,
54 PP_Var* result,
55 bool* was_resource) OVERRIDE {
56 *was_resource = false;
57 return true;
59 virtual bool ToV8Value(const PP_Var& var,
60 v8::Handle<v8::Context> context,
61 v8::Handle<v8::Value>* result) OVERRIDE {
62 return false;
66 // Maps PP_Var IDs to the V8 value handle they correspond to.
67 typedef base::hash_map<int64_t, v8::Handle<v8::Value> > VarHandleMap;
69 bool Equals(const PP_Var& var,
70 v8::Handle<v8::Value> val,
71 VarHandleMap* visited_ids) {
72 if (ppapi::VarTracker::IsVarTypeRefcounted(var.type)) {
73 VarHandleMap::iterator it = visited_ids->find(var.value.as_id);
74 if (it != visited_ids->end())
75 return it->second == val;
76 (*visited_ids)[var.value.as_id] = val;
79 if (val->IsUndefined()) {
80 return var.type == PP_VARTYPE_UNDEFINED;
81 } else if (val->IsNull()) {
82 return var.type == PP_VARTYPE_NULL;
83 } else if (val->IsBoolean() || val->IsBooleanObject()) {
84 return var.type == PP_VARTYPE_BOOL &&
85 PP_FromBool(val->ToBoolean()->Value()) == var.value.as_bool;
86 } else if (val->IsInt32()) {
87 return var.type == PP_VARTYPE_INT32 &&
88 val->ToInt32()->Value() == var.value.as_int;
89 } else if (val->IsNumber() || val->IsNumberObject()) {
90 return var.type == PP_VARTYPE_DOUBLE &&
91 fabs(val->ToNumber()->Value() - var.value.as_double) <= 1.0e-4;
92 } else if (val->IsString() || val->IsStringObject()) {
93 if (var.type != PP_VARTYPE_STRING)
94 return false;
95 StringVar* string_var = StringVar::FromPPVar(var);
96 DCHECK(string_var);
97 v8::String::Utf8Value utf8(val->ToString());
98 return std::string(*utf8, utf8.length()) == string_var->value();
99 } else if (val->IsArray()) {
100 if (var.type != PP_VARTYPE_ARRAY)
101 return false;
102 ArrayVar* array_var = ArrayVar::FromPPVar(var);
103 DCHECK(array_var);
104 v8::Handle<v8::Array> v8_array = val.As<v8::Array>();
105 if (v8_array->Length() != array_var->elements().size())
106 return false;
107 for (uint32 i = 0; i < v8_array->Length(); ++i) {
108 v8::Handle<v8::Value> child_v8 = v8_array->Get(i);
109 if (!Equals(array_var->elements()[i].get(), child_v8, visited_ids))
110 return false;
112 return true;
113 } else if (val->IsObject()) {
114 if (var.type == PP_VARTYPE_ARRAY_BUFFER) {
115 // TODO(raymes): Implement this when we have tests for array buffers.
116 NOTIMPLEMENTED();
117 return false;
118 } else {
119 v8::Handle<v8::Object> v8_object = val->ToObject();
120 if (var.type != PP_VARTYPE_DICTIONARY)
121 return false;
122 DictionaryVar* dict_var = DictionaryVar::FromPPVar(var);
123 DCHECK(dict_var);
124 v8::Handle<v8::Array> property_names(v8_object->GetOwnPropertyNames());
125 if (property_names->Length() != dict_var->key_value_map().size())
126 return false;
127 for (uint32 i = 0; i < property_names->Length(); ++i) {
128 v8::Handle<v8::Value> key(property_names->Get(i));
130 if (!key->IsString() && !key->IsNumber())
131 return false;
132 v8::Handle<v8::Value> child_v8 = v8_object->Get(key);
134 v8::String::Utf8Value name_utf8(key->ToString());
135 ScopedPPVar release_key(ScopedPPVar::PassRef(),
136 StringVar::StringToPPVar(std::string(
137 *name_utf8, name_utf8.length())));
138 if (!dict_var->HasKey(release_key.get()))
139 return false;
140 ScopedPPVar release_value(ScopedPPVar::PassRef(),
141 dict_var->Get(release_key.get()));
142 if (!Equals(release_value.get(), child_v8, visited_ids))
143 return false;
145 return true;
148 return false;
151 bool Equals(const PP_Var& var, v8::Handle<v8::Value> val) {
152 VarHandleMap var_handle_map;
153 return Equals(var, val, &var_handle_map);
156 class V8VarConverterTest : public testing::Test {
157 public:
158 V8VarConverterTest()
159 : isolate_(v8::Isolate::GetCurrent()), conversion_success_(false) {
160 PP_Instance dummy = 1234;
161 converter_.reset(new V8VarConverter(
162 dummy,
163 scoped_ptr<ResourceConverter>(new MockResourceConverter).Pass()));
165 virtual ~V8VarConverterTest() {}
167 // testing::Test implementation.
168 virtual void SetUp() {
169 ProxyLock::Acquire();
170 v8::HandleScope handle_scope(isolate_);
171 v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate_);
172 context_.Reset(isolate_, v8::Context::New(isolate_, NULL, global));
174 virtual void TearDown() {
175 context_.Reset();
176 ASSERT_TRUE(PpapiGlobals::Get()->GetVarTracker()->GetLiveVars().empty());
177 ProxyLock::Release();
180 protected:
181 bool FromV8ValueSync(v8::Handle<v8::Value> val,
182 v8::Handle<v8::Context> context,
183 PP_Var* result) {
184 base::RunLoop loop;
185 converter_->FromV8Value(val,
186 context,
187 base::Bind(&V8VarConverterTest::FromV8ValueComplete,
188 base::Unretained(this),
189 loop.QuitClosure()));
190 loop.Run();
191 if (conversion_success_)
192 *result = conversion_result_;
193 return conversion_success_;
196 void FromV8ValueComplete(base::Closure quit_closure,
197 const ScopedPPVar& scoped_var,
198 bool success) {
199 conversion_success_ = success;
200 if (success) {
201 ScopedPPVar var = scoped_var;
202 conversion_result_ = var.Release();
204 quit_closure.Run();
207 bool RoundTrip(const PP_Var& var, PP_Var* result) {
208 v8::HandleScope handle_scope(isolate_);
209 v8::Local<v8::Context> context =
210 v8::Local<v8::Context>::New(isolate_, context_);
211 v8::Context::Scope context_scope(context);
212 v8::Handle<v8::Value> v8_result;
213 if (!converter_->ToV8Value(var, context, &v8_result))
214 return false;
215 if (!Equals(var, v8_result))
216 return false;
217 if (!FromV8ValueSync(v8_result, context, result))
218 return false;
219 return true;
222 // Assumes a ref for var.
223 bool RoundTripAndCompare(const PP_Var& var) {
224 ScopedPPVar expected(ScopedPPVar::PassRef(), var);
225 PP_Var actual_var;
226 if (!RoundTrip(expected.get(), &actual_var))
227 return false;
228 ScopedPPVar actual(ScopedPPVar::PassRef(), actual_var);
229 return TestEqual(expected.get(), actual.get(), false);
232 v8::Isolate* isolate_;
234 // Context for the JavaScript in the test.
235 v8::Persistent<v8::Context> context_;
237 scoped_ptr<V8VarConverter> converter_;
239 private:
240 TestGlobals globals_;
242 PP_Var conversion_result_;
243 bool conversion_success_;
244 base::MessageLoop message_loop_;
247 } // namespace
249 TEST_F(V8VarConverterTest, SimpleRoundTripTest) {
250 EXPECT_TRUE(RoundTripAndCompare(PP_MakeUndefined()));
251 EXPECT_TRUE(RoundTripAndCompare(PP_MakeNull()));
252 EXPECT_TRUE(RoundTripAndCompare(PP_MakeInt32(100)));
253 EXPECT_TRUE(RoundTripAndCompare(PP_MakeBool(PP_TRUE)));
254 EXPECT_TRUE(RoundTripAndCompare(PP_MakeDouble(53.75)));
257 TEST_F(V8VarConverterTest, StringRoundTripTest) {
258 EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("")));
259 EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("hello world!")));
262 TEST_F(V8VarConverterTest, ArrayBufferRoundTripTest) {
263 // TODO(raymes): Testing this here requires spinning up some of WebKit.
264 // Work out how to do this.
267 TEST_F(V8VarConverterTest, DictionaryArrayRoundTripTest) {
268 // Empty array.
269 scoped_refptr<ArrayVar> array(new ArrayVar);
270 ScopedPPVar release_array(ScopedPPVar::PassRef(), array->GetPPVar());
271 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
273 size_t index = 0;
275 // Array with primitives.
276 array->Set(index++, PP_MakeUndefined());
277 array->Set(index++, PP_MakeNull());
278 array->Set(index++, PP_MakeInt32(100));
279 array->Set(index++, PP_MakeBool(PP_FALSE));
280 array->Set(index++, PP_MakeDouble(0.123));
281 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
283 // Array with 2 references to the same string.
284 ScopedPPVar release_string(ScopedPPVar::PassRef(),
285 StringVar::StringToPPVar("abc"));
286 array->Set(index++, release_string.get());
287 array->Set(index++, release_string.get());
288 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
290 // Array with nested array that references the same string.
291 scoped_refptr<ArrayVar> array2(new ArrayVar);
292 ScopedPPVar release_array2(ScopedPPVar::PassRef(), array2->GetPPVar());
293 array2->Set(0, release_string.get());
294 array->Set(index++, release_array2.get());
295 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
297 // Empty dictionary.
298 scoped_refptr<DictionaryVar> dictionary(new DictionaryVar);
299 ScopedPPVar release_dictionary(ScopedPPVar::PassRef(),
300 dictionary->GetPPVar());
301 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
303 // Dictionary with primitives.
304 dictionary->SetWithStringKey("1", PP_MakeUndefined());
305 dictionary->SetWithStringKey("2", PP_MakeNull());
306 dictionary->SetWithStringKey("3", PP_MakeInt32(-100));
307 dictionary->SetWithStringKey("4", PP_MakeBool(PP_TRUE));
308 dictionary->SetWithStringKey("5", PP_MakeDouble(-103.52));
309 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
311 // Dictionary with 2 references to the same string.
312 dictionary->SetWithStringKey("6", release_string.get());
313 dictionary->SetWithStringKey("7", release_string.get());
314 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
316 // Dictionary with nested dictionary that references the same string.
317 scoped_refptr<DictionaryVar> dictionary2(new DictionaryVar);
318 ScopedPPVar release_dictionary2(ScopedPPVar::PassRef(),
319 dictionary2->GetPPVar());
320 dictionary2->SetWithStringKey("abc", release_string.get());
321 dictionary->SetWithStringKey("8", release_dictionary2.get());
322 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
324 // Array with dictionary.
325 array->Set(index++, release_dictionary.get());
326 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
328 // Array with dictionary with array.
329 array2->Set(0, PP_MakeInt32(100));
330 dictionary->SetWithStringKey("9", release_array2.get());
331 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
334 TEST_F(V8VarConverterTest, Cycles) {
335 // Check that cycles aren't converted.
336 v8::HandleScope handle_scope(isolate_);
337 v8::Local<v8::Context> context =
338 v8::Local<v8::Context>::New(isolate_, context_);
339 v8::Context::Scope context_scope(context);
341 // Var->V8 conversion.
343 scoped_refptr<DictionaryVar> dictionary(new DictionaryVar);
344 ScopedPPVar release_dictionary(ScopedPPVar::PassRef(),
345 dictionary->GetPPVar());
346 scoped_refptr<ArrayVar> array(new ArrayVar);
347 ScopedPPVar release_array(ScopedPPVar::PassRef(), array->GetPPVar());
349 dictionary->SetWithStringKey("1", release_array.get());
350 array->Set(0, release_dictionary.get());
352 v8::Handle<v8::Value> v8_result;
354 // Array <-> dictionary cycle.
355 dictionary->SetWithStringKey("1", release_array.get());
356 ASSERT_FALSE(
357 converter_->ToV8Value(release_dictionary.get(), context, &v8_result));
358 // Break the cycle.
359 // TODO(raymes): We need some better machinery for releasing vars with
360 // cycles. Remove the code below once we have that.
361 dictionary->DeleteWithStringKey("1");
363 // Array with self reference.
364 array->Set(0, release_array.get());
365 ASSERT_FALSE(
366 converter_->ToV8Value(release_array.get(), context, &v8_result));
367 // Break the self reference.
368 array->Set(0, PP_MakeUndefined());
371 // V8->Var conversion.
373 v8::Handle<v8::Object> object = v8::Object::New(isolate_);
374 v8::Handle<v8::Array> array = v8::Array::New(isolate_);
376 PP_Var var_result;
378 // Array <-> dictionary cycle.
379 std::string key = "1";
380 object->Set(
381 v8::String::NewFromUtf8(
382 isolate_, key.c_str(), v8::String::kNormalString, key.length()),
383 array);
384 array->Set(0, object);
386 ASSERT_FALSE(FromV8ValueSync(object, context, &var_result));
388 // Array with self reference.
389 array->Set(0, array);
390 ASSERT_FALSE(FromV8ValueSync(array, context, &var_result));
394 TEST_F(V8VarConverterTest, StrangeDictionaryKeyTest) {
396 // Test keys with '.'.
397 scoped_refptr<DictionaryVar> dictionary(new DictionaryVar);
398 dictionary->SetWithStringKey(".", PP_MakeUndefined());
399 dictionary->SetWithStringKey("x.y", PP_MakeUndefined());
400 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
404 // Test non-string key types. They should be cast to strings.
405 v8::HandleScope handle_scope(isolate_);
406 v8::Local<v8::Context> context =
407 v8::Local<v8::Context>::New(isolate_, context_);
408 v8::Context::Scope context_scope(context);
410 const char* source =
411 "(function() {"
412 "return {"
413 "1: 'foo',"
414 "'2': 'bar',"
415 "true: 'baz',"
416 "false: 'qux',"
417 "null: 'quux',"
418 "undefined: 'oops'"
419 "};"
420 "})();";
422 v8::Handle<v8::Script> script(
423 v8::Script::Compile(v8::String::NewFromUtf8(isolate_, source)));
424 v8::Handle<v8::Object> object = script->Run().As<v8::Object>();
425 ASSERT_FALSE(object.IsEmpty());
427 PP_Var actual;
428 ASSERT_TRUE(FromV8ValueSync(
429 object, v8::Local<v8::Context>::New(isolate_, context_), &actual));
430 ScopedPPVar release_actual(ScopedPPVar::PassRef(), actual);
432 scoped_refptr<DictionaryVar> expected(new DictionaryVar);
433 ScopedPPVar foo(ScopedPPVar::PassRef(), StringVar::StringToPPVar("foo"));
434 expected->SetWithStringKey("1", foo.get());
435 ScopedPPVar bar(ScopedPPVar::PassRef(), StringVar::StringToPPVar("bar"));
436 expected->SetWithStringKey("2", bar.get());
437 ScopedPPVar baz(ScopedPPVar::PassRef(), StringVar::StringToPPVar("baz"));
438 expected->SetWithStringKey("true", baz.get());
439 ScopedPPVar qux(ScopedPPVar::PassRef(), StringVar::StringToPPVar("qux"));
440 expected->SetWithStringKey("false", qux.get());
441 ScopedPPVar quux(ScopedPPVar::PassRef(), StringVar::StringToPPVar("quux"));
442 expected->SetWithStringKey("null", quux.get());
443 ScopedPPVar oops(ScopedPPVar::PassRef(), StringVar::StringToPPVar("oops"));
444 expected->SetWithStringKey("undefined", oops.get());
445 ScopedPPVar release_expected(ScopedPPVar::PassRef(), expected->GetPPVar());
447 ASSERT_TRUE(TestEqual(release_expected.get(), release_actual.get(), true));
451 } // namespace content