rdevlin.cronin | d982fdf | 2017-03-23 22:17:43 | [diff] [blame] | 1 | // Copyright 2017 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. |
| 4 | |
| 5 | #include "gin/arguments.h" |
| 6 | |
| 7 | #include "base/bind.h" |
| 8 | #include "gin/converter.h" |
| 9 | #include "gin/object_template_builder.h" |
| 10 | #include "gin/public/isolate_holder.h" |
| 11 | #include "gin/test/v8_test.h" |
| 12 | #include "v8/include/v8.h" |
| 13 | |
| 14 | namespace gin { |
| 15 | |
| 16 | using ArgumentsTest = V8Test; |
| 17 | |
| 18 | // Test that Arguments::GetHolderCreationContext returns the proper context. |
| 19 | TEST_F(ArgumentsTest, TestArgumentsHolderCreationContext) { |
| 20 | v8::Isolate* isolate = instance_->isolate(); |
| 21 | v8::HandleScope handle_scope(isolate); |
| 22 | |
| 23 | v8::Local<v8::Context> creation_context = context_.Get(instance_->isolate()); |
| 24 | |
| 25 | auto check_creation_context = [](v8::Local<v8::Context> expected_context, |
| 26 | gin::Arguments* arguments) { |
| 27 | EXPECT_EQ(expected_context, arguments->GetHolderCreationContext()); |
| 28 | }; |
| 29 | |
| 30 | // Create an object that will compare GetHolderCreationContext() with |
| 31 | // |creation_context|. |
| 32 | v8::Local<v8::ObjectTemplate> object_template = |
| 33 | ObjectTemplateBuilder(isolate) |
| 34 | .SetMethod("checkCreationContext", |
| 35 | base::Bind(check_creation_context, creation_context)) |
| 36 | .Build(); |
| 37 | |
| 38 | v8::Local<v8::Object> object = |
| 39 | object_template->NewInstance(creation_context).ToLocalChecked(); |
| 40 | |
| 41 | // Call checkCreationContext() on the generated object using the passed-in |
| 42 | // context as the current context. |
| 43 | auto test_context = [object, isolate](v8::Local<v8::Context> context) { |
| 44 | v8::Context::Scope context_scope(context); |
| 45 | const char kCallFunction[] = "(function(o) { o.checkCreationContext(); })"; |
| 46 | v8::Local<v8::Script> script = |
| 47 | v8::Script::Compile(context, StringToV8(isolate, kCallFunction)) |
| 48 | .ToLocalChecked(); |
| 49 | v8::Local<v8::Function> function; |
| 50 | ASSERT_TRUE(ConvertFromV8(isolate, script->Run(), &function)); |
| 51 | v8::Local<v8::Value> args[] = {object}; |
| 52 | function->Call(v8::Undefined(isolate), arraysize(args), args); |
| 53 | }; |
| 54 | |
| 55 | // Test calling in the creation context. |
| 56 | test_context(creation_context); |
| 57 | |
| 58 | { |
| 59 | // Create a second context, and test calling in that. The creation context |
| 60 | // should be the same (even though the current context has changed). |
| 61 | v8::Local<v8::Context> second_context = |
| 62 | v8::Context::New(isolate, nullptr, v8::Local<v8::ObjectTemplate>()); |
| 63 | test_context(second_context); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | } // namespace gin |