aboutsummaryrefslogtreecommitdiffstats
path: root/messagebus/src/tests/replygate/replygate.cpp
blob: 56b849833e0412c9aa4cdf00fd304d6920edbc87 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/messagebus/emptyreply.h>
#include <vespa/messagebus/imessagehandler.h>
#include <vespa/messagebus/replygate.h>
#include <vespa/messagebus/routablequeue.h>
#include <vespa/messagebus/testlib/simplemessage.h>
#include <vespa/vespalib/testkit/testapp.h>

using namespace mbus;

namespace {

struct MyGate : public ReplyGate {
    static int ctorCnt;
    static int dtorCnt;

    MyGate(IMessageHandler &sender) : ReplyGate(sender) {
        ++ctorCnt;
    }

    ~MyGate() override {
        ++dtorCnt;
    }
};

int MyGate::ctorCnt = 0;
int MyGate::dtorCnt = 0;

struct MyReply : public EmptyReply {
    static int ctorCnt;
    static int dtorCnt;

    MyReply() : EmptyReply() {
        ++ctorCnt;
    }

    ~MyReply() override {
        ++dtorCnt;
    }
};

int MyReply::ctorCnt = 0;
int MyReply::dtorCnt = 0;

struct MySender : public IMessageHandler {
    // giving a sync reply here is against the API contract, but it is
    // ok for testing.
    void handleMessage(Message::UP msg) override {
        auto reply = std::make_unique<MyReply>();
        msg->swapState(*reply);
        IReplyHandler &handler = reply->getCallStack().pop(*reply);
        handler.handleReply(std::move(reply));
    }
};
}

TEST("replygate_test") {
    {
        RoutableQueue q;
        MySender      sender;
        auto gate = vespalib::make_ref_counted<MyGate>(sender);
        {
            auto msg = std::make_unique<SimpleMessage>("test");
            msg->pushHandler(q);
            gate->handleMessage(std::move(msg));
        }
        EXPECT_TRUE(q.size() == 1);
        EXPECT_TRUE(MyReply::ctorCnt == 1);
        EXPECT_TRUE(MyReply::dtorCnt == 0);
        gate->close();
        {
            auto msg = std::make_unique<SimpleMessage>("test");
            msg->pushHandler(q);
            gate->handleMessage(std::move(msg));
        }
        EXPECT_TRUE(q.size() == 1);
        EXPECT_TRUE(MyReply::ctorCnt == 2);
        EXPECT_TRUE(MyReply::dtorCnt == 1);
        EXPECT_TRUE(MyGate::ctorCnt == 1);
        EXPECT_TRUE(MyGate::dtorCnt == 0);
        gate.reset();
        EXPECT_TRUE(MyGate::ctorCnt == 1);
        EXPECT_TRUE(MyGate::dtorCnt == 1);
    }
    EXPECT_TRUE(MyReply::ctorCnt == 2);
    EXPECT_TRUE(MyReply::dtorCnt == 2);
}

TEST_MAIN() { TEST_RUN_ALL(); }