summaryrefslogtreecommitdiff
path: root/chromium/fuchsia/base/agent_impl_unittests.cc
blob: f6a95df10a642565b0988eaa38763b64c5de26a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "fuchsia/base/agent_impl.h"

#include <lib/sys/cpp/component_context.h>

#include "base/fuchsia/fuchsia_logging.h"
#include "base/logging.h"
#include "base/test/task_environment.h"
#include "base/testfidl/cpp/fidl.h"
#include "fuchsia/base/fit_adapter.h"
#include "fuchsia/base/result_receiver.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace cr_fuchsia {

namespace {

const char kNoServicesComponentId[] = "no-services";
const char kAccumulatorComponentId1[] = "accumulator1";
const char kAccumulatorComponentId2[] = "accumulator2";
const char kKeepAliveComponentId[] = "keep-alive";

class EmptyComponentState : public AgentImpl::ComponentStateBase {
 public:
  EmptyComponentState(base::StringPiece component)
      : ComponentStateBase(component) {}
};

class AccumulatingTestInterfaceImpl : public base::testfidl::TestInterface {
 public:
  AccumulatingTestInterfaceImpl() = default;

  // TestInterface implementation:
  void Add(int32_t a, int32_t b, AddCallback callback) override {
    accumulated_ += a + b;
    callback(accumulated_);
  }

 private:
  int32_t accumulated_ = 0;

  DISALLOW_COPY_AND_ASSIGN(AccumulatingTestInterfaceImpl);
};

class AccumulatorComponentState : public AgentImpl::ComponentStateBase {
 public:
  AccumulatorComponentState(base::StringPiece component)
      : ComponentStateBase(component),
        service_binding_(outgoing_directory(), &service_) {}

 protected:
  AccumulatingTestInterfaceImpl service_;
  base::fuchsia::ScopedServiceBinding<base::testfidl::TestInterface>
      service_binding_;
};

class KeepAliveComponentState : public AccumulatorComponentState {
 public:
  KeepAliveComponentState(base::StringPiece component)
      : AccumulatorComponentState(component) {
    AddKeepAliveBinding(&service_binding_);
  }

  void DisconnectClientsAndTeardown() {
    AgentImpl::ComponentStateBase::DisconnectClientsAndTeardown();
  }
};

class AgentImplTest : public ::testing::Test {
 public:
  AgentImplTest() {
    fidl::InterfaceHandle<::fuchsia::io::Directory> directory;
    services_.GetOrCreateDirectory("svc")->Serve(
        fuchsia::io::OPEN_RIGHT_READABLE | fuchsia::io::OPEN_RIGHT_WRITABLE,
        directory.NewRequest().TakeChannel());

    services_client_ =
        std::make_unique<sys::ServiceDirectory>(std::move(directory));
  }

  fuchsia::modular::AgentPtr CreateAgentAndConnect() {
    DCHECK(!agent_impl_);
    agent_impl_ = std::make_unique<AgentImpl>(
        &services_, base::BindRepeating(&AgentImplTest::OnComponentConnect,
                                        base::Unretained(this)));
    fuchsia::modular::AgentPtr agent;
    services_client_->Connect(agent.NewRequest());
    return agent;
  }

  void TeardownKeepAliveComponentState() {
    std::move(disconnect_clients_and_teardown_).Run();
  }

 protected:
  std::unique_ptr<AgentImpl::ComponentStateBase> OnComponentConnect(
      base::StringPiece component_id) {
    if (component_id == kNoServicesComponentId) {
      return std::make_unique<EmptyComponentState>(component_id);
    } else if (component_id == kAccumulatorComponentId1 ||
               component_id == kAccumulatorComponentId2) {
      return std::make_unique<AccumulatorComponentState>(component_id);
    } else if (component_id == kKeepAliveComponentId) {
      auto component_state =
          std::make_unique<KeepAliveComponentState>(component_id);
      disconnect_clients_and_teardown_ =
          base::BindOnce(&KeepAliveComponentState::DisconnectClientsAndTeardown,
                         base::Unretained(component_state.get()));
      return component_state;
    }
    return nullptr;
  }

  base::test::SingleThreadTaskEnvironment task_environment_{
      base::test::SingleThreadTaskEnvironment::MainThreadType::IO};
  sys::OutgoingDirectory services_;
  std::unique_ptr<sys::ServiceDirectory> services_client_;

  std::unique_ptr<AgentImpl> agent_impl_;

  // Set only if a keep-alive component was connected, to allow the test to
  // forcibly teardown the ComponentState for it.
  base::OnceClosure disconnect_clients_and_teardown_;

  DISALLOW_COPY_AND_ASSIGN(AgentImplTest);
};

}  // namespace

// Verify that the Agent can publish and unpublish itself.
TEST_F(AgentImplTest, PublishAndUnpublish) {
  cr_fuchsia::ResultReceiver<zx_status_t> client_disconnect_status1;
  fuchsia::modular::AgentPtr agent = CreateAgentAndConnect();
  agent.set_error_handler(cr_fuchsia::CallbackToFitFunction(
      client_disconnect_status1.GetReceiveCallback()));

  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(client_disconnect_status1.has_value());

  // Teardown the Agent.
  agent_impl_.reset();

  // Verify that the client got disconnected on teardown.
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(*client_disconnect_status1, ZX_ERR_PEER_CLOSED);

  // Verify that the Agent service is no longer available.
  cr_fuchsia::ResultReceiver<zx_status_t> client_disconnect_status2;
  services_client_->Connect(agent.NewRequest());
  agent.set_error_handler(cr_fuchsia::CallbackToFitFunction(
      client_disconnect_status2.GetReceiveCallback()));

  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(*client_disconnect_status2, ZX_ERR_PEER_CLOSED);
}

// Verify that multiple connection attempts with the different component Ids
// to the same service get different instances.
TEST_F(AgentImplTest, DifferentComponentIdSameService) {
  fuchsia::modular::AgentPtr agent = CreateAgentAndConnect();

  // Connect to the Agent twice using the same component Id.
  fuchsia::sys::ServiceProviderPtr component_services1;
  agent->Connect(kAccumulatorComponentId1, component_services1.NewRequest());
  fuchsia::sys::ServiceProviderPtr component_services2;
  agent->Connect(kAccumulatorComponentId2, component_services2.NewRequest());

  // Request the TestInterface from each of the service directories.
  base::testfidl::TestInterfacePtr test_interface1;
  component_services1->ConnectToService(
      base::testfidl::TestInterface::Name_,
      test_interface1.NewRequest().TakeChannel());
  base::testfidl::TestInterfacePtr test_interface2;
  component_services2->ConnectToService(
      base::testfidl::TestInterface::Name_,
      test_interface2.NewRequest().TakeChannel());

  // Both TestInterface pointers should remain valid until we are done.
  test_interface1.set_error_handler([](zx_status_t status) {
    ZX_LOG(ERROR, status);
    ADD_FAILURE();
  });
  test_interface2.set_error_handler([](zx_status_t status) {
    ZX_LOG(ERROR, status);
    ADD_FAILURE();
  });

  // Call Add() via one TestInterface and verify accumulator had been at zero.
  {
    base::RunLoop loop;
    test_interface1->Add(1, 2,
                         [quit_loop = loop.QuitClosure()](int32_t result) {
                           EXPECT_EQ(result, 3);
                           quit_loop.Run();
                         });
    loop.RunUntilIdle();
  }

  // Call Add() via the second TestInterface, and verify that first Add() call's
  // effects aren't visible.
  {
    base::RunLoop loop;
    test_interface2->Add(3, 4,
                         [quit_loop = loop.QuitClosure()](int32_t result) {
                           EXPECT_EQ(result, 7);
                           quit_loop.Run();
                         });
    loop.RunUntilIdle();
  }

  // Cleanly unbind the test interfaces now that we're done with them.
  test_interface1 = nullptr;
  test_interface2 = nullptr;

  // Tear down connections to the agent and let the error handlers unwind.
  {
    base::RunLoop loop;
    component_services1.Unbind();
    component_services2.Unbind();
    loop.RunUntilIdle();
  }
}

// Verify that multiple connection attempts with the same component Id connect
// it to the same service instances.
TEST_F(AgentImplTest, SameComponentIdSameService) {
  fuchsia::modular::AgentPtr agent = CreateAgentAndConnect();

  // Connect to the Agent twice using the same component Id.
  fuchsia::sys::ServiceProviderPtr component_services1;
  agent->Connect(kAccumulatorComponentId1, component_services1.NewRequest());
  fuchsia::sys::ServiceProviderPtr component_services2;
  agent->Connect(kAccumulatorComponentId1, component_services2.NewRequest());

  // Request the TestInterface from each of the service directories.
  base::testfidl::TestInterfacePtr test_interface1;
  component_services1->ConnectToService(
      base::testfidl::TestInterface::Name_,
      test_interface1.NewRequest().TakeChannel());
  base::testfidl::TestInterfacePtr test_interface2;
  component_services2->ConnectToService(
      base::testfidl::TestInterface::Name_,
      test_interface2.NewRequest().TakeChannel());

  // Both TestInterface pointers should remain valid until we are done.
  test_interface1.set_error_handler([](zx_status_t status) {
    ZX_LOG(ERROR, status);
    ADD_FAILURE();
  });
  test_interface2.set_error_handler([](zx_status_t status) {
    ZX_LOG(ERROR, status);
    ADD_FAILURE();
  });

  // Call Add() via one TestInterface and verify accumulator had been at zero.
  {
    base::RunLoop loop;
    test_interface1->Add(1, 2,
                         [quit_loop = loop.QuitClosure()](int32_t result) {
                           EXPECT_EQ(result, 3);
                           quit_loop.Run();
                         });
    loop.RunUntilIdle();
  }

  // Call Add() via the other TestInterface, and verify that the result of the
  // previous Add() was already in the accumulator.
  {
    base::RunLoop loop;
    test_interface2->Add(3, 4,
                         [quit_loop = loop.QuitClosure()](int32_t result) {
                           EXPECT_EQ(result, 10);
                           quit_loop.Run();
                         });
    loop.RunUntilIdle();
  }

  // Cleanly unbind the test interfaces now that we're done with them.
  test_interface1 = nullptr;
  test_interface2 = nullptr;

  // Tear down connections to the agent and let the error handlers unwind.
  {
    base::RunLoop loop;
    component_services1.Unbind();
    component_services2.Unbind();
    loop.RunUntilIdle();
  }
}

// Verify that connections to a service registered to keep-alive the
// ComponentStateBase keeps it alive after the ServiceProvider is dropped.
TEST_F(AgentImplTest, KeepAliveBinding) {
  fuchsia::modular::AgentPtr agent = CreateAgentAndConnect();

  {
    // Connect to the Agent and request the TestInterface.
    fuchsia::sys::ServiceProviderPtr component_services;
    agent->Connect(kAccumulatorComponentId1, component_services.NewRequest());
    base::testfidl::TestInterfacePtr test_interface;
    component_services->ConnectToService(
        base::testfidl::TestInterface::Name_,
        test_interface.NewRequest().TakeChannel());

    // The TestInterface pointer should be closed as soon as we Unbind() the
    // ServiceProvider.
    test_interface.set_error_handler(
        [](zx_status_t status) { EXPECT_EQ(status, ZX_ERR_PEER_CLOSED); });

    // After disconnecting ServiceProvider, TestInterface should remain valid.
    component_services.Unbind();
    base::RunLoop().RunUntilIdle();
    EXPECT_FALSE(test_interface);
  }

  {
    // Connect to the Agent and request the TestInterface.
    fuchsia::sys::ServiceProviderPtr component_services;
    agent->Connect(kKeepAliveComponentId, component_services.NewRequest());
    base::testfidl::TestInterfacePtr test_interface;
    component_services->ConnectToService(
        base::testfidl::TestInterface::Name_,
        test_interface.NewRequest().TakeChannel());

    // The TestInterface pointer should remain valid until we are done.
    test_interface.set_error_handler([](zx_status_t status) {
      ZX_LOG(ERROR, status);
      ADD_FAILURE();
    });

    // After disconnecting ServiceProvider, TestInterface should remain valid.
    component_services.Unbind();
    base::RunLoop().RunUntilIdle();
    EXPECT_TRUE(test_interface);
  }

  // Spin the MessageLoop to let the AgentImpl see that TestInterface is gone.
  base::RunLoop().RunUntilIdle();
}

// Verify that connections to a service registered to keep-alive the
// ComponentStateBase is disconnected by DisconnectClientsAndTeardown.
TEST_F(AgentImplTest, DisconnectClientsAndTeardown) {
  fuchsia::modular::AgentPtr agent = CreateAgentAndConnect();

  {
    // Connect to the Agent and request the TestInterface.
    fuchsia::sys::ServiceProviderPtr component_services;
    agent->Connect(kKeepAliveComponentId, component_services.NewRequest());
    base::testfidl::TestInterfacePtr test_interface;
    component_services->ConnectToService(
        base::testfidl::TestInterface::Name_,
        test_interface.NewRequest().TakeChannel());

    // The TestInterface pointer should remain valid until we call
    // DisconnectClientsAndTeardown().
    test_interface.set_error_handler(
        [](zx_status_t status) { ZX_LOG_IF(ERROR, status != ZX_OK, status); });

    // After disconnecting ServiceProvider, TestInterface should remain valid.
    component_services.Unbind();
    base::RunLoop().RunUntilIdle();
    EXPECT_TRUE(test_interface);

    // After invoking DisconnectClientsAndTeardown(), TestInterface should
    // be disconnected.
    TeardownKeepAliveComponentState();
    base::RunLoop().RunUntilIdle();
    EXPECT_FALSE(test_interface);
  }
}

}  // namespace cr_fuchsia