-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathBasicFuncTests.cpp
1574 lines (1371 loc) · 53.8 KB
/
BasicFuncTests.cpp
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// clang-format off
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
#include "mat/config.h"
#ifdef HAVE_MAT_DEFAULT_HTTP_CLIENT
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#endif
#include "common/Common.hpp"
#include "common/HttpServer.hpp"
#include "utils/Utils.hpp"
#include "api/LogManagerImpl.hpp"
#include "bond/All.hpp"
#include "CsProtocol_types.hpp"
#include "bond/generated/CsProtocol_readers.hpp"
#include "LogManager.hpp"
#include "CompliantByDefaultFilterApi.hpp"
#include <fstream>
#include <atomic>
#include <assert.h>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <vector>
#include "PayloadDecoder.hpp"
using namespace testing;
using namespace MAT;
// LOGMANAGER_INSTANCE
namespace PAL_NS_BEGIN
{
class PALTest
{
public:
static long GetPalRefCount()
{
return PAL::GetPAL().m_palStarted.load();
};
static std::shared_ptr<ITaskDispatcher> GetTaskDispatcher()
{
return PAL::GetPAL().m_taskDispatcher;
};
static std::shared_ptr<ISystemInformation> GetSystemInformation()
{
return PAL::GetPAL().m_SystemInformation;
}
static std::shared_ptr<INetworkInformation> GetNetworkInformation()
{
return PAL::GetPAL().m_NetworkInformation;
}
static std::shared_ptr<IDeviceInformation> GetDeviceInformation()
{
return PAL::GetPAL().m_DeviceInformation;
}
};
}
PAL_NS_END;
namespace MAT_NS_BEGIN
{
class ModuleA : public ILogConfiguration
{
};
class LogManagerA : public LogManagerBase<ModuleA>
{
};
class ModuleB : public ILogConfiguration
{
};
class LogManagerB : public LogManagerBase<ModuleB>
{
};
// Two distinct LogManagerX 'singelton' instances
DEFINE_LOGMANAGER(LogManagerB, ModuleB);
DEFINE_LOGMANAGER(LogManagerA, ModuleA);
}
MAT_NS_END
char const* const TEST_STORAGE_FILENAME = "BasicFuncTests.db";
// 1DSCppSdktest sandbox key
#define TEST_TOKEN "7c8b1796cbc44bd5a03803c01c2b9d61-b6e370dd-28d9-4a52-9556-762543cf7aa7-6991"
#define KILLED_TOKEN "deadbeefdeadbeefdeadbeefdeadbeef-c2d379e0-4408-4325-9b4d-2a7d78131e14-7322"
#define HTTP_PORT 19000
#undef LOCKGUARD
#define LOCKGUARD(macro_mutex) std::lock_guard<decltype(macro_mutex)> TOKENPASTE2(__guard_, __LINE__) (macro_mutex);
class HttpPostListener : public DebugEventListener
{
public:
virtual void OnDebugEvent(DebugEvent &evt)
{
static unsigned seq = 0;
switch (evt.type)
{
case EVT_HTTP_OK:
{
seq++;
std::string out;
std::vector<uint8_t> reqBody((unsigned char *)evt.data, (unsigned char *)(evt.data) + evt.size);
MAT::exporters::DecodeRequest(reqBody, out, false);
printf(">>>> REQUEST [%u]:%s\n", seq, out.c_str());
}
break;
default:
break;
};
};
};
class BasicFuncTests : public ::testing::Test,
public HttpServer::Callback
{
protected:
std::mutex mtx_requests;
std::vector<HttpServer::Request> receivedRequests;
std::string serverAddress;
HttpServer server;
ILogger* logger;
ILogger* logger2;
std::atomic<bool> isSetup;
std::atomic<bool> isRunning;
std::condition_variable cv_gotEvents;
std::mutex cv_m;
public:
BasicFuncTests() :
isSetup(false) ,
isRunning(false)
{};
virtual void SetUp() override
{
if (isSetup.exchange(true))
{
return;
}
int port = server.addListeningPort(HTTP_PORT);
std::ostringstream os;
os << "localhost:" << port;
serverAddress = "http://" + os.str() + "/simple/";
server.setServerName(os.str());
server.addHandler("/simple/", *this);
server.addHandler("/slow/", *this);
server.addHandler("/503/", *this);
server.setKeepalive(false); // This test doesn't work well with keep-alive enabled
server.start();
isRunning = true;
}
virtual void TearDown() override
{
if (!isSetup.exchange(false))
return;
server.stop();
isRunning = false;
}
virtual void CleanStorage()
{
std::string fileName = MAT::GetTempDirectory();
fileName += PATH_SEPARATOR_CHAR;
fileName += TEST_STORAGE_FILENAME;
std::remove(fileName.c_str());
}
virtual void Initialize()
{
receivedRequests.clear();
auto configuration = LogManager::GetLogConfiguration();
configuration[CFG_INT_TRACE_LEVEL_MASK] = 0xFFFFFFFF;
#ifdef NDEBUG
configuration[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Warn;
#else
configuration[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Trace;
#endif
configuration[CFG_INT_SDK_MODE] = SdkModeTypes::SdkModeTypes_CS;
configuration[CFG_INT_RAM_QUEUE_SIZE] = 4096 * 20;
configuration[CFG_STR_CACHE_FILE_PATH] = TEST_STORAGE_FILENAME;
configuration[CFG_INT_MAX_TEARDOWN_TIME] = 2; // 2 seconds wait on shutdown
configuration[CFG_STR_COLLECTOR_URL] = serverAddress.c_str();
configuration[CFG_MAP_HTTP][CFG_BOOL_HTTP_COMPRESSION] = false; // disable compression for now
configuration[CFG_MAP_METASTATS_CONFIG][CFG_INT_METASTATS_INTERVAL] = 30 * 60; // 30 mins
configuration["name"] = __FILE__;
configuration["version"] = "1.0.0";
configuration["config"] = { { "host", __FILE__ } }; // Host instance
LogManager::Initialize(TEST_TOKEN, configuration);
LogManager::SetLevelFilter(DIAG_LEVEL_DEFAULT, { DIAG_LEVEL_DEFAULT_MIN, DIAG_LEVEL_DEFAULT_MAX });
LogManager::ResumeTransmission();
logger = LogManager::GetLogger(TEST_TOKEN, "source1");
logger2 = LogManager::GetLogger(TEST_TOKEN, "source2");
}
virtual void FlushAndTeardown()
{
LogManager::Flush();
LogManager::FlushAndTeardown();
}
virtual int onHttpRequest(HttpServer::Request const& request, HttpServer::Response& response) override
{
if (request.uri.compare(0, 5, "/503/") == 0) {
return 503;
}
if (request.uri.compare(0, 6, "/slow/") == 0) {
PAL::sleep(static_cast<unsigned int>(request.content.size() / DELAY_FACTOR_FOR_SERVER));
}
{
LOCKGUARD(mtx_requests);
receivedRequests.push_back(request);
}
response.headers["Content-Type"] = "text/plain";
response.content = "{ \"status\": \"0\" }";
return 200;
}
bool waitForRequests(unsigned timeOutSec, unsigned expected_count = 1)
{
std::unique_lock<std::mutex> lk(cv_m);
if (cv_gotEvents.wait_for(lk, std::chrono::milliseconds(1000 * timeOutSec), [&] { return receivedRequests.size() >= expected_count; }))
{
return true;
}
return false;
}
void waitForEvents(unsigned timeOutSec, unsigned expected_count = 1)
{
unsigned receivedEvents = 0;
auto start = PAL::getUtcSystemTimeMs();
size_t lastIdx = 0;
while ( ((PAL::getUtcSystemTimeMs()-start)<(1000* timeOutSec)) && (receivedEvents!=expected_count) )
{
/* Give time for our friendly HTTP server thread to process incoming request */
std::this_thread::yield();
{
LOCKGUARD(mtx_requests);
if (receivedRequests.size())
{
size_t size = receivedRequests.size();
//requests can come within 100 milisec sleep
for (size_t index = lastIdx; index < size; index++)
{
auto request = receivedRequests.at(index);
auto payload = decodeRequest(request, false);
receivedEvents+= (unsigned)payload.size();
}
lastIdx = size;
}
}
}
ASSERT_EQ(receivedEvents, expected_count);
}
std::vector<CsProtocol::Record> decodeRequest(HttpServer::Request const& request, bool decompress)
{
UNREFERENCED_PARAMETER(decompress);
// TODO: [MG] - implement decompression
std::vector<CsProtocol::Record> vector;
size_t data = 0;
size_t length = 0;
while (data < request.content.size())
{
CsProtocol::Record result;
length = request.content.size() - data;
std::vector<uint8_t> test(request.content.data() + data, request.content.data() + data + length);
size_t index = 3;
bool found = false;
while (index < length)
{
while (index < length && test[index] != '\x3')
{
index++;
}
if (index < length)
{
if (index + 2 < length)
{
// Search for Version marker after \x3 in Bond stream
if (test[index + 1] == ('0'+::CsProtocol::CS_VER_MAJOR) && test[index + 2] == '.')
{
found = true;
break;
}
}
index++;
}
}
if (!found)
{
index += 1;
}
std::vector<uint8_t> input(request.content.data() + data, request.content.data() + data + index - 1);
bond_lite::CompactBinaryProtocolReader reader(input);
EXPECT_THAT(bond_lite::Deserialize(reader, result), true);
data += index - 1;
vector.push_back(result);
}
return vector;
}
void verifyEvent(EventProperties const& expected, ::CsProtocol::Record const& actual)
{
EXPECT_THAT(actual.name, Not(IsEmpty()));
int64_t now = PAL::getUtcSystemTimeinTicks();
EXPECT_THAT(actual.time, Gt(now - 60000000000));
EXPECT_THAT(actual.time, Le(now));
EXPECT_THAT(actual.name, expected.GetName());
// If empty event property bag, then verify the name and return
if (!actual.data.size())
{
EXPECT_THAT(actual.name, expected.GetName());
return;
}
for (const auto& prop : expected.GetProperties())
{
if (prop.second.piiKind == PiiKind_None)
{
std::map<std::string, CsProtocol::Value>::const_iterator iter = actual.data[0].properties.find(prop.first);
if (iter != actual.data[0].properties.end())
{
CsProtocol::Value temp = iter->second;
switch (temp.type)
{
case ::CsProtocol::ValueInt64:
case ::CsProtocol::ValueUInt64:
case ::CsProtocol::ValueInt32:
case ::CsProtocol::ValueUInt32:
case ::CsProtocol::ValueBool:
case ::CsProtocol::ValueDateTime:
{
EXPECT_THAT(temp.longValue, prop.second.as_int64);
break;
}
case ::CsProtocol::ValueDouble:
{
EXPECT_THAT(temp.doubleValue, prop.second.as_double);
break;
}
case ::CsProtocol::ValueString:
{
EXPECT_THAT(temp.stringValue, prop.second.as_string);
break;
}
case ::CsProtocol::ValueGuid:
{
uint8_t guid_bytes[16] = { 0 };
prop.second.as_guid.to_bytes(guid_bytes);
std::vector<uint8_t> guid = std::vector<uint8_t>(guid_bytes, guid_bytes + sizeof(guid_bytes) / sizeof(guid_bytes[0]));
EXPECT_THAT(temp.guidValue[0].size(), guid.size());
for (size_t index = 0; index < guid.size(); index++)
{
uint8_t val1 = temp.guidValue.at(0).at(index);
uint8_t val2 = guid[index];
EXPECT_THAT(val1, val2);
}
break;
}
case ::CsProtocol::ValueArrayInt64:
case ::CsProtocol::ValueArrayUInt64:
case ::CsProtocol::ValueArrayInt32:
case ::CsProtocol::ValueArrayUInt32:
case ::CsProtocol::ValueArrayBool:
case ::CsProtocol::ValueArrayDateTime:
{
std::vector<int64_t>& vectror = temp.longArray.at(0);
EXPECT_THAT(vectror.size(), prop.second.as_longArray->size());
for (size_t index = 0; index < prop.second.as_longArray->size(); index++)
{
uint64_t val1 = vectror.at(index);
uint64_t val2 = prop.second.as_longArray->at(index);
EXPECT_THAT(val1, val2);
}
break;
}
case ::CsProtocol::ValueArrayDouble:
{
std::vector<double>& vectror = temp.doubleArray.at(0);
EXPECT_THAT(vectror.size(), prop.second.as_doubleArray->size());
for (size_t index = 0; index < prop.second.as_doubleArray->size(); index++)
{
double val1 = vectror.at(index);
double val2 = prop.second.as_doubleArray->at(index);
EXPECT_THAT(val1, val2);
}
break;
}
case ::CsProtocol::ValueArrayString:
{
std::vector<std::string>& vectror = temp.stringArray.at(0);
EXPECT_THAT(vectror.size(), prop.second.as_stringArray->size());
for (size_t index = 0; index < prop.second.as_stringArray->size(); index++)
{
std::string val1 = vectror.at(index);
std::string val2 = prop.second.as_stringArray->at(index);
EXPECT_THAT(val1, val2);
}
break;
}
case ::CsProtocol::ValueArrayGuid:
{
// EXPECT_THAT(temp.guidArray, prop.second.as_guidArray);
std::vector<std::vector<uint8_t>>& vectror = temp.guidArray.at(0);
EXPECT_THAT(vectror.size(), prop.second.as_guidArray->size());
for (size_t index = 0; index < prop.second.as_guidArray->size(); index++)
{
uint8_t guid_bytes[16] = { 0 };
prop.second.as_guidArray->at(index).to_bytes(guid_bytes);
std::vector<uint8_t> guid = std::vector<uint8_t>(guid_bytes, guid_bytes + sizeof(guid_bytes) / sizeof(guid_bytes[0]));
EXPECT_THAT(vectror.at(index).size(), guid.size());
for (size_t index1 = 0; index1 < guid.size(); index1++)
{
uint8_t val1 = vectror.at(index).at(index1);
uint8_t val2 = guid[index1];
EXPECT_THAT(val1, val2);
}
}
break;
}
default:
{
break;
}
}
}
}
}
for (auto const& property : expected.GetPiiProperties())
{
::CsProtocol::PII pii;
pii.Kind = static_cast<::CsProtocol::PIIKind>(property.second.second);
// EXPECT_THAT(actual.PIIExtensions, Contains(Pair(property.first, pii)));
}
/* for (auto const& property : expected.GetCustomerContentProperties())
{
::CsProtocol::CustomerContent cc;
cc.Kind = static_cast< ::CsProtocol::CustomerContentKind>(property.second.second);
//EXPECT_THAT(actual.CustomerContentExtensions, Contains(Pair(property.first, cc)));
}
*/
}
int64_t getFileSize(std::string const& filename)
{
std::ifstream ifile(filename);
ifile.seekg(0, std::ios_base::end);
return ifile.tellg();
}
std::vector<CsProtocol::Record> records()
{
std::vector<CsProtocol::Record> result;
if (receivedRequests.size())
{
for (auto &request : receivedRequests)
{
// TODO: [MG] - add compression support
auto payload = decodeRequest(request, false);
for (auto &record : payload)
{
result.push_back(std::move(record));
}
}
}
return result;
}
// Find first matching event
CsProtocol::Record find(const std::string& name)
{
CsProtocol::Record result;
result.name = "";
if (receivedRequests.size())
{
for (auto &request : receivedRequests)
{
// TODO: [MG] - add compression support
auto payload = decodeRequest(request, false);
for (auto &record : payload)
{
if (record.name == name)
{
result = record;
return result;
}
}
}
}
return result;
}
};
TEST_F(BasicFuncTests, doNothing)
{
CleanStorage();
Initialize();
std::this_thread::sleep_for(std::chrono::seconds(5));
FlushAndTeardown();
}
TEST_F(BasicFuncTests, sendOneEvent_immediatelyStop)
{
CleanStorage();
Initialize();
EventProperties event("first_event");
event.SetProperty("property", "value");
logger->LogEvent(event);
LogManager::UploadNow();
PAL::sleep(500); // for a certain value of immediately
FlushAndTeardown();
EXPECT_GE(receivedRequests.size(), (size_t)1); // at least 1 HTTP request with customer payload and stats
}
TEST_F(BasicFuncTests, sendNoPriorityEvents)
{
CleanStorage();
Initialize();
/* Verify both:
- local deserializer implementation in verifyEvent
- public MAT::exporters::DecodeRequest(...) via debug callback
*/
HttpPostListener listener;
LogManager::AddEventListener(EVT_HTTP_OK, listener);
EventProperties event("first_event");
event.SetProperty("property", "value");
logger->LogEvent(event);
EventProperties event2("second_event");
event2.SetProperty("property", "value2");
event2.SetProperty("property2", "another value");
logger->LogEvent(event2);
LogManager::UploadNow();
waitForEvents(1, 3);
EXPECT_GE(receivedRequests.size(), (size_t)1);
LogManager::RemoveEventListener(EVT_HTTP_OK, listener);
FlushAndTeardown();
if (receivedRequests.size() >= 1)
{
verifyEvent(event, find("first_event"));
verifyEvent(event2, find("second_event"));
}
}
TEST_F(BasicFuncTests, sendSamePriorityNormalEvents)
{
CleanStorage();
Initialize();
EventProperties event("first_event");
event.SetPriority(EventPriority_Normal);
event.SetProperty("property", "value");
std::vector<int64_t> intvector(8);
std::fill(intvector.begin(), intvector.begin() + 4, 5);
std::fill(intvector.begin() + 3, intvector.end() - 2, 8);
event.SetProperty("property1", intvector);
std::vector<double> dvector(8);
std::fill(dvector.begin(), dvector.begin() + 4, 4.9999);
std::fill(dvector.begin() + 3, dvector.end() - 2, 7.9999);
event.SetProperty("property2", dvector);
std::vector<std::string> svector(8);
std::fill(svector.begin(), svector.begin() + 4, "string");
std::fill(svector.begin() + 3, svector.end() - 2, "string2");
event.SetProperty("property3", svector);
std::vector<GUID_t> gvector(8);
std::fill(gvector.begin(), gvector.begin() + 4, GUID_t("00010203-0405-0607-0809-0A0B0C0D0E0F"));
std::fill(gvector.begin() + 3, gvector.end() - 2, GUID_t("00000000-0000-0000-0000-000000000000"));
event.SetProperty("property4", gvector);
logger->LogEvent(event);
EventProperties event2("second_event");
event2.SetPriority(EventPriority_Normal);
event2.SetProperty("property", "value2");
event2.SetProperty("property2", "another value");
event2.SetProperty("pii_property", "pii_value", PiiKind_Identity);
event2.SetProperty("cc_property", "cc_value", CustomerContentKind_GenericData);
logger->LogEvent(event2);
waitForEvents(3, 3);
for (const auto &evt : { event, event2 })
{
verifyEvent(evt, find(evt.GetName()));
}
FlushAndTeardown();
}
TEST_F(BasicFuncTests, sendDifferentPriorityEvents)
{
CleanStorage();
Initialize();
EventProperties event("first_event");
event.SetPriority(EventPriority_Normal);
event.SetProperty("property", "value");
std::vector<int64_t> intvector(8);
std::fill(intvector.begin(), intvector.begin() + 4, 5);
std::fill(intvector.begin() + 3, intvector.end() - 2, 8);
event.SetProperty("property1", intvector);
std::vector<double> dvector(8);
std::fill(dvector.begin(), dvector.begin() + 4, 4.9999);
std::fill(dvector.begin() + 3, dvector.end() - 2, 7.9999);
event.SetProperty("property2", dvector);
std::vector<std::string> svector(8);
std::fill(svector.begin(), svector.begin() + 4, "string");
std::fill(svector.begin() + 3, svector.end() - 2, "string2");
event.SetProperty("property3", svector);
std::vector<GUID_t> gvector(8);
std::fill(gvector.begin(), gvector.begin() + 4, GUID_t("00010203-0405-0607-0809-0A0B0C0D0E0F"));
std::fill(gvector.begin() + 3, gvector.end() - 2, GUID_t("00000000-0000-0000-0000-000000000000"));
event.SetProperty("property4", gvector);
logger->LogEvent(event);
EventProperties event2("second_event");
event2.SetPriority(EventPriority_High);
event2.SetProperty("property", "value2");
event2.SetProperty("property2", "another value");
event2.SetProperty("pii_property", "pii_value", PiiKind_Identity);
event2.SetProperty("cc_property", "cc_value", CustomerContentKind_GenericData);
logger->LogEvent(event2);
LogManager::UploadNow();
// 2 x customer events + 1 x evt_stats on start
waitForEvents(1, 3);
for (const auto &evt : { event, event2 })
{
verifyEvent(evt, find(evt.GetName()));
}
FlushAndTeardown();
}
TEST_F(BasicFuncTests, sendMultipleTenantsTogether)
{
CleanStorage();
Initialize();
EventProperties event1("first_event");
event1.SetProperty("property", "value");
std::vector<int64_t> intvector(8);
std::fill(intvector.begin(), intvector.begin() + 4, 5);
std::fill(intvector.begin() + 3, intvector.end() - 2, 8);
event1.SetProperty("property1", intvector);
std::vector<double> dvector(8);
std::fill(dvector.begin(), dvector.begin() + 4, 4.9999);
std::fill(dvector.begin() + 3, dvector.end() - 2, 7.9999);
event1.SetProperty("property2", dvector);
std::vector<std::string> svector(8);
std::fill(svector.begin(), svector.begin() + 4, "string");
std::fill(svector.begin() + 3, svector.end() - 2, "string2");
event1.SetProperty("property3", svector);
std::vector<GUID_t> gvector(8);
std::fill(gvector.begin(), gvector.begin() + 4, GUID_t("00010203-0405-0607-0809-0A0B0C0D0E0F"));
std::fill(gvector.begin() + 3, gvector.end() - 2, GUID_t("00000000-0000-0000-0000-000000000000"));
event1.SetProperty("property4", gvector);
logger->LogEvent(event1);
EventProperties event2("second_event");
event2.SetProperty("property", "value2");
event2.SetProperty("property2", "another value");
logger2->LogEvent(event2);
LogManager::UploadNow();
// 2 x customer events + 1 x evt_stats on start
waitForEvents(1, 3);
for (const auto &evt : { event1, event2 })
{
verifyEvent(evt, find(evt.GetName()));
}
FlushAndTeardown();
}
TEST_F(BasicFuncTests, configDecorations)
{
CleanStorage();
Initialize();
EventProperties event1("first_event");
logger->LogEvent(event1);
EventProperties event2("second_event");
logger->LogEvent(event2);
EventProperties event3("third_event");
logger->LogEvent(event3);
EventProperties event4("4th_event");
logger->LogEvent(event4);
LogManager::UploadNow();
waitForEvents(2, 5);
for (const auto &evt : { event1, event2, event3, event4 })
{
verifyEvent(evt, find(evt.GetName()));
}
FlushAndTeardown();
}
TEST_F(BasicFuncTests, restartRecoversEventsFromStorage)
{
{
CleanStorage();
Initialize();
// This code is a bit racy because ResumeTransmission is done in Initialize
LogManager::PauseTransmission();
EventProperties event1("first_event");
EventProperties event2("second_event");
event1.SetProperty("property1", "value1");
event2.SetProperty("property2", "value2");
event1.SetLatency(MAT::EventLatency::EventLatency_RealTime);
event1.SetPersistence(MAT::EventPersistence::EventPersistence_Critical);
event2.SetLatency(MAT::EventLatency::EventLatency_RealTime);
event2.SetPersistence(MAT::EventPersistence::EventPersistence_Critical);
logger->LogEvent(event1);
logger->LogEvent(event2);
FlushAndTeardown();
}
{
Initialize();
EventProperties fooEvent("fooEvent");
fooEvent.SetLatency(EventLatency_RealTime);
fooEvent.SetPersistence(EventPersistence_Critical);
LogManager::GetLogger()->LogEvent(fooEvent);
LogManager::UploadNow();
// 1st request for realtime event
waitForEvents(3, 5); // start, first_event, second_event, ongoing, stop, start, fooEvent
// we drop two of the events during pause, though.
EXPECT_GE(receivedRequests.size(), (size_t)1);
if (receivedRequests.size() != 0)
{
auto payload = decodeRequest(receivedRequests[receivedRequests.size() - 1], false);
}
FlushAndTeardown();
}
/*
ASSERT_THAT(receivedRequests, SizeIs(1));
auto payload = decodeRequest(receivedRequests[0], false);
ASSERT_THAT(payload.TokenToDataPackagesMap, Contains(Key("functests-tenant-token")));
ASSERT_THAT(payload.TokenToDataPackagesMap["functests-tenant-token"], SizeIs(1));
auto const& dp = payload.TokenToDataPackagesMap["functests-tenant-token"][0];
ASSERT_THAT(payload, SizeIs(2));
verifyEvent(event1, payload[0]);
verifyEvent(event2, payload[1]);
*/
}
#if 0 // FIXME: 1445871 [v3][1DS] Offline storage size may exceed configured limit
TEST_F(BasicFuncTests, storageFileSizeDoesntExceedConfiguredSize)
{
CleanStorage();
static int64_t const ONE_EVENT_SIZE = 500 * 1024;
static int64_t const MAX_FILE_SIZE = 8 * 1024 * 1024;
static int64_t const ALLOWED_OVERFLOW = 10 * MAX_FILE_SIZE / 100;
auto &configuration = LogManager::GetLogConfiguration();
configuration[CFG_INT_MAX_TEARDOWN_TIME] = 0;
configuration[CFG_INT_CACHE_FILE_SIZE] = MAX_FILE_SIZE;
std::string slowServiceUrl;
slowServiceUrl.insert(slowServiceUrl.find('/', sizeof("http://")) + 1, "slow/");
configuration[CFG_STR_COLLECTOR_URL] = slowServiceUrl.c_str();
{
Initialize();
LogManager::PauseTransmission();
for (int i = 0; i < 50; i++) {
EventProperties event("event" + toString(i));
event.SetPriority(EventPriority_Normal);
event.SetProperty("property", "value");
event.SetProperty("big_data", std::string(ONE_EVENT_SIZE, '\42'));
logger->LogEvent(event);
}
// Check meta stats after restart. Because of their high priority, they will
// be sent alone in the very first request regardless of other events.
FlushAndTeardown();
std::string fileName = MAT::GetTempDirectory();
fileName += "\\";
fileName += TEST_STORAGE_FILENAME;
size_t fileSize = getFileSize(fileName);
EXPECT_LE(fileSize, (size_t)(MAX_FILE_SIZE + ALLOWED_OVERFLOW));
}
// Restore fast URL
configuration[CFG_STR_COLLECTOR_URL] = serverAddress.c_str();
{
Initialize();
waitForEvents(2, 8);
if (receivedRequests.size())
{
auto payload = decodeRequest(receivedRequests[0], false);
/* auto payload = decodeRequest(receivedRequests[0], false);
ASSERT_THAT(payload.TokenToDataPackagesMap["metastats-tenant-token"], SizeIs(1));
auto const& dp = payload.TokenToDataPackagesMap["metastats-tenant-token"][0];
ASSERT_THAT(payload, SizeIs(2));
EXPECT_THAT(payload[0].Id, Not(IsEmpty()));
EXPECT_THAT(payload[0].Type, Eq("client_telemetry"));
EXPECT_THAT(payload[0].Extension, Contains(Pair("stats_rollup_kind", "stop")));
// The expected number of dropped events is hard to estimate because of database overhead,
// varying timing, some events have been sent etc. Just check that it's at least a quarter.
EXPECT_THAT(payload[0].Extension, Contains(Pair("records_dropped_offline_storage_overflow", StrAsIntGt(50 / 4))));
*/
}
FlushAndTeardown();
}
}
#endif
TEST_F(BasicFuncTests, sendMetaStatsOnStart)
{
CleanStorage();
// Run offline
Initialize();
LogManager::PauseTransmission();
EventProperties event1("first_event");
event1.SetPriority(EventPriority_High);
event1.SetProperty("property1", "value1");
logger->LogEvent(event1);
EventProperties event2("second_event");
event2.SetProperty("property2", "value2");
logger->LogEvent(event2);
FlushAndTeardown();
auto r1 = records();
ASSERT_EQ(r1.size(), size_t { 0 });
// Check
Initialize();
LogManager::ResumeTransmission(); // ?
LogManager::UploadNow();
PAL::sleep(2000);
auto r2 = records();
ASSERT_GE(r2.size(), (size_t)4); // (start + stop) + (2 events + start)
for (const auto &evt : { event1, event2 })
{
verifyEvent(evt, find(evt.GetName()));
}
FlushAndTeardown();
}
TEST_F(BasicFuncTests, DiagLevelRequiredOnly_OneEventWithoutLevelOneWithButNotAllowedOneAllowed_OnlyAllowedEventSent)
{
CleanStorage();
Initialize();
LogManager::SetLevelFilter(DIAG_LEVEL_OPTIONAL, { DIAG_LEVEL_REQUIRED });
EventProperties eventWithoutLevel("EventWithoutLevel");
logger->LogEvent(eventWithoutLevel);
EventProperties eventWithNotAllowedLevel("EventWithNotAllowedLevel");
eventWithNotAllowedLevel.SetLevel(DIAG_LEVEL_OPTIONAL);
logger->LogEvent(eventWithNotAllowedLevel);
EventProperties eventWithAllowedLevel("EventWithAllowedLevel");
eventWithAllowedLevel.SetLevel(DIAG_LEVEL_REQUIRED);
logger->LogEvent(eventWithAllowedLevel);
LogManager::UploadNow();
waitForEvents(1 /*timeout*/, 2 /*expected count*/); // Start and EventWithAllowedLevel
ASSERT_EQ(records().size(), static_cast<size_t>(2)); // Start and EventWithAllowedLevel
verifyEvent(eventWithAllowedLevel, find(eventWithAllowedLevel.GetName()));
FlushAndTeardown();
}
void SendEventWithOptionalThenRequired(ILogger* logger) noexcept
{
EventProperties eventWithOptionalLevel("EventWithOptionalLevel");
eventWithOptionalLevel.SetLevel(DIAG_LEVEL_OPTIONAL);
logger->LogEvent(eventWithOptionalLevel);
EventProperties eventWithRequiredLevel("EventWithRequiredLevel");
eventWithRequiredLevel.SetLevel(DIAG_LEVEL_REQUIRED);
logger->LogEvent(eventWithRequiredLevel);
}
static std::vector<CsProtocol::Record> GetEventsWithName(const char* name, const std::vector<CsProtocol::Record>& records) noexcept
{
std::vector<CsProtocol::Record> results;
for (const auto& record : records)
{
if (record.name.compare(name) == 0)
results.push_back(record);
}
return results;
}
TEST_F(BasicFuncTests, DiagLevelRequiredOnly_SendTwoEventsUpdateAllowedLevelsSendTwoEvents_ThreeEventsSent)
{
CleanStorage();
Initialize();
LogManager::SetLevelFilter(DIAG_LEVEL_OPTIONAL, { DIAG_LEVEL_REQUIRED });
SendEventWithOptionalThenRequired(logger);
LogManager::SetLevelFilter(DIAG_LEVEL_OPTIONAL, { DIAG_LEVEL_OPTIONAL, DIAG_LEVEL_REQUIRED });
SendEventWithOptionalThenRequired(logger);
LogManager::UploadNow();
waitForEvents(2 /*timeout*/, 4 /*expected count*/); // Start and EventWithAllowedLevel
auto sentRecords = records();
ASSERT_EQ(sentRecords.size(), static_cast<size_t>(4)); // Start and EventWithAllowedLevel
ASSERT_EQ(GetEventsWithName("EventWithOptionalLevel", sentRecords).size(), size_t{ 1 });
ASSERT_EQ(GetEventsWithName("EventWithRequiredLevel", sentRecords).size(), size_t{ 2 });
FlushAndTeardown();
}
class RequestMonitor : public DebugEventListener
{
const size_t IDX_OK = 0;
const size_t IDX_ERR = 1;
const size_t IDX_ABRT = 2;
std::atomic<size_t> counts[3];
public:
RequestMonitor() : DebugEventListener()
{
reset();
}
void reset()
{