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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
// Copyright (C) 2023-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Kea Hooks Basic
// Commercial End User License Agreement v2.0. See COPYING file in the premium/
// directory.

/// @file This file contains tests which exercise the attribute,
/// attribute collection and config attribute collection classes.

#include <config.h>

#include <client_exchange.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <testutils/gtest_utils.h>
#include <testutils/test_to_element.h>
#include <attribute_test.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <gtest/gtest.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sstream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

using namespace isc;
using namespace isc::asiolink;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::radius;
using namespace isc::test;
using namespace std;
using namespace std::chrono;

namespace {

// Verify the async constructor.
TEST(TestExchange, async) {
    ExchangePtr exchange;
    IOServicePtr io_service;
    MessagePtr msg;
    Servers servers;

    // No IO service.
    EXPECT_THROW_MSG(exchange.reset(new Exchange(io_service, msg, 0, servers, 0)),
                     BadValue, "null IO service");

    // No message.
    io_service.reset(new IOService());
    EXPECT_THROW_MSG(exchange.reset(new Exchange(io_service, msg, 0, servers, 0)),
                     BadValue, "null request");

    // No servers.
    uint8_t code = PW_ACCOUNTING_REQUEST;
    vector<uint8_t> auth;
    AttributesPtr attrs;
    string secret = "foobar";
    ASSERT_NO_THROW_LOG(msg.reset(new Message(code, 0, auth, secret, attrs)));
    EXPECT_THROW_MSG(exchange.reset(new Exchange(io_service, msg, 0, servers, 0)),
                     BadValue, "no server");

    // No handler.
    ServerPtr server;
    IOAddress addr("127.0.0.1");
    ASSERT_NO_THROW_LOG(server.reset(new Server(addr, 11646, addr, secret, 0)));
    servers.push_back(server);
    EXPECT_THROW_MSG(exchange.reset(new Exchange(io_service, msg, 0, servers, 0)),
                     BadValue, "null handler");

    // No error.
    auto handler = [] (const ExchangePtr&) { };
    ASSERT_NO_THROW_LOG(exchange.reset(new Exchange(io_service, msg, 0,
                                                    servers, handler)));

    // Check exchange.
    ASSERT_TRUE(exchange);
    // getId returns a random value.
    EXPECT_EQ(ERROR_RC, exchange->getRC());
    MessagePtr request = exchange->getRequest();
    ASSERT_TRUE(request);
    EXPECT_EQ(request, msg);
    MessagePtr response = exchange->getResponse();
    EXPECT_FALSE(response);

    // As a best practice, call any remaining handlers.
    io_service->stop();
    io_service->restart();
    try {
        io_service->poll();
    } catch (...) {
        // Ignore exceptions from handlers.
    }
}

// Verify the sync constructor.
TEST(TestExchange, sync) {<--- syntax error
    ExchangePtr exchange;
    MessagePtr msg;
    Servers servers;

    // No message.
    EXPECT_THROW_MSG(exchange.reset(new Exchange(msg, 0, servers)), BadValue,
                     "null request");

    // No servers.
    uint8_t code = PW_ACCESS_REQUEST;
    vector<uint8_t> auth;
    AttributesPtr attrs;
    string secret = "foobar";
    ASSERT_NO_THROW_LOG(msg.reset(new Message(code, 0, auth, secret, attrs)));
    EXPECT_THROW_MSG(exchange.reset(new Exchange(msg, 0, servers)), BadValue,
                     "no server");

    // No error.
    ServerPtr server;
    IOAddress addr("127.0.0.1");
    ASSERT_NO_THROW_LOG(server.reset(new Server(addr, 11645, addr, secret, 0)));
    servers.push_back(server);
    ASSERT_NO_THROW_LOG(exchange.reset(new Exchange(msg, 0, servers)));

    // Check exchange.
    ASSERT_TRUE(exchange);
    // getId returns a random value.
    EXPECT_EQ(ERROR_RC, exchange->getRC());
    MessagePtr request = exchange->getRequest();
    ASSERT_TRUE(request);
    EXPECT_EQ(request, msg);
    MessagePtr response = exchange->getResponse();
    EXPECT_FALSE(response);
}

/// Test Exchange class.
class TestExchange : public Exchange {
public:
    /// Constructor.
    ///
    TestExchange(const asiolink::IOServicePtr& io_service,
                 const MessagePtr& request,
                 unsigned maxretries,
                 const Servers& servers,
                 Exchange::Handler handler)
        : Exchange(io_service, request, maxretries, servers, handler) {
    }

    /// Visible members.
    using Exchange::identifier_;
    using Exchange::sync_;
    using Exchange::started_;
    using Exchange::terminated_;
    using Exchange::rc_;
    using Exchange::start_time_;
    using Exchange::socket_;
    using Exchange::ep_;
    using Exchange::timer_;
    using Exchange::server_;
    using Exchange::idx_;
    using Exchange::sent_;
    using Exchange::received_;
    using Exchange::buffer_;
    using Exchange::size_;
    using Exchange::retries_;
    using Exchange::postponed_;

    /// Visible methods.
    using Exchange::buildRequest;
    using Exchange::open;
    using Exchange::receivedHandler;
};

/// Type of shared pointers to test exchange objets.
typedef boost::shared_ptr<TestExchange> TestExchangePtr;


/// Test fixture for testing code of exchange class.
class ExchangeTest : public radius::test::AttributeTest {
public:
    // Constructor.
    ExchangeTest()
        : radius::test::AttributeTest (), io_service_(new IOService()),
          code_(0), secret_("foobar"), addr_("127.0.0.1"),
          port_(11460), timeout_(10), deadtime_(0), maxretries_(3),
          called_(false),
          handler_([this] (const ExchangePtr&) { called_ = true; }) {
    }

    // Destructor.
    virtual ~ExchangeTest() {
        if (exchange_) {
            exchange_->shutdown();
        }
        servers_.clear();

        // As a best practice, call any remaining handlers before destroying the
        // IO context.
        io_service_->stop();
        io_service_->restart();
        try {
            io_service_->poll();
        } catch (...) {
            // Ignore exceptions from handlers.
        }

        exchange_.reset();
        io_service_.reset();
        request_.reset();
        servers_.clear();
    }

    // Create request.
    void createRequest() {
        ASSERT_NO_THROW_LOG(request_.reset(new Message(code_, 0, auth_,
                                                       secret_, send_attrs_)));
        ASSERT_TRUE(request_);
    }

    // Add server.
    void addServer() {
        ServerPtr server;
        ASSERT_NO_THROW_LOG(server.reset(new Server(addr_, port_, addr_,
                                                    secret_, timeout_,
                                                    deadtime_)));
        ASSERT_TRUE(server);
        servers_.push_back(server);
        ASSERT_FALSE(servers_.empty());
    }

    // Create exchange.
    void createExchange() {
        ASSERT_NO_THROW_LOG(exchange_.reset(new TestExchange(io_service_,
                                                             request_,
                                                             maxretries_,
                                                             servers_,
                                                             handler_)));
        ASSERT_TRUE(exchange_);
    }

    // IO service.
    IOServicePtr io_service_;

    // Request.
    MessagePtr request_;

    // Request code.
    uint8_t code_;

    // Request authenticator.
    vector<uint8_t> auth_;

    // Secret.
    string secret_;

    // Request attributes.
    AttributesPtr send_attrs_;

    // Servers.
    Servers servers_;

    // Address.
    IOAddress addr_;

    // Port.
    uint16_t port_;

    // Timeout.
    unsigned timeout_;

    // Deadtime.
    unsigned deadtime_;

    // Max retries.
    unsigned maxretries_;

    // Terminated flag: true if and only if the handler was called.
    bool called_;

    // Handler.
    Exchange::Handler handler_;

    // Exchange.
    TestExchangePtr exchange_;
};

// Verify the buildRequest method.
TEST_F(ExchangeTest, buildRequest) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // server_ is required.
    EXPECT_THROW_MSG(exchange_->buildRequest(), Unexpected, "no server");
    exchange_->server_ = servers_[0];
    EXPECT_NO_THROW_LOG(exchange_->buildRequest());

    // Check the to-be-sent message.
    MessagePtr msg = exchange_->sent_;
    ASSERT_TRUE(msg);
    EXPECT_EQ(code_, msg->getCode());
    AttributesPtr attrs = msg->getAttributes();
    ASSERT_TRUE(attrs);
    Attributes expected;
    expected.add(Attribute::fromIpAddr(PW_NAS_IP_ADDRESS,
                                       IOAddress("127.0.0.1")));
    EXPECT_TRUE(compare(expected, *attrs))
        << "expected: " << expected.toText() << "\n"
        << "got: " << attrs->toText() << "\n";
}

// Verify the buildRequest method for accounting and IPv6.
TEST_F(ExchangeTest, buildRequest6) {
    code_ = PW_ACCOUNTING_REQUEST;
    createRequest();
    addr_ = IOAddress("::1");
    addServer();
    createExchange();

    // server_ is required.
    EXPECT_THROW_MSG(exchange_->buildRequest(), Unexpected, "no server");
    exchange_->server_ = servers_[0];
    EXPECT_NO_THROW_LOG(exchange_->buildRequest());

    // Check the to-be-sent message.
    MessagePtr msg = exchange_->sent_;
    ASSERT_TRUE(msg);
    EXPECT_EQ(code_, msg->getCode());
    AttributesPtr attrs = msg->getAttributes();
    ASSERT_TRUE(attrs);
    Attributes expected;
    // Assume that there is less than one second delay in the test.
    expected.add(Attribute::fromInt(PW_ACCT_DELAY_TIME, 0));
    expected.add(Attribute::fromIpv6Addr(PW_NAS_IPV6_ADDRESS, addr_));
    EXPECT_TRUE(compare(expected, *attrs))
        << "expected: " << expected.toText() << "\n"
        << "got: " << attrs->toText() << "\n";
}

// Verify exchange initial state and start.
TEST_F(ExchangeTest, start) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Check initial state.
    ASSERT_FALSE(exchange_->identifier_.empty());
    ASSERT_FALSE(exchange_->sync_);
    ASSERT_FALSE(exchange_->server_);
    ASSERT_EQ(0, exchange_->idx_);
    ASSERT_FALSE(exchange_->started_);
    ASSERT_FALSE(exchange_->terminated_);
    ASSERT_EQ(ERROR_RC, exchange_->rc_);
    ASSERT_FALSE(exchange_->socket_);
    ASSERT_FALSE(exchange_->ep_);
    ASSERT_FALSE(exchange_->timer_);
    ASSERT_FALSE(exchange_->server_);
    ASSERT_EQ(0, exchange_->idx_);
    ASSERT_FALSE(exchange_->sent_);
    ASSERT_FALSE(exchange_->received_);
    ASSERT_TRUE(exchange_->buffer_.empty());
    ASSERT_EQ(0, exchange_->size_);
    ASSERT_EQ(0, exchange_->retries_);
    ASSERT_TRUE(exchange_->postponed_.empty());
    ASSERT_FALSE(called_);

    ASSERT_NO_THROW_LOG(exchange_->start());
    EXPECT_TRUE(exchange_->started_);
    ASSERT_NO_THROW_LOG(exchange_->shutdown());
}

// Verify open in the initial case.
TEST_F(ExchangeTest, openInit) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Check initial state.
    EXPECT_FALSE(exchange_->server_);
    EXPECT_EQ(0, exchange_->idx_);

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_TRUE(exchange_->server_);
    EXPECT_EQ(servers_[0], exchange_->server_);
    EXPECT_EQ(0, exchange_->idx_);
    EXPECT_TRUE(exchange_->sent_);
    ASSERT_TRUE(exchange_->ep_);
    EXPECT_TRUE(exchange_->timer_);
    EXPECT_EQ(addr_.toText(), exchange_->ep_->getAddress().toText());
    EXPECT_EQ(port_, exchange_->ep_->getPort());
    EXPECT_TRUE(exchange_->socket_);
    EXPECT_FALSE(exchange_->buffer_.empty());
    EXPECT_EQ(code_, exchange_->buffer_[0]);
    EXPECT_LT(AUTH_HDR_LEN, exchange_->size_);
    EXPECT_EQ(exchange_->size_, exchange_->buffer_.size());
    EXPECT_FALSE(called_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was not called.
    EXPECT_FALSE(called_);
}

// Verify open with next server being null.
TEST_F(ExchangeTest, openNullServer) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    ServerPtr null_server;
    servers_.push_back(null_server);
    createExchange();

    // Call open.
    EXPECT_THROW_MSG(exchange_->open(), Unexpected, "null server at 0");
}

// Verify open with next server in hold-down state.
TEST_F(ExchangeTest, openPostpone) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    deadtime_ = 60;
    addServer();
    createExchange();

    // Put the server in hold-down.
    ServerPtr server = servers_[0];
    ASSERT_TRUE(server);
    server->setDeadtimeEnd(steady_clock().now() + seconds(deadtime_));

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_EQ(1, exchange_->idx_);
    ASSERT_EQ(1, exchange_->postponed_.size());
    EXPECT_EQ(0, exchange_->postponed_.front());
}

// Verify open in second pass with no postponed servers.
TEST_F(ExchangeTest, openNoPostponed) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Put the exchange in the second pass,
    exchange_->idx_ = 1;
    ASSERT_EQ(servers_.size(), exchange_->idx_);
    ASSERT_TRUE(exchange_->postponed_.empty());

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_EQ(1, exchange_->idx_);
    EXPECT_FALSE(exchange_->terminated_);
    EXPECT_FALSE(called_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was called.
    EXPECT_TRUE(exchange_->terminated_);
    EXPECT_TRUE(called_);
}

// Verify open in second pass with bad postponed index.
TEST_F(ExchangeTest, openBadPostponed) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Put the exchange in the second pass,
    exchange_->idx_ = 1;
    ASSERT_EQ(servers_.size(), exchange_->idx_);

    // Add a bad index in the postponed list.
    exchange_->postponed_.push_back(10);

    // Call open.
    EXPECT_THROW_MSG(exchange_->open(), Unexpected,
                     "out of range server 10 >= 1");
}

// Verify open in second pass with null postponed server.
TEST_F(ExchangeTest, openNullPostponed) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    ServerPtr null_server;
    servers_.push_back(null_server);
    createExchange();

    // Put the exchange in the second pass,
    exchange_->idx_ = 1;
    ASSERT_EQ(servers_.size(), exchange_->idx_);

    // Add the null server to the postponed list.
    exchange_->postponed_.push_back(0);

    // Call open.
    EXPECT_THROW_MSG(exchange_->open(), Unexpected, "null server at 0");
}

// Verify open in second pass.
TEST_F(ExchangeTest, openPostponed) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Put the exchange in the second pass,
    exchange_->idx_ = 1;
    ASSERT_EQ(servers_.size(), exchange_->idx_);

    // Add the server to the postponed list.
    exchange_->postponed_.push_back(0);

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_TRUE(exchange_->server_);
    EXPECT_EQ(servers_[0], exchange_->server_);
    EXPECT_EQ(1, exchange_->idx_);
    EXPECT_TRUE(exchange_->sent_);
    EXPECT_TRUE(exchange_->timer_);
    ASSERT_TRUE(exchange_->ep_);
    EXPECT_EQ(addr_.toText(), exchange_->ep_->getAddress().toText());
    EXPECT_EQ(port_, exchange_->ep_->getPort());
    EXPECT_TRUE(exchange_->socket_);
    EXPECT_FALSE(exchange_->buffer_.empty());
    EXPECT_EQ(code_, exchange_->buffer_[0]);
    EXPECT_LT(AUTH_HDR_LEN, exchange_->size_);
    EXPECT_EQ(exchange_->size_, exchange_->buffer_.size());
    EXPECT_FALSE(called_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was not called.
    EXPECT_FALSE(called_);
}

// Verify open with error in send.
TEST_F(ExchangeTest, openSendError) {
    // Make the request encode to fail with too large message.
    send_attrs_.reset(new Attributes());
    string msg = "too too too too too too too too too too  too too ";
    msg += "too too too too too too too too too too  too too ";
    msg += "too too too too too too too too too too  too too ";
    msg += "too too too too too too too too too too  too too ";
    msg += "too too too too too too too too too too  too too long!!!";
    // Hard limit is 253 so be close but lower...
    EXPECT_EQ(252, msg.size());
    AttributePtr attr = Attribute::fromString(PW_REPLY_MESSAGE, msg);
    ASSERT_TRUE(attr);
    for (size_t i = 0; i < 16; ++i) {
        send_attrs_->add(attr);
    }
    send_attrs_->add(Attribute::fromString(PW_USER_PASSWORD, "foobar"));

    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_TRUE(exchange_->server_);
    EXPECT_EQ(servers_[0], exchange_->server_);
    EXPECT_EQ(0, exchange_->idx_);
    EXPECT_TRUE(exchange_->sent_);
    EXPECT_FALSE(exchange_->ep_);
    EXPECT_FALSE(exchange_->timer_);
    EXPECT_FALSE(exchange_->socket_);
    EXPECT_EQ(0, exchange_->retries_);
    EXPECT_EQ(ERROR_RC, exchange_->rc_);
}

// Verify open puts on timeout a server on hold-down.
TEST_F(ExchangeTest, openHoldsDown) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    deadtime_ = 60;
    addServer();
    createExchange();

    // Set the exchange on last retry.
    ServerPtr server = servers_[0];
    exchange_->server_ = server;
    exchange_->retries_ = maxretries_;
    server->setDeadtimeEnd(exchange_->start_time_ - seconds(10));

    // Set the error code to timeout.
    exchange_->rc_ = TIMEOUT_RC;

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check server.
    auto dead_time_end = server->getDeadtimeEnd();
    EXPECT_EQ(exchange_->start_time_ + seconds(deadtime_), dead_time_end);
}

// Verify open tries next server after last retry.
TEST_F(ExchangeTest, openNextServer) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    // Add a second server.
    addServer();
    createExchange();

    // Set the exchange on last retry.
    exchange_->server_ = servers_[0];
    exchange_->retries_ = maxretries_;

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check next state.
    EXPECT_EQ(0, exchange_->retries_);
    EXPECT_FALSE(exchange_->server_);
    EXPECT_FALSE(exchange_->ep_);
    EXPECT_EQ(1, exchange_->idx_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was not called.
    EXPECT_FALSE(called_);
}

// Verify open terminates after the last retry of the last server.
TEST_F(ExchangeTest, openLastServer) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    // Add a second server.
    addServer();
    createExchange();

    // Set the exchange on last retry of last server.
    exchange_->server_ = servers_[1];
    exchange_->retries_ = maxretries_;
    exchange_->idx_ = 1;
    ASSERT_EQ(servers_.size(), exchange_->idx_ + 1);
    ASSERT_TRUE(exchange_->postponed_.empty());

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_EQ(2, exchange_->idx_);
    EXPECT_EQ(servers_.size(), exchange_->idx_);
    EXPECT_FALSE(exchange_->terminated_);
    EXPECT_FALSE(called_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was called.
    EXPECT_TRUE(exchange_->terminated_);
    EXPECT_TRUE(called_);
}

// Verify open in second pass tries next postponed server after last retry.
TEST_F(ExchangeTest, openNextPostponedServer) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    // Add a second server.
    addServer();
    createExchange();

    // Put the exchange in the second pass,
    exchange_->idx_ = 2;
    ASSERT_EQ(servers_.size(), exchange_->idx_);

    // Add servers to the postponed list.
    exchange_->postponed_.push_back(0);
    exchange_->postponed_.push_back(1);
    ASSERT_EQ(2, exchange_->postponed_.size());

    // Set the exchange on last retry.
    exchange_->server_ = servers_[0];
    exchange_->retries_ = maxretries_;

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check next state.
    EXPECT_EQ(0, exchange_->retries_);
    EXPECT_FALSE(exchange_->server_);
    EXPECT_FALSE(exchange_->ep_);
    EXPECT_EQ(2, exchange_->idx_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was not called.
    EXPECT_FALSE(called_);
}

// Verify open in second pass terminates after the last retry of the last
// postponed server.
TEST_F(ExchangeTest, openLastPostponedServer) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    // Add a second server.
    addServer();
    createExchange();

    // Put the exchange in the second pass,
    exchange_->idx_ = 2;
    ASSERT_EQ(servers_.size(), exchange_->idx_);
    exchange_->postponed_.push_back(0);

    // Set the exchange on last retry of last server.
    exchange_->server_ = servers_[0];
    exchange_->retries_ = maxretries_;
    ASSERT_EQ(1, exchange_->postponed_.size());

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_EQ(2, exchange_->idx_);
    EXPECT_EQ(servers_.size(), exchange_->idx_);
    EXPECT_FALSE(exchange_->terminated_);
    EXPECT_FALSE(called_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was called.
    EXPECT_TRUE(exchange_->terminated_);
    EXPECT_TRUE(called_);
}

// Verify open retries.
TEST_F(ExchangeTest, openRetry) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Set the exchange to the first server.
    exchange_->server_ = servers_[0];

    // Set the endpoint.
    exchange_->ep_.reset(new UDPEndpoint(addr_, port_));

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_EQ(1, exchange_->retries_);
    EXPECT_TRUE(exchange_->sent_);
    EXPECT_TRUE(exchange_->timer_);
    ASSERT_TRUE(exchange_->ep_);
    EXPECT_EQ(addr_.toText(), exchange_->ep_->getAddress().toText());
    EXPECT_EQ(port_, exchange_->ep_->getPort());
    EXPECT_TRUE(exchange_->socket_);
    EXPECT_FALSE(exchange_->buffer_.empty());
    EXPECT_EQ(code_, exchange_->buffer_[0]);
    EXPECT_LT(AUTH_HDR_LEN, exchange_->size_);
    EXPECT_EQ(exchange_->size_, exchange_->buffer_.size());
    EXPECT_FALSE(called_);

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was not called.
    EXPECT_FALSE(called_);
}

// Verify open with error in retry.
TEST_F(ExchangeTest, openRetryError) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Set the exchange to the first server.
    exchange_->server_ = servers_[0];
    ASSERT_FALSE(exchange_->ep_);

    // Call open.
    ASSERT_NO_THROW_LOG(exchange_->open());

    // Check new state.
    EXPECT_EQ(1, exchange_->retries_);
    EXPECT_FALSE(exchange_->sent_);
    EXPECT_FALSE(exchange_->timer_);
    EXPECT_FALSE(exchange_->socket_);
    EXPECT_EQ(ERROR_RC, exchange_->rc_);
}

// Verify receivedHandler with null exchange.
TEST_F(ExchangeTest, receivedHandlerNull) {
    auto no_error = boost::system::error_code();
    EXPECT_THROW_MSG(TestExchange::receivedHandler(0, no_error, 0), Unexpected,
                     "null exchange in receivedHandler");
}

// Verify receivedHandler on error.
TEST_F(ExchangeTest, receivedHandlerError) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    addServer();
    createExchange();

    // Call the handler with an error.
    auto ec = boost::asio::error::timed_out;
    EXPECT_NO_THROW_LOG(TestExchange::receivedHandler(exchange_, ec, 0));

    // Poll the I/O service.
    ASSERT_NO_THROW_LOG(io_service_->poll());

    // Terminate was not called.
    EXPECT_FALSE(called_);
}

// Verify receivedHandler removes servers from hold-down.
TEST_F(ExchangeTest, receivedHandlerNoHoldDown) {
    code_ = PW_ACCESS_REQUEST;
    createRequest();
    deadtime_ = 60;
    addServer();
    createExchange();

    // Put the server in hold-down.
    ServerPtr server = servers_[0];
    server->setDeadtimeEnd(steady_clock().now() + seconds(deadtime_));
    exchange_->server_ = server;

    // Call the handler.
    auto no_error = boost::system::error_code();
    exchange_->sent_ = request_;
    EXPECT_NO_THROW_LOG(TestExchange::receivedHandler(exchange_, no_error, 0));

    // Check the server.
    EXPECT_EQ(exchange_->start_time_, server->getDeadtimeEnd());
}

} // end of anonymous namespace