-
Notifications
You must be signed in to change notification settings - Fork 131
/
yang_parse_tree_test.cc
5084 lines (4346 loc) · 204 KB
/
yang_parse_tree_test.cc
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
// Copyright 2018 Google LLC
// Copyright 2018-present Open Networking Foundation
// SPDX-License-Identifier: Apache-2.0
#include "absl/synchronization/mutex.h"
#include "gmock/gmock.h"
#include "gnmi/gnmi.pb.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "openconfig/openconfig.pb.h"
#include "stratum/glue/status/status_test_util.h"
#include "stratum/hal/lib/common/constants.h"
#include "stratum/hal/lib/common/gnmi_publisher.h"
#include "stratum/hal/lib/common/subscribe_reader_writer_mock.h"
#include "stratum/hal/lib/common/switch_mock.h"
#include "stratum/hal/lib/common/utils.h"
#include "stratum/hal/lib/common/writer_mock.h"
#include "stratum/hal/lib/common/yang_parse_tree_mock.h"
#include "stratum/lib/constants.h"
#include "stratum/lib/test_utils/matchers.h"
#include "stratum/lib/utils.h"
namespace stratum {
namespace hal {
using test_utils::StatusIs;
using ::testing::_;
using ::testing::ContainsRegex;
using ::testing::DoAll;
using ::testing::HasSubstr;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::SizeIs;
using ::testing::WithArg;
using ::testing::WithArgs;
class YangParseTreeTest : public ::testing::Test {
protected:
using OnEventAction = GnmiEventHandler (TreeNode::*)() const;
using OnSetAction = GnmiSetHandler (TreeNode::*)() const;
static constexpr int kInterface1NodeId = 3;
static constexpr int kInterface1PortId = 3;
static constexpr uint32 kInterface1QueueId = 0;
static constexpr char kInterface1QueueName[] = "BE1";
static constexpr int kOpticalInterface1ModuleId = 5;
static constexpr int kOpticalInterface1PortId = 5;
static constexpr int kOpticalInterface1NetIfId = 5;
static constexpr uint64 kOpticalInterface1Frequency = 123456000000;
static constexpr float kOpticalInterface1TargetOutputPower = 1.2345;
static constexpr uint64 kOpticalInterface1OpMode = 67890;
static constexpr char kAlarmDescription[] = "alarm";
static constexpr char kAlarmSeverityText[] = "CRITICAL";
static constexpr Alarm::Severity kAlarmSeverityEnum = Alarm::CRITICAL;
static constexpr uint64 kAlarmTimeCreated = 12345ull;
static constexpr bool kAlarmStatusTrue = true;
static constexpr uint64 kInterfaceMac = 0x112233445566ull;
YangParseTreeTest() : parse_tree_(&switch_) {}
void SetUp() override {}
void PrintNode(const TreeNode& node, const std::string& prefix) const {
LOG(INFO) << prefix << node.name();
for (const auto& entry : node.children_) {
PrintNode(entry.second, prefix + " ");
}
}
void PrintNodeWithOnTimer(const TreeNode& node,
const std::string& prefix) const {
LOG(INFO) << prefix << node.name() << ": "
<< node.AllSubtreeLeavesSupportOnTimer() << " "
<< node.supports_on_timer_;
for (const auto& entry : node.children_) {
PrintNodeWithOnTimer(entry.second, prefix + " ");
}
}
void PrintPath(const ::gnmi::Path& path) const {
LOG(INFO) << path.ShortDebugString();
}
const TreeNode& GetRoot() const { return parse_tree_.root_; }
TreeNode* AddNode(const ::gnmi::Path& path) {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
return parse_tree_.AddNode(path);
}
// A proxy for YangParseTree::PerformActionForAllNonWildcardNodes().
::util::Status PerformActionForAllNonWildcardNodes(
const gnmi::Path& path, const gnmi::Path& subpath,
const std::function<::util::Status(const TreeNode& leaf)>& action) const {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
return parse_tree_.PerformActionForAllNonWildcardNodes(path, subpath,
action);
}
// A proxy for YangParseTree::gnmi_event_writer_.
void SetGnmiEventWriter(WriterInterface<GnmiEventPtr>* channel) {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
parse_tree_.gnmi_event_writer_.reset(channel);
}
// A proxy for YangParseTree::AddSubtreeInterface().
void AddSubtreeInterface(const std::string& name,
SingletonPort* singleton_p = nullptr) {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
// Add one singleton port.
SingletonPort singleton;
SingletonPort* singleton_ptr =
(singleton_p == nullptr) ? &singleton : singleton_p;
singleton_ptr->set_name(name);
singleton_ptr->set_node(kInterface1NodeId);
singleton_ptr->set_id(kInterface1PortId);
singleton_ptr->set_speed_bps(kTwentyFiveGigBps);
singleton_ptr->mutable_config_params()
->mutable_mac_address()
->set_mac_address(kInterfaceMac);
// Add one per port per queue stat for this interface.
NodeConfigParams node_config;
{
auto* entry =
node_config.mutable_qos_config()->add_traffic_class_mapping();
entry->set_internal_priority(2); // some internal priority
entry->set_traffic_class(TrafficClass::BE1);
}
{
auto* entry = node_config.mutable_qos_config()->add_cosq_mapping();
entry->set_internal_priority(2); // some internal priority
entry->set_q_num(kInterface1QueueId);
}
parse_tree_.AddSubtreeInterfaceFromSingleton(*singleton_ptr, node_config);
}
// Create /components/component[name]/optical-channel subtree from the
// default OpticalNetworkInterface instance.
void AddSubtreeOpticalInterface(const std::string& name) {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
OpticalNetworkInterface optical_port;
optical_port.set_name(name);
optical_port.set_line_port("line-port-1");
optical_port.set_module(kOpticalInterface1ModuleId);
optical_port.set_network_interface(kOpticalInterface1NetIfId);
optical_port.set_id(kOpticalInterface1PortId);
optical_port.set_frequency(kOpticalInterface1Frequency);
optical_port.set_target_output_power(kOpticalInterface1TargetOutputPower);
optical_port.set_operational_mode(kOpticalInterface1OpMode);
parse_tree_.AddSubtreeInterfaceFromOptical(optical_port);
}
// A proxy for YangParseTree::AddSubtreeChassis().
void AddSubtreeChassis(const std::string& name) {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
Chassis chassis;
chassis.set_name(name);
parse_tree_.AddSubtreeChassis(chassis);
}
// A proxy for YangParseTree::AddSubtreeNode().
void AddSubtreeNode(const std::string& name, uint64 node_id) {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
Node node;
node.set_name(name);
node.set_id(node_id);
parse_tree_.AddSubtreeNode(node);
}
void AddSubtreeSystem() {
absl::WriterMutexLock l(&parse_tree_.root_access_lock_);
parse_tree_.AddSubtreeSystem();
}
// A method helping testing if the OnXxx method of a leaf specified by 'path'.
// It takes care of all the boiler plate code:
// - adds an interface named "interface-1"
// - adds a node named "node-1"
// - creates a stream that will write the response proto-buf into 'resp'
// - finds the node in the parse three
// - gets the requested handler
// - calls the handler with 'event'
// - returns status produced by execution of the handler.
::util::Status ExecuteOnAction(const ::gnmi::Path& path,
const OnEventAction& action,
const GnmiEvent& event,
::gnmi::SubscribeResponse* resp) {
// After tree creation only three leafs are defined:
// /interfaces/interface[name=*]/state/id
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
// The test requires one interface branch to be added.
AddSubtreeInterface("interface-1");
// The test requires one node branch to be added.
AddSubtreeNode("node-1", kInterface1NodeId);
// The test requires one optical interface branch to be added.
AddSubtreeOpticalInterface("optical-interface-1");
// The test requires the system branch to be added.
AddSubtreeSystem();
// Mock gRPC stream that copies parameter of Write() to 'resp'. The contents
// of the 'resp' variable is then checked.
SubscribeReaderWriterMock stream;
EXPECT_CALL(stream, Write(_, _))
.WillOnce(DoAll(
WithArgs<0>(Invoke(
[resp](const ::gnmi::SubscribeResponse& r) { *resp = r; })),
Return(true)));
// Find the leaf under test.
auto* node = GetRoot().FindNodeOrNull(path);
if (node == nullptr) {
return MAKE_ERROR() << "Cannot find the requested path.";
}
// Get its 'action' handler and call it.
const auto& handler = (node->*action)();
return handler(event, &stream);
}
// A method helping testing if the OnPoll method of a leaf specified by
// 'path'. It calls ExecuteOnAction() that takes care of all the boiler plate
// code:
// - adds an interface named "interface-1"
// - creates a stream that will write the response proto-buf into 'resp'
// - finds the node in the parse three
// - gets the OnPoll event handler
// - calls the handler with PollEvent event
// - returns status produced by execution of the handler.
// The caller can then check if the contents of 'resp' is the expected one
// (assuming the returned status is ::util::OkStatus())
::util::Status ExecuteOnPoll(const ::gnmi::Path& path,
::gnmi::SubscribeResponse* resp) {
return ExecuteOnAction(path, &TreeNode::GetOnPollHandler, PollEvent(),
resp);
}
// A method helping testing if the OnTimer method of a leaf specified by
// 'path'. It calls ExecuteOnAction() that takes care of all the boiler plate
// code:
// - adds an interface named "interface-1"
// - creates a stream that will write the response proto-buf into 'resp'
// - finds the node in the parse three
// - gets the OmTimer event handler
// - calls the handler with TimerEvent event
// - returns status produced by execution of the handler.
// The caller can then check if the contents of 'resp' is the expected one
// (assuming the returned status is ::util::OkStatus())
::util::Status ExecuteOnTimer(const ::gnmi::Path& path,
::gnmi::SubscribeResponse* resp) {
return ExecuteOnAction(path, &TreeNode::GetOnTimerHandler, TimerEvent(),
resp);
}
// A method helping testing if the OnChange method of a leaf specified by
// 'path'. It calls ExecuteOnAction() that takes care of all the boiler plate
// code:
// - adds an interface named "interface-1"
// - creates a stream that will write the response proto-buf into 'resp'
// - finds the node in the parse three
// - gets the OnChange event handler
// - calls the handler with 'event' event
// - returns status produced by execution of the handler.
// The caller can then check if the contents of 'resp' is the expected one
// (assuming the returned status is ::util::OkStatus())
::util::Status ExecuteOnChange(const ::gnmi::Path& path,
const GnmiEvent& event,
::gnmi::SubscribeResponse* resp) {
return ExecuteOnAction(path, &TreeNode::GetOnChangeHandler, event, resp);
}
// A method helping testing if the OnChange method of
// /components/component/chassis/alarms sub-tree leaf specified by 'path'.
// It takes care of all the boiler plate code:
// - adds a chassis named "chassis-1"
// - creates a stream that will write the response proto-buf into 'resp'
// - finds the node in the parse three
// - gets the OnChange event handler
// - calls the handler with event of type 'A'
// - returns status produced by execution of the handler.
// - checks if the received response in field that is read using 'get_value'
// of type 'U' is equal to 'expected_value' of type 'V'
template <class A, class U, class V>
void TestOnChangeAlarmLeaf(const ::gnmi::Path& path,
U (::gnmi::TypedValue::*get_value)() const,
V expected_value) {
// The test requires chassis component branch to be added.
AddSubtreeChassis("chassis-1");
// Call the event handler. 'resp' will contain the message that is sent to
// the controller.
::gnmi::SubscribeResponse resp;
ASSERT_OK(
ExecuteOnChange(path, A(kAlarmTimeCreated, kAlarmDescription), &resp));
// Check that the result of the call is what is expected.
ASSERT_THAT(resp.update().update(), SizeIs(1));
EXPECT_EQ((resp.update().update(0).val().*get_value)(), expected_value);
}
// A method helping testing if the OnPoll method of
// /components/component/chassis/alarms sub-tree leaf specified by 'path'.
// It takes care of all the boiler plate code:
// - adds a chassis named "chassis-1"
// - creates a stream that will write the response proto-buf into 'resp' with
// value 'conf_value' of type 'W'
// - finds the node in the parse three
// - gets the OnPoll event handler
// - calls the handler with PollEvent event
// - returns status produced by execution of the handler.
// - checks if the received response in field that is read using 'get_value'
// of type 'U' is equal to 'expected_value' of type 'V'
template <class U, class V, class W, class Y>
void TestOnPollAlarmLeaf(const ::gnmi::Path& path,
U (::gnmi::TypedValue::*get_value)() const,
Alarm* (DataResponse::*mutable_alarm)(),
void (Alarm::*set_value)(Y), V expected_value,
W conf_value) {
// The test requires chassis component branch to be added.
AddSubtreeChassis("chassis-1");
// Mock implementation of RetrieveValue() that sends a response set to
// 'expected_value'.
EXPECT_CALL(switch_, RetrieveValue(_, _, _, _))
.WillOnce(DoAll(
WithArg<2>(Invoke([mutable_alarm, set_value,
conf_value](WriterInterface<DataResponse>* w) {
DataResponse resp;
// Set the response.
((resp.*mutable_alarm)()->*set_value)(conf_value);
// Send it to the caller.
w->Write(resp);
})),
Return(::util::OkStatus())));
// Call the event handler. 'resp' will contain the message that is sent to
// the controller.
::gnmi::SubscribeResponse resp;
ASSERT_OK(ExecuteOnPoll(path, &resp));
// Check that the result of the call is what is expected.
ASSERT_THAT(resp.update().update(), SizeIs(1));
EXPECT_EQ((resp.update().update(0).val().*get_value)(), expected_value)
<< resp.ShortDebugString();
}
// A specialization of generic template method TestOnPollAlarmLeaf().
// It is used when 'expected_value' and 'conf_value' are the same.
template <class U, class V>
void TestOnPollAlarmLeaf(const ::gnmi::Path& path,
U (::gnmi::TypedValue::*get_value)() const,
Alarm* (DataResponse::*mutable_alarm)(),
void (Alarm::*set_value)(U), V expected_value) {
TestOnPollAlarmLeaf(path, get_value, mutable_alarm, set_value,
expected_value, expected_value);
}
// A method helping testing if the OnXxx method of a leaf specified by 'path'.
// It takes care of all the boiler plate code:
// - adds an interface named "interface-1"
// - adds a node named "node-1"
// - creates a mock method that will write the set request proto-buf into
// 'req'
// - finds the node in the parse three
// - gets the requested handler
// - calls the handler with 'val'
// - returns status produced by execution of the handler.
::util::Status ExecuteOnSet(const ::gnmi::Path& path,
const OnSetAction& action,
const ::google::protobuf::Message& val,
SetRequest* req, GnmiEventPtr* notification) {
// After tree creation only three leafs are defined:
// /interfaces/interface[name=*]/state/id
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
ChassisConfig chassis_config;
// The test requires one interface branch to be added.
AddSubtreeInterface("interface-1", chassis_config.add_singleton_ports());
// The test requires one node branch to be added.
AddSubtreeNode("node-1", kInterface1NodeId);
// The test requires one optical interface branch to be added.
AddSubtreeOpticalInterface("optical-interface-1");
// The test requires the system branch to be added.
AddSubtreeSystem();
// Make a copy-on-write pointer to current chassis configuration.
CopyOnWriteChassisConfig config(&chassis_config);
// Expect the SetValue() call only if the 'req' is not nullptr.
if (req) {
EXPECT_CALL(switch_, SetValue(_, _, _))
.WillOnce(DoAll(
WithArgs<1>(Invoke([req](const SetRequest& r) { *req = r; })),
Return(::util::OkStatus())));
} else {
EXPECT_CALL(switch_, SetValue(_, _, _)).Times(0);
}
if (notification) {
EXPECT_CALL(parse_tree_, SendNotification(_))
.WillOnce(WithArg<0>(Invoke(
[notification](const GnmiEventPtr& n) { *notification = n; })));
} else {
EXPECT_CALL(parse_tree_, SendNotification(_)).Times(0);
}
// Find the leaf under test.
auto* node = GetRoot().FindNodeOrNull(path);
if (node == nullptr) {
return MAKE_ERROR() << "Cannot find the requested path.";
}
// Get its 'action' handler and call it.
const auto& handler = (node->*action)();
auto status = handler(path, val, &config);
if (config.HasBeenChanged()) delete config.PassOwnership();
return status;
}
// A method helping testing if the OnUpdate method of a leaf specified by
// 'path'. It calls ExecuteOnSet() that takes care of all the boiler plate
// code:
// - adds an interface named "interface-1"
// - adds a node named "node-1"
// - creates a mock method that will write the set request proto-buf into
// 'req'
// - finds the node in the parse three
// - gets the requested OnUpdate handler
// - calls the handler with 'val'
// - returns status produced by execution of the handler.
// The caller can then check if the contents of 'req' is the expected one
// (assuming the returned status is ::util::OkStatus())
::util::Status ExecuteOnUpdate(const ::gnmi::Path& path,
const ::google::protobuf::Message& val,
SetRequest* req, GnmiEventPtr* notification) {
return ExecuteOnSet(path, &TreeNode::GetOnUpdateHandler, val, req,
notification);
}
// A method helping testing if the OnReplace method of a leaf specified by
// 'path'. It calls ExecuteOnSet() that takes care of all the boiler plate
// code:
// - adds an interface named "interface-1"
// - adds a node named "node-1"
// - creates a mock method that will write the set request proto-buf into
// 'req'
// - finds the node in the parse three
// - gets the requested OnReplace handler
// - calls the handler with 'val'
// - returns status produced by execution of the handler.
// The caller can then check if the contents of 'req' is the expected one
// (assuming the returned status is ::util::OkStatus())
::util::Status ExecuteOnReplace(const ::gnmi::Path& path,
const ::google::protobuf::Message& val,
SetRequest* req, GnmiEventPtr* notification) {
return ExecuteOnSet(path, &TreeNode::GetOnReplaceHandler, val, req,
notification);
}
// A mock of a switch that implements the switch interface.
SwitchMock switch_;
// The implementation under test.
YangParseTreeMock parse_tree_;
// A gnmi::Path comparator.
PathComparator compare_;
};
class YangParseTreeOpticalChannelTest : public YangParseTreeTest {
protected:
// Prepare TypedValue instance with uint 'value' set.
::gnmi::TypedValue GetTypedValue(uint value) const {
::gnmi::TypedValue typed_value;
typed_value.set_uint_val(value);
return typed_value;
}
// Prepare TypedValue instance with string 'value' set.
::gnmi::TypedValue GetTypedValue(const std::string& value) const {
::gnmi::TypedValue typed_value;
typed_value.set_string_val(value);
return typed_value;
}
// Mock switch::RetrieveValue to return the desired value.
template <typename TOption, typename TSetterValue, typename TValue>
void SubstituteOpticalChannelRetrieveValue(
TOption* (OpticalTransceiverInfo::*option_getter)(),
void (TOption::*value_setter)(TSetterValue), const TValue& value) {
const auto mockedRetrieve = [=](WriterInterface<DataResponse>* w) {
DataResponse resp;
OpticalTransceiverInfo* optical_netif_info =
resp.mutable_optical_transceiver_info();
((optical_netif_info->*option_getter)()->*value_setter)(value);
w->Write(resp);
};
EXPECT_CALL(switch_, RetrieveValue(_, _, _, _))
.WillOnce(DoAll(WithArg<2>(Invoke(mockedRetrieve)),
Return(::util::OkStatus())));
}
// Mock switch::RetrieveValue to return the desired value.
template <typename TOption, typename TSetterValue, typename TValue>
void SubstituteOpticalChannelRetrieveValue(
void (TOption::*value_setter)(TSetterValue), const TValue& value) {
const auto mockedRetrieve = [=](WriterInterface<DataResponse>* w) {
DataResponse resp;
OpticalTransceiverInfo* optical_netif_info =
resp.mutable_optical_transceiver_info();
(optical_netif_info->*value_setter)(value);
w->Write(resp);
};
EXPECT_CALL(switch_, RetrieveValue(_, _, _, _))
.WillOnce(DoAll(WithArg<2>(Invoke(mockedRetrieve)),
Return(::util::OkStatus())));
}
};
constexpr int YangParseTreeTest::kInterface1PortId;
constexpr int YangParseTreeTest::kInterface1NodeId;
constexpr char YangParseTreeTest::kInterface1QueueName[];
constexpr char YangParseTreeTest::kAlarmDescription[];
constexpr char YangParseTreeTest::kAlarmSeverityText[];
constexpr uint64 YangParseTreeTest::kAlarmTimeCreated;
constexpr bool YangParseTreeTest::kAlarmStatusTrue;
constexpr uint32 YangParseTreeTest::kInterface1QueueId;
constexpr uint64 YangParseTreeTest::kOpticalInterface1Frequency;
constexpr float YangParseTreeTest::kOpticalInterface1TargetOutputPower;
constexpr uint64 YangParseTreeTest::kOpticalInterface1OpMode;
TEST_F(YangParseTreeTest, LazyOneTimeCopyOnWritePtrModifiedViaPtr) {
ChassisConfig config;
CopyOnWriteChassisConfig lazy_config(&config);
// Check that the lazy copy has not been modified.
// const std::string description = lazy_config->description();
// EXPECT_EQ(description.size(), 0);
EXPECT_EQ(lazy_config->nodes_size(), 0);
EXPECT_FALSE(lazy_config.HasBeenChanged());
// Modify the lazy copy
lazy_config.writable()->set_description("test");
// Check that only the lazy copy has been modified.
EXPECT_TRUE(lazy_config.HasBeenChanged());
EXPECT_THAT(lazy_config->description(), HasSubstr("test"));
EXPECT_EQ(config.description().size(), 0);
}
TEST_F(YangParseTreeTest, LazyOneTimeCopyOnWritePtrModifiedViaRef) {
ChassisConfig config;
CopyOnWriteChassisConfig lazy_config(&config);
// Check that the lazy copy has not been modified.
const std::string description = (*lazy_config).description();
EXPECT_EQ(description.size(), 0);
EXPECT_FALSE(lazy_config.HasBeenChanged());
// Modify the lazy copy
(*lazy_config.writable()).set_description("test");
// Check that only the lazy copy has been modified.
EXPECT_TRUE(lazy_config.HasBeenChanged());
EXPECT_THAT((*lazy_config).description(), HasSubstr("test"));
EXPECT_EQ(config.description().size(), 0);
delete lazy_config.PassOwnership();
}
TEST_F(YangParseTreeTest, CopySubtree) { PrintNode(GetRoot(), ""); }
TEST_F(YangParseTreeTest, AllSupportOnTime) {
EXPECT_FALSE(GetRoot().AllSubtreeLeavesSupportOnTimer());
PrintNodeWithOnTimer(GetRoot(), "");
}
TEST_F(YangParseTreeTest, AllSupportOnChange) {
EXPECT_TRUE(GetRoot().AllSubtreeLeavesSupportOnChange());
}
TEST_F(YangParseTreeTest, AllSupportOnPoll) {
EXPECT_TRUE(GetRoot().AllSubtreeLeavesSupportOnPoll());
}
TEST_F(YangParseTreeTest, AllSupportOnUpdate) {
EXPECT_FALSE(GetRoot().AllSubtreeLeavesSupportOnUpdate());
}
TEST_F(YangParseTreeTest, AllSupportOnReplace) {
EXPECT_FALSE(GetRoot().AllSubtreeLeavesSupportOnReplace());
}
TEST_F(YangParseTreeTest, AllSupportOnDelete) {
EXPECT_FALSE(GetRoot().AllSubtreeLeavesSupportOnDelete());
}
TEST_F(YangParseTreeTest, GetPathWithoutKey) {
auto path =
GetRoot().FindNodeOrNull(GetPath("interfaces")("interface")())->GetPath();
PrintPath(path);
ASSERT_EQ(path.elem_size(), 2);
EXPECT_EQ(path.elem(0).name(), "interfaces");
EXPECT_EQ(path.elem(0).key_size(), 0);
EXPECT_EQ(path.elem(1).name(), "interface");
EXPECT_EQ(path.elem(1).key_size(), 0);
}
TEST_F(YangParseTreeTest, GetPathWithKey) {
auto path = GetRoot()
.FindNodeOrNull(GetPath("interfaces")("interface", "*")())
->GetPath();
PrintPath(path);
ASSERT_EQ(path.elem_size(), 2);
EXPECT_EQ(path.elem(0).name(), "interfaces");
EXPECT_EQ(path.elem(0).key_size(), 0);
EXPECT_EQ(path.elem(1).name(), "interface");
ASSERT_EQ(path.elem(1).key_size(), 1);
EXPECT_EQ(path.elem(1).key().at("name"), "*");
}
TEST_F(YangParseTreeTest, FindRoot) {
auto path = GetPath()();
ASSERT_EQ(path.elem_size(), 0);
auto node = GetRoot().FindNodeOrNull(path);
ASSERT_NE(node, nullptr);
ASSERT_EQ(node, &GetRoot());
auto root = AddNode(GetPath()());
ASSERT_EQ(node, root);
openconfig::Device device;
ASSERT_OK(ReadProtoFromTextFile(
"stratum/hal/lib/common/testdata/simple_oc_device.pb.txt", &device));
std::string msg_bytes;
device.SerializeToString(&msg_bytes);
// Prepare a SET request.
::gnmi::TypedValue req;
req.set_bytes_val(msg_bytes);
ChassisConfig config;
CopyOnWriteChassisConfig copy_on_write_config(&config);
ASSERT_OK(node->GetOnReplaceHandler()(path, req, ©_on_write_config));
}
TEST_F(YangParseTreeTest, PerformActionForAllNodesNonePresent) {
// After tree creation only three leafs are defined:
// /interfaces/interface[name=*]/state/id
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
int counter = 0;
const auto& action = [&counter](const TreeNode& leaf) {
// Count every execution of this action.
++counter;
return ::util::OkStatus();
};
EXPECT_OK(PerformActionForAllNonWildcardNodes(
GetPath("interfaces")("interface")(), GetPath("state")("ifindex")(),
action));
// The action should never be called as there is no nodes in the tree matching
// the request.
EXPECT_EQ(0, counter);
}
// Check if the action is executed for all qualified leafs.
TEST_F(YangParseTreeTest, PerformActionForAllNodesOnePresent) {
// After tree creation only three leafs are defined:
// /interfaces/interface[name=*]/state/id
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
// The test requires one interface branch to be added.
AddSubtreeInterface("interface-1");
std::vector<const TreeNode*> nodes;
const auto& action = [&nodes](const TreeNode& leaf) {
// Store every leaf this action was executed on.
nodes.push_back(&leaf);
return ::util::OkStatus();
};
EXPECT_OK(PerformActionForAllNonWildcardNodes(
GetPath("interfaces")("interface")(), GetPath("state")("ifindex")(),
action));
// The action should be called once as there is one node in the tree matching
// the request.
ASSERT_EQ(1, nodes.size());
EXPECT_FALSE(compare_(
nodes.at(0)->GetPath(),
GetPath("interfaces")("interface", "interface-1")("state")("ifindex")()));
}
// Check if RetrieveValue is called.
TEST_F(YangParseTreeTest, GetDataFromSwitchInterfaceCalled) {
// Create a fake switch interface object.
SwitchMock switch_interface;
EXPECT_CALL(switch_interface, RetrieveValue(_, _, _, _))
.WillOnce(Return(::util::OkStatus()));
// Create a data retrieval request.
uint64 node_id = 0;
DataRequest req;
DataResponseWriter writer([](const DataResponse&) { return true; });
// Request the data.
EXPECT_OK(switch_interface.RetrieveValue(node_id, req, &writer, nullptr));
}
// Check if the response message is set correctly.
TEST_F(YangParseTreeTest, GetDataFromSwitchInterfaceDataCopied) {
// Create a fake switch interface object.
SwitchMock switch_interface;
EXPECT_CALL(switch_interface, RetrieveValue(_, _, _, _))
.WillOnce(DoAll(WithArgs<2>(Invoke([](WriterInterface<DataResponse>* w) {
DataResponse resp;
// Set the response.
resp.mutable_oper_status()->set_state(PORT_STATE_UP);
// Send it to the caller.
w->Write(resp);
})),
Return(::util::OkStatus())));
// Create a data retrieval request.
uint64 node_id = 0;
DataRequest req;
DataResponse resp;
DataResponseWriter writer([&resp](const DataResponse& in) {
resp = in;
return true;
});
// Pre-test check.
ASSERT_FALSE(resp.has_oper_status());
// Request the data.
EXPECT_OK(switch_interface.RetrieveValue(node_id, req, &writer, nullptr));
// Check that the data has been modified.
ASSERT_TRUE(resp.has_oper_status());
EXPECT_EQ(resp.oper_status().state(), PORT_STATE_UP);
}
// A class that implements a channel that is used by the YANG tree node handlers
// to send notifications to GnmiPublisher.
class GnmiEventWriterMock : public WriterInterface<GnmiEventPtr> {
public:
GnmiEventWriterMock() {}
// The only work method defined by the interface - it is called every time
// there is a data to be processed.
MOCK_METHOD1(Write, bool(const GnmiEventPtr& resp));
};
// Check if the notification message is send correctly.
TEST_F(YangParseTreeTest, SendNotificationPass) {
// Always forward SendNotifications to YangParseTree::SendNotification().
EXPECT_CALL(parse_tree_, SendNotification(_))
.WillRepeatedly(WithArg<0>(Invoke([this](const GnmiEventPtr& n) {
this->parse_tree_.YangParseTree::SendNotification(n);
})));
// Test SendNotification() without seting up the channel
SetGnmiEventWriter(nullptr);
parse_tree_.SendNotification(GnmiEventPtr(new PortHealthIndicatorChangedEvent(
/*node_id*/ 0, /*port_id*/ 0, HealthState::HEALTH_STATE_BAD)));
// Test SendNotification() with channel set up.
// Scenario #1: correct processing.
auto* channel = new GnmiEventWriterMock();
SetGnmiEventWriter(channel);
GnmiEventPtr notification;
EXPECT_CALL(*channel, Write(_))
.WillOnce(
DoAll(WithArgs<0>(Invoke([¬ification](const GnmiEventPtr& n) {
notification = n;
})),
Return(true)));
EXPECT_CALL(parse_tree_, SendNotification(_))
.WillRepeatedly(WithArg<0>(Invoke([this](const GnmiEventPtr& n) {
this->parse_tree_.YangParseTree::SendNotification(n);
})));
parse_tree_.SendNotification(GnmiEventPtr(new PortHealthIndicatorChangedEvent(
/*node_id*/ 0, /*port_id*/ 0, HealthState::HEALTH_STATE_BAD)));
// Test SendNotification() with channel set up.
// Scenario #3: incorrect processing.
EXPECT_CALL(*channel, Write(_))
.WillOnce(
DoAll(WithArgs<0>(Invoke([¬ification](const GnmiEventPtr& n) {
notification = n;
})),
Return(false)));
parse_tree_.SendNotification(GnmiEventPtr(new PortHealthIndicatorChangedEvent(
/*node_id*/ 0, /*port_id*/ 0, HealthState::HEALTH_STATE_BAD)));
}
// Check if the action is executed for all qualified leafs.
TEST_F(YangParseTreeTest, GetDataFromSwitchInterfaceDataConvertedCorrectly) {
// After tree creation only three leafs are defined:
// /interfaces/interface[name=*]/state/id
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
// The test requires one interface branch to be added.
AddSubtreeInterface("interface-1");
// Mock implementation of RetrieveValue() that sends a response set to
// HW_STATE_READY.
EXPECT_CALL(switch_, RetrieveValue(_, _, _, _))
.WillOnce(DoAll(WithArgs<2>(Invoke([](WriterInterface<DataResponse>* w) {
DataResponse resp;
// Set the response.
resp.mutable_oper_status()->set_state(PORT_STATE_UP);
// Send it to the caller.
w->Write(resp);
})),
Return(::util::OkStatus())));
// Mock gRPC stream that copies parameter of Write() to 'resp'. The contents
// of the 'resp' variable is then checked.
SubscribeReaderWriterMock stream;
::gnmi::SubscribeResponse resp;
EXPECT_CALL(stream, Write(_, _))
.WillOnce(
DoAll(WithArgs<0>(Invoke(
[&resp](const ::gnmi::SubscribeResponse& r) { resp = r; })),
Return(true)));
// Find the 'oper-state' leaf.
auto* node = GetRoot().FindNodeOrNull(GetPath("interfaces")(
"interface", "interface-1")("state")("oper-status")());
ASSERT_NE(node, nullptr);
// Get its OnTimer() handler and call it.
const auto& handler = node->GetOnTimerHandler();
EXPECT_OK(handler(TimerEvent(), &stream));
// Check that the result of the call is what is expected.
ASSERT_EQ(resp.update().update_size(), 1);
EXPECT_EQ(resp.update().update(0).val().string_val(), "UP");
}
// Check if the default action applying target defined mode to a
// subscription does not set the SAMPLE mode. This is needed for the following
// test to work correctly.
TEST_F(YangParseTreeTest, DefaultTargetDefinedModeIsNotSample) {
TreeNode node;
::gnmi::Subscription subscription;
ASSERT_OK(node.ApplyTargetDefinedModeToSubscription(&subscription));
EXPECT_NE(subscription.mode(), ::gnmi::SubscriptionMode::SAMPLE);
}
// Check if changing target defined mode works correctly.
TEST_F(YangParseTreeTest, ChangeDefaultTargetDefinedMode) {
TreeNode node;
auto new_target_defined_mode = [](::gnmi::Subscription* subscription) {
subscription->set_mode(::gnmi::SubscriptionMode::SAMPLE);
return ::util::OkStatus();
};
ASSERT_EQ(node.SetTargetDefinedMode(new_target_defined_mode), &node);
::gnmi::Subscription subscription;
ASSERT_OK(node.ApplyTargetDefinedModeToSubscription(&subscription));
EXPECT_EQ(subscription.mode(), ::gnmi::SubscriptionMode::SAMPLE);
}
// Check if the default action applying target defined mode to a
// subscription for "/interfaces/interface/state/counters" sets it to ON_CHANGE.
TEST_F(YangParseTreeTest, DefaultTargetDefinedModeIsSampleForCounters) {
// The test requires one interface branch to be added.
AddSubtreeInterface("interface-1");
const TreeNode* node = GetRoot().FindNodeOrNull(
GetPath("interfaces")("interface", "interface-1")("state")("counters")());
ASSERT_NE(node, nullptr);
::gnmi::Subscription subscription;
ASSERT_OK(node->ApplyTargetDefinedModeToSubscription(&subscription));
EXPECT_EQ(subscription.mode(), ::gnmi::SubscriptionMode::SAMPLE);
EXPECT_EQ(subscription.sample_interval(), 1000);
}
// Check if the 'oper-status' OnPoll action works correctly.
TEST_F(YangParseTreeTest, InterfacesInterfaceStateOperStatusOnPollSuccess) {
auto path = GetPath("interfaces")("interface",
"interface-1")("state")("oper-status")();
// Mock implementation of RetrieveValue() that sends a response set to
// OPER_STATE_UP.
EXPECT_CALL(switch_, RetrieveValue(_, _, _, _))
.WillOnce(DoAll(WithArgs<2>(Invoke([](WriterInterface<DataResponse>* w) {
DataResponse resp;
// Set the response.
resp.mutable_oper_status()->set_state(PORT_STATE_UP);
// Send it to the caller.
w->Write(resp);
})),
Return(::util::OkStatus())));
::gnmi::SubscribeResponse resp;
EXPECT_OK(ExecuteOnPoll(path, &resp));
// Check that the result of the call is what is expected.
ASSERT_EQ(resp.update().update_size(), 1);
EXPECT_EQ(resp.update().update(0).val().string_val(), "UP");
}
// Check if the 'oper-status' OnChange action works correctly.
TEST_F(YangParseTreeTest, InterfacesInterfaceStateOperStatusOnChangeSuccess) {
auto path = GetPath("interfaces")("interface",
"interface-1")("state")("oper-status")();
::gnmi::SubscribeResponse resp;
EXPECT_OK(ExecuteOnChange(
path,
PortOperStateChangedEvent(kInterface1NodeId, kInterface1PortId,
PORT_STATE_UP, 0),
&resp));
// Check that the result of the call is what is expected.
ASSERT_EQ(resp.update().update_size(), 1);
EXPECT_EQ(resp.update().update(0).val().string_val(), "UP");
}
// Check if the 'admin-status' OnPoll action works correctly.
TEST_F(YangParseTreeTest, InterfacesInterfaceStateAdminStatusOnPollSuccess) {
auto path = GetPath("interfaces")("interface",
"interface-1")("state")("admin-status")();
// Mock implementation of RetrieveValue() that sends a response set to
// ADMIN_STATE_ENABLED.
EXPECT_CALL(switch_, RetrieveValue(_, _, _, _))
.WillOnce(DoAll(WithArgs<2>(Invoke([](WriterInterface<DataResponse>* w) {
DataResponse resp;
// Set the response.
resp.mutable_admin_status()->set_state(
ADMIN_STATE_ENABLED);
// Send it to the caller.
w->Write(resp);
})),
Return(::util::OkStatus())));
::gnmi::SubscribeResponse resp;
EXPECT_OK(ExecuteOnPoll(path, &resp));
// Check that the result of the call is what is expected.
ASSERT_EQ(resp.update().update_size(), 1);
EXPECT_EQ(resp.update().update(0).val().string_val(), "UP");
}
// Check if the 'admin-status' OnChange action works correctly.
TEST_F(YangParseTreeTest, InterfacesInterfaceStateAdminStatusOnChangeSuccess) {
auto path = GetPath("interfaces")("interface",
"interface-1")("state")("admin-status")();
::gnmi::SubscribeResponse resp;
EXPECT_OK(ExecuteOnChange(
path,
PortAdminStateChangedEvent(kInterface1NodeId, kInterface1PortId,
ADMIN_STATE_ENABLED),
&resp));
// Check that the result of the call is what is expected.
ASSERT_EQ(resp.update().update_size(), 1);
EXPECT_EQ(resp.update().update(0).val().string_val(), "UP");
}
// Check if the action is executed correctly.
TEST_F(YangParseTreeTest, InterfacesInterfaceStateNameOnPollSuccess) {
// After tree creation only three leafs are defined:
// /interfaces/interface[name=*]/state/id
// /interfaces/interface[name=*]/state/ifindex
// /interfaces/interface[name=*]/state/name
// The test requires one interface branch to be added.
AddSubtreeInterface("interface-1");
// Mock gRPC stream that copies parameter of Write() to 'resp'. The contents
// of the 'resp' variable is then checked.
SubscribeReaderWriterMock stream;
::gnmi::SubscribeResponse resp;
EXPECT_CALL(stream, Write(_, _))
.WillOnce(
DoAll(WithArgs<0>(Invoke(
[&resp](const ::gnmi::SubscribeResponse& r) { resp = r; })),
Return(true)));
// Find the 'name' leaf.