forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestWriteChunking.cpp
684 lines (555 loc) · 27.2 KB
/
TestWriteChunking.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
/*
*
* Copyright (c) 2022 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include <utility>
#include <pw_unit_test/framework.h>
#include "app-common/zap-generated/ids/Attributes.h"
#include "app-common/zap-generated/ids/Clusters.h"
#include "app/ConcreteAttributePath.h"
#include "protocols/interaction_model/Constants.h"
#include <app-common/zap-generated/cluster-objects.h>
#include <app/AttributeAccessInterface.h>
#include <app/AttributeAccessInterfaceRegistry.h>
#include <app/CommandHandlerInterface.h>
#include <app/InteractionModelEngine.h>
#include <app/WriteClient.h>
#include <app/data-model/Decode.h>
#include <app/tests/AppTestContext.h>
#include <app/util/DataModelHandler.h>
#include <app/util/attribute-storage.h>
#include <controller/InvokeInteraction.h>
#include <lib/core/ErrorStr.h>
#include <lib/core/StringBuilderAdapters.h>
#include <lib/support/logging/CHIPLogging.h>
using namespace chip;
using namespace chip::app;
using namespace chip::app::Clusters;
namespace {
uint32_t gIterationCount = 0;
//
// The generated endpoint_config for the controller app has Endpoint 1
// already used in the fixed endpoint set of size 1. Consequently, let's use the next
// number higher than that for our dynamic test endpoint.
//
constexpr EndpointId kTestEndpointId = 2;
constexpr AttributeId kTestListAttribute = 6;
constexpr AttributeId kTestListAttribute2 = 7;
constexpr uint32_t kTestListLength = 5;
// We don't really care about the content, we just need a buffer.
uint8_t sByteSpanData[app::kMaxSecureSduLengthBytes];
class TestWriteChunking : public Test::AppContext
{
private:
using PathStatus = std::pair<app::ConcreteAttributePath, bool>;
protected:
enum class Operations : uint8_t
{
kNoop,
kShutdownWriteClient,
};
enum class ListData : uint8_t
{
kNull,
kList,
kBadValue,
};
struct Instructions
{
// The paths used in write request
std::vector<ConcreteAttributePath> paths;
// The type of content of the list, it should be an empty vector or its size should equals to the list of paths.
std::vector<ListData> data;
// operations on OnListWriteBegin and OnListWriteEnd on the server side.
std::function<Operations(const app::ConcreteAttributePath & path)> onListWriteBeginActions;
// The expected status when OnListWriteEnd is called. In the same order as paths
std::vector<bool> expectedStatus;
};
void RunTest(Instructions instructions);
};
//clang-format off
DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(testClusterAttrsOnEndpoint)
DECLARE_DYNAMIC_ATTRIBUTE(kTestListAttribute, ARRAY, 1, ATTRIBUTE_MASK_WRITABLE),
DECLARE_DYNAMIC_ATTRIBUTE(kTestListAttribute2, ARRAY, 1, ATTRIBUTE_MASK_WRITABLE), DECLARE_DYNAMIC_ATTRIBUTE_LIST_END();
DECLARE_DYNAMIC_CLUSTER_LIST_BEGIN(testEndpointClusters)
DECLARE_DYNAMIC_CLUSTER(Clusters::UnitTesting::Id, testClusterAttrsOnEndpoint, ZAP_CLUSTER_MASK(SERVER), nullptr, nullptr),
DECLARE_DYNAMIC_CLUSTER_LIST_END;
DECLARE_DYNAMIC_ENDPOINT(testEndpoint, testEndpointClusters);
DataVersion dataVersionStorage[ArraySize(testEndpointClusters)];
//clang-format on
class TestWriteCallback : public app::WriteClient::Callback
{
public:
void OnResponse(const app::WriteClient * apWriteClient, const app::ConcreteDataAttributePath & aPath,
app::StatusIB status) override
{
if (status.mStatus == Protocols::InteractionModel::Status::Success)
{
mSuccessCount++;
}
else
{
mLastErrorReason = status;
mErrorCount++;
}
}
void OnError(const app::WriteClient * apWriteClient, CHIP_ERROR aError) override
{
mLastErrorReason = app::StatusIB(aError);
mErrorCount++;
}
void OnDone(app::WriteClient * apWriteClient) override { mOnDoneCount++; }
uint32_t mSuccessCount = 0;
uint32_t mErrorCount = 0;
uint32_t mOnDoneCount = 0;
app::StatusIB mLastErrorReason;
};
class TestAttrAccess : public app::AttributeAccessInterface
{
public:
// Register for the Test Cluster cluster on all endpoints.
TestAttrAccess() : AttributeAccessInterface(Optional<EndpointId>::Missing(), Clusters::UnitTesting::Id) {}
CHIP_ERROR Read(const app::ConcreteReadAttributePath & aPath, app::AttributeValueEncoder & aEncoder) override;
CHIP_ERROR Write(const app::ConcreteDataAttributePath & aPath, app::AttributeValueDecoder & aDecoder) override;
void OnListWriteBegin(const app::ConcreteAttributePath & aPath) override
{
if (mOnListWriteBegin)
{
mOnListWriteBegin(aPath);
}
}
void OnListWriteEnd(const app::ConcreteAttributePath & aPath, bool aWriteWasSuccessful) override
{
if (mOnListWriteEnd)
{
mOnListWriteEnd(aPath, aWriteWasSuccessful);
}
}
std::function<void(const app::ConcreteAttributePath & path)> mOnListWriteBegin;
std::function<void(const app::ConcreteAttributePath & path, bool wasSuccessful)> mOnListWriteEnd;
} testServer;
CHIP_ERROR TestAttrAccess::Read(const app::ConcreteReadAttributePath & aPath, app::AttributeValueEncoder & aEncoder)
{
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
CHIP_ERROR TestAttrAccess::Write(const app::ConcreteDataAttributePath & aPath, app::AttributeValueDecoder & aDecoder)
{
// We only care about the number of attribute data.
if (!aPath.IsListItemOperation())
{
app::DataModel::Nullable<app::DataModel::DecodableList<ByteSpan>> list;
CHIP_ERROR err = aDecoder.Decode(list);
ChipLogError(Zcl, "Decode result: %s", err.AsString());
return err;
}
if (aPath.mListOp == app::ConcreteDataAttributePath::ListOperation::AppendItem)
{
ByteSpan listItem;
CHIP_ERROR err = aDecoder.Decode(listItem);
ChipLogError(Zcl, "Decode result: %s", err.AsString());
return err;
}
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
/*
* This validates all the various corner cases encountered during chunking by artificially reducing the size of a packet buffer used
* to encode attribute data to force chunking to happen over multiple packets even with a small number of attributes and then slowly
* increasing the available size by 1 byte in each test iteration and re-running the write request generation logic. This 1-byte
* incremental approach sweeps through from a base scenario of N attributes fitting in a write request chunk, to eventually
* resulting in N+1 attributes fitting in a write request chunk.
*
* This will cause all the various corner cases encountered of closing out the various containers within the write request and
* thoroughly and definitely validate those edge cases.
*/
TEST_F(TestWriteChunking, TestListChunking)
{
auto sessionHandle = GetSessionBobToAlice();
// Initialize the ember side server logic
InitDataModelHandler();
// Register our fake dynamic endpoint.
emberAfSetDynamicEndpoint(0, kTestEndpointId, &testEndpoint, Span<DataVersion>(dataVersionStorage));
// Register our fake attribute access interface.
AttributeAccessInterfaceRegistry::Instance().Register(&testServer);
app::AttributePathParams attributePath(kTestEndpointId, app::Clusters::UnitTesting::Id, kTestListAttribute);
//
// We've empirically determined that by reserving all but 75 bytes in the packet buffer, we can fit 2
// AttributeDataIBs into the packet. ~30-40 bytes covers a single write chunk, but let's 2-3x that
// to ensure we'll sweep from fitting 2 chunks to 3-4 chunks.
//
constexpr size_t minReservationSize = kMaxSecureSduLengthBytes - 75 - 100;
for (uint32_t i = 100; i > 0; i--)
{
CHIP_ERROR err = CHIP_NO_ERROR;
TestWriteCallback writeCallback;
ChipLogDetail(DataManagement, "Running iteration %d\n", static_cast<int>(i));
gIterationCount = i;
app::WriteClient writeClient(&GetExchangeManager(), &writeCallback, Optional<uint16_t>::Missing(),
static_cast<uint16_t>(minReservationSize + i) /* reserved buffer size */);
ByteSpan list[kTestListLength];
err = writeClient.EncodeAttribute(attributePath, app::DataModel::List<ByteSpan>(list, kTestListLength));
EXPECT_EQ(err, CHIP_NO_ERROR);
err = writeClient.SendWriteRequest(sessionHandle);
EXPECT_EQ(err, CHIP_NO_ERROR);
//
// Service the IO + Engine till we get a ReportEnd callback on the client.
// Since bugs can happen, we don't want this test to never stop, so create a ceiling for how many
// times this can run without seeing expected results.
//
for (int j = 0; j < 10 && writeCallback.mOnDoneCount == 0; j++)
{
DrainAndServiceIO();
}
EXPECT_EQ(writeCallback.mSuccessCount, kTestListLength + 1 /* an extra item for the empty list at the beginning */);
EXPECT_EQ(writeCallback.mErrorCount, 0u);
EXPECT_EQ(writeCallback.mOnDoneCount, 1u);
EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u);
//
// Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs.
//
if (HasFailure())
{
break;
}
}
emberAfClearDynamicEndpoint(0);
}
// We encode a pretty large write payload to test the corner cases related to message layer and secure session overheads.
// The test should gurantee that if encode returns no error, the send should also success.
// As the actual overhead may change, we will test over a few possible payload lengths, from 850 to MTU used in write clients.
TEST_F(TestWriteChunking, TestBadChunking)
{
auto sessionHandle = GetSessionBobToAlice();
bool atLeastOneRequestSent = false;
bool atLeastOneRequestFailed = false;
// Initialize the ember side server logic
InitDataModelHandler();
// Register our fake dynamic endpoint.
emberAfSetDynamicEndpoint(0, kTestEndpointId, &testEndpoint, Span<DataVersion>(dataVersionStorage));
// Register our fake attribute access interface.
AttributeAccessInterfaceRegistry::Instance().Register(&testServer);
app::AttributePathParams attributePath(kTestEndpointId, app::Clusters::UnitTesting::Id, kTestListAttribute);
for (int i = 850; i < static_cast<int>(chip::app::kMaxSecureSduLengthBytes); i++)
{
CHIP_ERROR err = CHIP_NO_ERROR;
TestWriteCallback writeCallback;
ChipLogDetail(DataManagement, "Running iteration with OCTET_STRING length = %d\n", i);
gIterationCount = (uint32_t) i;
app::WriteClient writeClient(&GetExchangeManager(), &writeCallback, Optional<uint16_t>::Missing());
ByteSpan list[kTestListLength];
for (auto & item : list)
{
item = ByteSpan(sByteSpanData, static_cast<uint32_t>(i));
}
err = writeClient.EncodeAttribute(attributePath, app::DataModel::List<ByteSpan>(list, kTestListLength));
if (err == CHIP_ERROR_NO_MEMORY || err == CHIP_ERROR_BUFFER_TOO_SMALL)
{
// This kind of error is expected.
atLeastOneRequestFailed = true;
continue;
}
atLeastOneRequestSent = true;
// If we successfully encoded the attribute, then we must be able to send the message.
err = writeClient.SendWriteRequest(sessionHandle);
EXPECT_EQ(err, CHIP_NO_ERROR);
//
// Service the IO + Engine till we get a ReportEnd callback on the client.
// Since bugs can happen, we don't want this test to never stop, so create a ceiling for how many
// times this can run without seeing expected results.
//
for (int j = 0; j < 10 && writeCallback.mOnDoneCount == 0; j++)
{
DrainAndServiceIO();
}
EXPECT_EQ(writeCallback.mSuccessCount, kTestListLength + 1 /* an extra item for the empty list at the beginning */);
EXPECT_EQ(writeCallback.mErrorCount, 0u);
EXPECT_EQ(writeCallback.mOnDoneCount, 1u);
EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u);
//
// Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs.
//
if (HasFailure())
{
break;
}
}
EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u);
EXPECT_TRUE(atLeastOneRequestSent && atLeastOneRequestFailed);
emberAfClearDynamicEndpoint(0);
}
/*
* When chunked write is enabled, it is dangerious to handle multiple write requests at the same time. In this case, we will reject
* the latter write requests to the same attribute.
*/
TEST_F(TestWriteChunking, TestConflictWrite)
{
auto sessionHandle = GetSessionBobToAlice();
// Initialize the ember side server logic
InitDataModelHandler();
// Register our fake dynamic endpoint.
emberAfSetDynamicEndpoint(0, kTestEndpointId, &testEndpoint, Span<DataVersion>(dataVersionStorage));
// Register our fake attribute access interface.
AttributeAccessInterfaceRegistry::Instance().Register(&testServer);
app::AttributePathParams attributePath(kTestEndpointId, app::Clusters::UnitTesting::Id, kTestListAttribute);
/* use a smaller chunk (128 bytes) so we only need a few attributes in the write request. */
constexpr size_t kReserveSize = kMaxSecureSduLengthBytes - 128;
TestWriteCallback writeCallback1;
app::WriteClient writeClient1(&GetExchangeManager(), &writeCallback1, Optional<uint16_t>::Missing(),
static_cast<uint16_t>(kReserveSize));
TestWriteCallback writeCallback2;
app::WriteClient writeClient2(&GetExchangeManager(), &writeCallback2, Optional<uint16_t>::Missing(),
static_cast<uint16_t>(kReserveSize));
ByteSpan list[kTestListLength];
CHIP_ERROR err = CHIP_NO_ERROR;
err = writeClient1.EncodeAttribute(attributePath, app::DataModel::List<ByteSpan>(list, kTestListLength));
EXPECT_EQ(err, CHIP_NO_ERROR);
err = writeClient2.EncodeAttribute(attributePath, app::DataModel::List<ByteSpan>(list, kTestListLength));
EXPECT_EQ(err, CHIP_NO_ERROR);
err = writeClient1.SendWriteRequest(sessionHandle);
EXPECT_EQ(err, CHIP_NO_ERROR);
err = writeClient2.SendWriteRequest(sessionHandle);
EXPECT_EQ(err, CHIP_NO_ERROR);
DrainAndServiceIO();
{
const TestWriteCallback * writeCallbackRef1 = &writeCallback1;
const TestWriteCallback * writeCallbackRef2 = &writeCallback2;
// Exactly one of WriteClient1 and WriteClient2 should success, not both.
if (writeCallback1.mSuccessCount == 0)
{
writeCallbackRef2 = &writeCallback1;
writeCallbackRef1 = &writeCallback2;
}
EXPECT_EQ(writeCallbackRef1->mSuccessCount, kTestListLength + 1 /* an extra item for the empty list at the beginning */);
EXPECT_EQ(writeCallbackRef1->mErrorCount, 0u);
EXPECT_EQ(writeCallbackRef2->mSuccessCount, 0u);
EXPECT_EQ(writeCallbackRef2->mErrorCount, kTestListLength + 1);
EXPECT_EQ(writeCallbackRef2->mLastErrorReason.mStatus, Protocols::InteractionModel::Status::Busy);
EXPECT_EQ(writeCallbackRef1->mOnDoneCount, 1u);
EXPECT_EQ(writeCallbackRef2->mOnDoneCount, 1u);
}
EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u);
emberAfClearDynamicEndpoint(0);
}
/*
* When chunked write is enabled, it is dangerious to handle multiple write requests at the same time. However, we will allow such
* change when writing to different attributes in parallel.
*/
TEST_F(TestWriteChunking, TestNonConflictWrite)
{
auto sessionHandle = GetSessionBobToAlice();
// Initialize the ember side server logic
InitDataModelHandler();
// Register our fake dynamic endpoint.
emberAfSetDynamicEndpoint(0, kTestEndpointId, &testEndpoint, Span<DataVersion>(dataVersionStorage));
// Register our fake attribute access interface.
AttributeAccessInterfaceRegistry::Instance().Register(&testServer);
app::AttributePathParams attributePath1(kTestEndpointId, app::Clusters::UnitTesting::Id, kTestListAttribute);
app::AttributePathParams attributePath2(kTestEndpointId, app::Clusters::UnitTesting::Id, kTestListAttribute2);
/* use a smaller chunk (128 bytes) so we only need a few attributes in the write request. */
constexpr size_t kReserveSize = kMaxSecureSduLengthBytes - 128;
TestWriteCallback writeCallback1;
app::WriteClient writeClient1(&GetExchangeManager(), &writeCallback1, Optional<uint16_t>::Missing(),
static_cast<uint16_t>(kReserveSize));
TestWriteCallback writeCallback2;
app::WriteClient writeClient2(&GetExchangeManager(), &writeCallback2, Optional<uint16_t>::Missing(),
static_cast<uint16_t>(kReserveSize));
ByteSpan list[kTestListLength];
CHIP_ERROR err = CHIP_NO_ERROR;
err = writeClient1.EncodeAttribute(attributePath1, app::DataModel::List<ByteSpan>(list, kTestListLength));
EXPECT_EQ(err, CHIP_NO_ERROR);
err = writeClient2.EncodeAttribute(attributePath2, app::DataModel::List<ByteSpan>(list, kTestListLength));
EXPECT_EQ(err, CHIP_NO_ERROR);
err = writeClient1.SendWriteRequest(sessionHandle);
EXPECT_EQ(err, CHIP_NO_ERROR);
err = writeClient2.SendWriteRequest(sessionHandle);
EXPECT_EQ(err, CHIP_NO_ERROR);
DrainAndServiceIO();
{
EXPECT_EQ(writeCallback1.mErrorCount, 0u);
EXPECT_EQ(writeCallback1.mSuccessCount, kTestListLength + 1);
EXPECT_EQ(writeCallback2.mErrorCount, 0u);
EXPECT_EQ(writeCallback2.mSuccessCount, kTestListLength + 1);
EXPECT_EQ(writeCallback1.mOnDoneCount, 1u);
EXPECT_EQ(writeCallback2.mOnDoneCount, 1u);
}
EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u);
emberAfClearDynamicEndpoint(0);
}
void TestWriteChunking::RunTest(Instructions instructions)
{
CHIP_ERROR err = CHIP_NO_ERROR;
auto sessionHandle = GetSessionBobToAlice();
TestWriteCallback writeCallback;
std::unique_ptr<WriteClient> writeClient = std::make_unique<WriteClient>(
&GetExchangeManager(), &writeCallback, Optional<uint16_t>::Missing(),
static_cast<uint16_t>(kMaxSecureSduLengthBytes -
128) /* use a smaller chunk so we only need a few attributes in the write request. */);
ConcreteAttributePath onGoingPath = ConcreteAttributePath();
std::vector<PathStatus> status;
testServer.mOnListWriteBegin = [&](const ConcreteAttributePath & aPath) {
EXPECT_EQ(onGoingPath, ConcreteAttributePath());
onGoingPath = aPath;
ChipLogProgress(Zcl, "OnListWriteBegin endpoint=%u Cluster=" ChipLogFormatMEI " attribute=" ChipLogFormatMEI,
aPath.mEndpointId, ChipLogValueMEI(aPath.mClusterId), ChipLogValueMEI(aPath.mAttributeId));
if (instructions.onListWriteBeginActions)
{
switch (instructions.onListWriteBeginActions(aPath))
{
case Operations::kNoop:
break;
case Operations::kShutdownWriteClient:
// By setting writeClient to nullptr, we actually shutdown the write interaction to simulate a timeout.
writeClient = nullptr;
}
}
};
testServer.mOnListWriteEnd = [&](const ConcreteAttributePath & aPath, bool aWasSuccessful) {
EXPECT_EQ(onGoingPath, aPath);
status.push_back(PathStatus(aPath, aWasSuccessful));
onGoingPath = ConcreteAttributePath();
ChipLogProgress(Zcl, "OnListWriteEnd endpoint=%u Cluster=" ChipLogFormatMEI " attribute=" ChipLogFormatMEI,
aPath.mEndpointId, ChipLogValueMEI(aPath.mClusterId), ChipLogValueMEI(aPath.mAttributeId));
};
ByteSpan list[kTestListLength];
uint8_t badList[kTestListLength];
if (instructions.data.size() == 0)
{
instructions.data = std::vector<ListData>(instructions.paths.size(), ListData::kList);
}
EXPECT_EQ(instructions.paths.size(), instructions.data.size());
for (size_t i = 0; i < instructions.paths.size(); i++)
{
const auto & p = instructions.paths[i];
switch (instructions.data[i])
{
case ListData::kNull: {
DataModel::Nullable<uint8_t> null; // The actual type is not important since we will only put a null value.
err = writeClient->EncodeAttribute(AttributePathParams(p.mEndpointId, p.mClusterId, p.mAttributeId), null);
break;
}
case ListData::kList: {
err = writeClient->EncodeAttribute(AttributePathParams(p.mEndpointId, p.mClusterId, p.mAttributeId),
DataModel::List<ByteSpan>(list, kTestListLength));
break;
}
case ListData::kBadValue: {
err = writeClient->EncodeAttribute(AttributePathParams(p.mEndpointId, p.mClusterId, p.mAttributeId),
DataModel::List<uint8_t>(badList, kTestListLength));
break;
}
}
EXPECT_EQ(err, CHIP_NO_ERROR);
}
err = writeClient->SendWriteRequest(sessionHandle);
EXPECT_EQ(err, CHIP_NO_ERROR);
GetIOContext().DriveIOUntil(sessionHandle->ComputeRoundTripTimeout(app::kExpectedIMProcessingTime) +
System::Clock::Seconds16(1),
[&]() { return GetExchangeManager().GetNumActiveExchanges() == 0; });
EXPECT_EQ(onGoingPath, app::ConcreteAttributePath());
EXPECT_EQ(status.size(), instructions.expectedStatus.size());
for (size_t i = 0; i < status.size(); i++)
{
EXPECT_EQ(status[i], PathStatus(instructions.paths[i], instructions.expectedStatus[i]));
}
testServer.mOnListWriteBegin = nullptr;
testServer.mOnListWriteEnd = nullptr;
}
TEST_F(TestWriteChunking, TestTransactionalList)
{
// Initialize the ember side server logic
InitDataModelHandler();
// Register our fake dynamic endpoint.
emberAfSetDynamicEndpoint(0, kTestEndpointId, &testEndpoint, Span<DataVersion>(dataVersionStorage));
// Register our fake attribute access interface.
AttributeAccessInterfaceRegistry::Instance().Register(&testServer);
// Test 1: we should receive transaction notifications
ChipLogProgress(Zcl, "Test 1: we should receive transaction notifications");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) },
.expectedStatus = { true },
});
ChipLogProgress(Zcl, "Test 2: we should receive transaction notifications for incomplete list operations");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) },
.onListWriteBeginActions = [&](const app::ConcreteAttributePath & aPath) { return Operations::kShutdownWriteClient; },
.expectedStatus = { false },
});
ChipLogProgress(Zcl, "Test 3: we should receive transaction notifications for every list in the transaction");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute),
ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute2) },
.expectedStatus = { true, true },
});
ChipLogProgress(Zcl, "Test 4: we should receive transaction notifications with the status of each list");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute),
ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute2) },
.onListWriteBeginActions =
[&](const app::ConcreteAttributePath & aPath) {
if (aPath.mAttributeId == kTestListAttribute2)
{
return Operations::kShutdownWriteClient;
}
return Operations::kNoop;
},
.expectedStatus = { true, false },
});
ChipLogProgress(Zcl,
"Test 5: transactional list callbacks will be called for nullable lists, test if it is handled correctly for "
"null value before non null values");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute),
ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) },
.data = { ListData::kNull, ListData::kList },
.expectedStatus = { true },
});
ChipLogProgress(Zcl,
"Test 6: transactional list callbacks will be called for nullable lists, test if it is handled correctly for "
"null value after non null values");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute),
ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) },
.data = { ListData::kList, ListData::kNull },
.expectedStatus = { true },
});
ChipLogProgress(Zcl,
"Test 7: transactional list callbacks will be called for nullable lists, test if it is handled correctly for "
"null value between non null values");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute),
ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute),
ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) },
.data = { ListData::kList, ListData::kNull, ListData::kList },
.expectedStatus = { true },
});
ChipLogProgress(Zcl, "Test 8: transactional list callbacks will be called for nullable lists");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) },
.data = { ListData::kNull },
.expectedStatus = { true },
});
ChipLogProgress(Zcl,
"Test 9: for nullable lists, we should receive notifications for unsuccessful writes when non-fatal occurred "
"during processing the requests");
RunTest(Instructions{
.paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) },
.data = { ListData::kBadValue },
.expectedStatus = { false },
});
EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u);
emberAfClearDynamicEndpoint(0);
}
} // namespace