Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / messaging / tests / TestChannel.cpp
1 /*
2  *
3  *    Copyright (c) 2021 Project CHIP Authors
4  *    All rights reserved.
5  *
6  *    Licensed under the Apache License, Version 2.0 (the "License");
7  *    you may not use this file except in compliance with the License.
8  *    You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *    Unless required by applicable law or agreed to in writing, software
13  *    distributed under the License is distributed on an "AS IS" BASIS,
14  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *    See the License for the specific language governing permissions and
16  *    limitations under the License.
17  */
18
19 /**
20  *    @file
21  *      This file implements unit tests for the ExchangeManager implementation.
22  */
23
24 #include "TestMessagingLayer.h"
25
26 #include <core/CHIPCore.h>
27 #include <messaging/ExchangeContext.h>
28 #include <messaging/ExchangeMgr.h>
29 #include <messaging/Flags.h>
30 #include <messaging/tests/MessagingContext.h>
31 #include <protocols/Protocols.h>
32 #include <support/CHIPMem.h>
33 #include <support/CodeUtils.h>
34 #include <transport/SecureSessionMgr.h>
35 #include <transport/TransportMgr.h>
36
37 #include <nlbyteorder.h>
38 #include <nlunit-test.h>
39
40 #include <errno.h>
41 #include <utility>
42
43 namespace {
44
45 using namespace chip;
46 using namespace chip::Inet;
47 using namespace chip::Transport;
48 using namespace chip::Messaging;
49
50 using TestContext = chip::Test::MessagingContext;
51
52 TestContext sContext;
53
54 class LoopbackTransport : public Transport::Base
55 {
56 public:
57     /// Transports are required to have a constructor that takes exactly one argument
58     CHIP_ERROR Init(const char * unused) { return CHIP_NO_ERROR; }
59
60     CHIP_ERROR SendMessage(const PacketHeader & header, const PeerAddress & address, System::PacketBufferHandle msgBuf) override
61     {
62         HandleMessageReceived(header, address, std::move(msgBuf));
63         return CHIP_NO_ERROR;
64     }
65
66     bool CanSendToPeer(const PeerAddress & address) override { return true; }
67 };
68
69 TransportMgr<LoopbackTransport> gTransportMgr;
70
71 class MockAppDelegate : public ExchangeDelegate
72 {
73 public:
74     void OnMessageReceived(ExchangeContext * ec, const PacketHeader & packetHeader, const PayloadHeader & payloadHeader,
75                            System::PacketBufferHandle buffer) override
76     {
77         IsOnMessageReceivedCalled = true;
78     }
79
80     void OnResponseTimeout(ExchangeContext * ec) override {}
81
82     bool IsOnMessageReceivedCalled = false;
83 };
84
85 class MockChannelDelegate : public ChannelDelegate
86 {
87 public:
88     ~MockChannelDelegate() override {}
89
90     void OnEstablished() override {}
91     void OnClosed() override {}
92     void OnFail(CHIP_ERROR err) override {}
93 };
94
95 void CheckExchangeChannels(nlTestSuite * inSuite, void * inContext)
96 {
97     TestContext & ctx = *reinterpret_cast<TestContext *>(inContext);
98
99     // create unsolicited exchange
100     MockAppDelegate mockUnsolicitedAppDelegate;
101     CHIP_ERROR err = ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::Id(VendorId::Common, 0x0001),
102                                                                                        0x0001, &mockUnsolicitedAppDelegate);
103     NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);
104
105     // create the channel
106     ChannelBuilder channelBuilder;
107     channelBuilder.SetPeerNodeId(ctx.GetDestinationNodeId()).SetForcePeerAddress(ctx.GetAddress());
108     MockChannelDelegate channelDelegate;
109     auto channelHandle = ctx.GetExchangeManager().EstablishChannel(channelBuilder, &channelDelegate);
110     return;
111
112 #if 0
113     // TODO: complete test when CASESession is completed
114     // wait for channel establishment
115     ctx.DriveIOUntil(1000, [&] { return channelHandle.GetState() == ChannelState::kReady; });
116     NL_TEST_ASSERT(inSuite, channelHandle.GetState() == ChannelState::kReady);
117
118     MockAppDelegate mockAppDelegate;
119     ExchangeContext * ec1 = channelHandle.NewExchange(&mockAppDelegate);
120
121     // send a malicious packet
122     ec1->SendMessage(0x0001, 0x0002, System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize),
123                      SendFlags(Messaging::SendMessageFlags::kNone));
124     NL_TEST_ASSERT(inSuite, !mockUnsolicitedAppDelegate.IsOnMessageReceivedCalled);
125
126     // send a good packet
127     ec1->SendMessage(0x0001, 0x0001, System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize),
128                      SendFlags(Messaging::SendMessageFlags::kNone));
129     NL_TEST_ASSERT(inSuite, mockUnsolicitedAppDelegate.IsOnMessageReceivedCalled);
130
131     ec1->Close();
132     channelHandle.Release();
133 #endif
134 }
135
136 // Test Suite
137
138 /**
139  *  Test Suite that lists all the test functions.
140  */
141 // clang-format off
142 const nlTest sTests[] =
143 {
144     NL_TEST_DEF("Test Channel/Exchange",               CheckExchangeChannels),
145
146     NL_TEST_SENTINEL()
147 };
148 // clang-format on
149
150 int Initialize(void * aContext);
151 int Finalize(void * aContext);
152
153 // clang-format off
154 nlTestSuite sSuite =
155 {
156     "Test-CHIP-ExchangeManager",
157     &sTests[0],
158     Initialize,
159     Finalize
160 };
161 // clang-format on
162
163 /**
164  *  Initialize the test suite.
165  */
166 int Initialize(void * aContext)
167 {
168     CHIP_ERROR err = chip::Platform::MemoryInit();
169     if (err != CHIP_NO_ERROR)
170         return FAILURE;
171
172     err = gTransportMgr.Init("LOOPBACK");
173     if (err != CHIP_NO_ERROR)
174         return FAILURE;
175
176     err = reinterpret_cast<TestContext *>(aContext)->Init(&sSuite, &gTransportMgr);
177     return (err == CHIP_NO_ERROR) ? SUCCESS : FAILURE;
178 }
179
180 /**
181  *  Finalize the test suite.
182  */
183 int Finalize(void * aContext)
184 {
185     CHIP_ERROR err = reinterpret_cast<TestContext *>(aContext)->Shutdown();
186     chip::Platform::MemoryShutdown();
187     return (err == CHIP_NO_ERROR) ? SUCCESS : FAILURE;
188 }
189
190 } // namespace
191
192 /**
193  *  Main
194  */
195 int TestChannel()
196 {
197     // Run test suit against one context
198     nlTestRunner(&sSuite, &sContext);
199
200     return (nlTestRunnerStats(&sSuite));
201 }