-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.cpp
More file actions
127 lines (104 loc) · 2.56 KB
/
test.cpp
File metadata and controls
127 lines (104 loc) · 2.56 KB
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
#include "gtest/gtest.h"
#include <chrono>
#include <exception>
#include <stdexcept>
#include <thread>
#include "../include/siddiqsoft/RunOnEnd.hpp"
TEST(examples, Example1)
{
bool passTest {false};
try
{
// Use initializer list-style instantiation; we do not allow move/assignment construction.
// Note that the `()` is not required when the lambda/function takes no argument.
siddiqsoft::RunOnEnd roe {[&passTest]
{
// Runs when this scope ends
passTest = true;
}};
}
catch (...)
{
EXPECT_TRUE(false); // if we throw then the test fails.
}
// Iff the lambda runs, it should be true
EXPECT_TRUE(passTest);
}
TEST(examples, Example2)
{
bool passTest {false};
uint64_t ttx {0};
try
{
siddiqsoft::RunOnEnd roe {[&passTest, &ttx]
{
// Runs when this scope ends
passTest = true;
ttx = std::chrono::system_clock::now().time_since_epoch().count();
}};
}
catch (...)
{
EXPECT_TRUE(false); // if we throw then the test fails.
}
// Iff the lambda runs, it should be true
EXPECT_TRUE(passTest);
EXPECT_NE(0, ttx);
}
#if defined(WIN32) || defined(WIN64)
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")
TEST(examples, Example3)
{
bool passTest {false};
struct UseWinsock : private siddiqsoft::RunOnEnd
{
UseWinsock() noexcept
: m_rc(E_FAIL)
, siddiqsoft::RunOnEnd(
[&]()
{
if (m_rc == S_OK) std::cerr << "Invoke WSACleanup():" << WSACleanup() << std::endl;
})
{
ZeroMemory(&m_wsaData, sizeof(m_wsaData));
m_rc = WSAStartup(MAKEWORD(2, 2), &m_wsaData);
m_rc = (m_rc == 0) ? S_OK : WSAGetLastError();
std::cerr << "WSAStartup(): " << m_rc << std::endl;
}
operator bool() { return (m_rc == S_OK); }
private:
int m_rc;
WSADATA m_wsaData;
};
try
{
UseWinsock ws;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
catch (...)
{
EXPECT_TRUE(false); // if we throw then the test fails.
}
// Iff the lambda runs we should have called WSACleanup in which case
// the second invocation should fail.
EXPECT_EQ(SOCKET_ERROR, WSACleanup());
EXPECT_EQ(WSANOTINITIALISED, GetLastError());
}
#include <winsock.h>
#endif
TEST(examples, Example4)
{
bool passTest = false;
try
{
siddiqsoft::RunOnEnd roe {[&passTest] { passTest = true; }};
// Throw deliberately!
throw std::runtime_error("Throw so we check for success.");
}
catch (std::runtime_error&)
{
// We throw inside and we expect that the ROE is invoked.
EXPECT_TRUE(passTest);
}
}