Add ICU message format support
[chromium-blink-merge.git] / content / renderer / pepper / v8_var_converter_unittest.cc
blob6742060ae6bd2556bc3d98f17f44576e96a625c3
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/test_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 void FromV8ValueComplete(const ScopedPPVar& scoped_var,
47 bool success) {
48 NOTREACHED();
51 class MockResourceConverter : public content::ResourceConverter {
52 public:
53 ~MockResourceConverter() override {}
54 void Reset() override {}
55 bool NeedsFlush() override { return false; }
56 void Flush(const base::Callback<void(bool)>& callback) override {
57 NOTREACHED();
59 bool FromV8Value(v8::Local<v8::Object> val,
60 v8::Local<v8::Context> context,
61 PP_Var* result,
62 bool* was_resource) override {
63 *was_resource = false;
64 return true;
66 bool ToV8Value(const PP_Var& var,
67 v8::Local<v8::Context> context,
68 v8::Local<v8::Value>* result) override {
69 return false;
73 // Maps PP_Var IDs to the V8 value handle they correspond to.
74 typedef base::hash_map<int64_t, v8::Local<v8::Value> > VarHandleMap;
76 bool Equals(const PP_Var& var,
77 v8::Local<v8::Value> val,
78 VarHandleMap* visited_ids) {
79 if (ppapi::VarTracker::IsVarTypeRefcounted(var.type)) {
80 VarHandleMap::iterator it = visited_ids->find(var.value.as_id);
81 if (it != visited_ids->end())
82 return it->second == val;
83 (*visited_ids)[var.value.as_id] = val;
86 v8::Isolate* isolate = v8::Isolate::GetCurrent();
87 if (val->IsUndefined()) {
88 return var.type == PP_VARTYPE_UNDEFINED;
89 } else if (val->IsNull()) {
90 return var.type == PP_VARTYPE_NULL;
91 } else if (val->IsBoolean() || val->IsBooleanObject()) {
92 return var.type == PP_VARTYPE_BOOL &&
93 PP_FromBool(val->ToBoolean(isolate)->Value()) == var.value.as_bool;
94 } else if (val->IsInt32()) {
95 return var.type == PP_VARTYPE_INT32 &&
96 val->ToInt32(isolate)->Value() == var.value.as_int;
97 } else if (val->IsNumber() || val->IsNumberObject()) {
98 return var.type == PP_VARTYPE_DOUBLE &&
99 fabs(val->ToNumber(isolate)->Value() - var.value.as_double) <=
100 1.0e-4;
101 } else if (val->IsString() || val->IsStringObject()) {
102 if (var.type != PP_VARTYPE_STRING)
103 return false;
104 StringVar* string_var = StringVar::FromPPVar(var);
105 DCHECK(string_var);
106 v8::String::Utf8Value utf8(val);
107 return std::string(*utf8, utf8.length()) == string_var->value();
108 } else if (val->IsArray()) {
109 if (var.type != PP_VARTYPE_ARRAY)
110 return false;
111 ArrayVar* array_var = ArrayVar::FromPPVar(var);
112 DCHECK(array_var);
113 v8::Local<v8::Array> v8_array = val.As<v8::Array>();
114 if (v8_array->Length() != array_var->elements().size())
115 return false;
116 for (uint32 i = 0; i < v8_array->Length(); ++i) {
117 v8::Local<v8::Value> child_v8 = v8_array->Get(i);
118 if (!Equals(array_var->elements()[i].get(), child_v8, visited_ids))
119 return false;
121 return true;
122 } else if (val->IsObject()) {
123 if (var.type == PP_VARTYPE_ARRAY_BUFFER) {
124 // TODO(raymes): Implement this when we have tests for array buffers.
125 NOTIMPLEMENTED();
126 return false;
127 } else {
128 v8::Local<v8::Object> v8_object = val.As<v8::Object>();
129 if (var.type != PP_VARTYPE_DICTIONARY)
130 return false;
131 DictionaryVar* dict_var = DictionaryVar::FromPPVar(var);
132 DCHECK(dict_var);
133 v8::Local<v8::Array> property_names(v8_object->GetOwnPropertyNames());
134 if (property_names->Length() != dict_var->key_value_map().size())
135 return false;
136 for (uint32 i = 0; i < property_names->Length(); ++i) {
137 v8::Local<v8::Value> key(property_names->Get(i));
139 if (!key->IsString() && !key->IsNumber())
140 return false;
141 v8::Local<v8::Value> child_v8 = v8_object->Get(key);
143 v8::String::Utf8Value name_utf8(key);
144 ScopedPPVar release_key(ScopedPPVar::PassRef(),
145 StringVar::StringToPPVar(std::string(
146 *name_utf8, name_utf8.length())));
147 if (!dict_var->HasKey(release_key.get()))
148 return false;
149 ScopedPPVar release_value(ScopedPPVar::PassRef(),
150 dict_var->Get(release_key.get()));
151 if (!Equals(release_value.get(), child_v8, visited_ids))
152 return false;
154 return true;
157 return false;
160 bool Equals(const PP_Var& var, v8::Local<v8::Value> val) {
161 VarHandleMap var_handle_map;
162 return Equals(var, val, &var_handle_map);
165 class V8VarConverterTest : public testing::Test {
166 public:
167 V8VarConverterTest()
168 : isolate_(v8::Isolate::GetCurrent()) {
169 PP_Instance dummy = 1234;
170 converter_.reset(new V8VarConverter(
171 dummy,
172 scoped_ptr<ResourceConverter>(new MockResourceConverter).Pass()));
174 ~V8VarConverterTest() override {}
176 // testing::Test implementation.
177 void SetUp() override {
178 ProxyLock::Acquire();
179 v8::HandleScope handle_scope(isolate_);
180 v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate_);
181 context_.Reset(isolate_, v8::Context::New(isolate_, NULL, global));
183 void TearDown() override {
184 context_.Reset();
185 ASSERT_TRUE(PpapiGlobals::Get()->GetVarTracker()->GetLiveVars().empty());
186 ProxyLock::Release();
189 protected:
190 bool FromV8ValueSync(v8::Local<v8::Value> val,
191 v8::Local<v8::Context> context,
192 PP_Var* result) {
193 V8VarConverter::VarResult conversion_result =
194 converter_->FromV8Value(val,
195 context,
196 base::Bind(&FromV8ValueComplete));
197 DCHECK(conversion_result.completed_synchronously);
198 if (conversion_result.success)
199 *result = conversion_result.var.Release();
201 return conversion_result.success;
204 bool RoundTrip(const PP_Var& var, PP_Var* result) {
205 v8::HandleScope handle_scope(isolate_);
206 v8::Local<v8::Context> context =
207 v8::Local<v8::Context>::New(isolate_, context_);
208 v8::Context::Scope context_scope(context);
209 v8::Local<v8::Value> v8_result;
210 if (!converter_->ToV8Value(var, context, &v8_result))
211 return false;
212 if (!Equals(var, v8_result))
213 return false;
214 if (!FromV8ValueSync(v8_result, context, result))
215 return false;
216 return true;
219 // Assumes a ref for var.
220 bool RoundTripAndCompare(const PP_Var& var) {
221 ScopedPPVar expected(ScopedPPVar::PassRef(), var);
222 PP_Var actual_var;
223 if (!RoundTrip(expected.get(), &actual_var))
224 return false;
225 ScopedPPVar actual(ScopedPPVar::PassRef(), actual_var);
226 return TestEqual(expected.get(), actual.get(), false);
229 v8::Isolate* isolate_;
231 // Context for the JavaScript in the test.
232 v8::Persistent<v8::Context> context_;
234 scoped_ptr<V8VarConverter> converter_;
236 private:
237 base::MessageLoop message_loop_; // Required to receive callbacks.
239 TestGlobals globals_;
242 } // namespace
244 TEST_F(V8VarConverterTest, SimpleRoundTripTest) {
245 EXPECT_TRUE(RoundTripAndCompare(PP_MakeUndefined()));
246 EXPECT_TRUE(RoundTripAndCompare(PP_MakeNull()));
247 EXPECT_TRUE(RoundTripAndCompare(PP_MakeInt32(100)));
248 EXPECT_TRUE(RoundTripAndCompare(PP_MakeBool(PP_TRUE)));
249 EXPECT_TRUE(RoundTripAndCompare(PP_MakeDouble(53.75)));
252 TEST_F(V8VarConverterTest, StringRoundTripTest) {
253 EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("")));
254 EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("hello world!")));
257 TEST_F(V8VarConverterTest, ArrayBufferRoundTripTest) {
258 // TODO(raymes): Testing this here requires spinning up some of WebKit.
259 // Work out how to do this.
262 TEST_F(V8VarConverterTest, DictionaryArrayRoundTripTest) {
263 // Empty array.
264 scoped_refptr<ArrayVar> array(new ArrayVar);
265 ScopedPPVar release_array(ScopedPPVar::PassRef(), array->GetPPVar());
266 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
268 size_t index = 0;
270 // Array with primitives.
271 array->Set(index++, PP_MakeUndefined());
272 array->Set(index++, PP_MakeNull());
273 array->Set(index++, PP_MakeInt32(100));
274 array->Set(index++, PP_MakeBool(PP_FALSE));
275 array->Set(index++, PP_MakeDouble(0.123));
276 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
278 // Array with 2 references to the same string.
279 ScopedPPVar release_string(ScopedPPVar::PassRef(),
280 StringVar::StringToPPVar("abc"));
281 array->Set(index++, release_string.get());
282 array->Set(index++, release_string.get());
283 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
285 // Array with nested array that references the same string.
286 scoped_refptr<ArrayVar> array2(new ArrayVar);
287 ScopedPPVar release_array2(ScopedPPVar::PassRef(), array2->GetPPVar());
288 array2->Set(0, release_string.get());
289 array->Set(index++, release_array2.get());
290 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
292 // Empty dictionary.
293 scoped_refptr<DictionaryVar> dictionary(new DictionaryVar);
294 ScopedPPVar release_dictionary(ScopedPPVar::PassRef(),
295 dictionary->GetPPVar());
296 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
298 // Dictionary with primitives.
299 dictionary->SetWithStringKey("1", PP_MakeUndefined());
300 dictionary->SetWithStringKey("2", PP_MakeNull());
301 dictionary->SetWithStringKey("3", PP_MakeInt32(-100));
302 dictionary->SetWithStringKey("4", PP_MakeBool(PP_TRUE));
303 dictionary->SetWithStringKey("5", PP_MakeDouble(-103.52));
304 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
306 // Dictionary with 2 references to the same string.
307 dictionary->SetWithStringKey("6", release_string.get());
308 dictionary->SetWithStringKey("7", release_string.get());
309 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
311 // Dictionary with nested dictionary that references the same string.
312 scoped_refptr<DictionaryVar> dictionary2(new DictionaryVar);
313 ScopedPPVar release_dictionary2(ScopedPPVar::PassRef(),
314 dictionary2->GetPPVar());
315 dictionary2->SetWithStringKey("abc", release_string.get());
316 dictionary->SetWithStringKey("8", release_dictionary2.get());
317 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
319 // Array with dictionary.
320 array->Set(index++, release_dictionary.get());
321 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
323 // Array with dictionary with array.
324 array2->Set(0, PP_MakeInt32(100));
325 dictionary->SetWithStringKey("9", release_array2.get());
326 EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
329 TEST_F(V8VarConverterTest, Cycles) {
330 // Check that cycles aren't converted.
331 v8::HandleScope handle_scope(isolate_);
332 v8::Local<v8::Context> context =
333 v8::Local<v8::Context>::New(isolate_, context_);
334 v8::Context::Scope context_scope(context);
336 // Var->V8 conversion.
338 scoped_refptr<DictionaryVar> dictionary(new DictionaryVar);
339 ScopedPPVar release_dictionary(ScopedPPVar::PassRef(),
340 dictionary->GetPPVar());
341 scoped_refptr<ArrayVar> array(new ArrayVar);
342 ScopedPPVar release_array(ScopedPPVar::PassRef(), array->GetPPVar());
344 dictionary->SetWithStringKey("1", release_array.get());
345 array->Set(0, release_dictionary.get());
347 v8::Local<v8::Value> v8_result;
349 // Array <-> dictionary cycle.
350 dictionary->SetWithStringKey("1", release_array.get());
351 ASSERT_FALSE(
352 converter_->ToV8Value(release_dictionary.get(), context, &v8_result));
353 // Break the cycle.
354 // TODO(raymes): We need some better machinery for releasing vars with
355 // cycles. Remove the code below once we have that.
356 dictionary->DeleteWithStringKey("1");
358 // Array with self reference.
359 array->Set(0, release_array.get());
360 ASSERT_FALSE(
361 converter_->ToV8Value(release_array.get(), context, &v8_result));
362 // Break the self reference.
363 array->Set(0, PP_MakeUndefined());
366 // V8->Var conversion.
368 v8::Local<v8::Object> object = v8::Object::New(isolate_);
369 v8::Local<v8::Array> array = v8::Array::New(isolate_);
371 PP_Var var_result;
373 // Array <-> dictionary cycle.
374 std::string key = "1";
375 object->Set(
376 v8::String::NewFromUtf8(
377 isolate_, key.c_str(), v8::String::kNormalString, key.length()),
378 array);
379 array->Set(0, object);
381 ASSERT_FALSE(FromV8ValueSync(object, context, &var_result));
383 // Array with self reference.
384 array->Set(0, array);
385 ASSERT_FALSE(FromV8ValueSync(array, context, &var_result));
389 TEST_F(V8VarConverterTest, StrangeDictionaryKeyTest) {
391 // Test keys with '.'.
392 scoped_refptr<DictionaryVar> dictionary(new DictionaryVar);
393 dictionary->SetWithStringKey(".", PP_MakeUndefined());
394 dictionary->SetWithStringKey("x.y", PP_MakeUndefined());
395 EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
399 // Test non-string key types. They should be cast to strings.
400 v8::HandleScope handle_scope(isolate_);
401 v8::Local<v8::Context> context =
402 v8::Local<v8::Context>::New(isolate_, context_);
403 v8::Context::Scope context_scope(context);
405 const char* source =
406 "(function() {"
407 "return {"
408 "1: 'foo',"
409 "'2': 'bar',"
410 "true: 'baz',"
411 "false: 'qux',"
412 "null: 'quux',"
413 "undefined: 'oops'"
414 "};"
415 "})();";
417 v8::Local<v8::Script> script(
418 v8::Script::Compile(v8::String::NewFromUtf8(isolate_, source)));
419 v8::Local<v8::Object> object = script->Run().As<v8::Object>();
420 ASSERT_FALSE(object.IsEmpty());
422 PP_Var actual;
423 ASSERT_TRUE(FromV8ValueSync(
424 object, v8::Local<v8::Context>::New(isolate_, context_), &actual));
425 ScopedPPVar release_actual(ScopedPPVar::PassRef(), actual);
427 scoped_refptr<DictionaryVar> expected(new DictionaryVar);
428 ScopedPPVar foo(ScopedPPVar::PassRef(), StringVar::StringToPPVar("foo"));
429 expected->SetWithStringKey("1", foo.get());
430 ScopedPPVar bar(ScopedPPVar::PassRef(), StringVar::StringToPPVar("bar"));
431 expected->SetWithStringKey("2", bar.get());
432 ScopedPPVar baz(ScopedPPVar::PassRef(), StringVar::StringToPPVar("baz"));
433 expected->SetWithStringKey("true", baz.get());
434 ScopedPPVar qux(ScopedPPVar::PassRef(), StringVar::StringToPPVar("qux"));
435 expected->SetWithStringKey("false", qux.get());
436 ScopedPPVar quux(ScopedPPVar::PassRef(), StringVar::StringToPPVar("quux"));
437 expected->SetWithStringKey("null", quux.get());
438 ScopedPPVar oops(ScopedPPVar::PassRef(), StringVar::StringToPPVar("oops"));
439 expected->SetWithStringKey("undefined", oops.get());
440 ScopedPPVar release_expected(ScopedPPVar::PassRef(), expected->GetPPVar());
442 ASSERT_TRUE(TestEqual(release_expected.get(), release_actual.get(), true));
446 } // namespace content