-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtests.cpp
More file actions
867 lines (690 loc) · 23.6 KB
/
tests.cpp
File metadata and controls
867 lines (690 loc) · 23.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
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
#include "yaml-path/yaml-accumulate.h"
#include "yaml-path/yaml-path.h"
#define DOCTEST_CONFIG_IMPLEMENT
#include <doctest/doctest.h>
#include <yaml-cpp/yaml.h>
#include <yaml-path/yaml-path.h>
#include <yaml-path/yaml-path-internals.h>
#include <iostream>
#include <assert.h>
struct YamlNodeForDocTest
{
YAML::Node m_node;
YamlNodeForDocTest(YAML::Node n) : m_node(n) {}
operator YAML::Node & () { return m_node; }
operator YAML::Node const & () const { return m_node; }
};
namespace YAML
{
template <typename TEnum>
doctest::String DT2String(TEnum value, std::initializer_list<std::pair<TEnum, char const *>> map)
{
char const * p = YamlPathDetail::MapValue(value, map);
if (p)
return p;
return (std::stringstream() << "(" << (int)value << ")").str().c_str();
}
doctest::String toString(EPathError value) { return DT2String(value, YamlPathDetail::MapEPathErrorName); }
namespace YamlPathDetail
{
doctest::String toString(EToken value) { return DT2String(value, MapETokenName); }
doctest::String toString(ESelector value) { return DT2String(value, MapESelectorName); }
}
doctest::String toString(YAML::Node const & n) { auto n2 = Clone(n); n2.SetStyle(EmitterStyle::Flow); return (Emitter() << n2).c_str(); }
}
using namespace YAML;
// two nodes with equal content - simplifies the tests
// map keys must be strings, and values are compared as strings
bool Equal(YAML::Node a, YAML::Node b)
{
if (a == b)
return true;
if (a.Type() != b.Type())
return false;
switch (a.Type())
{
case YAML::NodeType::Map:
{
if (a.size() != b.size())
return false;
for (auto it = a.begin(); it != a.end(); ++it)
{
auto key = it->first.as<std::string>();
auto rval = b[key]; // value with the same key. If all are the same, and size is the same, also there are no unchecked nodes
if (!Equal(rval, it->second))
return false;
}
return true;
}
case YAML::NodeType::Sequence:
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); ++i)
if (!Equal(a[i], b[i]))
return false;
return true;
case YAML::NodeType::Scalar:
return a.as<std::string>() == b.as<std::string>();
case YAML::NodeType::Null:
case YAML::NodeType::Undefined:
return true;
default:
assert(false); // unknown node type
return false;
}
}
bool operator == (YamlNodeForDocTest const & a, YamlNodeForDocTest const & b) { return Equal(a, b); }
bool operator != (YamlNodeForDocTest const & a, YamlNodeForDocTest const & b) { return Equal(a, b); }
using T = YamlNodeForDocTest;
TEST_CASE("ThisCrashes")
{
Node n = Create("{a=1,b=2}");
auto nb = n["b"]; // crash here if original code without vectors is used (github: https://github.com/jbeder/yaml-cpp/issues/688)
/* Minimal repro:
Node root(NodeType::Null);
Node next;
next.push_back(root);
Node el = next[0];
{
Node assignTo;
assignTo.push_back(el["a"]);
assignTo[0] = Node(std::string("1"));
}
{
Node assignTo;
assignTo.push_back(el["b"]);
assignTo[0] = Node(std::string("2"));
}
Node nb = root["b"]; // doesn't crash, can be omitted
next.reset();
el.reset();
Node nbA = root["a"]; // doesn't crash, can be omitted
Node nbB = root["b"]; // crashes
*/
}
TEST_CASE("SelectByKey")
{
{
Node n = Load("{ A : aa, B : bb }");
CHECK(SelectByKey(n, "A") == EPathError::OK);
CHECK(n.as<std::string>() == "aa");
}
{
Node n = Load("[ { A : aa, B : bb }, { X : xx, A : aaa } ]");
CHECK(SelectByKey(n, "A") == EPathError::OK);
CHECK(n.IsSequence());
CHECK(n.size() == 2);
CHECK(n[0].as<std::string>() == "aa");
CHECK(n[1].as<std::string>() == "aaa");
}
{
Node n = Load("{ A : aa, B : bb }");
CHECK(SelectByKey(n, "X") == EPathError::NodeNotFound);
}
{
Node n = Load("abcd");
CHECK(SelectByKey(n, "X") == EPathError::InvalidNodeType);
}
}
TEST_CASE("SelectByIndex")
{
{
Node n = Load("[1, 2, 3, 4]");
CHECK(SelectByIndex(n, 0) == EPathError::OK);
CHECK(n.as<std::string>() == "1");
}
{
Node n = Load("[1, 2, 3, 4]");
CHECK(SelectByIndex(n, 3) == EPathError::OK);
CHECK(n.as<std::string>() == "4");
}
{
Node n = Load("[1, 2, 3, 4]");
CHECK(SelectByIndex(n, 7) == EPathError::NodeNotFound);
CHECK(n.IsSequence());
}
{
Node n = Load("abcd");
CHECK(SelectByIndex(n, 0) == EPathError::OK);
CHECK(n.as<std::string>() == "abcd");
}
{
Node n = Load("abcd");
CHECK(SelectByIndex(n, 1) == EPathError::NodeNotFound);
CHECK(n.as<std::string>() == "abcd");
}
}
// ---- parse level 0: SplitAt, Split
TEST_CASE("Internal: SplitAt")
{
using namespace YAML::YamlPathDetail;
auto Check = [](PathArg p, size_t offset, PathArg expectedResult, PathArg expectedP)
{
CHECK(p.size() == expectedResult.size() + expectedP.size());
auto result = SplitAt(p, offset);
CHECK(result == expectedResult);
CHECK(p == expectedP);
};
Check("", 0, "", "");
Check("", 1, "", "");
Check("a", 0, "", "a");
Check("a", 1, "a", "");
Check("a", 2, "a", "");
Check("abc", 0, "", "abc");
Check("abc", 1, "a", "bc");
Check("abc", 2, "ab", "c");
Check("abc", 3, "abc", "");
Check("abc", 4, "abc", "");
}
namespace
{
void CheckSplit(PathArg p, PathArg expectedResult, PathArg expectedP)
{
using namespace YAML::YamlPathDetail;
CHECK(p.size() == expectedResult.size() + expectedP.size());
auto result = Split(p, isdigit);
CHECK(result == expectedResult);
CHECK(p == expectedP);
}
}
TEST_CASE("Internal: Split")
{
CheckSplit("", "", "");
CheckSplit("12ab", "12", "ab");
CheckSplit("1234", "1234", "");
}
// ---- parse level 1: TokenScanner
TEST_CASE("Internal: TokenScanner")
{
using namespace YamlPathDetail;
{
PathArg scanMe = "a.beta.'a b[c]'.\"a.b\".[].#.abc";
PathScanner scan(scanMe);
CHECK(scan);
CHECK(scan.NextToken().id == EToken::UnquotedIdentifier);
CHECK(scan.Token().value == "a");
CHECK(scan);
CHECK(scan.NextToken().id == EToken::Period);
CHECK(scan.NextToken().id == EToken::UnquotedIdentifier);
CHECK(scan.Token().value == "beta");
CHECK(scan.NextToken().id == EToken::Period);
CHECK(scan.NextToken().id == EToken::QuotedIdentifier);
CHECK(scan.Token().value== "a b[c]");
CHECK(scan.NextToken().id == EToken::Period);
CHECK(scan.NextToken().id == EToken::QuotedIdentifier);
CHECK(scan.Token().value == "a.b");
CHECK(scan.NextToken().id == EToken::Period);
CHECK(scan.NextToken().id == EToken::OpenBracket);
CHECK(scan.NextToken().id == EToken::CloseBracket);
CHECK(scan.NextToken().id == EToken::Period);
CHECK(scan.NextToken().id == EToken::Invalid);
CHECK(!scan); // at end when invalid
CHECK(scan.NextToken().id == EToken::Invalid); // remains at "invalid"
}
}
// --- parse level 2: selector scanner
namespace
{
void CheckSelectorError(std::string_view s, EPathError expectedError, std::string_view expectedResolved, std::string_view expectedRight)
{
using namespace YamlPathDetail;
PathException x;
PathScanner scan(s, {}, &x);
while (1)
{
auto st = scan.NextSelector();
CHECK(st != ESelector::None);
if (st == ESelector::Invalid)
break;
}
CHECK(scan.Error() == expectedError);
CHECK(x.ResolvedPath() == expectedResolved);
CHECK(scan.Right() == expectedRight);
// TODO: check expected diagnostics?
}
}
TEST_CASE("ScanSelector")
{
using namespace YamlPathDetail;
{
PathScanner scan("1.test.'xyz'.[0].abc[2][3]");
CHECK(scan.NextSelector() == ESelector::Key);
CHECK(scan.SelectorData< ArgKey>().key == "1");
CHECK(scan.NextSelector() == ESelector::Key);
CHECK(scan.SelectorData<ArgKey>().key == "test");
CHECK(scan.NextSelector() == ESelector::Key);
CHECK(scan.SelectorData<ArgKey>().key == "xyz");
CHECK(scan.NextSelector() == ESelector::Index);
CHECK(scan.SelectorData<ArgIndex>().index == 0);
CHECK(scan.NextSelector() == ESelector::Key);
CHECK(scan.SelectorData<ArgKey>().key == "abc");
CHECK(scan.NextSelector() == ESelector::Index);
CHECK(scan.SelectorData<ArgIndex>().index == 2);
CHECK(scan.NextSelector() == ESelector::Index);
CHECK(scan.SelectorData<ArgIndex>().index == 3);
}
{
// these tests go a little bit into implementation details,
// particularly "expectedRight" and "expectedErrorValue" are for diagnostic purposes only, and not exactly guaranteed by the API.
// However, we check here that they make SOME sense, i.e. not be totally off
CheckSelectorError(".a", EPathError::InvalidToken, "", "a");
CheckSelectorError("a.", EPathError::UnexpectedEnd, "a", "");
CheckSelectorError("a..b", EPathError::InvalidToken, "a", "b");
CheckSelectorError("a[.]", EPathError::InvalidIndex, "a", "]");
}
}
TEST_CASE("ScanSelector - bound arguments")
{
using namespace YamlPathDetail;
{
PathScanner scan("node.%.[%].edon", { "param", 42 });
CHECK(scan.NextSelector() == ESelector::Key);
CHECK(scan.SelectorData< ArgKey>().key == "node");
CHECK(scan.NextSelector() == ESelector::Key);
CHECK(scan.SelectorData< ArgKey>().key == "param");
CHECK(scan.NextSelector() == ESelector::Index);
CHECK(scan.SelectorData< ArgIndex>().index == 42);
CHECK(scan.NextSelector() == ESelector::Key);
CHECK(scan.SelectorData< ArgKey>().key == "edon");
}
}
TEST_CASE("PathValidate")
{
CHECK(PathValidate("") == EPathError::OK);
CHECK(PathValidate("a") == EPathError::OK);
CHECK(PathValidate("a.b") == EPathError::OK);
CHECK(PathValidate("a.[2]") == EPathError::OK);
CHECK(PathValidate("a[2]") == EPathError::OK);
CHECK(PathValidate("[2]") == EPathError::OK);
CHECK(PathValidate("~") == EPathError::InvalidToken);
CHECK(PathValidate("[2[") == EPathError::InvalidToken);
CHECK(PathValidate("[2222222222222222222222]") == EPathError::InvalidIndex); // index overflows 64 bit uint
CHECK(PathValidate(".a.b") == EPathError::InvalidToken);
CHECK(PathValidate("].a.b") == EPathError::InvalidToken);
CHECK(PathValidate("a.") == EPathError::UnexpectedEnd);
}
YAML::Node CheckPathResolve(YAML::Node node, YAML::PathArg path, std::string expectedRemainder)
{
PathResolve(node, path);
CHECK(path == expectedRemainder);
return node;
}
TEST_CASE("PathResolve - Sequence")
{
YAML::Node root = YAML::Load("[1, 2, 3]");
{
auto n = CheckPathResolve(root, "", "");
CHECK(n == root); // should be the same node
}
{
auto n = CheckPathResolve(root, "[0]", "");
CHECK(n.as<std::string>() == "1");
}
{
auto n = CheckPathResolve(root, "[1]", "");
CHECK(n.as<std::string>() == "2");
}
{
auto n = CheckPathResolve(root, "[2]", "");
CHECK(n.as<std::string>() == "3");
}
{
auto n = CheckPathResolve(root, "[5]", "[5]");
CHECK(n.size() == 3);
}
}
TEST_CASE("PathResolve - Map")
{
char const * sroot =
R"(1 : Hello
2 : World
3 :
- SeqA
- SeqB
- { Letter : X, Digit : 4 })";
using S = std::string;
auto root = YAML::Load(sroot);
{
auto n = CheckPathResolve(root, "1", "");
CHECK(n.as<S>() == "Hello");
}
{
auto n = CheckPathResolve(root, "2", "");
CHECK(n.as<S>() == "World");
}
{
auto n = CheckPathResolve(root, "3", "");
CHECK(n.IsSequence());
}
{
auto n = CheckPathResolve(root, "3[0]", "");
CHECK(n.as<S>() == "SeqA");
}
{
auto n = CheckPathResolve(root, "3[2].Letter", "");
CHECK(n.as<S>() == "X");
}
{
auto n = CheckPathResolve(root, "3[2].Digit", "");
CHECK(n.as<S>() == "4");
}
}
TEST_CASE("PathResolve - SeqMap")
{
char const * sroot =
R"(
- name : Joe
color: red
names: 3
- name : Sina
color: blue
names: 4
- name : Estragon
voice : none)";
using S = std::string;
{
auto node = YAML::Load(sroot);
PathArg path = "name";
CHECK(PathResolve(node, path) == EPathError::OK);
CHECK(path == "");
CHECK(node.IsSequence());
CHECK(node.size() == 3);
CHECK(node[0].as<S>("") == "Joe");
CHECK(node[1].as<S>("") == "Sina");
CHECK(node[2].as<S>("") == "Estragon");
}
{
auto node = YAML::Load(sroot);
PathArg path = "voice";
CHECK(PathResolve(node, path) == EPathError::OK);
CHECK(path == "");
CHECK(node.IsSequence());
CHECK(node.size() == 1);
CHECK(node[0].as<S>("") == "none");
}
{
auto node = YAML::Load(sroot);
PathArg path = "xyz";
CHECK(PathResolve(node, path) == EPathError::NodeNotFound);
CHECK(path == "xyz");
CHECK(node.IsSequence());
CHECK(node.size() == 3);
CHECK(node[0].IsMap());
}
}
TEST_CASE("PathResolve - MapFilter (adapted from initial syntax)")
{
char const * sroot =
R"(
- name : Joe
color: red
place: here
- name : Sina
color: blue
- name : Estragon
color: blue
place: there)";
using S = std::string;
{ // has 3 nodes with any "name"
auto node = YAML::Load(sroot);
PathArg path = "{name=}"; // all having a name
CHECK(PathResolve(node, path) == EPathError::OK);
CHECK(path == "");
CHECK(node.IsSequence());
CHECK(node.size() == 3);
CHECK(node[0].IsMap());
CHECK(node[0].size() == 3);
CHECK(node[0]["name"].as<S>() == "Joe");
CHECK(node[0]["color"].as<S>() == "red");
CHECK(node[1].IsMap());
CHECK(node[1].size() == 2);
CHECK(node[1]["name"].as<S>() == "Sina");
CHECK(node[1]["color"].as<S>() == "blue");
CHECK(node[2].IsMap());
CHECK(node[2].size() == 3);
CHECK(node[2]["name"].as<S>() == "Estragon");
CHECK(node[2]["color"].as<S>() == "blue");
}
{ // has no node with empty "name"
auto node = YAML::Load(sroot);
PathArg path = "{name=''}";
CHECK(PathResolve(node, path) == EPathError::NodeNotFound);
CHECK(path == "{name=''}");
CHECK(node.IsSequence());
CHECK(node.size() == 3);
CHECK(node[2]["name"].as<S>() == "Estragon"); // let's call that "sufficient check if this is still the root node"
}
{ // has two nodes with any "place"
auto node = YAML::Load(sroot);
PathArg path = "{place=}";
CHECK(PathResolve(node, path) == EPathError::OK);
CHECK(path == "");
CHECK(node.IsSequence());
CHECK(node.size() == 2);
CHECK(node[0]["name"].as<S>() == "Joe");
CHECK(node[1]["name"].as<S>() == "Estragon");
}
{ // has three nodes with any color
auto node = YAML::Load(sroot);
PathArg path = "{color=}";
CHECK(PathResolve(node, path) == EPathError::OK);
CHECK(path == "");
CHECK(node.IsSequence());
CHECK(node.size() == 3);
}
{ // has three nodes with color "blue"
auto node = YAML::Load(sroot);
PathArg path = "{color=blue}";
CHECK(PathResolve(node, path) == EPathError::OK);
CHECK(path == "");
CHECK(node.IsSequence());
CHECK(node.size() == 2);
CHECK(node[0]["name"].as<S>() == "Sina");
CHECK(node[1]["name"].as<S>() == "Estragon");
}
}
TEST_CASE("Accumulate (simple, tests AccumulateRefOp)")
{
{
auto n = Load("[2, 3, 4, 5]");
int result = Accumulate<int>(n, 1);
CHECK(result == 15);
}
{
auto n = Load("{ a : 2, b : 3, c : 4, d : 5}");
int result = Accumulate<int>(n, 1);
CHECK(result == 15);
}
{
auto n = Load("23");
int result = Accumulate<int>(n, 17);
CHECK(result == 40);
}
}
TEST_CASE("Accumulate with custom op")
{
auto n = Load("[2, 3, 4, 5]");
int result = Accumulate<int>(n, 1, [](int a, int b) {return a * b; });
CHECK(result == 120);
}
void CheckCreate(char const * path, char const * expectedNode)
{
auto n = YAML::Create(path);
std::string forDbg = (YAML::Emitter() << n).c_str();
auto expectedN = YAML::Load(expectedNode);
CHECK(T(n) == T(expectedN));
}
TEST_CASE("Create")
{
CheckCreate("keyA.keyB", "{ keyA : { keyB : ~ } }");
CheckCreate("keyA[2].keyB", "{ keyA : [ ~ , ~ , { keyB : ~ } ] } ");
// --- MapFilter Selector:
CheckCreate("keyA.{X}.keyB", "{ keyA : { X : { keyB : ~ } } }"); // MFS: create one key
CheckCreate("keyA.{X,Y}.keyB", "{ keyA : { X : { keyB : ~ }, Y : { keyB : ~ } } }"); // MFS: create two keys
CheckCreate("keyA.{X=11,Y}.keyB", "{ keyA : { X : 11, Y : { keyB : ~ } } }"); // MFS: create one, assign one
CheckCreate("keyA.{X=11,Y=12}", "{ keyA : { X : 11, Y : 12 } }"); // MFS: assign two
CheckCreate("keyA.{X=11}", "{ keyA : { X : 11 } }"); // MFS: assign one
CheckCreate("{keyA=11,keyB,keyC}.{keyD,keyE=12}",
"{ keyA : 11, keyB : { keyD : ~, keyE : 12 }, keyC : { keyD : ~, keyE : 12 } }");
// should fail:
// CheckCreateFai("keyA.{X=11}.keyB");
// CheckCreateFai("keyA.{X=11,Y=12}.keyB");
}
void CheckEnsure(char const * initial, char const * path, size_t expectedEndNodeCount, char const * expectedRoot, char const * expectedAfterAssignment)
{
YAML::Node root = initial ? YAML::Load(initial) : YAML::Node(YAML::NodeType::Null);
YAML::Node result = YAML::Ensure(root, path);
if (expectedEndNodeCount)
{
CHECK(result.IsSequence());
CHECK(result.size() == expectedEndNodeCount);
}
else
CHECK(result.size() == 0);
YAML::Node expectedRootY = YAML::Load(expectedRoot);
YAML::Node expectedAfterAssignmentY = YAML::Load(expectedAfterAssignment);
std::string rootS = (YAML::Emitter() << root).c_str();
CHECK(T(root) == T(expectedRootY));
for (size_t i=0; i<result.size(); ++i)
{
if (result[i].IsNull())
result[i] = YAML::Node("111");
}
std::string afterAssignmentS = (YAML::Emitter() << root).c_str();
CHECK(T(root) == T(expectedAfterAssignmentY));
}
TEST_CASE("Ensure")
{
CheckEnsure(nullptr, "keyA.keyB", 1,
"{ keyA : { keyB : ~ } }",
"{ keyA : { keyB : 111 } }");
CheckEnsure("keyA : ", "keyA.keyB", 1,
"{ keyA : { keyB : ~ } }",
"{ keyA : { keyB : 111 } }");
CheckEnsure("keyA : 12", "{keyA,keyB}.keyC", 1,
"{ keyA : 12, keyB : { keyC : ~ } }",
"{ keyA : 12, keyB : { keyC : 111 } }");
CheckEnsure("keyA : 12", "{keyA=22,keyB}.{keyC=33,keyD,keyE}", 2,
"{ keyA : 12, keyB : { keyC : 33, keyD : ~, keyE : ~ } }",
"{ keyA : 12, keyB : { keyC : 33, keyD : 111, keyE : 111 } }");
}
bool is(char const * a, char const * b) { return _stricmp(a, b) == 0; }
bool is(char const * a, char const * b, char const * balt) { return is(a,b) || (balt && is(a,balt)); }
int main(int argc, char ** argv)
{
auto is_ = [&](int argidx, char const * b, char const * balt = nullptr)
{
return argc > argidx && is(argv[argidx], b, balt);
};
if (is_(1, "--runtests", "-r"))
return doctest::Context(argc-1, argv+1).run();
if (argc == 1 || (argc == 2 && is_(1, "--help", "-h")))
{
std::cout << R"(Options:
--runtest, -r (must be first) Run unit tests. all following arguments are passed to doctest.
--help, -h (must be the only argument) show this help
<YAMLFile> <path> [-v|--verbose] [<command>]
Run a YAML path command against the specified YAML
YAMLFile can be:
a path to a YAML file,
* for the embedded YAML sample,
*<yaml> where <yaml> is a raw YAML string
<path> is a YAML path
-v to enable verbose output, appending secondary data and diagnostics
<command> is the command to run
Select or S (default)
Require or R
PathResolve or P
PathValidate or V
Ensure or E
)";
return 0;
}
if (argc >= 2 && argc <= 5)
{
const bool verbose = is_(3, "--verbose", "-v");
try
{
YAML::Node root;
char const * sroot = argv[1];
if (*sroot == '*')
{
++sroot;
if (*sroot)
root = YAML::Load(sroot);
else
root = YAML::Load(R"(
- name : Joe
color: red
friends : ~
- name : Sina
color: blue
- name : Estragon
color : red
friends :
Wladimir : good
Godot : unreliable)");
}
else
root = YAML::LoadFile(sroot);
char const * yamlPath = "";
if (argc >= 3)
yamlPath = argv[2];
int cmdidx = verbose ? 4 : 3;
if (is_(cmdidx, "S", "Select") || argc <= cmdidx || is_(cmdidx, "")) // Select
{
auto result = YAML::Select(root, yamlPath);
std::cout << (YAML::Emitter() << result).c_str() << "\n";
}
else if (is_(cmdidx, "R", "Require"))
{
auto result = YAML::Require(root, yamlPath);
std::cout << (YAML::Emitter() << result).c_str() << "\n";
}
else if (is_(cmdidx, "P", "PathResolve"))
{
YAML::PathException x;
YAML::PathArg path = yamlPath;
auto result = PathResolve(root, path, {}, verbose ? &x : nullptr);
std::cout << (YAML::Emitter() << root).c_str() << "\n";
if (verbose)
{
std::cout << "---\n";
if (result != YAML::EPathError::OK)
std::cout << "DIAGS: " << x.what();
else
std::cout << "DIAGS: OK\n";
std::cout << "---\n"
<< "remaining path: " << std::string(path);
}
}
else if (is_(cmdidx, "V", "PathValidate"))
{
YAML::PathException x;
std::string valid;
size_t erroffs = 0;
auto result = YAML::PathValidate(yamlPath, &valid, &erroffs);
std::cout << "---\n" << YAML::PathException::GetErrorMessage(result) << "\n"
<< "valid path: " << valid << "\n"
<< "error offset: " << erroffs << "\n";
}
else if (is_(cmdidx, "E", "EnsureNode"))
{
YAML::PathException x;
std::string valid;
size_t erroffs = 0;
auto result = YAML::Ensure(root, yamlPath);
std::cout << (YAML::Emitter() << root).c_str() << "\n";
}
else
throw std::exception("unknown command");
}
catch (std::exception const & x)
{
if (verbose)
std::cout << "---\nERROR: " << x.what() << "\n";
}
}
else
std::cout << "unknown arguments. use -h for help.\n";
}