Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / extensions / renderer / mojo / keep_alive_client_unittest.cc
blob4f23621eb007bd47073c41689fd964baceacc20e
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.
5 #include "extensions/common/mojo/keep_alive.mojom.h"
6 #include "extensions/renderer/api_test_base.h"
7 #include "grit/extensions_renderer_resources.h"
8 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_impl.h"
10 // A test launcher for tests for the stash client defined in
11 // extensions/test/data/keep_alive_client_unittest.js.
13 namespace extensions {
14 namespace {
16 // A KeepAlive implementation that calls provided callbacks on creation and
17 // destruction.
18 class TestKeepAlive : public mojo::InterfaceImpl<KeepAlive> {
19 public:
20 explicit TestKeepAlive(const base::Closure& on_destruction)
21 : on_destruction_(on_destruction) {}
23 ~TestKeepAlive() override { on_destruction_.Run(); }
25 static void Create(const base::Closure& on_creation,
26 const base::Closure& on_destruction,
27 mojo::InterfaceRequest<KeepAlive> keep_alive) {
28 mojo::BindToRequest(new TestKeepAlive(on_destruction), &keep_alive);
29 on_creation.Run();
32 private:
33 const base::Closure on_destruction_;
36 } // namespace
38 class KeepAliveClientTest : public ApiTestBase {
39 public:
40 KeepAliveClientTest() {}
42 void SetUp() override {
43 ApiTestBase::SetUp();
44 service_provider()->AddService(
45 base::Bind(&TestKeepAlive::Create,
46 base::Bind(&KeepAliveClientTest::KeepAliveCreated,
47 base::Unretained(this)),
48 base::Bind(&KeepAliveClientTest::KeepAliveDestroyed,
49 base::Unretained(this))));
50 created_keep_alive_ = false;
51 destroyed_keep_alive_ = false;
54 void WaitForKeepAlive() {
55 // Wait for a keep-alive to be created and destroyed.
56 while (!created_keep_alive_ || !destroyed_keep_alive_) {
57 base::RunLoop run_loop;
58 stop_run_loop_ = run_loop.QuitClosure();
59 run_loop.Run();
61 EXPECT_TRUE(created_keep_alive_);
62 EXPECT_TRUE(destroyed_keep_alive_);
65 private:
66 void KeepAliveCreated() {
67 created_keep_alive_ = true;
68 if (!stop_run_loop_.is_null())
69 stop_run_loop_.Run();
71 void KeepAliveDestroyed() {
72 destroyed_keep_alive_ = true;
73 if (!stop_run_loop_.is_null())
74 stop_run_loop_.Run();
77 bool created_keep_alive_;
78 bool destroyed_keep_alive_;
79 base::Closure stop_run_loop_;
81 DISALLOW_COPY_AND_ASSIGN(KeepAliveClientTest);
84 TEST_F(KeepAliveClientTest, KeepAliveWithSuccessfulCall) {
85 RunTest("keep_alive_client_unittest.js", "testKeepAliveWithSuccessfulCall");
86 WaitForKeepAlive();
89 TEST_F(KeepAliveClientTest, KeepAliveWithError) {
90 RunTest("keep_alive_client_unittest.js", "testKeepAliveWithError");
91 WaitForKeepAlive();
94 } // namespace extensions