Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / transport / raw / tests / TestUDP.cpp
1 /*
2  *
3  *    Copyright (c) 2020-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 UdpTransport implementation.
22  */
23
24 #include "NetworkTestHelpers.h"
25
26 #include <core/CHIPCore.h>
27 #include <support/CodeUtils.h>
28 #include <support/UnitTestRegistration.h>
29 #include <transport/TransportMgr.h>
30 #include <transport/raw/UDP.h>
31
32 #include <nlbyteorder.h>
33 #include <nlunit-test.h>
34
35 #include <errno.h>
36
37 using namespace chip;
38 using namespace chip::Inet;
39
40 static int Initialize(void * aContext);
41 static int Finalize(void * aContext);
42
43 namespace {
44
45 constexpr NodeId kSourceNodeId      = 123654;
46 constexpr NodeId kDestinationNodeId = 111222333;
47 constexpr uint32_t kMessageId       = 18;
48
49 using TestContext = chip::Test::IOContext;
50 TestContext sContext;
51
52 const char PAYLOAD[]        = "Hello!";
53 int ReceiveHandlerCallCount = 0;
54
55 class MockTransportMgrDelegate : public TransportMgrDelegate
56 {
57 public:
58     MockTransportMgrDelegate(nlTestSuite * inSuite) : mSuite(inSuite) {}
59     ~MockTransportMgrDelegate() override {}
60
61     void OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source,
62                            System::PacketBufferHandle msgBuf) override
63     {
64         NL_TEST_ASSERT(mSuite, header.GetSourceNodeId() == Optional<NodeId>::Value(kSourceNodeId));
65         NL_TEST_ASSERT(mSuite, header.GetDestinationNodeId() == Optional<NodeId>::Value(kDestinationNodeId));
66         NL_TEST_ASSERT(mSuite, header.GetMessageId() == kMessageId);
67
68         size_t data_len = msgBuf->DataLength();
69         int compare     = memcmp(msgBuf->Start(), PAYLOAD, data_len);
70         NL_TEST_ASSERT(mSuite, compare == 0);
71
72         ReceiveHandlerCallCount++;
73     }
74
75 private:
76     nlTestSuite * mSuite;
77 };
78
79 } // namespace
80
81 /////////////////////////// Init test
82
83 void CheckSimpleInitTest(nlTestSuite * inSuite, void * inContext, Inet::IPAddressType type)
84 {
85     TestContext & ctx = *reinterpret_cast<TestContext *>(inContext);
86
87     Transport::UDP udp;
88
89     CHIP_ERROR err = udp.Init(Transport::UdpListenParameters(&ctx.GetInetLayer()).SetAddressType(type));
90
91     NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);
92 }
93
94 #if INET_CONFIG_ENABLE_IPV4
95 void CheckSimpleInitTest4(nlTestSuite * inSuite, void * inContext)
96 {
97     CheckSimpleInitTest(inSuite, inContext, kIPAddressType_IPv4);
98 }
99 #endif
100
101 void CheckSimpleInitTest6(nlTestSuite * inSuite, void * inContext)
102 {
103     CheckSimpleInitTest(inSuite, inContext, kIPAddressType_IPv6);
104 }
105
106 /////////////////////////// Messaging test
107
108 void CheckMessageTest(nlTestSuite * inSuite, void * inContext, const IPAddress & addr)
109 {
110     TestContext & ctx = *reinterpret_cast<TestContext *>(inContext);
111
112     uint16_t payload_len = sizeof(PAYLOAD);
113
114     chip::System::PacketBufferHandle buffer = chip::System::PacketBufferHandle::NewWithData(PAYLOAD, payload_len);
115     NL_TEST_ASSERT(inSuite, !buffer.IsNull());
116
117     CHIP_ERROR err = CHIP_NO_ERROR;
118
119     Transport::UDP udp;
120
121     err = udp.Init(Transport::UdpListenParameters(&ctx.GetInetLayer()).SetAddressType(addr.Type()));
122     NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);
123
124     MockTransportMgrDelegate gMockTransportMgrDelegate(inSuite);
125     TransportMgrBase gTransportMgrBase;
126     gTransportMgrBase.SetSecureSessionMgr(&gMockTransportMgrDelegate);
127     gTransportMgrBase.SetRendezvousSession(&gMockTransportMgrDelegate);
128     gTransportMgrBase.Init(&udp);
129
130     ReceiveHandlerCallCount = 0;
131
132     PacketHeader header;
133     header.SetSourceNodeId(kSourceNodeId).SetDestinationNodeId(kDestinationNodeId).SetMessageId(kMessageId);
134
135     // Should be able to send a message to itself by just calling send.
136     err = udp.SendMessage(header, Transport::PeerAddress::UDP(addr), std::move(buffer));
137     if (err == System::MapErrorPOSIX(EADDRNOTAVAIL))
138     {
139         // TODO(#2698): the underlying system does not support IPV6. This early return
140         // should be removed and error should be made fatal.
141         printf("%s:%u: System does NOT support IPV6.\n", __FILE__, __LINE__);
142         return;
143     }
144
145     NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);
146
147     ctx.DriveIOUntil(1000 /* ms */, []() { return ReceiveHandlerCallCount != 0; });
148
149     NL_TEST_ASSERT(inSuite, ReceiveHandlerCallCount == 1);
150 }
151
152 void CheckMessageTest4(nlTestSuite * inSuite, void * inContext)
153 {
154     IPAddress addr;
155     IPAddress::FromString("127.0.0.1", addr);
156     CheckMessageTest(inSuite, inContext, addr);
157 }
158
159 void CheckMessageTest6(nlTestSuite * inSuite, void * inContext)
160 {
161     IPAddress addr;
162     IPAddress::FromString("::1", addr);
163     CheckMessageTest(inSuite, inContext, addr);
164 }
165
166 // Test Suite
167
168 /**
169  *  Test Suite that lists all the test functions.
170  */
171 // clang-format off
172 static const nlTest sTests[] =
173 {
174 #if INET_CONFIG_ENABLE_IPV4
175     NL_TEST_DEF("Simple Init Test IPV4",   CheckSimpleInitTest4),
176     NL_TEST_DEF("Message Self Test IPV4",  CheckMessageTest4),
177 #endif
178
179     NL_TEST_DEF("Simple Init Test IPV6",   CheckSimpleInitTest6),
180     NL_TEST_DEF("Message Self Test IPV6",  CheckMessageTest6),
181
182     NL_TEST_SENTINEL()
183 };
184 // clang-format on
185
186 // clang-format off
187 static nlTestSuite sSuite =
188 {
189     "Test-CHIP-Udp",
190     &sTests[0],
191     Initialize,
192     Finalize
193 };
194 // clang-format on
195
196 /**
197  *  Initialize the test suite.
198  */
199 static int Initialize(void * aContext)
200 {
201     CHIP_ERROR err = reinterpret_cast<TestContext *>(aContext)->Init(&sSuite);
202     return (err == CHIP_NO_ERROR) ? SUCCESS : FAILURE;
203 }
204
205 /**
206  *  Finalize the test suite.
207  */
208 static int Finalize(void * aContext)
209 {
210     CHIP_ERROR err = reinterpret_cast<TestContext *>(aContext)->Shutdown();
211     return (err == CHIP_NO_ERROR) ? SUCCESS : FAILURE;
212 }
213
214 int TestUDP()
215 {
216     // Run test suit against one context
217     nlTestRunner(&sSuite, &sContext);
218
219     return (nlTestRunnerStats(&sSuite));
220 }
221
222 CHIP_REGISTER_TEST_SUITE(TestUDP);