Repository navigation
Expand file tree
/
Copy pathgtest_loggers.cpp
More file actions
655 lines (528 loc) · 17.6 KB
/
Copy pathgtest_loggers.cpp
File metadata and controls
655 lines (528 loc) · 17.6 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
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
/* Copyright (C) 2018-2025 Davide Faconti - All Rights Reserved
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "behaviortree_cpp/bt_factory.h"
#include "behaviortree_cpp/loggers/bt_cout_logger.h"
#include "behaviortree_cpp/loggers/bt_file_logger_v2.h"
#include "behaviortree_cpp/loggers/bt_minitrace_logger.h"
#include "behaviortree_cpp/loggers/bt_observer.h"
#include "behaviortree_cpp/loggers/bt_sqlite_logger.h"
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <gtest/gtest.h>
using namespace BT;
class LoggerTest : public testing::Test
{
protected:
BT::BehaviorTreeFactory factory;
std::string test_dir;
void SetUp() override
{
// Create a temporary directory for test files
test_dir = std::filesystem::temp_directory_path().string() + "/bt_logger_test";
std::filesystem::create_directories(test_dir);
}
void TearDown() override
{
// Clean up test files
std::filesystem::remove_all(test_dir);
}
BT::Tree createSimpleTree()
{
const std::string xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<Sequence>
<AlwaysSuccess name="ActionA"/>
<AlwaysSuccess name="ActionB"/>
</Sequence>
</BehaviorTree>
</root>)";
return factory.createTreeFromText(xml_text);
}
};
// ============ StdCoutLogger tests ============
TEST_F(LoggerTest, StdCoutLogger_Creation)
{
auto tree = createSimpleTree();
// Should not throw
StdCoutLogger logger(tree);
// Execute the tree - logger should capture transitions
tree.tickWhileRunning();
// Flush should not throw
logger.flush();
}
TEST_F(LoggerTest, StdCoutLogger_Enabled)
{
auto tree = createSimpleTree();
StdCoutLogger logger(tree);
// Test enabled/disabled
ASSERT_TRUE(logger.enabled());
logger.setEnabled(false);
ASSERT_FALSE(logger.enabled());
logger.setEnabled(true);
ASSERT_TRUE(logger.enabled());
tree.tickWhileRunning();
}
TEST_F(LoggerTest, StdCoutLogger_TransitionToIdle)
{
auto tree = createSimpleTree();
StdCoutLogger logger(tree);
// Test transition to idle setting
ASSERT_TRUE(logger.showsTransitionToIdle());
logger.enableTransitionToIdle(false);
ASSERT_FALSE(logger.showsTransitionToIdle());
logger.enableTransitionToIdle(true);
ASSERT_TRUE(logger.showsTransitionToIdle());
tree.tickWhileRunning();
}
TEST_F(LoggerTest, StdCoutLogger_TimestampType)
{
auto tree = createSimpleTree();
StdCoutLogger logger(tree);
// Test timestamp type setting (default is absolute)
logger.setTimestampType(TimestampType::relative);
tree.tickWhileRunning();
logger.setTimestampType(TimestampType::absolute);
tree.haltTree();
tree.tickWhileRunning();
}
// ============ FileLogger2 tests ============
TEST_F(LoggerTest, FileLogger2_Creation)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/test.btlog";
{
FileLogger2 logger(tree, filepath);
tree.tickWhileRunning();
logger.flush();
} // Logger destructor closes the file
// File should exist
ASSERT_TRUE(std::filesystem::exists(filepath));
// File should have content
auto file_size = std::filesystem::file_size(filepath);
ASSERT_GT(file_size, 0u);
}
TEST_F(LoggerTest, FileLogger2_WrongExtension)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/test.txt";
// Should throw with wrong extension
ASSERT_THROW(FileLogger2 logger(tree, filepath), RuntimeError);
}
TEST_F(LoggerTest, FileLogger2_FileHeader)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/header_test.btlog";
{
FileLogger2 logger(tree, filepath);
tree.tickWhileRunning();
}
// Read the file and check header
std::ifstream file(filepath, std::ios::binary);
ASSERT_TRUE(file.is_open());
char header[18];
file.read(header, 18);
std::string header_str(header, 18);
ASSERT_EQ(header_str, "BTCPP4-FileLogger2");
}
TEST_F(LoggerTest, FileLogger2_MultipleTicks)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/multi_tick.btlog";
{
FileLogger2 logger(tree, filepath);
// Multiple tick cycles
for(int i = 0; i < 3; i++)
{
tree.tickWhileRunning();
tree.haltTree();
}
logger.flush();
}
ASSERT_TRUE(std::filesystem::exists(filepath));
}
// A minimal action that stays RUNNING until halted -- SimpleActionNode/SyncActionNode explicitly
// forbid returning RUNNING, so the drain-race repro below needs a real (if synchronous) action
// node instead.
namespace
{
class AlwaysRunningNode : public BT::ActionNodeBase
{
public:
AlwaysRunningNode(const std::string& name, const BT::NodeConfig& config)
: BT::ActionNodeBase(name, config)
{}
static BT::PortsList providedPorts()
{
return {};
}
BT::NodeStatus tick() override
{
return BT::NodeStatus::RUNNING;
}
void halt() override
{}
};
} // namespace
// FileLogger2's destructor used to join the writer thread without draining
// _p->transitions_queue afterward: a transition pushed after the writer's last swap (typically
// the root's RUNNING->IDLE from a haltTree() issued right before the logger is destroyed) could
// be lost, leaving the .btlog missing its final transition. The window is a scheduling race, not
// deterministic, so this loops many iterations rather than asserting on a single run.
TEST_F(LoggerTest, FileLogger2_DrainsQueueAfterHaltThenImmediateDestroy)
{
BT::BehaviorTreeFactory local_factory;
local_factory.registerNodeType<AlwaysRunningNode>("AlwaysRunning");
const std::string xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<Sequence>
<AlwaysRunning name="ActionA"/>
</Sequence>
</BehaviorTree>
</root>)";
constexpr int kIterations = 300;
for(int i = 0; i < kIterations; i++)
{
auto tree = local_factory.createTreeFromText(xml_text);
const std::string filepath = test_dir + "/drain_" + std::to_string(i) + ".btlog";
const uint16_t root_uid = tree.rootNode()->UID();
{
FileLogger2 logger(tree, filepath);
tree.tickOnce(); // root -> RUNNING, pushed onto the queue
tree.haltTree(); // root -> IDLE, pushed right before the logger is destroyed
} // ~FileLogger2() runs here: join the writer thread, then (with the fix) drain the queue
// Parse the .btlog by hand (format documented in bt_file_logger_v2.h): 18-byte magic
// ("BTCPP4-FileLogger2"), 1-byte protocol, 4-byte XML length, the XML itself, 8-byte first
// timestamp, then a sequence of 9-byte Transition records (6 bytes timestamp, 2 bytes
// node_uid, 1 byte status).
std::ifstream file(filepath, std::ios::binary);
ASSERT_TRUE(file.is_open()) << "iteration " << i;
file.seekg(18 + 1);
int32_t xml_len = 0;
file.read(reinterpret_cast<char*>(&xml_len), sizeof(xml_len));
ASSERT_TRUE(file.good()) << "iteration " << i;
file.seekg(xml_len, std::ios::cur);
file.seekg(8, std::ios::cur); // skip the first timestamp
uint8_t last_root_status = 0xFF;
std::array<char, 9> record{};
while(file.read(record.data(), record.size()))
{
uint16_t uid = 0;
uint8_t status = 0xFF;
std::memcpy(&uid, record.data() + 6, sizeof(uid));
std::memcpy(&status, record.data() + 8, sizeof(status));
if(uid == root_uid)
{
last_root_status = status;
}
}
ASSERT_EQ(last_root_status, static_cast<uint8_t>(NodeStatus::IDLE))
<< "iteration " << i << ": the root's last recorded transition is status "
<< int(last_root_status)
<< ", not IDLE(0) -- the tree's halt never reached the .btlog before the file "
"closed";
}
}
// ============ MinitraceLogger tests ============
TEST_F(LoggerTest, MinitraceLogger_Creation)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/trace.json";
{
MinitraceLogger logger(tree, filepath.c_str());
tree.tickWhileRunning();
logger.flush();
} // Logger destructor flushes and shuts down
// File should exist
ASSERT_TRUE(std::filesystem::exists(filepath));
// File should have content
auto file_size = std::filesystem::file_size(filepath);
ASSERT_GT(file_size, 0u);
}
TEST_F(LoggerTest, MinitraceLogger_JsonContent)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/trace_content.json";
{
MinitraceLogger logger(tree, filepath.c_str());
tree.tickWhileRunning();
}
// Read file and check it's valid JSON-ish (starts with proper content)
std::ifstream file(filepath);
ASSERT_TRUE(file.is_open());
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// Minitrace JSON should contain traceEvents
ASSERT_NE(content.find("traceEvents"), std::string::npos);
}
TEST_F(LoggerTest, MinitraceLogger_TransitionTypes)
{
// Test different node types are logged correctly
const std::string xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<Sequence name="SeqNode">
<Inverter name="InvNode">
<AlwaysFailure name="FailNode"/>
</Inverter>
<AlwaysSuccess name="SuccessNode"/>
</Sequence>
</BehaviorTree>
</root>)";
auto tree = factory.createTreeFromText(xml_text);
std::string filepath = test_dir + "/trace_types.json";
{
MinitraceLogger logger(tree, filepath.c_str());
logger.enableTransitionToIdle(true);
tree.tickWhileRunning();
}
ASSERT_TRUE(std::filesystem::exists(filepath));
}
TEST_F(LoggerTest, MinitraceLogger_LongNodeName)
{
// The node name goes into a 1024 byte line buffer. A name long enough to
// overflow it used to be written out with snprintf's would-be length, which
// reads past the buffer and copies stack bytes into the trace file.
const std::string long_name(1000, 'A');
const std::string xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<AlwaysSuccess name=")" +
long_name + R"("/>
</BehaviorTree>
</root>)";
auto tree = factory.createTreeFromText(xml_text);
std::string filepath = test_dir + "/trace_long_name.json";
{
MinitraceLogger logger(tree, filepath.c_str());
tree.tickWhileRunning();
logger.flush();
}
ASSERT_TRUE(std::filesystem::exists(filepath));
ASSERT_LT(std::filesystem::file_size(filepath), 4096u);
}
// ============ SqliteLogger tests ============
TEST_F(LoggerTest, SqliteLogger_Creation_db3)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/test.db3";
{
SqliteLogger logger(tree, filepath);
tree.tickWhileRunning();
logger.flush();
}
// File should exist
ASSERT_TRUE(std::filesystem::exists(filepath));
}
TEST_F(LoggerTest, SqliteLogger_Creation_btdb)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/test.btdb";
{
SqliteLogger logger(tree, filepath);
tree.tickWhileRunning();
logger.flush();
}
// File should exist
ASSERT_TRUE(std::filesystem::exists(filepath));
}
TEST_F(LoggerTest, SqliteLogger_WrongExtension)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/test.sqlite";
// Should throw with wrong extension
ASSERT_THROW(SqliteLogger logger(tree, filepath), RuntimeError);
}
TEST_F(LoggerTest, SqliteLogger_AppendMode)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/append_test.db3";
// First session
{
SqliteLogger logger(tree, filepath, false);
tree.tickWhileRunning();
}
auto size_after_first = std::filesystem::file_size(filepath);
// Second session with append=true
{
SqliteLogger logger(tree, filepath, true);
tree.tickWhileRunning();
}
auto size_after_second = std::filesystem::file_size(filepath);
ASSERT_GT(size_after_second, size_after_first);
}
TEST_F(LoggerTest, SqliteLogger_NoAppendMode)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/noappend_test.db3";
// First session
{
SqliteLogger logger(tree, filepath, false);
tree.tickWhileRunning();
}
// Second session with append=false should clear data
{
SqliteLogger logger(tree, filepath, false);
tree.tickWhileRunning();
}
// File should still exist
ASSERT_TRUE(std::filesystem::exists(filepath));
}
TEST_F(LoggerTest, SqliteLogger_ExtraCallback)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/extra_callback.db3";
int callback_count = 0;
{
SqliteLogger logger(tree, filepath);
logger.setAdditionalCallback([&callback_count](Duration, const TreeNode&, NodeStatus,
NodeStatus) -> std::string {
callback_count++;
return "extra_data";
});
tree.tickWhileRunning();
}
ASSERT_GT(callback_count, 0);
}
TEST_F(LoggerTest, SqliteLogger_ExecSqlStatement)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/exec_sql.db3";
{
SqliteLogger logger(tree, filepath);
tree.tickWhileRunning();
// Execute a custom SQL statement
logger.execSqlStatement("SELECT COUNT(*) FROM Transitions;");
}
ASSERT_TRUE(std::filesystem::exists(filepath));
}
TEST_F(LoggerTest, SqliteLogger_MultipleTicks)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/multi_tick.db3";
{
SqliteLogger logger(tree, filepath);
for(int i = 0; i < 5; i++)
{
tree.tickWhileRunning();
tree.haltTree();
}
}
ASSERT_TRUE(std::filesystem::exists(filepath));
}
// ============ Multiple loggers simultaneously ============
TEST_F(LoggerTest, MultipleLoggers)
{
auto tree = createSimpleTree();
std::string btlog_path = test_dir + "/multi.btlog";
std::string json_path = test_dir + "/multi.json";
std::string db_path = test_dir + "/multi.db3";
{
StdCoutLogger cout_logger(tree);
FileLogger2 file_logger(tree, btlog_path);
MinitraceLogger trace_logger(tree, json_path.c_str());
SqliteLogger sql_logger(tree, db_path);
tree.tickWhileRunning();
cout_logger.flush();
file_logger.flush();
trace_logger.flush();
sql_logger.flush();
}
// All files should exist
ASSERT_TRUE(std::filesystem::exists(btlog_path));
ASSERT_TRUE(std::filesystem::exists(json_path));
ASSERT_TRUE(std::filesystem::exists(db_path));
}
// ============ Logger with async actions ============
TEST_F(LoggerTest, LoggerWithAsyncTree)
{
const std::string xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<Sequence>
<Sleep msec="10" name="Sleep1"/>
<AlwaysSuccess name="Action"/>
</Sequence>
</BehaviorTree>
</root>)";
auto tree = factory.createTreeFromText(xml_text);
std::string filepath = test_dir + "/async.db3";
{
SqliteLogger logger(tree, filepath);
tree.tickWhileRunning();
}
ASSERT_TRUE(std::filesystem::exists(filepath));
}
// ============ Edge cases ============
TEST_F(LoggerTest, Logger_EmptyTree)
{
const std::string xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<AlwaysSuccess/>
</BehaviorTree>
</root>)";
auto tree = factory.createTreeFromText(xml_text);
std::string filepath = test_dir + "/empty.db3";
{
SqliteLogger logger(tree, filepath);
tree.tickWhileRunning();
}
ASSERT_TRUE(std::filesystem::exists(filepath));
}
TEST_F(LoggerTest, Logger_DisabledDuringExecution)
{
auto tree = createSimpleTree();
std::string filepath = test_dir + "/disabled.db3";
{
SqliteLogger logger(tree, filepath);
logger.setEnabled(false);
tree.tickWhileRunning();
logger.setEnabled(true);
tree.haltTree();
tree.tickWhileRunning();
}
ASSERT_TRUE(std::filesystem::exists(filepath));
}
TEST(TreeObserverTest, NodesWithTheSameName)
{
// Two siblings with the same name have the same fullPath()
static const char* xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree ID="MainTree">
<Sequence>
<AlwaysSuccess name="step"/>
<AlwaysSuccess name="step"/>
</Sequence>
</BehaviorTree>
</root>)";
BehaviorTreeFactory factory;
auto tree = factory.createTreeFromText(xml_text);
std::unique_ptr<TreeObserver> observer;
ASSERT_NO_THROW(observer = std::make_unique<TreeObserver>(tree));
ASSERT_EQ(tree.tickWhileRunning(), NodeStatus::SUCCESS);
const auto& nodes = tree.subtrees.front()->nodes;
ASSERT_EQ(nodes.size(), 3u);
EXPECT_EQ(observer->statistics().size(), 3u);
EXPECT_EQ(observer->uidToPath().size(), 3u);
for(const auto& node : nodes)
{
EXPECT_EQ(observer->uidToPath().at(node->UID()), node->fullPath());
EXPECT_EQ(observer->getStatistics(node->UID()).success_count, 1u);
}
EXPECT_EQ(observer->pathToUID().at("step"), nodes[1]->UID());
}