Skip to content

Commit 2e222d9

Browse files
michalpasztamobicaadbridge
authored andcommitted
test for InternetSocket::close blocking
Close should not take place in case there is someone reading or writing to the socket.
1 parent 1655c37 commit 2e222d9

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

UNITTESTS/features/netsocket/InternetSocket/test_InternetSocket.cpp

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818
#include "gtest/gtest.h"
1919
#include "features/netsocket/InternetSocket.h"
2020
#include "NetworkStack_stub.h"
21+
#include <future>
22+
#include <thread>
23+
#include <chrono>
2124

2225
extern std::list<uint32_t> eventFlagsStubNextRetval;
2326

@@ -155,20 +158,26 @@ TEST_F(TestInternetSocket, close_during_read)
155158
{
156159
stack.return_value = NSAPI_ERROR_OK;
157160
socket->open((NetworkStack *)&stack);
158-
// when c++11 is available use something like the code below to test the blocking behavior
159-
// socket->add_reader();
160-
// std::async(c[](){std::this_thread::sleep_for(1ms); socket->rem_reader()});
161+
// Simulate the blocking behavior by adding a reader.
162+
socket->add_reader();
163+
// The reader will be removed after we attempt to close the socket.
164+
auto delay = std::chrono::milliseconds(2);
165+
auto fut = std::async(std::launch::async, [&](){std::this_thread::sleep_for(delay); socket->rem_reader();});
166+
167+
// close() will block until the other thread calls rem_reader()
168+
auto start = std::chrono::system_clock::now();
161169
EXPECT_EQ(socket->close(), NSAPI_ERROR_OK);
170+
auto end = std::chrono::system_clock::now();
171+
172+
auto diff = end - start;
173+
EXPECT_LE(delay, end - start);
162174
}
163175

164176
TEST_F(TestInternetSocket, modify_multicast_group)
165177
{
166178
SocketAddress a("127.0.0.1", 1024);
167179
stack.return_value = NSAPI_ERROR_OK;
168180
socket->open((NetworkStack *)&stack);
169-
// when c++11 is available use something like the code below to test the blocking behavior
170-
// socket->add_reader();
171-
// std::async(c[](){std::this_thread::sleep_for(1ms); socket->rem_reader()});
172181
EXPECT_EQ(socket->join_multicast_group(a), NSAPI_ERROR_UNSUPPORTED);
173182
EXPECT_EQ(socket->leave_multicast_group(a), NSAPI_ERROR_UNSUPPORTED);
174183
}

0 commit comments

Comments
 (0)