Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a test to exercise MTRCommandWithRequiredResponse encode/decode. #37521

Merged
merged 1 commit into from
Mar 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions src/darwin/Framework/CHIP/MTRCommandWithRequiredResponse.mm
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
* limitations under the License.
*/

#import <Matter/Matter.h>

#import "MTRDeviceDataValidation.h"
#import "MTRLogging_Internal.h"
#import <Matter/Matter.h>
#import "MTRUtilities.h"

@implementation MTRCommandWithRequiredResponse
- (instancetype)initWithPath:(MTRCommandPath *)path
Expand Down Expand Up @@ -66,7 +68,14 @@ - (nullable instancetype)initWithCoder:(NSCoder *)decoder
return nil;
}

_commandFields = [decoder decodeObjectOfClasses:[NSSet setWithArray:@[ [NSDictionary class], [NSString class], [NSNumber class], [NSArray class], [NSData class] ]] forKey:sFieldsKey];
// The classes of things that can appear in a data-value dictionary.
static NSSet * const sDataValueClasses = [NSSet setWithArray:@[ NSDictionary.class, NSArray.class, NSData.class, NSString.class, NSNumber.class ]];

// Unfortunately, decodeDictionaryWithKeysOfClasses:objectsOfClasses:forKey:
// does not work when the objects stored in the dictionary can include
// collections, so we have to use decodeObjectOfClasses: and then manually
// validate we got a dictionary.
_commandFields = [decoder decodeObjectOfClasses:sDataValueClasses forKey:sFieldsKey];
if (_commandFields) {
if (![_commandFields isKindOfClass:NSDictionary.class]) {
MTR_LOG_ERROR("MTRCommandWithRequiredResponse decoded %@ for commandFields, not NSDictionary.", _commandFields);
Expand All @@ -79,7 +88,7 @@ - (nullable instancetype)initWithCoder:(NSCoder *)decoder
}
}

_requiredResponse = [decoder decodeObjectOfClasses:[NSSet setWithArray:@[ [NSDictionary class], [NSString class], [NSNumber class], [NSArray class], [NSData class] ]] forKey:sExpectedResultKey];
_requiredResponse = [decoder decodeObjectOfClasses:sDataValueClasses forKey:sExpectedResultKey];
if (_requiredResponse) {
if (![_requiredResponse isKindOfClass:NSDictionary.class]) {
MTR_LOG_ERROR("MTRCommandWithRequiredResponse decoded %@ for requiredResponse, not NSDictionary.", _requiredResponse);
Expand Down Expand Up @@ -116,4 +125,19 @@ - (void)encodeWithCoder:(NSCoder *)coder
}
}

- (BOOL)_isEqualToOther:(MTRCommandWithRequiredResponse *)other
{
return MTREqualObjects(_path, other.path)
&& MTREqualObjects(_commandFields, other.commandFields)
&& MTREqualObjects(_requiredResponse, other.requiredResponse);
}

- (BOOL)isEqual:(id)object
{
if ([object class] != [self class]) {
return NO;
}
return [self _isEqualToOther:object];
}

@end
139 changes: 138 additions & 1 deletion src/darwin/Framework/CHIPTests/MTRDeviceTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -3350,14 +3350,23 @@ - (void)test031_MTRDeviceAttributeCacheLocalTestStorage
XCTAssertTrue(storedAttributeCountDifferenceFromMTRDeviceReport > 300);
}

- (void)doEncodeDecodeRoundTrip:(id<NSSecureCoding>)encodable
- (NSData *)_encodeEncodable:(id<NSSecureCoding>)encodable
{
// We know all our encodables are in fact NSObject.
NSObject * obj = (NSObject *) encodable;

NSError * encodeError;
NSData * encodedData = [NSKeyedArchiver archivedDataWithRootObject:encodable requiringSecureCoding:YES error:&encodeError];
XCTAssertNil(encodeError, @"Failed to encode %@", NSStringFromClass(obj.class));
return encodedData;
}

- (void)doEncodeDecodeRoundTrip:(id<NSSecureCoding>)encodable
{
NSData * encodedData = [self _encodeEncodable:encodable];

// We know all our encodables are in fact NSObject.
NSObject * obj = (NSObject *) encodable;

NSError * decodeError;
id decodedValue = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObject:obj.class] fromData:encodedData error:&decodeError];
Expand All @@ -3367,6 +3376,19 @@ - (void)doEncodeDecodeRoundTrip:(id<NSSecureCoding>)encodable
XCTAssertEqualObjects(obj, decodedValue, @"Decoding for %@ did not round-trip correctly", NSStringFromClass([obj class]));
}

- (void)_ensureDecodeFails:(id<NSSecureCoding>)encodable
{
NSData * encodedData = [self _encodeEncodable:encodable];

// We know all our encodables are in fact NSObject.
NSObject * obj = (NSObject *) encodable;

NSError * decodeError;
id decodedValue = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObject:obj.class] fromData:encodedData error:&decodeError];
XCTAssertNil(decodedValue);
XCTAssertNotNil(decodeError);
}

- (void)test032_MTRPathClassesEncoding
{
// Test attribute path encode / decode
Expand Down Expand Up @@ -6023,6 +6045,121 @@ - (void)test045_MTRDeviceInvokeGroups
[self waitForExpectations:@[ updateFabricLabelExpectingWrongValueExpectation ] timeout:(2 * kTimeoutInSeconds)];
}

- (void)test046_MTRCommandWithRequiredResponseEncoding
{
// Basic test with no command fields or required response.
__auto_type * onPath = [MTRCommandPath commandPathWithEndpointID:@(1)
clusterID:@(MTRClusterIDTypeOnOffID)
commandID:@(MTRCommandIDTypeClusterOnOffCommandOnID)];
__auto_type * onCommand = [[MTRCommandWithRequiredResponse alloc] initWithPath:onPath commandFields:nil requiredResponse:nil];
[self doEncodeDecodeRoundTrip:onCommand];

// Test with both command fields and an interesting required response.
//
// NSSecureCoding tracks object identity, so we need to create new objects
// for every instance of a thing we decode/encode with a given coder to make
// sure all codepaths are exercised. Use a block that returns a new
// dictionary each time to handle this.
__auto_type structureWithAllTypes = ^{
return @{
MTRTypeKey : MTRStructureValueType,
MTRValueKey : @[
@{
MTRContextTagKey : @(0),
MTRDataKey : @ {
MTRTypeKey : MTRSignedIntegerValueType,
MTRValueKey : @(5),
},
},
@{
MTRContextTagKey : @(1),
MTRDataKey : @ {
MTRTypeKey : MTRUnsignedIntegerValueType,
MTRValueKey : @(5),
},
},
@{
MTRContextTagKey : @(2),
MTRDataKey : @ {
MTRTypeKey : MTRBooleanValueType,
MTRValueKey : @(YES),
},
},
@{
MTRContextTagKey : @(3),
MTRDataKey : @ {
MTRTypeKey : MTRUTF8StringValueType,
MTRValueKey : @("abc"),
},
},
@{
MTRContextTagKey : @(4),
MTRDataKey : @ {
MTRTypeKey : MTROctetStringValueType,
MTRValueKey : [[NSData alloc] initWithBase64EncodedString:@"APJj" options:0],
},
},
@{
MTRContextTagKey : @(5),
MTRDataKey : @ {
MTRTypeKey : MTRFloatValueType,
MTRValueKey : @(1.0),
},
},
@{
MTRContextTagKey : @(6),
MTRDataKey : @ {
MTRTypeKey : MTRDoubleValueType,
MTRValueKey : @(5.0),
},
},
@{
MTRContextTagKey : @(7),
MTRDataKey : @ {
MTRTypeKey : MTRNullValueType,
},
},
@{
MTRContextTagKey : @(8),
MTRDataKey : @ {
MTRTypeKey : MTRArrayValueType,
MTRValueKey : @[
@{
MTRDataKey : @ {
MTRTypeKey : MTRUnsignedIntegerValueType,
MTRValueKey : @(9),
},
},
],
}
},
],
};
};

// Invalid commandFields (not a dictionary)
onCommand.commandFields = (id) @[];
[self _ensureDecodeFails:onCommand];

// Invalid required response (not a dictionary)
onCommand.commandFields = nil;
onCommand.requiredResponse = (id) @[];
[self _ensureDecodeFails:onCommand];

// Invalid required response (key is not NSNumber)
onCommand.requiredResponse = @{
@("abc") : structureWithAllTypes(),
};
[self _ensureDecodeFails:onCommand];

onCommand.commandFields = structureWithAllTypes();
onCommand.requiredResponse = @{
@(1) : structureWithAllTypes(),
@(13) : structureWithAllTypes(),
};
[self doEncodeDecodeRoundTrip:onCommand];
}

@end

@interface MTRDeviceEncoderTests : XCTestCase
Expand Down
Loading