capability-test.c++ 25.5 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21

22 23 24 25 26 27
#include "schema.capnp.h"

#ifdef CAPNP_CAPABILITY_H_
#error "schema.capnp should not depend on capability.h, because it contains no interfaces."
#endif

Kenton Varda's avatar
Kenton Varda committed
28
#include <capnp/test.capnp.h>
29 30 31 32 33

#ifndef CAPNP_CAPABILITY_H_
#error "test.capnp did not include capability.h."
#endif

34 35 36 37 38 39 40 41 42 43
#include "capability.h"
#include "test-util.h"
#include <kj/debug.h>
#include <gtest/gtest.h>

namespace capnp {
namespace _ {
namespace {

TEST(Capability, Basic) {
44
  kj::EventLoop loop;
45
  kj::WaitScope waitScope(loop);
46

47
  int callCount = 0;
48
  test::TestInterface::Client client(kj::heap<TestInterfaceImpl>(callCount));
49 50 51 52 53 54 55 56 57 58

  auto request1 = client.fooRequest();
  request1.setI(123);
  request1.setJ(true);
  auto promise1 = request1.send();

  auto request2 = client.bazRequest();
  initTestMessage(request2.initS());
  auto promise2 = request2.send();

59
  bool barFailed = false;
60
  auto request3 = client.barRequest();
61
  auto promise3 = request3.send().then(
62 63
      [](Response<test::TestInterface::BarResults>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
64
      }, [&](kj::Exception&& e) {
65
        EXPECT_EQ(kj::Exception::Type::UNIMPLEMENTED, e.getType());
66
        barFailed = true;
67 68 69 70
      });

  EXPECT_EQ(0, callCount);

71
  auto response1 = promise1.wait(waitScope);
72 73 74

  EXPECT_EQ("foo", response1.getX());

75
  auto response2 = promise2.wait(waitScope);
76

77
  promise3.wait(waitScope);
78 79

  EXPECT_EQ(2, callCount);
80
  EXPECT_TRUE(barFailed);
81 82 83
}

TEST(Capability, Inheritance) {
84
  kj::EventLoop loop;
85
  kj::WaitScope waitScope(loop);
86

87
  int callCount = 0;
88
  test::TestExtends::Client client1(kj::heap<TestExtendsImpl>(callCount));
89 90
  test::TestInterface::Client client2 = client1;
  auto client = client2.castAs<test::TestExtends>();
91 92 93 94 95 96 97 98 99 100

  auto request1 = client.fooRequest();
  request1.setI(321);
  auto promise1 = request1.send();

  auto request2 = client.graultRequest();
  auto promise2 = request2.send();

  EXPECT_EQ(0, callCount);

101
  auto response2 = promise2.wait(waitScope);
102 103 104

  checkTestMessage(response2);

105
  auto response1 = promise1.wait(waitScope);
106 107 108 109 110 111

  EXPECT_EQ("bar", response1.getX());

  EXPECT_EQ(2, callCount);
}

112
TEST(Capability, Pipelining) {
113
  kj::EventLoop loop;
114
  kj::WaitScope waitScope(loop);
115 116 117

  int callCount = 0;
  int chainedCallCount = 0;
118
  test::TestPipeline::Client client(kj::heap<TestPipelineImpl>(callCount));
119 120

  auto request = client.getCapRequest();
121
  request.setN(234);
122
  request.setInCap(test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));
123 124 125

  auto promise = request.send();

126
  auto pipelineRequest = promise.getOutBox().getCap().fooRequest();
127 128 129
  pipelineRequest.setI(321);
  auto pipelinePromise = pipelineRequest.send();

130 131 132 133 134
  auto pipelineRequest2 = promise.getOutBox().getCap().castAs<test::TestExtends>().graultRequest();
  auto pipelinePromise2 = pipelineRequest2.send();

  promise = nullptr;  // Just to be annoying, drop the original promise.

135 136 137
  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

138
  auto response = pipelinePromise.wait(waitScope);
139 140
  EXPECT_EQ("bar", response.getX());

141
  auto response2 = pipelinePromise2.wait(waitScope);
142 143 144 145 146 147
  checkTestMessage(response2);

  EXPECT_EQ(3, callCount);
  EXPECT_EQ(1, chainedCallCount);
}

148
TEST(Capability, TailCall) {
149
  kj::EventLoop loop;
150
  kj::WaitScope waitScope(loop);
151 152 153 154

  int calleeCallCount = 0;
  int callerCallCount = 0;

155 156
  test::TestTailCallee::Client callee(kj::heap<TestTailCalleeImpl>(calleeCallCount));
  test::TestTailCaller::Client caller(kj::heap<TestTailCallerImpl>(callerCallCount));
157 158 159 160 161 162 163 164 165

  auto request = caller.fooRequest();
  request.setI(456);
  request.setCallee(callee);

  auto promise = request.send();

  auto dependentCall0 = promise.getC().getCallSequenceRequest().send();

166
  auto response = promise.wait(waitScope);
167 168 169 170 171 172 173
  EXPECT_EQ(456, response.getI());
  EXPECT_EQ(456, response.getI());

  auto dependentCall1 = promise.getC().getCallSequenceRequest().send();

  auto dependentCall2 = response.getC().getCallSequenceRequest().send();

174 175 176
  EXPECT_EQ(0, dependentCall0.wait(waitScope).getN());
  EXPECT_EQ(1, dependentCall1.wait(waitScope).getN());
  EXPECT_EQ(2, dependentCall2.wait(waitScope).getN());
177 178 179 180 181

  EXPECT_EQ(1, calleeCallCount);
  EXPECT_EQ(1, callerCallCount);
}

182
TEST(Capability, AsyncCancelation) {
183
  // Tests allowCancellation().
184

185
  kj::EventLoop loop;
186
  kj::WaitScope waitScope(loop);
187 188 189

  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
190
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);
191 192

  int callCount = 0;
193
  int handleCount = 0;
194

195
  test::TestMoreStuff::Client client(kj::heap<TestMoreStuffImpl>(callCount, handleCount));
196 197 198 199 200

  kj::Promise<void> promise = nullptr;

  bool returned = false;
  {
201
    auto request = client.expectCancelRequest();
202
    request.setCap(test::TestInterface::Client(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller))));
203
    promise = request.send().then(
204
        [&](Response<test::TestMoreStuff::ExpectCancelResults>&& response) {
205
      returned = true;
206
    }).eagerlyEvaluate(nullptr);
207
  }
208 209
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);
210 211 212 213 214 215

  // We can detect that the method was canceled because it will drop the cap.
  EXPECT_FALSE(destroyed);
  EXPECT_FALSE(returned);

  promise = nullptr;  // request cancellation
216
  destructionPromise.wait(waitScope);
217 218 219 220 221

  EXPECT_TRUE(destroyed);
  EXPECT_FALSE(returned);
}

222 223 224
// =======================================================================================

TEST(Capability, DynamicClient) {
225
  kj::EventLoop loop;
226
  kj::WaitScope waitScope(loop);
227 228 229

  int callCount = 0;
  DynamicCapability::Client client =
230
      test::TestInterface::Client(kj::heap<TestInterfaceImpl>(callCount));
231 232 233 234 235 236 237 238 239 240 241 242

  auto request1 = client.newRequest("foo");
  request1.set("i", 123);
  request1.set("j", true);
  auto promise1 = request1.send();

  auto request2 = client.newRequest("baz");
  initDynamicTestMessage(request2.init("s").as<DynamicStruct>());
  auto promise2 = request2.send();

  bool barFailed = false;
  auto request3 = client.newRequest("bar");
243
  auto promise3 = request3.send().then(
244 245 246
      [](Response<DynamicStruct>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
      }, [&](kj::Exception&& e) {
247
        EXPECT_EQ(kj::Exception::Type::UNIMPLEMENTED, e.getType());
248 249 250 251 252
        barFailed = true;
      });

  EXPECT_EQ(0, callCount);

253
  auto response1 = promise1.wait(waitScope);
254 255 256

  EXPECT_EQ("foo", response1.get("x").as<Text>());

257
  auto response2 = promise2.wait(waitScope);
258

259
  promise3.wait(waitScope);
260 261 262 263 264 265

  EXPECT_EQ(2, callCount);
  EXPECT_TRUE(barFailed);
}

TEST(Capability, DynamicClientInheritance) {
266
  kj::EventLoop loop;
267
  kj::WaitScope waitScope(loop);
268 269 270 271

  int callCount = 0;

  DynamicCapability::Client client1 =
272
      test::TestExtends::Client(kj::heap<TestExtendsImpl>(callCount));
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  EXPECT_EQ(Schema::from<test::TestExtends>(), client1.getSchema());
  EXPECT_NE(Schema::from<test::TestInterface>(), client1.getSchema());

  DynamicCapability::Client client2 = client1.upcast(Schema::from<test::TestInterface>());
  EXPECT_EQ(Schema::from<test::TestInterface>(), client2.getSchema());

  EXPECT_ANY_THROW(client2.upcast(Schema::from<test::TestExtends>()));
  auto client = client2.castAs<DynamicCapability>(Schema::from<test::TestExtends>());

  auto request1 = client.newRequest("foo");
  request1.set("i", 321);
  auto promise1 = request1.send();

  auto request2 = client.newRequest("grault");
  auto promise2 = request2.send();

  EXPECT_EQ(0, callCount);

291
  auto response2 = promise2.wait(waitScope);
292 293 294

  checkDynamicTestMessage(response2.as<DynamicStruct>());

295
  auto response1 = promise1.wait(waitScope);
296 297 298

  EXPECT_EQ("bar", response1.get("x").as<Text>());

299
  EXPECT_EQ(2, callCount);
300 301 302
}

TEST(Capability, DynamicClientPipelining) {
303
  kj::EventLoop loop;
304
  kj::WaitScope waitScope(loop);
305 306 307 308

  int callCount = 0;
  int chainedCallCount = 0;
  DynamicCapability::Client client =
309
      test::TestPipeline::Client(kj::heap<TestPipelineImpl>(callCount));
310 311 312

  auto request = client.newRequest("getCap");
  request.set("n", 234);
313
  request.set("inCap", test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

  auto promise = request.send();

  auto outCap = promise.get("outBox").releaseAs<DynamicStruct>()
                       .get("cap").releaseAs<DynamicCapability>();
  auto pipelineRequest = outCap.newRequest("foo");
  pipelineRequest.set("i", 321);
  auto pipelinePromise = pipelineRequest.send();

  auto pipelineRequest2 = outCap.castAs<test::TestExtends>().graultRequest();
  auto pipelinePromise2 = pipelineRequest2.send();

  promise = nullptr;  // Just to be annoying, drop the original promise.

  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

331
  auto response = pipelinePromise.wait(waitScope);
332 333
  EXPECT_EQ("bar", response.get("x").as<Text>());

334
  auto response2 = pipelinePromise2.wait(waitScope);
335 336 337
  checkTestMessage(response2);

  EXPECT_EQ(3, callCount);
338 339 340
  EXPECT_EQ(1, chainedCallCount);
}

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
// =======================================================================================

class TestInterfaceDynamicImpl final: public DynamicCapability::Server {
public:
  TestInterfaceDynamicImpl(int& callCount)
      : DynamicCapability::Server(Schema::from<test::TestInterface>()),
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "foo") {
      ++callCount;
      auto params = context.getParams();
      EXPECT_EQ(123, params.get("i").as<int>());
      EXPECT_TRUE(params.get("j").as<bool>());
      context.getResults().set("x", "foo");
      return kj::READY_NOW;
    } else if (methodName == "baz") {
      ++callCount;
      auto params = context.getParams();
      checkDynamicTestMessage(params.get("s").as<DynamicStruct>());
      context.releaseParams();
      EXPECT_ANY_THROW(context.getParams());
      return kj::READY_NOW;
    } else {
369
      KJ_UNIMPLEMENTED("Method not implemented", methodName) { break; }
370
      return kj::READY_NOW;
371 372 373 374 375
    }
  }
};

TEST(Capability, DynamicServer) {
376
  kj::EventLoop loop;
377
  kj::WaitScope waitScope(loop);
378 379 380

  int callCount = 0;
  test::TestInterface::Client client =
381
      DynamicCapability::Client(kj::heap<TestInterfaceDynamicImpl>(callCount))
382 383 384 385 386 387 388 389 390 391 392 393 394
          .castAs<test::TestInterface>();

  auto request1 = client.fooRequest();
  request1.setI(123);
  request1.setJ(true);
  auto promise1 = request1.send();

  auto request2 = client.bazRequest();
  initTestMessage(request2.initS());
  auto promise2 = request2.send();

  bool barFailed = false;
  auto request3 = client.barRequest();
395
  auto promise3 = request3.send().then(
396 397 398
      [](Response<test::TestInterface::BarResults>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
      }, [&](kj::Exception&& e) {
399
        EXPECT_EQ(kj::Exception::Type::UNIMPLEMENTED, e.getType());
400 401 402 403 404
        barFailed = true;
      });

  EXPECT_EQ(0, callCount);

405
  auto response1 = promise1.wait(waitScope);
406 407 408

  EXPECT_EQ("foo", response1.getX());

409
  auto response2 = promise2.wait(waitScope);
410

411
  promise3.wait(waitScope);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

  EXPECT_EQ(2, callCount);
  EXPECT_TRUE(barFailed);
}

class TestExtendsDynamicImpl final: public DynamicCapability::Server {
public:
  TestExtendsDynamicImpl(int& callCount)
      : DynamicCapability::Server(Schema::from<test::TestExtends>()),
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "foo") {
      ++callCount;
      auto params = context.getParams();
      EXPECT_EQ(321, params.get("i").as<int>());
      EXPECT_FALSE(params.get("j").as<bool>());
      context.getResults().set("x", "bar");
      return kj::READY_NOW;
    } else if (methodName == "grault") {
      ++callCount;
      context.releaseParams();
      initDynamicTestMessage(context.getResults());
      return kj::READY_NOW;
    } else {
      KJ_FAIL_ASSERT("Method not implemented", methodName);
    }
  }
};

TEST(Capability, DynamicServerInheritance) {
447
  kj::EventLoop loop;
448
  kj::WaitScope waitScope(loop);
449 450 451

  int callCount = 0;
  test::TestExtends::Client client1 =
452
      DynamicCapability::Client(kj::heap<TestExtendsDynamicImpl>(callCount))
453 454 455 456 457 458 459 460 461 462 463 464 465
          .castAs<test::TestExtends>();
  test::TestInterface::Client client2 = client1;
  auto client = client2.castAs<test::TestExtends>();

  auto request1 = client.fooRequest();
  request1.setI(321);
  auto promise1 = request1.send();

  auto request2 = client.graultRequest();
  auto promise2 = request2.send();

  EXPECT_EQ(0, callCount);

466
  auto response2 = promise2.wait(waitScope);
467 468 469

  checkTestMessage(response2);

470
  auto response1 = promise1.wait(waitScope);
471 472 473 474 475 476 477 478 479

  EXPECT_EQ("bar", response1.getX());

  EXPECT_EQ(2, callCount);
}

class TestPipelineDynamicImpl final: public DynamicCapability::Server {
public:
  TestPipelineDynamicImpl(int& callCount)
480
      : DynamicCapability::Server(Schema::from<test::TestPipeline>()),
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "getCap") {
      ++callCount;

      auto params = context.getParams();
      EXPECT_EQ(234, params.get("n").as<uint32_t>());

      auto cap = params.get("inCap").as<DynamicCapability>();
      context.releaseParams();

      auto request = cap.newRequest("foo");
      request.set("i", 123);
      request.set("j", true);

      return request.send().then(
          [this,context](capnp::Response<DynamicStruct>&& response) mutable {
            EXPECT_EQ("foo", response.get("x").as<Text>());

            auto result = context.getResults();
            result.set("s", "bar");

            auto box = result.init("outBox").as<DynamicStruct>();

            // Too lazy to write a whole separate test for each of these cases...  so just make
            // sure they both compile here, and only actually test the latter.
512 513
            box.set("cap", kj::heap<TestExtendsDynamicImpl>(callCount));
            box.set("cap", kj::heap<TestExtendsImpl>(callCount));
514 515 516 517 518 519 520 521
          });
    } else {
      KJ_FAIL_ASSERT("Method not implemented", methodName);
    }
  }
};

TEST(Capability, DynamicServerPipelining) {
522
  kj::EventLoop loop;
523
  kj::WaitScope waitScope(loop);
524 525 526

  int callCount = 0;
  int chainedCallCount = 0;
527 528 529
  test::TestPipeline::Client client =
      DynamicCapability::Client(kj::heap<TestPipelineDynamicImpl>(callCount))
          .castAs<test::TestPipeline>();
530 531 532

  auto request = client.getCapRequest();
  request.setN(234);
533
  request.setInCap(test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

  auto promise = request.send();

  auto pipelineRequest = promise.getOutBox().getCap().fooRequest();
  pipelineRequest.setI(321);
  auto pipelinePromise = pipelineRequest.send();

  auto pipelineRequest2 = promise.getOutBox().getCap().castAs<test::TestExtends>().graultRequest();
  auto pipelinePromise2 = pipelineRequest2.send();

  promise = nullptr;  // Just to be annoying, drop the original promise.

  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

549
  auto response = pipelinePromise.wait(waitScope);
550 551
  EXPECT_EQ("bar", response.getX());

552
  auto response2 = pipelinePromise2.wait(waitScope);
553 554 555 556 557 558
  checkTestMessage(response2);

  EXPECT_EQ(3, callCount);
  EXPECT_EQ(1, chainedCallCount);
}

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
class TestTailCallerDynamicImpl final: public DynamicCapability::Server {
public:
  TestTailCallerDynamicImpl(int& callCount)
      : DynamicCapability::Server(Schema::from<test::TestTailCaller>()),
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "foo") {
      ++callCount;

      auto params = context.getParams();
      auto tailRequest = params.get("callee").as<DynamicCapability>().newRequest("foo");
      tailRequest.set("i", params.get("i"));
      tailRequest.set("t", "from TestTailCaller");
      return context.tailCall(kj::mv(tailRequest));
    } else {
      KJ_FAIL_ASSERT("Method not implemented", methodName);
    }
  }
};

TEST(Capability, DynamicServerTailCall) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  int calleeCallCount = 0;
  int callerCallCount = 0;

  test::TestTailCallee::Client callee(kj::heap<TestTailCalleeImpl>(calleeCallCount));
  test::TestTailCaller::Client caller =
      DynamicCapability::Client(kj::heap<TestTailCallerDynamicImpl>(callerCallCount))
          .castAs<test::TestTailCaller>();

  auto request = caller.fooRequest();
  request.setI(456);
  request.setCallee(callee);

  auto promise = request.send();

  auto dependentCall0 = promise.getC().getCallSequenceRequest().send();

  auto response = promise.wait(waitScope);
  EXPECT_EQ(456, response.getI());
  EXPECT_EQ(456, response.getI());

  auto dependentCall1 = promise.getC().getCallSequenceRequest().send();

  auto dependentCall2 = response.getC().getCallSequenceRequest().send();

  EXPECT_EQ(0, dependentCall0.wait(waitScope).getN());
  EXPECT_EQ(1, dependentCall1.wait(waitScope).getN());
  EXPECT_EQ(2, dependentCall2.wait(waitScope).getN());

  EXPECT_EQ(1, calleeCallCount);
  EXPECT_EQ(1, callerCallCount);
}

620 621
// =======================================================================================

622 623
void verifyClient(test::TestInterface::Client client, const int& callCount,
                  kj::WaitScope& waitScope) {
624 625 626 627
  int origCount = callCount;
  auto request = client.fooRequest();
  request.setI(123);
  request.setJ(true);
628
  auto response = request.send().wait(waitScope);
629 630 631 632
  EXPECT_EQ("foo", response.getX());
  EXPECT_EQ(origCount + 1, callCount);
}

633 634
void verifyClient(DynamicCapability::Client client, const int& callCount,
                  kj::WaitScope& waitScope) {
635 636 637 638
  int origCount = callCount;
  auto request = client.newRequest("foo");
  request.set("i", 123);
  request.set("j", true);
639
  auto response = request.send().wait(waitScope);
640 641 642 643
  EXPECT_EQ("foo", response.get("x").as<Text>());
  EXPECT_EQ(origCount + 1, callCount);
}

644
TEST(Capability, AnyPointersAndOrphans) {
645
  kj::EventLoop loop;
646
  kj::WaitScope waitScope(loop);
647 648 649 650 651 652 653

  int callCount1 = 0;
  int callCount2 = 0;

  // We use a TestPipeline instance here merely as a way to conveniently obtain an imbued message
  // instance.
  test::TestPipeline::Client baseClient(nullptr);
654 655
  test::TestInterface::Client client1(kj::heap<TestInterfaceImpl>(callCount1));
  test::TestInterface::Client client2(kj::heap<TestInterfaceImpl>(callCount2));
656 657 658 659 660 661 662 663 664 665 666

  auto request = baseClient.testPointersRequest();
  request.setCap(client1);

  EXPECT_TRUE(request.hasCap());

  Orphan<test::TestInterface> orphan = request.disownCap();
  EXPECT_FALSE(orphan == nullptr);

  EXPECT_FALSE(request.hasCap());

667 668
  verifyClient(orphan.get(), callCount1, waitScope);
  verifyClient(orphan.getReader(), callCount1, waitScope);
669 670 671 672

  request.getObj().adopt(kj::mv(orphan));
  EXPECT_TRUE(orphan == nullptr);

673 674
  verifyClient(request.getObj().getAs<test::TestInterface>(), callCount1, waitScope);
  verifyClient(request.asReader().getObj().getAs<test::TestInterface>(), callCount1, waitScope);
675
  verifyClient(request.getObj().getAs<DynamicCapability>(
676
      Schema::from<test::TestInterface>()), callCount1, waitScope);
677
  verifyClient(request.asReader().getObj().getAs<DynamicCapability>(
678
      Schema::from<test::TestInterface>()), callCount1, waitScope);
679 680 681 682 683

  request.getObj().clear();
  EXPECT_FALSE(request.hasObj());

  request.getObj().setAs<test::TestInterface>(client2);
684
  verifyClient(request.getObj().getAs<test::TestInterface>(), callCount2, waitScope);
685 686 687

  Orphan<DynamicCapability> dynamicOrphan = request.getObj().disownAs<DynamicCapability>(
      Schema::from<test::TestInterface>());
688 689
  verifyClient(dynamicOrphan.get(), callCount2, waitScope);
  verifyClient(dynamicOrphan.getReader(), callCount2, waitScope);
690 691

  Orphan<DynamicValue> dynamicValueOrphan = kj::mv(dynamicOrphan);
692
  verifyClient(dynamicValueOrphan.get().as<DynamicCapability>(), callCount2, waitScope);
693 694 695

  orphan = dynamicValueOrphan.releaseAs<test::TestInterface>();
  EXPECT_FALSE(orphan == nullptr);
696
  verifyClient(orphan.get(), callCount2, waitScope);
697 698 699 700

  request.adoptCap(kj::mv(orphan));
  EXPECT_TRUE(orphan == nullptr);

701
  verifyClient(request.getCap(), callCount2, waitScope);
702 703

  Orphan<DynamicCapability> dynamicOrphan2 = request.disownCap();
704 705
  verifyClient(dynamicOrphan2.get(), callCount2, waitScope);
  verifyClient(dynamicOrphan2.getReader(), callCount2, waitScope);
706 707 708
}

TEST(Capability, Lists) {
709
  kj::EventLoop loop;
710
  kj::WaitScope waitScope(loop);
711 712 713 714

  int callCount1 = 0;
  int callCount2 = 0;
  int callCount3 = 0;
715 716 717 718
  test::TestPipeline::Client baseClient(kj::heap<TestPipelineImpl>(callCount1));
  test::TestInterface::Client client1(kj::heap<TestInterfaceImpl>(callCount1));
  test::TestInterface::Client client2(kj::heap<TestInterfaceImpl>(callCount2));
  test::TestInterface::Client client3(kj::heap<TestInterfaceImpl>(callCount3));
719 720 721 722 723 724 725 726

  auto request = baseClient.testPointersRequest();

  auto list = request.initList(3);
  list.set(0, client1);
  list.set(1, client2);
  list.set(2, client3);

727 728 729
  verifyClient(list[0], callCount1, waitScope);
  verifyClient(list[1], callCount2, waitScope);
  verifyClient(list[2], callCount3, waitScope);
730 731

  auto listReader = request.asReader().getList();
732 733 734
  verifyClient(listReader[0], callCount1, waitScope);
  verifyClient(listReader[1], callCount2, waitScope);
  verifyClient(listReader[2], callCount3, waitScope);
735 736

  auto dynamicList = toDynamic(list);
737 738 739
  verifyClient(dynamicList[0].as<DynamicCapability>(), callCount1, waitScope);
  verifyClient(dynamicList[1].as<DynamicCapability>(), callCount2, waitScope);
  verifyClient(dynamicList[2].as<DynamicCapability>(), callCount3, waitScope);
740 741

  auto dynamicListReader = toDynamic(listReader);
742 743 744
  verifyClient(dynamicListReader[0].as<DynamicCapability>(), callCount1, waitScope);
  verifyClient(dynamicListReader[1].as<DynamicCapability>(), callCount2, waitScope);
  verifyClient(dynamicListReader[2].as<DynamicCapability>(), callCount3, waitScope);
745 746
}

747 748 749 750 751 752 753
TEST(Capability, KeywordMethods) {
  // Verify that keywords are only munged where necessary.

  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);
  bool called = false;

Kenton Varda's avatar
Kenton Varda committed
754
  class TestKeywordMethodsImpl final: public test::TestKeywordMethods::Server {
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
  public:
    TestKeywordMethodsImpl(bool& called): called(called) {}

    kj::Promise<void> delete_(DeleteContext context) override {
      called = true;
      return kj::READY_NOW;
    }

  private:
    bool& called;
  };

  test::TestKeywordMethods::Client client = kj::heap<TestKeywordMethodsImpl>(called);
  client.deleteRequest().send().wait(waitScope);

  EXPECT_TRUE(called);
}

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
TEST(Capability, Generics) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  typedef test::TestGenerics<TestAllTypes>::Interface<List<uint32_t>> Interface;
  Interface::Client client = nullptr;

  auto request = client.callRequest();
  request.setBaz("hello");
  initTestMessage(request.initInnerBound().initFoo());
  initTestMessage(request.initInnerUnbound().getFoo().initAs<TestAllTypes>());

  auto promise = request.send().then([](capnp::Response<Interface::CallResults>&& response) {
    // This doesn't actually execute; we're just checking that it compiles.
    List<uint32_t>::Reader qux = response.getQux();
    qux.size();
    checkTestMessage(response.getGen().getFoo());
  }, [](kj::Exception&& e) {});

  promise.wait(waitScope);
}

TEST(Capability, Generics2) {
  MallocMessageBuilder builder;
  auto root = builder.getRoot<test::TestUseGenerics>();

  root.initCap().setFoo(test::TestInterface::Client(nullptr));
}

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
TEST(Capability, ImplicitParams) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  typedef test::TestImplicitMethodParams Interface;
  Interface::Client client = nullptr;

  capnp::Request<Interface::CallParams<Text, TestAllTypes>,
                 test::TestGenerics<Text, TestAllTypes>> request =
      client.callRequest<Text, TestAllTypes>();
  request.setFoo("hello");
  initTestMessage(request.initBar());

  auto promise = request.send()
      .then([](capnp::Response<test::TestGenerics<Text, TestAllTypes>>&& response) {
    // This doesn't actually execute; we're just checking that it compiles.
    Text::Reader text = response.getFoo();
    text.size();
    checkTestMessage(response.getRev().getFoo());
  }, [](kj::Exception&& e) {});

  promise.wait(waitScope);
}

826 827 828
}  // namespace
}  // namespace _
}  // namespace capnp