1 // Copyright 2014 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 "base/message_loop/message_loop.h" 6 #include "extensions/common/extension.h" 7 #include "extensions/common/features/feature.h" 8 #include "extensions/renderer/script_context.h" 9 #include "extensions/renderer/script_context_set.h" 10 #include "gin/public/context_holder.h" 11 #include "testing/gtest/include/gtest/gtest.h" 12 #include "third_party/WebKit/public/web/WebFrame.h" 13 #include "v8/include/v8.h" 14 15 namespace extensions { 16 17 TEST(ScriptContextSet, Lifecycle) { 18 base::MessageLoop loop; 19 20 ScriptContextSet context_set; 21 22 v8::Isolate* isolate = v8::Isolate::GetCurrent(); 23 v8::HandleScope handle_scope(isolate); 24 gin::ContextHolder context_holder(isolate); 25 context_holder.SetContext(v8::Context::New(isolate)); 26 27 // Dirty hack, but we don't actually need the frame, and this is easier than 28 // creating a whole webview. 29 blink::WebFrame* frame = reinterpret_cast<blink::WebFrame*>(1); 30 const Extension* extension = NULL; 31 ScriptContext* context = 32 new ScriptContext(context_holder.context(), 33 frame, 34 extension, 35 Feature::BLESSED_EXTENSION_CONTEXT, 36 extension, 37 Feature::BLESSED_EXTENSION_CONTEXT); 38 39 context_set.Add(context); 40 EXPECT_EQ(1u, context_set.GetAll().count(context)); 41 EXPECT_EQ(context, context_set.GetByV8Context(context->v8_context())); 42 43 // Adding the same item multiple times should be OK and deduped. 44 context_set.Add(context); 45 EXPECT_EQ(1u, context_set.GetAll().count(context)); 46 47 // GetAll() returns a copy so removing from one should not remove from others. 48 ScriptContextSet::ContextSet set_copy = context_set.GetAll(); 49 EXPECT_EQ(1u, set_copy.count(context)); 50 51 context_set.Remove(context); 52 EXPECT_EQ(0, context_set.size()); 53 EXPECT_FALSE(context_set.GetByV8Context(context->v8_context())); 54 EXPECT_EQ(1u, set_copy.size()); 55 56 // After removal, the context should be marked for destruction. 57 EXPECT_FALSE(context->web_frame()); 58 59 // Run loop to do the actual deletion. 60 loop.RunUntilIdle(); 61 } 62 63 } // namespace extensions 64