diff --git a/Code/Network/RKObjectParameterization.m b/Code/Network/RKObjectParameterization.m index 6e120091..e740c4c8 100644 --- a/Code/Network/RKObjectParameterization.m +++ b/Code/Network/RKObjectParameterization.m @@ -82,8 +82,8 @@ RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:self.object destinationObject:dictionary mapping:self.mapping]; operation.dataSource = dataSource; operation.delegate = self; - BOOL success = [operation performMapping:error]; - if (!success) { + [operation start]; + if (operation.error) { return nil; } diff --git a/Code/ObjectMapping/RKDynamicMapping.h b/Code/ObjectMapping/RKDynamicMapping.h index 5ebf06eb..0d8c45be 100644 --- a/Code/ObjectMapping/RKDynamicMapping.h +++ b/Code/ObjectMapping/RKDynamicMapping.h @@ -38,6 +38,7 @@ typedef RKObjectMapping *(^RKDynamicMappingDelegateBlock)(id); @param block The block object to invoke to select the object mapping with which to map the given object representation. */ - (void)setObjectMappingForDataBlock:(RKDynamicMappingDelegateBlock)block; +// TODO: Better method signature... /** Defines a dynamic mapping rule stating that when the value of the key property matches the specified value, the given mapping should be used to map the representation. diff --git a/Code/ObjectMapping/RKMapperOperation.h b/Code/ObjectMapping/RKMapperOperation.h index 42db82ca..b404b462 100644 --- a/Code/ObjectMapping/RKMapperOperation.h +++ b/Code/ObjectMapping/RKMapperOperation.h @@ -170,7 +170,7 @@ @param mapper The mapper operation performing the mapping. @param dictionaryOrArrayOfDictionaries The `NSDictictionary` or `NSArray` of `NSDictionary` object representations that was found at the `keyPath`. - @param keyPath The key path that the representation was read from in the `sourceObject`. + @param keyPath The key path that the representation was read from in the `sourceObject`. If the `keyPath` was `[NSNull null]` in the `mappingsDictionary`, it will be given as `nil` to the delegate. */ - (void)mapper:(RKMapperOperation *)mapper didFindRespresentation:(id)dictionaryOrArrayOfDictionaries atKeyPath:(NSString *)keyPath; @@ -178,7 +178,7 @@ Tells the delegate that the mapper failed to find a mappable object at a key path specified in the `mappingsDictionary`. @param mapper The mapper operation performing the mapping. - @param keyPath The key path that was searched for a mappable object representation. + @param keyPath The key path that was searched for a mappable object representation. */ - (void)mapper:(RKMapperOperation *)mapper didNotFindReprsentationAtKeyPath:(NSString *)keyPath; @@ -191,7 +191,7 @@ @param mapper The mapper operation performing the mapping. @param mappingOperation The mapping operation that is about to be started. - @param keyPath The key path that was mapped. + @param keyPath The key path that was mapped. A `nil` key path indicates that the mapping matched the entire `sourceObject`. */ - (void)mapper:(RKMapperOperation *)mapper willStartMappingOperation:(RKMappingOperation *)mappingOperation forKeyPath:(NSString *)keyPath; @@ -200,7 +200,7 @@ @param mapper The mapper operation performing the mapping. @param mappingOperation The mapping operation that has finished. - @param keyPath The key path that was mapped. + @param keyPath The key path that was mapped. A `nil` key path indicates that the mapping matched the entire `sourceObject`. */ - (void)mapper:(RKMapperOperation *)mapper didFinishMappingOperation:(RKMappingOperation *)mappingOperation forKeyPath:(NSString *)keyPath; @@ -209,7 +209,7 @@ @param mapper The mapper operation performing the mapping. @param mappingOperation The mapping operation that has failed. - @param keyPath The key path that was mapped. + @param keyPath The key path that was mapped. A `nil` key path indicates that the mapping matched the entire `sourceObject`. @param error The error that occurred during the execution of the mapping operation. */ - (void)mapper:(RKMapperOperation *)mapper didFailMappingOperation:(RKMappingOperation *)mappingOperation forKeyPath:(NSString *)keyPath withError:(NSError *)error; diff --git a/Code/ObjectMapping/RKMapperOperation.m b/Code/ObjectMapping/RKMapperOperation.m index dc8d4736..4c25ebe2 100644 --- a/Code/ObjectMapping/RKMapperOperation.m +++ b/Code/ObjectMapping/RKMapperOperation.m @@ -32,6 +32,11 @@ NSString * const RKMappingErrorKeyPathErrorKey = @"keyPath"; #undef RKLogComponent #define RKLogComponent lcl_cRestKitObjectMapping +static NSString *RKDelegateKeyPathFromKeyPath(NSString *keyPath) +{ + return ([keyPath isEqual:[NSNull null]]) ? nil : keyPath; +} + @interface RKMapperOperation () @property (nonatomic, strong, readwrite) NSError *error; @@ -80,6 +85,7 @@ NSString * const RKMappingErrorKeyPathErrorKey = @"keyPath"; [userInfo addEntriesFromDictionary:otherInfo]; NSError *error = [NSError errorWithDomain:RKErrorDomain code:errorCode userInfo:userInfo]; [self addError:error]; + self.error = error; } - (void)addErrorForUnmappableKeyPath:(NSString *)keyPath @@ -204,27 +210,27 @@ NSString * const RKMappingErrorKeyPathErrorKey = @"keyPath"; NSAssert(mapping != nil, @"Cannot map without an mapping"); RKLogDebug(@"Asked to map source object %@ with mapping %@", mappableObject, mapping); - NSError *error = nil; RKMappingOperation *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:mappableObject destinationObject:destinationObject mapping:mapping]; mappingOperation.dataSource = self.mappingOperationDataSource; - if ([self.delegate respondsToSelector:@selector(mapper:willStartMappingOperation:)]) { - [self.delegate mapper:self willStartMappingOperation:mappingOperation forKeyPath:keyPath]; + if ([self.delegate respondsToSelector:@selector(mapper:willStartMappingOperation:forKeyPath:)]) { + [self.delegate mapper:self willStartMappingOperation:mappingOperation forKeyPath:RKDelegateKeyPathFromKeyPath(keyPath)]; } - BOOL success = [mappingOperation performMapping:&error]; - if (success) { - if ([self.delegate respondsToSelector:@selector(mapper:didFinishMappingOperation:)]) { - [self.delegate mapper:self didFinishMappingOperation:mappingOperation forKeyPath:keyPath]; + [mappingOperation start]; + if (mappingOperation.error) { + if ([self.delegate respondsToSelector:@selector(mapper:didFailMappingOperation:forKeyPath:withError:)]) { + [self.delegate mapper:self didFailMappingOperation:mappingOperation forKeyPath:RKDelegateKeyPathFromKeyPath(keyPath) withError:mappingOperation.error]; } - } else if (error) { - if ([self.delegate respondsToSelector:@selector(mapper:didFailMappingOperation:withError:)]) { - [self.delegate mapper:self didFailMappingOperation:mappingOperation forKeyPath:keyPath withError:error]; + [self addError:mappingOperation.error]; + + return NO; + } else { + if ([self.delegate respondsToSelector:@selector(mapper:didFinishMappingOperation:forKeyPath:)]) { + [self.delegate mapper:self didFinishMappingOperation:mappingOperation forKeyPath:RKDelegateKeyPathFromKeyPath(keyPath)]; } - [self addError:error]; + + return YES; } - - - return success; } - (id)objectWithMapping:(RKMapping *)mapping andData:(id)mappableData @@ -286,7 +292,7 @@ NSString * const RKMappingErrorKeyPathErrorKey = @"keyPath"; RKLogDebug(@"Found unmappable value at keyPath: %@", keyPath); if ([self.delegate respondsToSelector:@selector(mapper:didNotFindReprsentationAtKeyPath:)]) { - [self.delegate mapper:self didNotFindReprsentationAtKeyPath:keyPath]; + [self.delegate mapper:self didNotFindReprsentationAtKeyPath:RKDelegateKeyPathFromKeyPath(keyPath)]; } continue; @@ -295,8 +301,8 @@ NSString * const RKMappingErrorKeyPathErrorKey = @"keyPath"; // Found something to map foundMappable = YES; RKMapping *mapping = [mappingsByKeyPath objectForKey:keyPath]; - if ([self.delegate respondsToSelector:@selector(mapper:didFindMappableObject:atKeyPath:)]) { - [self.delegate mapper:self didFindRespresentation:mappableValue atKeyPath:keyPath]; + if ([self.delegate respondsToSelector:@selector(mapper:didFindRespresentation:atKeyPath:)]) { + [self.delegate mapper:self didFindRespresentation:mappableValue atKeyPath:RKDelegateKeyPathFromKeyPath(keyPath)]; } mappingResult = [self performMappingForObject:mappableValue atKeyPath:keyPath usingMapping:mapping]; diff --git a/Code/ObjectMapping/RKMappingOperation.h b/Code/ObjectMapping/RKMappingOperation.h index 0f6c5795..b5138a74 100644 --- a/Code/ObjectMapping/RKMappingOperation.h +++ b/Code/ObjectMapping/RKMappingOperation.h @@ -55,7 +55,7 @@ @param operation The object mapping operation being performed. @param value A new value that was set on the destination object. @param keyPath The key path in the destination object for which a new value has been set. - @param propertyMapping The RKAttributeMapping or RKRelationshipMapping found for the key path. + @param propertyMapping The `RKAttributeMapping` or `RKRelationshipMapping` found for the key path. */ - (void)mappingOperation:(RKMappingOperation *)operation didSetValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKPropertyMapping *)propertyMapping; @@ -65,7 +65,7 @@ @param operation The object mapping operation being performed. @param value A unchanged value for the key path in the destination object. @param keyPath The key path in the destination object for which a unchanged value was not set. - @param propertyMapping The RKAttributeMapping or RKRelationshipMapping found for the key path. + @param propertyMapping The `RKAttributeMapping` or `RKRelationshipMapping` found for the key path. */ - (void)mappingOperation:(RKMappingOperation *)operation didNotSetUnchangedValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKPropertyMapping *)propertyMapping; @@ -80,7 +80,7 @@ /** Tells the delegate that the mapping operation has selected a concrete object mapping with which to map the source object. - Only sent if the receiver was initialized with an instance of RKDynamicMapping as the mapping. + Only sent if the receiver was initialized with an instance of `RKDynamicMapping` as the mapping. @param operation The mapping operation. @param objectMapping The concrete object mapping with which to perform the mapping. @@ -93,7 +93,7 @@ /** Instances of `RKMappingOperation` perform transformation between object representations according to the rules expressed in `RKObjectMapping` objects. Mapping operations provide the foundation for the RestKit object mapping engine and perform the work of inspecting the attributes and relationships of a source object and determining how to map them into new representations on a destination object. */ -@interface RKMappingOperation : NSObject +@interface RKMappingOperation : NSOperation ///--------------------------------------- /// @name Initializing a Mapping Operation @@ -146,6 +146,11 @@ */ @property (nonatomic, weak) id dataSource; +/** + The error, if any, that occurred during the execution of the mapping operation. + */ +@property (nonatomic, strong, readonly) NSError *error; + ///------------------------- /// @name Performing Mapping ///------------------------- diff --git a/Code/ObjectMapping/RKMappingOperation.m b/Code/ObjectMapping/RKMappingOperation.m index 3721aaa6..45115a6f 100644 --- a/Code/ObjectMapping/RKMappingOperation.m +++ b/Code/ObjectMapping/RKMappingOperation.m @@ -72,6 +72,7 @@ extern NSString * const RKObjectMappingNestingAttributeKeyName; @property (nonatomic, strong, readwrite) id destinationObject; @property (nonatomic, strong) NSDictionary *nestedAttributeSubstitution; @property (nonatomic, strong) NSError *validationError; +@property (nonatomic, strong, readwrite) NSError *error; @property (nonatomic, strong) RKObjectMapping *objectMapping; // The concrete mapping @end @@ -425,7 +426,9 @@ extern NSString * const RKObjectMappingNestingAttributeKeyName; RKMappingOperation *subOperation = [[RKMappingOperation alloc] initWithSourceObject:anObject destinationObject:anotherObject mapping:relationshipMapping.mapping]; subOperation.dataSource = self.dataSource; subOperation.delegate = self.delegate; - if (NO == [subOperation performMapping:&error]) { + [subOperation start]; + + if (subOperation.error) { RKLogWarning(@"WARNING: Failed mapping nested object: %@", [error localizedDescription]); } @@ -626,7 +629,7 @@ extern NSString * const RKObjectMappingNestingAttributeKeyName; } } -- (BOOL)performMapping:(NSError **)error +- (void)start { RKLogDebug(@"Starting mapping operation..."); RKLogTrace(@"Performing mapping operation: %@", self); @@ -653,23 +656,29 @@ extern NSString * const RKObjectMappingNestingAttributeKeyName; if ([self.dataSource respondsToSelector:@selector(commitChangesForMappingOperation:)]) { [self.dataSource commitChangesForMappingOperation:self]; } - return YES; + return; } - if (_validationError) { + if (self.validationError) { // We failed out due to validation - if (error) *error = _validationError; + self.error = _validationError; if ([self.delegate respondsToSelector:@selector(mappingOperation:didFailWithError:)]) { - [self.delegate mappingOperation:self didFailWithError:_validationError]; + [self.delegate mappingOperation:self didFailWithError:self.error]; } - RKLogError(@"Failed mapping operation: %@", [_validationError localizedDescription]); + RKLogError(@"Failed mapping operation: %@", [self.error localizedDescription]); } else { // We did not find anything to do RKLogDebug(@"Mapping operation did not find any mappable content"); + self.error = [NSError errorWithDomain:RKErrorDomain code:RKMappingErrorUnmappableContent userInfo:nil]; } +} - return NO; +- (BOOL)performMapping:(NSError **)error +{ + [self start]; + if (error) *error = self.error; + return self.error == nil; } - (NSString *)description diff --git a/Code/ObjectMapping/RKObjectMapping.h b/Code/ObjectMapping/RKObjectMapping.h index d72c726e..1018dc9c 100644 --- a/Code/ObjectMapping/RKObjectMapping.h +++ b/Code/ObjectMapping/RKObjectMapping.h @@ -81,6 +81,20 @@ */ @property (nonatomic, strong, readonly) NSArray *propertyMappings; +/** + Returns the property mappings of the receiver in a dictionary, where the keys are the source key paths and the values are instances of `RKAttributeMapping` or `RKRelationshipMapping`. + + @return The property mappings of the receiver in a dictionary, where the keys are the source key paths and the values are instances of `RKAttributeMapping` or `RKRelationshipMapping`. + */ +@property (nonatomic, readonly) NSDictionary *propertyMappingsBySourceKeyPath; + +/** + Returns the property mappings of the receiver in a dictionary, where the keys are the destination key paths and the values are instances of `RKAttributeMapping` or `RKRelationshipMapping`. + + @return The property mappings of the receiver in a dictionary, where the keys are the destination key paths and the values are instances of `RKAttributeMapping` or `RKRelationshipMapping`. + */ +@property (nonatomic, readonly) NSDictionary *propertyMappingsByDestinationKeyPath; + /** The collection of attribute mappings within this object mapping. */ @@ -156,6 +170,7 @@ */ - (void)mapKeyOfNestedDictionaryToAttribute:(NSString *)attributeName; +// TODO: Can we eliminate this API??? /** Returns the attribute mapping targeting the key of a nested dictionary in the source JSON. @@ -239,7 +254,7 @@ quickly generate a corresponding serialization mapping from a configured object mapping. The inverse mapping will have the source and destination keyPaths swapped for all attribute and relationship mappings. */ -//- (RKObjectMapping *)inverseMapping; +- (RKObjectMapping *)inverseMapping; // TODO: Keep or kill inverse??? ///--------------------------------------------------- diff --git a/Code/ObjectMapping/RKObjectMapping.m b/Code/ObjectMapping/RKObjectMapping.m index 5764f090..4e22296d 100644 --- a/Code/ObjectMapping/RKObjectMapping.m +++ b/Code/ObjectMapping/RKObjectMapping.m @@ -28,6 +28,7 @@ // Constants NSString * const RKObjectMappingNestingAttributeKeyName = @""; +static NSUInteger RKObjectMappingMaximumInverseMappingRecursionDepth = 100; @interface RKObjectMapping () @property (nonatomic, weak, readwrite) Class objectClass; @@ -87,6 +88,26 @@ NSString * const RKObjectMappingNestingAttributeKeyName = @" -#import "RKTestEnvironment.h" -#import "RKURL.h" - -@interface RKClientTest : RKTestCase -@end - - -@implementation RKClientTest - -- (void)setUp -{ - [RKTestFactory setUp]; -} - -- (void)tearDown -{ - [RKTestFactory tearDown]; -} - -- (void)testShouldDetectNetworkStatusWithAHostname -{ - RKClient *client = [[RKClient alloc] initWithBaseURLString:@"http://restkit.org"]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle - RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; - assertThatInt(status, is(equalToInt(RKReachabilityReachableViaWiFi))); - [client release]; -} - -- (void)testShouldDetectNetworkStatusWithAnIPAddressBaseName -{ - RKClient *client = [[RKClient alloc] initWithBaseURLString:@"http://173.45.234.197"]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle - RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; - assertThatInt(status, isNot(equalToInt(RKReachabilityIndeterminate))); - [client release]; -} - -- (void)testShouldSetTheCachePolicyOfTheRequest -{ - RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; - client.cachePolicy = RKRequestCachePolicyLoadIfOffline; - RKRequest *request = [client requestWithResourcePath:@""]; - assertThatInt(request.cachePolicy, is(equalToInt(RKRequestCachePolicyLoadIfOffline))); -} - -- (void)testShouldInitializeTheCacheOfTheRequest -{ - RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; - client.requestCache = [[[RKRequestCache alloc] init] autorelease]; - RKRequest *request = [client requestWithResourcePath:@""]; - assertThat(request.cache, is(equalTo(client.requestCache))); -} - -- (void)testShouldLoadPageWithNoContentTypeInformation -{ - RKClient *client = [RKClient clientWithBaseURLString:@"http://www.semiose.fr"]; - client.defaultHTTPEncoding = NSISOLatin1StringEncoding; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [client requestWithResourcePath:@"/"]; - request.delegate = loader; - [request send]; - [loader waitForResponse]; - assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); - assertThat([loader.response bodyEncodingName], is(nilValue())); - assertThatInteger([loader.response bodyEncoding], is(equalToInteger(NSISOLatin1StringEncoding))); -} - -- (void)testShouldAllowYouToChangeTheBaseURL -{ - RKClient *client = [RKClient clientWithBaseURLString:@"http://www.google.com"]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle - assertThatBool([client isNetworkReachable], is(equalToBool(YES))); - client.baseURL = [RKURL URLWithString:@"http://www.restkit.org"]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle - assertThatBool([client isNetworkReachable], is(equalToBool(YES))); - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [client requestWithResourcePath:@"/"]; - request.delegate = loader; - [request send]; - [loader waitForResponse]; - assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); -} - -- (void)testShouldLetYouChangeTheHTTPAuthCredentials -{ - RKClient *client = [RKTestFactory client]; - client.authenticationType = RKRequestAuthenticationTypeHTTP; - client.username = @"invalid"; - client.password = @"password"; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - [client get:@"/authentication/basic" delegate:responseLoader]; - [responseLoader waitForResponse]; - assertThatBool(responseLoader.wasSuccessful, is(equalToBool(NO))); - assertThat(responseLoader.error, is(notNilValue())); - client.username = @"restkit"; - client.password = @"authentication"; - [client get:@"/authentication/basic" delegate:responseLoader]; - [responseLoader waitForResponse]; - assertThatBool(responseLoader.wasSuccessful, is(equalToBool(YES))); -} - -- (void)testShouldSuspendTheQueueOnBaseURLChangeWhenReachabilityHasNotBeenEstablished -{ - RKClient *client = [RKClient clientWithBaseURLString:@"http://www.google.com"]; - client.baseURL = [RKURL URLWithString:@"http://restkit.org"]; - assertThatBool(client.requestQueue.suspended, is(equalToBool(YES))); -} - -- (void)testShouldNotSuspendTheMainQueueOnBaseURLChangeWhenReachabilityHasBeenEstablished -{ - RKReachabilityObserver *observer = [RKReachabilityObserver reachabilityObserverForInternet]; - [observer getFlags]; - assertThatBool([observer isReachabilityDetermined], is(equalToBool(YES))); - RKClient *client = [RKClient clientWithBaseURLString:@"http://www.google.com"]; - assertThatBool(client.requestQueue.suspended, is(equalToBool(YES))); - client.reachabilityObserver = observer; - assertThatBool(client.requestQueue.suspended, is(equalToBool(NO))); -} - -- (void)testShouldAllowYouToChangeTheTimeoutInterval -{ - RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; - client.timeoutInterval = 20.0; - RKRequest *request = [client requestWithResourcePath:@""]; - assertThatFloat(request.timeoutInterval, is(equalToFloat(20.0))); -} - -- (void)testShouldPerformAPUTWithParams -{ - NSLog(@"PENDING ---> FIX ME!!!"); - return; - RKClient *client = [RKClient clientWithBaseURLString:@"http://ohblockhero.appspot.com/api/v1"]; - client.cachePolicy = RKRequestCachePolicyNone; - RKParams *params = [RKParams params]; - [params setValue:@"username" forParam:@"username"]; - [params setValue:@"Dear Daniel" forParam:@"fullName"]; - [params setValue:@"aa@aa.com" forParam:@"email"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - [client put:@"/userprofile" params:params delegate:loader]; - STAssertNoThrow([loader waitForResponse], @""); - [loader waitForResponse]; - assertThatBool(loader.wasSuccessful, is(equalToBool(NO))); -} - -- (void)testShouldAllowYouToChangeTheCacheTimeoutInterval -{ - RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; - client.cacheTimeoutInterval = 20.0; - RKRequest *request = [client requestWithResourcePath:@""]; - assertThatFloat(request.cacheTimeoutInterval, is(equalToFloat(20.0))); -} - -- (void)testThatRunLoopModePropertyRespected -{ - // FIXME: This test results in the suite hanging for some reason... - RKLogCritical(@"Test disabled"); - return; - NSString * const dummyRunLoopMode = @"dummyRunLoopMode"; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKClient *client = [RKTestFactory client]; - client.runLoopMode = dummyRunLoopMode; - [client get:[[RKTestFactory baseURL] absoluteString] delegate:loader]; - for (NSUInteger i = 0; i < 25; i++) { - [[NSRunLoop currentRunLoop] runMode:dummyRunLoopMode beforeDate:[[NSRunLoop currentRunLoop] limitDateForMode:dummyRunLoopMode]]; - } - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); -} - -@end diff --git a/Tests/Logic/Network/RKOAuthClientTest.m b/Tests/Logic/Network/RKOAuthClientTest.m deleted file mode 100644 index d3ac9339..00000000 --- a/Tests/Logic/Network/RKOAuthClientTest.m +++ /dev/null @@ -1,96 +0,0 @@ -// -// RKOAuthClientTest.m -// RestKit -// -// Created by Rodrigo Garcia on 8/4/11. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKPortCheck.h" - -#define RKOAuthClientTestSkipWithoutMongoDB() \ - if (! [self isMongoRunning]) { \ - NSLog(@"!! Skipping OAuth Test: MongoDB not running"); \ - return; \ - } - -@interface RKOAuthClientTest : RKTestCase - -@end - -@implementation RKOAuthClientTest - -- (BOOL)isMongoRunning -{ - static RKPortCheck *portCheck = nil; - if (! portCheck) { - portCheck = [[RKPortCheck alloc] initWithHost:@"localhost" port:27017]; - [portCheck run]; - } - - return [portCheck isOpen]; -} - -- (void)testShouldGetAccessToken -{ - RKOAuthClientTestSkipWithoutMongoDB(); - - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKOAuthClient *client = RKTestNewOAuthClient(loader); - client.authorizationCode = @"4fa8182d7184797dd5000002"; - client.callbackURL = @"http://someURL.com"; - [client validateAuthorizationCode]; - [loader waitForResponse]; - assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); -} - -- (void)testShouldNotGetAccessToken -{ - RKOAuthClientTestSkipWithoutMongoDB(); - - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKOAuthClient *client = RKTestNewOAuthClient(loader); - client.authorizationCode = @"someInvalidAuthorizationCode"; - client.callbackURL = @"http://someURL.com"; - [client validateAuthorizationCode]; - [loader waitForResponse]; - - assertThatBool(loader.wasSuccessful, is(equalToBool(NO))); -} - -- (void)testShouldGetProtectedResource -{ - RKOAuthClientTestSkipWithoutMongoDB(); - - //TODO: Encapsulate this code in a correct manner - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKOAuthClient *client = RKTestNewOAuthClient(loader); - client.authorizationCode = @"4fa8182d7184797dd5000002"; - client.callbackURL = @"http://someURL.com"; - [client validateAuthorizationCode]; - - RKTestResponseLoader *resourceLoader = [RKTestResponseLoader responseLoader]; - RKClient *requestClient = [RKClient clientWithBaseURLString:[client authorizationURL]]; - requestClient.OAuth2AccessToken = client.accessToken; - requestClient.authenticationType = RKRequestAuthenticationTypeOAuth2; - RKRequest *request = [requestClient requestWithResourcePath:@"/oauth2/pregen/me"]; - request.delegate = resourceLoader; - [request send]; - [resourceLoader waitForResponse]; - assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); -} - -@end diff --git a/Tests/Logic/Network/RKParamsAttachmentTest.m b/Tests/Logic/Network/RKParamsAttachmentTest.m deleted file mode 100644 index bba8f8a7..00000000 --- a/Tests/Logic/Network/RKParamsAttachmentTest.m +++ /dev/null @@ -1,63 +0,0 @@ -// -// RKParamsAttachmentTest.m -// RestKit -// -// Created by Blake Watters on 10/27/10. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKParamsAttachment.h" - -@interface RKParamsAttachmentTest : RKTestCase { -} - -@end - - -@implementation RKParamsAttachmentTest - -- (void)testShouldRaiseAnExceptionWhenTheAttachedFileDoesNotExist -{ - NSException *exception = nil; - @try { - [[RKParamsAttachment alloc] initWithName:@"woot" file:@"/this/is/an/invalid/path"]; - } - @catch (NSException *e) { - exception = e; - } - assertThat(exception, isNot(nilValue())); -} - -- (void)testShouldReturnAnMD5ForSimpleValues -{ - RKParamsAttachment *attachment = [[[RKParamsAttachment alloc] initWithName:@"foo" value:@"bar"] autorelease]; - assertThat([attachment MD5], is(equalTo(@"37b51d194a7513e45b56f6524f2d51f2"))); -} - -- (void)testShouldReturnAnMD5ForNSData -{ - RKParamsAttachment *attachment = [[[RKParamsAttachment alloc] initWithName:@"foo" data:[@"bar" dataUsingEncoding:NSUTF8StringEncoding]] autorelease]; - assertThat([attachment MD5], is(equalTo(@"37b51d194a7513e45b56f6524f2d51f2"))); -} - -- (void)testShouldReturnAnMD5ForFiles -{ - NSString *filePath = [RKTestFixture pathForFixture:@"blake.png"]; - RKParamsAttachment *attachment = [[[RKParamsAttachment alloc] initWithName:@"foo" file:filePath] autorelease]; - assertThat([attachment MD5], is(equalTo(@"db6cb9d879b58e7e15a595632af345cd"))); -} - -@end diff --git a/Tests/Logic/Network/RKParamsTest.m b/Tests/Logic/Network/RKParamsTest.m deleted file mode 100644 index e2d3de1d..00000000 --- a/Tests/Logic/Network/RKParamsTest.m +++ /dev/null @@ -1,122 +0,0 @@ -// -// RKParamsTest.m -// RestKit -// -// Created by Blake Watters on 6/30/11. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKParams.h" -#import "RKRequest.h" - -@interface RKParamsTest : RKTestCase - -@end - -@implementation RKParamsTest - -- (void)testShouldNotOverReleaseTheParams -{ - NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"foo" forKey:@"bar"]; - RKParams *params = [[RKParams alloc] initWithDictionary:dictionary]; - NSURL *URL = [NSURL URLWithString:[[RKTestFactory baseURLString] stringByAppendingFormat:@"/echo_params"]]; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.method = RKRequestMethodPOST; - request.params = params; - request.delegate = responseLoader; - [request sendAsynchronously]; - [responseLoader waitForResponse]; - [request release]; -} - -- (void)testShouldUploadFilesViaRKParams -{ - RKClient *client = [RKTestFactory client]; - RKParams *params = [RKParams params]; - [params setValue:@"one" forParam:@"value"]; - [params setValue:@"two" forParam:@"value"]; - [params setValue:@"three" forParam:@"value"]; - [params setValue:@"four" forParam:@"value"]; - NSData *data = [RKTestFixture dataWithContentsOfFixture:@"blake.png"]; - [params setData:data MIMEType:@"image/png" forParam:@"file"]; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - [client post:@"/upload" params:params delegate:responseLoader]; - [responseLoader waitForResponse]; - assertThatInteger(responseLoader.response.statusCode, is(equalToInt(200))); -} - -- (void)testShouldUploadFilesViaRKParamsWithMixedTypes -{ - NSNumber *idUsuari = [NSNumber numberWithInt:1234]; - NSArray *userList = [NSArray arrayWithObjects:@"one", @"two", @"three", nil]; - NSNumber *idTema = [NSNumber numberWithInt:1234]; - NSString *titulo = @"whatever"; - NSString *texto = @"more text"; - NSData *data = [RKTestFixture dataWithContentsOfFixture:@"blake.png"]; - NSNumber *cel = [NSNumber numberWithFloat:1.232442]; - NSNumber *lon = [NSNumber numberWithFloat:18231.232442];; - NSNumber *lat = [NSNumber numberWithFloat:13213123.232442];; - - RKParams *params = [RKParams params]; - - // Set values - [params setValue:idUsuari forParam:@"idUsuariPropietari"]; - [params setValue:userList forParam:@"telUser"]; - [params setValue:idTema forParam:@"idTema"]; - [params setValue:titulo forParam:@"titulo"]; - [params setValue:texto forParam:@"texto"]; - - [params setData:data MIMEType:@"image/png" forParam:@"file"]; - - [params setValue:cel forParam:@"cel"]; - [params setValue:lon forParam:@"lon"]; - [params setValue:lat forParam:@"lat"]; - - RKClient *client = [RKTestFactory client]; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - [client post:@"/upload" params:params delegate:responseLoader]; - [responseLoader waitForResponse]; - assertThatInteger(responseLoader.response.statusCode, is(equalToInt(200))); -} - -- (void)testShouldCalculateAnMD5ForTheParams -{ - NSDictionary *values = [NSDictionary dictionaryWithObjectsAndKeys:@"foo", @"bar", @"this", @"that", nil]; - RKParams *params = [RKParams paramsWithDictionary:values]; - NSString *MD5 = [params MD5]; - assertThat(MD5, is(equalTo(@"da7d80084b86aa5022b434e3bf084caf"))); -} - -- (void)testShouldProperlyCalculateContentLengthForFileUploads -{ - RKClient *client = [RKTestFactory client]; - RKParams *params = [RKParams params]; - [params setValue:@"one" forParam:@"value"]; - [params setValue:@"two" forParam:@"value"]; - [params setValue:@"three" forParam:@"value"]; - [params setValue:@"four" forParam:@"value"]; - NSData *data = [RKTestFixture dataWithContentsOfFixture:@"blake.png"]; - [params setData:data MIMEType:@"image/png" forParam:@"file"]; - RKRequest *request = [client requestWithResourcePath:@"/upload"]; - [request setMethod:RKRequestMethodPOST]; - request.params = params; - [request prepareURLRequest]; - assertThatInteger([params HTTPHeaderValueForContentLength], is(equalToInt(23166))); - assertThat([[request.URLRequest allHTTPHeaderFields] objectForKey:@"Content-Length"], is(equalTo(@"23166"))); -} - -@end diff --git a/Tests/Logic/Network/RKRequestQueueTest.m b/Tests/Logic/Network/RKRequestQueueTest.m deleted file mode 100644 index 65e11823..00000000 --- a/Tests/Logic/Network/RKRequestQueueTest.m +++ /dev/null @@ -1,301 +0,0 @@ -// -// RKRequestQueueTest.m -// RestKit -// -// Created by Blake Watters on 3/28/11. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" - -// Expose the request queue's [add|remove]LoadingRequest methods testing purposes... -@interface RKRequestQueue () -- (void)addLoadingRequest:(RKRequest *)request; -- (void)removeLoadingRequest:(RKRequest *)request; -@end - -@interface RKRequestQueueTest : RKTestCase { - NSAutoreleasePool *_autoreleasePool; -} - -@end - - -@implementation RKRequestQueueTest - -- (void)setUp -{ - _autoreleasePool = [NSAutoreleasePool new]; -} - -- (void)tearDown -{ - [_autoreleasePool drain]; -} - -- (void)testShouldBeSuspendedWhenInitialized -{ - RKRequestQueue *queue = [RKRequestQueue new]; - assertThatBool(queue.suspended, is(equalToBool(YES))); - [queue release]; -} - -#if TARGET_OS_IPHONE - -// TODO: Crashing... -- (void)testShouldSuspendTheQueueOnTransitionToTheBackground -{ - return; - RKRequestQueue *queue = [RKRequestQueue new]; - assertThatBool(queue.suspended, is(equalToBool(YES))); - queue.suspended = NO; - [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil]; - assertThatBool(queue.suspended, is(equalToBool(YES))); - [queue release]; -} - -- (void)testShouldUnsuspendTheQueueOnTransitionToTheForeground -{ - // TODO: Crashing... - return; - RKRequestQueue *queue = [RKRequestQueue new]; - assertThatBool(queue.suspended, is(equalToBool(YES))); - [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillEnterForegroundNotification object:nil]; - assertThatBool(queue.suspended, is(equalToBool(NO))); - [queue release]; -} - -#endif - -- (void)testShouldInformTheDelegateWhenSuspended -{ - RKRequestQueue *queue = [RKRequestQueue new]; - assertThatBool(queue.suspended, is(equalToBool(YES))); - queue.suspended = NO; - OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; - [[delegateMock expect] requestQueueWasSuspended:queue]; - queue.delegate = (NSObject *)delegateMock; - queue.suspended = YES; - [delegateMock verify]; - [queue release]; -} - -- (void)testShouldInformTheDelegateWhenUnsuspended -{ - RKRequestQueue *queue = [RKRequestQueue new]; - assertThatBool(queue.suspended, is(equalToBool(YES))); - OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; - [[delegateMock expect] requestQueueWasUnsuspended:queue]; - queue.delegate = (NSObject *)delegateMock; - queue.suspended = NO; - [delegateMock verify]; - [queue release]; -} - -- (void)testShouldInformTheDelegateOnTransitionFromEmptyToProcessing -{ - RKRequestQueue *queue = [RKRequestQueue new]; - OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; - [[delegateMock expect] requestQueueDidBeginLoading:queue]; - queue.delegate = (NSObject *)delegateMock; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - [queue addLoadingRequest:request]; - [delegateMock verify]; - [queue release]; -} - -- (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmpty -{ - RKRequestQueue *queue = [RKRequestQueue new]; - OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; - [[delegateMock expect] requestQueueDidFinishLoading:queue]; - queue.delegate = (NSObject *)delegateMock; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - [queue addLoadingRequest:request]; - [queue removeLoadingRequest:request]; - [delegateMock verify]; - [queue release]; -} - -- (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmptyForQueuesWithASingleRequest -{ - OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - - NSString *url = [NSString stringWithFormat:@"%@/ok-with-delay/0.3", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.delegate = loader; - - RKRequestQueue *queue = [RKRequestQueue new]; - queue.delegate = (NSObject *)delegateMock; - [[delegateMock expect] requestQueueDidFinishLoading:queue]; - [queue addRequest:request]; - [queue start]; - [loader waitForResponse]; - [delegateMock verify]; - [queue release]; -} - -// TODO: These tests cannot pass in the unit testing environment... Need to migrate to an integration -// testing area -//- (void)testShouldBeginSpinningTheNetworkActivityIfAsked { -// [[UIApplication sharedApplication] rk_resetNetworkActivity]; -// RKRequestQueue *queue = [RKRequestQueue new]; -// queue.showsNetworkActivityIndicatorWhenBusy = YES; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(NO))); -// [queue setValue:[NSNumber numberWithInt:1] forKey:@"loadingCount"]; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(YES))); -// [queue release]; -//} -// -//- (void)testShouldStopSpinningTheNetworkActivityIfAsked { -// [[UIApplication sharedApplication] rk_resetNetworkActivity]; -// RKRequestQueue *queue = [RKRequestQueue new]; -// queue.showsNetworkActivityIndicatorWhenBusy = YES; -// [queue setValue:[NSNumber numberWithInt:1] forKey:@"loadingCount"]; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(YES))); -// [queue setValue:[NSNumber numberWithInt:0] forKey:@"loadingCount"]; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(NO))); -// [queue release]; -//} -// -//- (void)testShouldJointlyManageTheNetworkActivityIndicator { -// [[UIApplication sharedApplication] rk_resetNetworkActivity]; -// RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; -// loader.timeout = 10; -// -// RKRequestQueue *queue1 = [RKRequestQueue new]; -// queue1.showsNetworkActivityIndicatorWhenBusy = YES; -// NSString *url1 = [NSString stringWithFormat:@"%@/ok-with-delay/2.0", [RKTestFactory baseURL]]; -// NSURL *URL1 = [NSURL URLWithString:url1]; -// RKRequest *request1 = [[RKRequest alloc] initWithURL:URL1]; -// request1.delegate = loader; -// -// RKRequestQueue *queue2 = [RKRequestQueue new]; -// queue2.showsNetworkActivityIndicatorWhenBusy = YES; -// NSString *url2 = [NSString stringWithFormat:@"%@/ok-with-delay/2.0", [RKTestFactory baseURL]]; -// NSURL *URL2 = [NSURL URLWithString:url2]; -// RKRequest *request2 = [[RKRequest alloc] initWithURL:URL2]; -// request2.delegate = loader; -// -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(NO))); -// [queue1 addRequest:request1]; -// [queue1 start]; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(YES))); -// [queue2 addRequest:request2]; -// [queue2 start]; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(YES))); -// [loader waitForResponse]; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(YES))); -// [loader waitForResponse]; -// assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(NO))); -//} - -- (void)testShouldLetYouReturnAQueueByName -{ - RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images"]; - assertThat(queue, isNot(nilValue())); - assertThat(queue.name, is(equalTo(@"Images"))); -} - -- (void)testShouldReturnAnExistingQueueByName -{ - RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images2"]; - assertThat(queue, isNot(nilValue())); - RKRequestQueue *secondQueue = [RKRequestQueue requestQueueWithName:@"Images2"]; - assertThat(queue, is(equalTo(secondQueue))); -} - -- (void)testShouldReturnTheQueueWithoutAModifiedRetainCount -{ - RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images3"]; - assertThat(queue, isNot(nilValue())); - assertThatUnsignedInteger([queue retainCount], is(equalToInt(1))); -} - -- (void)testShouldReturnYESWhenAQueueExistsWithAGivenName -{ - assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images4"], is(equalToBool(NO))); - [RKRequestQueue requestQueueWithName:@"Images4"]; - assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images4"], is(equalToBool(YES))); -} - -- (void)testShouldRemoveTheQueueFromTheNamedInstancesOnDealloc -{ - // TODO: Crashing... - return; - RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images5"]; - assertThat(queue, isNot(nilValue())); - assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images5"], is(equalToBool(YES))); - [queue release]; - assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images5"], is(equalToBool(NO))); -} - -- (void)testShouldReturnANewOwningReferenceViaNewRequestWithName -{ - RKRequestQueue *requestQueue = [RKRequestQueue newRequestQueueWithName:@"Images6"]; - assertThat(requestQueue, isNot(nilValue())); - assertThatUnsignedInteger([requestQueue retainCount], is(equalToInt(1))); -} - -- (void)testShouldReturnNilIfNewRequestQueueWithNameIsCalledForAnExistingName -{ - RKRequestQueue *queue = [RKRequestQueue newRequestQueueWithName:@"Images7"]; - assertThat(queue, isNot(nilValue())); - RKRequestQueue *queue2 = [RKRequestQueue newRequestQueueWithName:@"Images7"]; - assertThat(queue2, is(nilValue())); -} - -- (void)testShouldRemoveItemsFromTheQueueWithAnUnmappableResponse -{ - RKRequestQueue *queue = [RKRequestQueue requestQueue]; - RKObjectManager *objectManager = [RKTestFactory objectManager]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKObjectLoader *objectLoader = [objectManager loaderWithResourcePath:@"/403"]; - objectLoader.delegate = loader; - [queue addRequest:(RKRequest *)objectLoader]; - [queue start]; - [loader waitForResponse]; - assertThatUnsignedInteger(queue.loadingCount, is(equalToInt(0))); -} - -- (void)testThatSendingRequestToInvalidURLDoesNotGetSentTwice -{ - RKRequestQueue *queue = [RKRequestQueue requestQueue]; - NSURL *URL = [NSURL URLWithString:@"http://localhost:7662/RKRequestQueueExample"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - id mockResponseLoader = [OCMockObject partialMockForObject:responseLoader]; - [[[mockResponseLoader expect] andForwardToRealObject] request:request didFailLoadWithError:OCMOCK_ANY]; - request.delegate = responseLoader; - id mockQueueDelegate = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; - __block NSUInteger invocationCount = 0; - [[mockQueueDelegate stub] requestQueue:queue willSendRequest:[OCMArg checkWithBlock:^BOOL(id request) { - invocationCount++; - return YES; - }]]; - [queue addRequest:request]; - queue.delegate = mockQueueDelegate; - [queue start]; - [mockResponseLoader waitForResponse]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]; - [mockResponseLoader verify]; - assertThatInteger(invocationCount, is(equalToInteger(1))); -} - -@end diff --git a/Tests/Logic/Network/RKRequestTest.m b/Tests/Logic/Network/RKRequestTest.m deleted file mode 100644 index d91e2cd8..00000000 --- a/Tests/Logic/Network/RKRequestTest.m +++ /dev/null @@ -1,1061 +0,0 @@ -// -// RKRequestTest.m -// RestKit -// -// Created by Blake Watters on 1/15/10. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKRequest.h" -#import "RKParams.h" -#import "RKResponse.h" -#import "RKURL.h" -#import "RKDirectoryUtilities.h" - -@interface RKRequest (Private) -- (void)fireAsynchronousRequest; -- (void)shouldDispatchRequest; -@end - -@interface RKRequestTest : RKTestCase { - int _methodInvocationCounter; -} - -@end - -@implementation RKRequestTest - -- (void)setUp -{ - [RKTestFactory setUp]; - - // Clear the cache directory - [RKTestFactory clearCacheDirectory]; - _methodInvocationCounter = 0; -} - -- (void)tearDown -{ - [RKTestFactory tearDown]; -} - -- (int)incrementMethodInvocationCounter -{ - return _methodInvocationCounter++; -} - -/** - * This spec requires the test Sinatra server to be running - * `ruby Tests/server.rb` - */ -- (void)testShouldSendMultiPartRequests -{ - NSString *URLString = [NSString stringWithFormat:@"http://127.0.0.1:4567/photo"]; - NSURL *URL = [NSURL URLWithString:URLString]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - RKParams *params = [[RKParams params] retain]; - NSString *filePath = [RKTestFixture pathForFixture:@"blake.png"]; - [params setFile:filePath forParam:@"file"]; - [params setValue:@"this is the value" forParam:@"test"]; - request.method = RKRequestMethodPOST; - request.params = params; - RKResponse *response = [request sendSynchronously]; - assertThatInteger(response.statusCode, is(equalToInt(200))); -} - -#pragma mark - Basics - -- (void)testShouldSetURLRequestHTTPBody -{ - NSURL *URL = [NSURL URLWithString:[RKTestFactory baseURLString]]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - NSString *JSON = @"whatever"; - NSData *data = [JSON dataUsingEncoding:NSASCIIStringEncoding]; - request.HTTPBody = data; - assertThat(request.URLRequest.HTTPBody, equalTo(data)); - assertThat(request.HTTPBody, equalTo(data)); - assertThat(request.HTTPBodyString, equalTo(JSON)); -} - -- (void)testShouldSetURLRequestHTTPBodyByString -{ - NSURL *URL = [NSURL URLWithString:[RKTestFactory baseURLString]]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - NSString *JSON = @"whatever"; - NSData *data = [JSON dataUsingEncoding:NSASCIIStringEncoding]; - request.HTTPBodyString = JSON; - assertThat(request.URLRequest.HTTPBody, equalTo(data)); - assertThat(request.HTTPBody, equalTo(data)); - assertThat(request.HTTPBodyString, equalTo(JSON)); -} - -- (void)testShouldTimeoutAtIntervalWhenSentAsynchronously -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - id loaderMock = [OCMockObject partialMockForObject:loader]; - NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.delegate = loaderMock; - request.timeoutInterval = 3.0; - [[[loaderMock expect] andForwardToRealObject] request:request didFailLoadWithError:OCMOCK_ANY]; - [request sendAsynchronously]; - [loaderMock waitForResponse]; - assertThatInt((int)loader.error.code, equalToInt(RKRequestConnectionTimeoutError)); - [request release]; -} - -- (void)testShouldTimeoutAtIntervalWhenSentSynchronously -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - id loaderMock = [OCMockObject partialMockForObject:loader]; - NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.delegate = loaderMock; - request.timeoutInterval = 3.0; - [[[loaderMock expect] andForwardToRealObject] request:request didFailLoadWithError:OCMOCK_ANY]; - [request sendSynchronously]; - assertThatInt((int)loader.error.code, equalToInt(RKRequestConnectionTimeoutError)); - [request release]; -} - -- (void)testShouldCreateOneTimeoutTimerWhenSentAsynchronously -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [[RKRequest alloc] initWithURL:[RKTestFactory baseURL]]; - request.delegate = loader; - id requestMock = [OCMockObject partialMockForObject:request]; - [[[requestMock expect] andCall:@selector(incrementMethodInvocationCounter) onObject:self] createTimeoutTimer]; - [requestMock sendAsynchronously]; - [loader waitForResponse]; - assertThatInt(_methodInvocationCounter, equalToInt(1)); - [request release]; -} - -- (void)testThatSendingDataInvalidatesTimeoutTimer -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - loader.timeout = 3.0; - NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.method = RKRequestMethodPOST; - request.delegate = loader; - request.params = [NSDictionary dictionaryWithObject:@"test" forKey:@"test"]; -request.timeoutInterval = 1.0; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - [request release]; -} - -- (void)testThatRunLoopModePropertyRespected -{ - // FIXME: This test results in the suite hanging for some reason... - RKLogCritical(@"Test disabled"); - return; - NSString * const dummyRunLoopMode = @"dummyRunLoopMode"; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [[RKRequest alloc] initWithURL:[RKTestFactory baseURL]]; - request.delegate = loader; - request.runLoopMode = dummyRunLoopMode; - [request sendAsynchronously]; - while ([[NSRunLoop currentRunLoop] runMode:dummyRunLoopMode beforeDate:[[NSRunLoop currentRunLoop] limitDateForMode:dummyRunLoopMode]]) - ; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - [request release]; -} - -#pragma mark - Background Policies - -#if TARGET_OS_IPHONE - -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyNone -{ - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyNone; - id requestMock = [OCMockObject partialMockForObject:request]; - [[requestMock expect] fireAsynchronousRequest]; // Not sure what else to test on this case - [request sendAsynchronously]; - [requestMock verify]; -} - -- (UIApplication *)sharedApplicationMock -{ - id mockApplication = [OCMockObject mockForClass:[UIApplication class]]; - return mockApplication; -} - -- (void)stubSharedApplicationWhileExecutingBlock:(void (^)(void))block -{ - [self swizzleMethod:@selector(sharedApplication) - inClass:[UIApplication class] - withMethod:@selector(sharedApplicationMock) - fromClass:[self class] - executeBlock:block]; -} - -- (void)testShouldObserveForAppBackgroundTransitionsAndCancelTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel -{ - [self stubSharedApplicationWhileExecutingBlock:^{ - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyCancel; - id requestMock = [OCMockObject partialMockForObject:request]; - [[requestMock expect] cancel]; - [requestMock sendAsynchronously]; - [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil]; - [requestMock verify]; - }]; -} - -- (void)testShouldInformTheDelegateOfCancelWhenTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel -{ - [RKTestFactory client]; - [self stubSharedApplicationWhileExecutingBlock:^{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyCancel; - request.delegate = loader; - [request sendAsynchronously]; - [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil]; - assertThatBool(loader.wasCancelled, is(equalToBool(YES))); - [request release]; - }]; -} - -- (void)testShouldDeallocTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel -{ - [RKTestFactory client]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyCancel; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatInteger([request retainCount], is(equalToInteger(1))); - [request release]; -} - -- (void)testShouldPutTheRequestBackOntoTheQueueWhenBackgroundPolicyIsRKRequestBackgroundPolicyRequeue -{ - [self stubSharedApplicationWhileExecutingBlock:^{ - RKRequestQueue *queue = [RKRequestQueue new]; - queue.suspended = YES; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyRequeue; - request.delegate = loader; - request.queue = queue; - [request sendAsynchronously]; - [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil]; - assertThatBool([request isLoading], is(equalToBool(NO))); - assertThatBool([queue containsRequest:request], is(equalToBool(YES))); - [queue release]; - }]; -} - -- (void)testShouldCreateABackgroundTaskWhenBackgroundPolicyIsRKRequestBackgroundPolicyContinue -{ - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyContinue; - [request sendAsynchronously]; - assertThatInt(request.backgroundTaskIdentifier, equalToInt(UIBackgroundTaskInvalid)); -} - -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsNone -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyNone; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); -} - -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsContinue -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyContinue; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); -} - -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsCancel -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyCancel; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); -} - -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsRequeue -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSURL *URL = [RKTestFactory baseURL]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.backgroundPolicy = RKRequestBackgroundPolicyRequeue; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); -} - -#endif - -#pragma mark RKRequestCachePolicy Tests - -- (void)testShouldSendTheRequestWhenTheCachePolicyIsNone -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyNone; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); -} - -- (void)testShouldCacheTheRequestHeadersAndBodyIncludingOurOwnCustomTimestampHeader -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - NSDictionary *headers = [cache headersForRequest:request]; - assertThat([headers valueForKey:@"X-RESTKIT-CACHEDATE"], isNot(nilValue())); - assertThat([headers valueForKey:@"Etag"], is(equalTo(@"686897696a7c876b7e"))); - assertThat([[cache responseForRequest:request] bodyAsString], is(equalTo(@"This Should Get Cached"))); -} - -- (void)testShouldGenerateAUniqueCacheKeyBasedOnTheUrlTheMethodAndTheHTTPBody -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.method = RKRequestMethodDELETE; - // Don't cache delete. cache key should be nil. - assertThat([request cacheKey], is(nilValue())); - - request.method = RKRequestMethodPOST; - assertThat([request cacheKey], is(nilValue())); - - request.method = RKRequestMethodPUT; - assertThat([request cacheKey], is(nilValue())); -} - -- (void)testShouldLoadFromCacheWhenWeRecieveA304 -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThat([cache etagForRequest:request], is(equalTo(@"686897696a7c876b7e"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); - } - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); - } -} - -- (void)testShouldUpdateTheInternalCacheDateWhenWeRecieveA304 -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - - NSDate *internalCacheDate1; - NSDate *internalCacheDate2; - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThat([cache etagForRequest:request], is(equalTo(@"686897696a7c876b7e"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); - internalCacheDate1 = [cache cacheDateForRequest:request]; - } - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.5]]; - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); - internalCacheDate2 = [cache cacheDateForRequest:request]; - } - assertThat(internalCacheDate1, isNot(internalCacheDate2)); -} - -- (void)testShouldLoadFromTheCacheIfThereIsAnError -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); - } - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyLoadOnError; - request.cache = cache; - request.delegate = loader; - [request didFailLoadWithError:[NSError errorWithDomain:@"Fake" code:0 userInfo:nil]]; - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); - } -} - -- (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - - NSString *url = [NSString stringWithFormat:@"%@/disk/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyTimeout; - request.cacheTimeoutInterval = 5; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached For 5 Seconds"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); - } - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyTimeout; - request.cacheTimeoutInterval = 5; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached For 5 Seconds"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); - } - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyTimeout; - request.cacheTimeoutInterval = 5; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached For 5 Seconds"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); - } - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyTimeout; - request.cacheTimeoutInterval = 0; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached For 5 Seconds"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); - } -} - -- (void)testShouldLoadFromTheCacheIfWeAreOffline -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - loader.timeout = 60; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); - } - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - loader.timeout = 60; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyLoadIfOffline; - request.cache = cache; - request.delegate = loader; - id mock = [OCMockObject partialMockForObject:request]; - BOOL returnValue = NO; - [[[mock expect] andReturnValue:OCMOCK_VALUE(returnValue)] shouldDispatchRequest]; - [mock sendAsynchronously]; - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); - } -} - -- (void)testShouldCacheTheStatusCodeMIMETypeAndURL -{ - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - - RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath - storagePolicy:RKRequestCacheStoragePolicyPermanently]; - [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThat([loader.response bodyAsString], is(equalTo(@"This Should Get Cached"))); - NSLog(@"Headers: %@", [cache headersForRequest:request]); - assertThat([cache etagForRequest:request], is(equalTo(@"686897696a7c876b7e"))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); - } - { - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL *URL = [NSURL URLWithString:url]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.cachePolicy = RKRequestCachePolicyEtag; - request.cache = cache; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); - assertThatInteger(loader.response.statusCode, is(equalToInt(200))); - assertThat(loader.response.MIMEType, is(equalTo(@"text/html"))); - assertThat([loader.response.URL absoluteString], is(equalTo(@"http://127.0.0.1:4567/etags/cached"))); - } -} - -- (void)testShouldPostSimpleKeyValuesViaRKParams -{ - RKParams *params = [RKParams params]; - - [params setValue:@"hello" forParam:@"username"]; - [params setValue:@"password" forParam:@"password"]; - - RKClient *client = [RKTestFactory client]; - client.cachePolicy = RKRequestCachePolicyNone; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - loader.timeout = 20; - [client post:@"/echo_params" params:params delegate:loader]; - [loader waitForResponse]; - assertThat([loader.response bodyAsString], is(equalTo(@"{\"username\":\"hello\",\"password\":\"password\"}"))); -} - -- (void)testShouldSetAnEmptyContentBodyWhenParamsIsNil -{ - RKClient *client = [RKTestFactory client]; - client.cachePolicy = RKRequestCachePolicyNone; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - loader.timeout = 20; - RKRequest *request = [client get:@"/echo_params" delegate:loader]; - [loader waitForResponse]; - assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); -} - -- (void)testShouldSetAnEmptyContentBodyWhenQueryParamsIsAnEmptyDictionary -{ - RKClient *client = [RKTestFactory client]; - client.cachePolicy = RKRequestCachePolicyNone; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - loader.timeout = 20; - RKRequest *request = [client get:@"/echo_params" queryParameters:[NSDictionary dictionary] delegate:loader]; - [loader waitForResponse]; - assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); -} - -- (void)testShouldPUTWithParams -{ - RKClient *client = [RKTestFactory client]; - RKParams *params = [RKParams params]; - [params setValue:@"ddss" forParam:@"username"]; - [params setValue:@"aaaa@aa.com" forParam:@"email"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - [client put:@"/ping" params:params delegate:loader]; - [loader waitForResponse]; - assertThat([loader.response bodyAsString], is(equalTo(@"{\"username\":\"ddss\",\"email\":\"aaaa@aa.com\"}"))); -} - -- (void)testShouldAllowYouToChangeTheURL -{ - NSURL *URL = [NSURL URLWithString:@"http://restkit.org/monkey"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - request.URL = [NSURL URLWithString:@"http://restkit.org/gorilla"]; - assertThat([request.URL absoluteString], is(equalTo(@"http://restkit.org/gorilla"))); -} - -- (void)testShouldAllowYouToChangeTheResourcePath -{ - RKURL *URL = [[RKURL URLWithString:@"http://restkit.org"] URLByAppendingResourcePath:@"/monkey"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - request.resourcePath = @"/gorilla"; - assertThat(request.resourcePath, is(equalTo(@"/gorilla"))); -} - -- (void)testShouldNotRaiseAnExceptionWhenAttemptingToMutateResourcePathOnAnNSURL -{ - NSURL *URL = [NSURL URLWithString:@"http://restkit.org/monkey"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - NSException *exception = nil; - @try { - request.resourcePath = @"/gorilla"; - } - @catch (NSException *e) { - exception = e; - } - @finally { - assertThat(exception, is(nilValue())); - } -} - -- (void)testShouldOptionallySkipSSLValidation -{ - NSURL *URL = [NSURL URLWithString:@"https://blakewatters.com/"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - request.disableCertificateValidation = YES; - RKResponse *response = [request sendSynchronously]; - assertThatBool([response isOK], is(equalToBool(YES))); -} - -- (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAGETRequest -{ - RKClient *client = [RKTestFactory client]; - client.disableCertificateValidation = YES; - NSURL *URL = [NSURL URLWithString:@"https://blakewatters.com/"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [RKRequest requestWithURL:URL]; - request.delegate = loader; - request.params = [NSDictionary dictionaryWithObject:@"foo" forKey:@"bar"]; - [request send]; - [loader waitForResponse]; - assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); -} - -- (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAHEADRequest -{ - RKClient *client = [RKTestFactory client]; - client.disableCertificateValidation = YES; - NSURL *URL = [NSURL URLWithString:@"https://blakewatters.com/"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [RKRequest requestWithURL:URL]; - request.delegate = loader; - request.method = RKRequestMethodHEAD; - request.params = [NSDictionary dictionaryWithObject:@"foo" forKey:@"bar"]; - [request send]; - [loader waitForResponse]; - assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); -} - -- (void)testShouldLetYouHandleResponsesWithABlock -{ - RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/ping"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - request.delegate = responseLoader; - __block BOOL blockInvoked = NO; - request.onDidLoadResponse = ^ (RKResponse *response) { - blockInvoked = YES; - }; - [request sendAsynchronously]; - [responseLoader waitForResponse]; - assertThatBool(blockInvoked, is(equalToBool(YES))); -} - -- (void)testShouldLetYouHandleErrorsWithABlock -{ - RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/fail"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - request.delegate = responseLoader; - __block BOOL blockInvoked = NO; - request.onDidLoadResponse = ^ (RKResponse *response) { - blockInvoked = YES; - }; - [request sendAsynchronously]; - [responseLoader waitForResponse]; - assertThatBool(blockInvoked, is(equalToBool(YES))); -} - -// TODO: Move to RKRequestCacheTest -- (void)testShouldReturnACachePathWhenTheRequestIsUsingRKParams -{ - RKParams *params = [RKParams params]; - [params setValue:@"foo" forParam:@"bar"]; - NSURL *URL = [NSURL URLWithString:@"http://restkit.org/"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - request.params = params; - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *requestCache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; - NSString *requestCachePath = [requestCache pathForRequest:request]; - NSArray *pathComponents = [requestCachePath pathComponents]; - NSString *cacheFile = [NSString pathWithComponents:[pathComponents subarrayWithRange:NSMakeRange([pathComponents count] - 2, 2)]]; - assertThat(cacheFile, is(equalTo(@"SessionStore/4ba47367884760141da2e38fda525a1f"))); -} - -- (void)testShouldReturnNilForCachePathWhenTheRequestIsADELETE -{ - RKParams *params = [RKParams params]; - [params setValue:@"foo" forParam:@"bar"]; - NSURL *URL = [NSURL URLWithString:@"http://restkit.org/"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - request.method = RKRequestMethodDELETE; - NSString *baseURL = [RKTestFactory baseURLString]; - NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString *cachePath = [RKCachesDirectory() - stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache *requestCache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; - NSString *requestCachePath = [requestCache pathForRequest:request]; - assertThat(requestCachePath, is(nilValue())); -} - -- (void)testShouldBuildAProperAuthorizationHeaderForOAuth1 -{ - RKRequest *request = [RKRequest requestWithURL:[RKURL URLWithString:@"http://restkit.org/this?that=foo&bar=word"]]; - request.authenticationType = RKRequestAuthenticationTypeOAuth1; - request.OAuth1AccessToken = @"12345"; - request.OAuth1AccessTokenSecret = @"monkey"; - request.OAuth1ConsumerKey = @"another key"; - request.OAuth1ConsumerSecret = @"more data"; - [request prepareURLRequest]; - NSString *authorization = [request.URLRequest valueForHTTPHeaderField:@"Authorization"]; - assertThat(authorization, isNot(nilValue())); -} - -- (void)testShouldBuildAProperAuthorizationHeaderForOAuth1ThatIsAcceptedByServer -{ - RKRequest *request = [RKRequest requestWithURL:[RKURL URLWithString:[NSString stringWithFormat:@"%@/oauth1/me", [RKTestFactory baseURLString]]]]; - request.authenticationType = RKRequestAuthenticationTypeOAuth1; - request.OAuth1AccessToken = @"12345"; - request.OAuth1AccessTokenSecret = @"monkey"; - request.OAuth1ConsumerKey = @"restkit_key"; - request.OAuth1ConsumerSecret = @"restkit_secret"; - [request prepareURLRequest]; - NSString *authorization = [request.URLRequest valueForHTTPHeaderField:@"Authorization"]; - assertThat(authorization, isNot(nilValue())); - - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - request.delegate = responseLoader; - [request sendAsynchronously]; - [responseLoader waitForResponse]; - assertThatBool(responseLoader.successful, is(equalToBool(YES))); -} - -- (void)testImproperOAuth1CredentialsShouldFall -{ - RKRequest *request = [RKRequest requestWithURL:[RKURL URLWithString:[NSString stringWithFormat:@"%@/oauth1/me", [RKTestFactory baseURLString]]]]; - request.authenticationType = RKRequestAuthenticationTypeOAuth1; - request.OAuth1AccessToken = @"12345"; - request.OAuth1AccessTokenSecret = @"monkey"; - request.OAuth1ConsumerKey = @"restkit_key"; - request.OAuth1ConsumerSecret = @"restkit_incorrect_secret"; - [request prepareURLRequest]; - NSString *authorization = [request.URLRequest valueForHTTPHeaderField:@"Authorization"]; - assertThat(authorization, isNot(nilValue())); - - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - request.delegate = responseLoader; - [request sendAsynchronously]; - [responseLoader waitForResponse]; - assertThatBool(responseLoader.successful, is(equalToBool(YES))); -} - -- (void)testOnDidLoadResponseBlockInvocation -{ - RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/200"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest *request = [RKRequest requestWithURL:URL]; - __block RKResponse *blockResponse = nil; - request.onDidLoadResponse = ^ (RKResponse *response) { - blockResponse = response; - }; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThat(blockResponse, is(notNilValue())); -} - -- (void)testOnDidFailLoadWithErrorBlockInvocation -{ - RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/503"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - __block NSError *blockError = nil; - request.onDidFailLoadWithError = ^ (NSError *error) { - blockError = error; - }; - NSError *expectedError = [NSError errorWithDomain:@"Test" code:1234 userInfo:nil]; - [request didFailLoadWithError:expectedError]; - assertThat(blockError, is(notNilValue())); -} - -- (void)testShouldBuildAProperRequestWhenSettingBodyByMIMEType -{ - RKClient *client = [RKTestFactory client]; - NSDictionary *bodyParams = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:10], @"number", - @"JSON String", @"string", - nil]; - RKRequest *request = [client requestWithResourcePath:@"/upload"]; - [request setMethod:RKRequestMethodPOST]; - [request setBody:bodyParams forMIMEType:RKMIMETypeJSON]; - [request prepareURLRequest]; - assertThat(request.HTTPBodyString, is(equalTo(@"{\"number\":10,\"string\":\"JSON String\"}"))); -} - -- (void)testThatGETRequestsAreConsideredCacheable -{ - RKRequest *request = [RKRequest new]; - request.method = RKRequestMethodGET; - assertThatBool([request isCacheable], is(equalToBool(YES))); -} - -- (void)testThatPOSTRequestsAreNotConsideredCacheable -{ - RKRequest *request = [RKRequest new]; - request.method = RKRequestMethodPOST; - assertThatBool([request isCacheable], is(equalToBool(NO))); -} - -- (void)testThatPUTRequestsAreNotConsideredCacheable -{ - RKRequest *request = [RKRequest new]; - request.method = RKRequestMethodPUT; - assertThatBool([request isCacheable], is(equalToBool(NO))); -} - -- (void)testThatDELETERequestsAreNotConsideredCacheable -{ - RKRequest *request = [RKRequest new]; - request.method = RKRequestMethodDELETE; - assertThatBool([request isCacheable], is(equalToBool(NO))); -} - -- (void)testInvocationOfDidReceiveResponse -{ - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - id loaderMock = [OCMockObject partialMockForObject:loader]; - NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/200"]; - RKRequest *request = [[RKRequest alloc] initWithURL:URL]; - request.delegate = loaderMock; - [[loaderMock expect] request:request didReceiveResponse:OCMOCK_ANY]; - [request sendAsynchronously]; - [loaderMock waitForResponse]; - [request release]; - [loaderMock verify]; -} - -- (void)testThatIsLoadingIsNoDuringDidFailWithErrorCallback -{ - NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:8765"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - - RKClient *client = [RKClient clientWithBaseURL:URL]; - RKRequest *request = [client requestWithResourcePath:@"/invalid"]; - request.method = RKRequestMethodGET; - request.delegate = loader; - request.onDidFailLoadWithError = ^(NSError *error) { - assertThatBool([request isLoading], is(equalToBool(NO))); - }; - [request sendAsynchronously]; - [loader waitForResponse]; -} - -- (void)testThatIsLoadedIsYesDuringDidFailWithErrorCallback -{ - NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:8765"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - - RKClient *client = [RKClient clientWithBaseURL:URL]; - RKRequest *request = [client requestWithResourcePath:@"/invalid"]; - request.method = RKRequestMethodGET; - request.delegate = loader; - request.onDidFailLoadWithError = ^(NSError *error) { - assertThatBool([request isLoaded], is(equalToBool(YES))); - }; - [request sendAsynchronously]; - [loader waitForResponse]; -} - -- (void)testUnavailabilityOfResponseInDidFailWithErrorCallback -{ - NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:8765"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - - RKClient *client = [RKClient clientWithBaseURL:URL]; - RKRequest *request = [client requestWithResourcePath:@"/invalid"]; - request.method = RKRequestMethodGET; - request.delegate = loader; - [request sendAsynchronously]; - [loader waitForResponse]; - assertThat(request.response, is(nilValue())); -} - -- (void)testAvailabilityOfResponseWhenFailedDueTo500Response -{ - RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/fail"]; - RKRequest *request = [RKRequest requestWithURL:URL]; - RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; - request.delegate = responseLoader; - [request sendAsynchronously]; - [responseLoader waitForResponse]; - assertThat(request.response, is(notNilValue())); - assertThatInteger(request.response.statusCode, is(equalToInteger(500))); -} - -@end diff --git a/Tests/Logic/Network/RKResponseTest.m b/Tests/Logic/Network/RKResponseTest.m deleted file mode 100644 index 7c045be7..00000000 --- a/Tests/Logic/Network/RKResponseTest.m +++ /dev/null @@ -1,338 +0,0 @@ -// -// RKResponseTest.m -// RestKit -// -// Created by Blake Watters on 1/15/10. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKResponse.h" - -@interface RKResponseTest : RKTestCase { - RKResponse *_response; -} - -@end - -@implementation RKResponseTest - -- (void)setUp -{ - _response = [[RKResponse alloc] init]; -} - -- (void)testShouldConsiderResponsesLessThanOneHudredOrGreaterThanSixHundredInvalid -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 99; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInvalid], is(equalToBool(YES))); - statusCode = 601; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInvalid], is(equalToBool(YES))); -} - -- (void)testShouldConsiderResponsesInTheOneHudredsInformational -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 100; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInformational], is(equalToBool(YES))); - statusCode = 199; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInformational], is(equalToBool(YES))); -} - -- (void)testShouldConsiderResponsesInTheTwoHundredsSuccessful -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger twoHundred = 200; - [[[mock stub] andReturnValue:OCMOCK_VALUE(twoHundred)] statusCode]; - assertThatBool([mock isSuccessful], is(equalToBool(YES))); - twoHundred = 299; - [[[mock stub] andReturnValue:OCMOCK_VALUE(twoHundred)] statusCode]; - assertThatBool([mock isSuccessful], is(equalToBool(YES))); -} - -- (void)testShouldConsiderResponsesInTheThreeHundredsRedirects -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 300; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirection], is(equalToBool(YES))); - statusCode = 399; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirection], is(equalToBool(YES))); -} - -- (void)testShouldConsiderResponsesInTheFourHundredsClientErrors -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 400; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isClientError], is(equalToBool(YES))); - statusCode = 499; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isClientError], is(equalToBool(YES))); -} - -- (void)testShouldConsiderResponsesInTheFiveHundredsServerErrors -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 500; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isServerError], is(equalToBool(YES))); - statusCode = 599; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isServerError], is(equalToBool(YES))); -} - -- (void)testShouldConsiderATwoHundredResponseOK -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 200; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isOK], is(equalToBool(YES))); -} - -- (void)testShouldConsiderATwoHundredAndOneResponseCreated -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 201; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isCreated], is(equalToBool(YES))); -} - -- (void)testShouldConsiderAFourOhThreeResponseForbidden -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 403; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isForbidden], is(equalToBool(YES))); -} - -- (void)testShouldConsiderAFourOhFourResponseNotFound -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 404; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isNotFound], is(equalToBool(YES))); -} - -- (void)testShouldConsiderAFourOhNineResponseConflict -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 409; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isConflict], is(equalToBool(YES))); -} - -- (void)testShouldConsiderAFourHundredAndTenResponseConflict -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 410; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isGone], is(equalToBool(YES))); -} - -- (void)testShouldConsiderVariousThreeHundredResponsesRedirect -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 301; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); - statusCode = 302; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); - statusCode = 303; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); - statusCode = 307; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); -} - -- (void)testShouldConsiderVariousResponsesEmpty -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 201; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isEmpty], is(equalToBool(YES))); - statusCode = 204; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isEmpty], is(equalToBool(YES))); - statusCode = 304; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isEmpty], is(equalToBool(YES))); -} - -- (void)testShouldMakeTheContentTypeHeaderAccessible -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary *headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThat([mock contentType], is(equalTo(@"application/xml"))); -} - -// Should this return a string??? -- (void)testShouldMakeTheContentLengthHeaderAccessible -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary *headers = [NSDictionary dictionaryWithObject:@"12345" forKey:@"Content-Length"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThat([mock contentLength], is(equalTo(@"12345"))); -} - -- (void)testShouldMakeTheLocationHeaderAccessible -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary *headers = [NSDictionary dictionaryWithObject:@"/foo/bar" forKey:@"Location"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThat([mock location], is(equalTo(@"/foo/bar"))); -} - -- (void)testShouldKnowIfItIsAnXMLResponse -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary *headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThatBool([mock isXML], is(equalToBool(YES))); -} - -- (void)testShouldKnowIfItIsAnJSONResponse -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary *headers = [NSDictionary dictionaryWithObject:@"application/json" forKey:@"Content-Type"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThatBool([mock isJSON], is(equalToBool(YES))); -} - -- (void)testShouldReturnParseErrorsWhenParsedBodyFails -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - [[[mock stub] andReturn:@"sad;sdvjnk;"] bodyAsString]; - [[[mock stub] andReturn:@"application/json"] MIMEType]; - NSError *error = nil; - id object = [mock parsedBody:&error]; - assertThat(object, is(nilValue())); - assertThat(error, isNot(nilValue())); - assertThat([error localizedDescription], is(equalTo(@"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."))); -} - -- (void)testShouldNotCrashOnFailureToParseBody -{ - RKResponse *response = [[RKResponse new] autorelease]; - id mockResponse = [OCMockObject partialMockForObject:response]; - [[[mockResponse stub] andReturn:@"test/fake"] MIMEType]; - [[[mockResponse stub] andReturn:@"whatever"] bodyAsString]; - NSError *error = nil; - id parsedResponse = [mockResponse parsedBody:&error]; - assertThat(parsedResponse, is(nilValue())); -} - -- (void)testShouldNotCrashWhenParserReturnsNilWithoutAnError -{ - RKResponse *response = [[[RKResponse alloc] init] autorelease]; - id mockResponse = [OCMockObject partialMockForObject:response]; - [[[mockResponse stub] andReturn:@""] bodyAsString]; - [[[mockResponse stub] andReturn:RKMIMETypeJSON] MIMEType]; - id mockParser = [OCMockObject mockForProtocol:@protocol(RKParser)]; - id mockRegistry = [OCMockObject partialMockForObject:[RKParserRegistry sharedRegistry]]; - [[[mockRegistry expect] andReturn:mockParser] parserForMIMEType:RKMIMETypeJSON]; - NSError *error = nil; - [[[mockParser expect] andReturn:nil] objectFromString:@"" error:[OCMArg setTo:error]]; - id object = [mockResponse parsedBody:&error]; - [mockRegistry verify]; - [mockParser verify]; - [RKParserRegistry setSharedRegistry:nil]; - assertThat(object, is(nilValue())); - assertThat(error, is(nilValue())); -} - -- (void)testLoadingNonUTF8Charset -{ - RKClient *client = [RKTestFactory client]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - [client get:@"/encoding" delegate:loader]; - [loader waitForResponse]; - assertThat([loader.response bodyEncodingName], is(equalTo(@"us-ascii"))); - assertThatInteger([loader.response bodyEncoding], is(equalToInteger(NSASCIIStringEncoding))); -} - -- (void)testFollowRedirect -{ - RKClient *client = [RKTestFactory client]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - [client get:@"/redirection" delegate:loader]; - [loader waitForResponse]; - assertThatInteger(loader.response.statusCode, is(equalToInteger(200))); - - id body = [loader.response parsedBody:NULL]; - assertThat([body objectForKey:@"redirected"], is(equalTo([NSNumber numberWithBool:YES]))); -} - -- (void)testNoFollowRedirect -{ - RKClient *client = [RKTestFactory client]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - - RKRequest *request = [client requestWithResourcePath:@"/redirection"]; - request.method = RKRequestMethodGET; - request.followRedirect = NO; - request.delegate = loader; - - [request send]; - [loader waitForResponse]; - - assertThatInteger(loader.response.statusCode, is(equalToInteger(302))); - assertThat([loader.response.allHeaderFields objectForKey:@"Location"], is(equalTo(@"/redirection/target"))); -} - -- (void)testThatLoadingInvalidURLDoesNotCrashApp -{ - NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:5629"]; - RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKClient *client = [RKClient clientWithBaseURL:URL]; - - RKRequest *request = [client requestWithResourcePath:@"/invalid"]; - request.method = RKRequestMethodGET; - request.delegate = loader; - - [request sendAsynchronously]; - [loader waitForResponse]; -} - -@end diff --git a/Tests/Logic/Network/RKURLTest.m b/Tests/Logic/Network/RKURLTest.m deleted file mode 100644 index 2bb0e1c2..00000000 --- a/Tests/Logic/Network/RKURLTest.m +++ /dev/null @@ -1,258 +0,0 @@ -// -// RKURLTest.m -// RestKit -// -// Created by Blake Watters on 6/29/11. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKURL.h" -#import "NSURL+RKAdditions.h" - -@interface RKURLTest : RKTestCase -@end - -@implementation RKURLTest - -- (void)testShouldNotExplodeBecauseOfUnicodeCharacters -{ - NSException *failed = nil; - @try { - [RKURL URLWithBaseURLString:@"http://test.com" resourcePath:@"/places.json?category=Automóviles"]; - } - @catch (NSException *exception) { - failed = exception; - } - @finally { - NSAssert((failed == nil), @"No exception should be generated by creating URL with Unicode chars"); - } -} - -- (void)testShouldEscapeQueryParameters -{ - NSDictionary *queryParams = [NSDictionary dictionaryWithObjectsAndKeys:@"What is your #1 e-mail?", @"question", @"john+restkit@gmail.com", @"answer", nil]; - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:queryParams]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test?answer=john%2Brestkit%40gmail.com&question=What%20is%20your%20%231%20e-mail%3F"))); -} - -- (void)testShouldHandleNilQueryParameters -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:nil]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test"))); -} - -- (void)testShouldHandleEmptyQueryParameters -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:[NSDictionary dictionary]]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test"))); -} - -- (void)testShouldHandleResourcePathWithoutLeadingSlash -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"test" queryParameters:nil]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test"))); -} - -- (void)testShouldHandleEmptyResourcePath -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"" queryParameters:nil]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org"))); -} - -- (void)testShouldHandleBaseURLsWithAPath -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org/this" resourcePath:@"/test" queryParameters:nil]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/this/test"))); -} - -- (void)testShouldSimplifyURLsWithSeveralSlashes -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org//this//" resourcePath:@"/test" queryParameters:nil]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/this/test"))); -} - -- (void)testShouldPreserveTrailingSlash -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test/" queryParameters:nil]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test/"))); -} - -- (void)testShouldReturnTheMIMETypeForURL -{ - NSURL *URL = [NSURL URLWithString:@"http://restkit.org/path/to/resource.xml"]; - assertThat([URL MIMETypeForPathExtension], is(equalTo(@"application/xml"))); -} - -- (void)testInitializationFromStringIsEqualToAbsoluteString -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org"))); -} - -- (void)testInitializationFromStringHasSelfAsBaseURL -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; - assertThat([[URL baseURL] absoluteString], is(equalTo(@"http://restkit.org"))); -} - -- (void)testInitializationFromStringHasNilResourcePath -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; - assertThat([URL resourcePath], is(nilValue())); -} - -- (void)testInitializationFromStringHasNilQueryParameters -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; - assertThat([URL query], is(nilValue())); - assertThat([URL queryParameters], is(nilValue())); -} - -- (void)testInitializationFromStringIncludingQueryParameters -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org/foo?bar=1&this=that"]; - assertThat([URL queryParameters], hasEntries(@"bar", equalTo(@"1"), @"this", equalTo(@"that"), nil)); -} - -- (void)testInitializationFromURLandResourcePathIncludingQueryParameters -{ - NSString *resourcePath = @"/bar?another=option"; - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org/foo?bar=1&this=that" resourcePath:resourcePath]; -#if TARGET_OS_IPHONE - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/foo/bar?bar=1&this=that&another=option"))); -#else - assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/foo/bar?bar=1&another=option&this=that"))); -#endif - assertThat([URL queryParameters], hasEntries(@"bar", equalTo(@"1"), - @"this", equalTo(@"that"), - @"another", equalTo(@"option"), nil)); -} - -- (void)testInitializationFromNSURL -{ - NSURL *URL = [NSURL URLWithString:@"http://restkit.org"]; - RKURL *rkURL = [RKURL URLWithBaseURL:URL]; - assertThat(URL, is(equalTo(rkURL))); -} - -- (void)testInitializationFromRKURL -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; - RKURL *rkURL = [RKURL URLWithBaseURL:URL]; - assertThat(URL, is(equalTo(rkURL))); -} - -- (void)testInitializationFromNSURLandAppendingOfResourcePath -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org/"]; - RKURL *rkURL = [RKURL URLWithBaseURL:URL resourcePath:@"/entries"]; - assertThat([rkURL absoluteString], equalTo(@"http://restkit.org/entries")); -} - -- (void)testMergingOfAdditionalQueryParameters -{ - NSURL *URL = [NSURL URLWithString:@"http://restkit.org/search?title=Hacking"]; - NSDictionary *params = [NSDictionary dictionaryWithObject:@"Computers" forKey:@"genre"]; - RKURL *newURL = [RKURL URLWithBaseURL:URL resourcePath:nil queryParameters:params]; - assertThat([newURL queryParameters], hasEntries(@"title", equalTo(@"Hacking"), @"genre", equalTo(@"Computers"), nil)); -} - -- (void)testReplacementOfExistingResourcePath -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org/" resourcePath:@"/articles"]; - RKURL *newURL = [URL URLByReplacingResourcePath:@"/files"]; - assertThat([newURL absoluteString], equalTo(@"http://restkit.org/files")); - assertThat([newURL resourcePath], equalTo(@"/files")); -} - -- (void)testReplacementOfNilResourcePath -{ - RKURL *URL = [RKURL URLWithString:@"http://restkit.org/whatever"]; - assertThat([URL resourcePath], is(nilValue())); - RKURL *newURL = [URL URLByReplacingResourcePath:@"/works"]; - assertThat([newURL resourcePath], is(equalTo(@"/works"))); - assertThat([newURL absoluteString], is(equalTo(@"http://restkit.org/whatever/works"))); -} - -- (void)testInterpolationOfResourcePath -{ - RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/paginate?page=:page&perPage=:per_page"]; - NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"page", @"25", @"per_page", nil]; - RKURL *interpolatedURL = [URL URLByInterpolatingResourcePathWithObject:dictionary]; - assertThat([interpolatedURL resourcePath], is(equalTo(@"/paginate?page=1&perPage=25"))); - - NSDictionary *queryParams = [NSDictionary dictionaryWithObjectsAndKeys: - @"25", @"perPage", - @"1", @"page", - nil]; - assertThat([interpolatedURL resourcePath], is(equalTo(@"/paginate?page=1&perPage=25"))); - assertThat([interpolatedURL queryParameters], is(equalTo(queryParams))); -} - -- (void)testShouldProperlyHandleLongURLParameterValues -{ - NSString *longResourcePath = @""; - for (NSUInteger index = 0; index < 1050; index++) { - longResourcePath = [longResourcePath stringByAppendingString:@"X"]; - } - assertThatInteger([longResourcePath length], is(equalToInt(1050))); - - RKURL *URL = [RKURL URLWithBaseURLString:[RKTestFactory baseURLString] - resourcePath:longResourcePath]; - assertThat([URL absoluteString], is(equalTo([NSString stringWithFormat:@"%@/%@", [RKTestFactory baseURLString], longResourcePath]))); -} - -- (void)testThatPathIsPreservedWhenURLIsConstructedFromAnotherRKURL -{ - RKURL *URL = [RKURL URLWithBaseURL:[RKTestFactory baseURL] resourcePath:@"/this/and/that"]; - RKURL *newURL = [URL URLByAppendingResourcePath:@"/the/other/thing" queryParameters:[NSDictionary dictionaryWithObject:@"up" forKey:@"word"]]; - assertThat([newURL absoluteString], is(equalTo(@"http://127.0.0.1:4567/this/and/that/the/other/thing?word=up"))); -} - -- (void)testThatResourcePathIsPreservedWhenURLIsConstructedFromAnotherRKURL -{ - RKURL *URL = [RKURL URLWithBaseURL:[RKTestFactory baseURL] resourcePath:@"/this/and/that"]; - RKURL *newURL = [URL URLByAppendingResourcePath:@"/the/other/thing" queryParameters:[NSDictionary dictionaryWithObject:@"up" forKey:@"word"]]; - assertThat([newURL resourcePath], is(equalTo(@"/the/other/thing"))); -} - -- (void)testThatPathAndQueryParamsArePreservedWhenURLIsConstructedFromAnotherRKURL -{ - RKURL *URL = [RKURL URLWithBaseURL:[RKTestFactory baseURL] resourcePath:@"/this/and/that" queryParameters:[NSDictionary dictionaryWithObject:@"who" forKey:@"where"]]; - RKURL *newURL = [URL URLByAppendingResourcePath:@"/the/other/thing" queryParameters:[NSDictionary dictionaryWithObject:@"up" forKey:@"word"]]; - assertThat([newURL absoluteString], is(equalTo(@"http://127.0.0.1:4567/this/and/that/the/other/thing?where=who&word=up"))); -} - -- (void)testCreationOfMultipleURLsFromASinglePattern -{ - RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/people/:personID"]; - NSDictionary *person1 = [NSDictionary dictionaryWithObject:@"1" forKey:@"personID"]; - NSDictionary *person2 = [NSDictionary dictionaryWithObject:@"2" forKey:@"personID"]; - NSDictionary *person3 = [NSDictionary dictionaryWithObject:@"3" forKey:@"personID"]; - NSArray *personURLs = [patternURL URLsByInterpolatingResourcePathWithObjects:[NSArray arrayWithObjects:person1, person2, person3, nil]]; - assertThat(personURLs, hasCountOf(3)); - assertThat([personURLs valueForKey:@"absoluteString"], hasItems(@"http://restkit.org/people/1", @"http://restkit.org/people/2", @"http://restkit.org/people/3", nil)); -} - -- (void)testCreationOfMultipleURLsFromInvalidPatternReturnsNil -{ - RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://•!.restkit.org" resourcePath:@"/people/:personID"]; - NSDictionary *person1 = [NSDictionary dictionaryWithObject:@"1" forKey:@"personID"]; - NSArray *personURLs = [patternURL URLsByInterpolatingResourcePathWithObjects:[NSArray arrayWithObject:person1]]; - assertThat(personURLs, is(nilValue())); -} - -@end diff --git a/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m b/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m index 6d99c135..a0b08f47 100644 --- a/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m +++ b/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m @@ -22,7 +22,7 @@ #import "RKDynamicMapping.h" #import "RKDynamicMappingModels.h" -@interface RKDynamicMappingTest : RKTestCase +@interface RKDynamicMappingTest : RKTestCase @end @@ -30,13 +30,11 @@ - (void)testShouldPickTheAppropriateMappingBasedOnAnAttributeValue { - RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; - RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; - RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; RKObjectMapping *mapping = [dynamicMapping objectMappingForRepresentation:[RKTestFixture parsedObjectWithContentsOfFixture:@"girl.json"]]; @@ -49,13 +47,11 @@ - (void)testShouldMatchOnAnNSNumberAttributeValue { - RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; - RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; - RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"numeric_type" isEqualTo:[NSNumber numberWithInt:0]]; [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"numeric_type" isEqualTo:[NSNumber numberWithInt:1]]; RKObjectMapping *mapping = [dynamicMapping objectMappingForRepresentation:[RKTestFixture parsedObjectWithContentsOfFixture:@"girl.json"]]; @@ -66,30 +62,18 @@ assertThat(NSStringFromClass(mapping.objectClass), is(equalTo(@"Boy"))); } -- (void)testShouldPickTheAppropriateMappingBasedOnDelegateCallback -{ - RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; - dynamicMapping.delegate = self; - RKObjectMapping *mapping = [dynamicMapping objectMappingForRepresentation:[RKTestFixture parsedObjectWithContentsOfFixture:@"girl.json"]]; - assertThat(mapping, is(notNilValue())); - assertThat(NSStringFromClass(mapping.objectClass), is(equalTo(@"Girl"))); - mapping = [dynamicMapping objectMappingForRepresentation:[RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]]; - assertThat(mapping, is(notNilValue())); - assertThat(NSStringFromClass(mapping.objectClass), is(equalTo(@"Boy"))); -} - - (void)testShouldPickTheAppropriateMappingBasedOnBlockDelegateCallback { - RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id data) { if ([[data valueForKey:@"type"] isEqualToString:@"Girl"]) { - return [RKObjectMapping mappingForClass:[Girl class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Girl class]]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; + return mapping; } else if ([[data valueForKey:@"type"] isEqualToString:@"Boy"]) { - return [RKObjectMapping mappingForClass:[Boy class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Boy class]]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; + return mapping; } return nil; @@ -105,7 +89,7 @@ - (void)testShouldFailAnAssertionWhenInvokedWithSomethingOtherThanADictionary { NSException *exception = nil; - RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; @try { [dynamicMapping objectMappingForRepresentation:(NSDictionary *)[NSArray array]]; } @@ -122,13 +106,13 @@ - (RKObjectMapping *)objectMappingForData:(id)data { if ([[data valueForKey:@"type"] isEqualToString:@"Girl"]) { - return [RKObjectMapping mappingForClass:[Girl class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Girl class]]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; + return mapping; } else if ([[data valueForKey:@"type"] isEqualToString:@"Boy"]) { - return [RKObjectMapping mappingForClass:[Boy class] usingBlock:^(RKObjectMapping *mapping) { - [mapping mapAttributes:@"name", nil]; - }]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Boy class]]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; + return mapping; } return nil; diff --git a/Tests/Logic/ObjectMapping/RKObjectAttributeMappingTest.m b/Tests/Logic/ObjectMapping/RKObjectAttributeMappingTest.m index 8cfef3f4..6f1ac420 100644 --- a/Tests/Logic/ObjectMapping/RKObjectAttributeMappingTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectAttributeMappingTest.m @@ -17,16 +17,16 @@ - (void)testThatAttributeMappingsWithTheSameSourceAndDestinationKeyPathAreConsideredEqual { - RKAttributeMapping *mapping1 = [RKAttributeMapping mappingFromKeyPath:@"this" toKeyPath:@"that"]; - RKAttributeMapping *mapping2 = [RKAttributeMapping mappingFromKeyPath:@"this" toKeyPath:@"that"]; + RKAttributeMapping *mapping1 = [RKAttributeMapping attributeMappingFromKeyPath:@"this" toKeyPath:@"that"]; + RKAttributeMapping *mapping2 = [RKAttributeMapping attributeMappingFromKeyPath:@"this" toKeyPath:@"that"]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(YES))); } - (void)testThatAttributeMappingsWithDifferingKeyPathsAreNotConsideredEqual { - RKAttributeMapping *mapping1 = [RKAttributeMapping mappingFromKeyPath:@"this" toKeyPath:@"that"]; - RKAttributeMapping *mapping2 = [RKAttributeMapping mappingFromKeyPath:@"this" toKeyPath:@"the other"]; + RKAttributeMapping *mapping1 = [RKAttributeMapping attributeMappingFromKeyPath:@"this" toKeyPath:@"that"]; + RKAttributeMapping *mapping2 = [RKAttributeMapping attributeMappingFromKeyPath:@"this" toKeyPath:@"the other"]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(NO))); } diff --git a/Tests/Logic/ObjectMapping/RKObjectLoaderTest.m b/Tests/Logic/ObjectMapping/RKObjectLoaderTest.m index 1e53f083..515aee3f 100644 --- a/Tests/Logic/ObjectMapping/RKObjectLoaderTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectLoaderTest.m @@ -105,18 +105,18 @@ - (RKObjectMappingProvider *)providerForComplexUser { - RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; + NSMutableDictionary *mappingDictionary = [NSMutableDictionary dictionary]; RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [userMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"firstname" toKeyPath:@"firstname"]]; - [provider setMapping:userMapping forKeyPath:@"data.STUser"]; + [userMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"firstname" toKeyPath:@"firstname"]]; + [mappingsDictionary setObject:userMapping forKey:@"data.STUser"]; return provider; } - (RKObjectMappingProvider *)errorMappingProvider { - RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; + NSMutableDictionary *mappingDictionary = [NSMutableDictionary dictionary]; RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]]; - [errorMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"" toKeyPath:@"errorMessage"]]; + [errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"" toKeyPath:@"errorMessage"]]; errorMapping.rootKeyPath = @"errors"; provider.errorMapping = errorMapping; return provider; @@ -265,9 +265,9 @@ { RKObjectManager *objectManager = [RKTestFactory objectManager]; RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[RKObjectLoaderTestResultModel class]]; - [objectMapping mapKeyPath:@"id" toAttribute:@"ID"]; - [objectMapping mapKeyPath:@"ends_at" toAttribute:@"endsAt"]; - [objectMapping mapKeyPath:@"photo_url" toAttribute:@"photoURL"]; + [objectMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"ID"]]; + [objectMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"ends_at" toKeyPath:@"endsAt"]]; + [objectMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"photo_url" toKeyPath:@"photoURL"]]; [objectManager.mappingProvider setMapping:objectMapping forKeyPath:@"results"]; RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; [objectManager loadObjectsAtResourcePath:@"/JSON/ArrayOfResults.json" delegate:loader]; @@ -291,7 +291,7 @@ - (void)testShouldAllowYouToPostAnObjectAndHandleAnEmpty204Response { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [mapping mapAttributes:@"firstname", @"lastname", @"email", nil]; + [mapping addAttributeMappingsFromArray:@[@"firstname", @"lastname", @"email"]]; RKObjectMapping *serializationMapping = [mapping inverseMapping]; RKObjectManager *objectManager = [RKTestFactory objectManager]; @@ -316,7 +316,7 @@ - (void)testShouldAllowYouToPOSTAnObjectAndMapBackNonNestedContent { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [mapping mapAttributes:@"firstname", @"lastname", @"email", nil]; + [mapping addAttributeMappingsFromArray:@[@"firstname", @"lastname", @"email"]]; RKObjectMapping *serializationMapping = [mapping inverseMapping]; RKObjectManager *objectManager = [RKTestFactory objectManager]; @@ -344,7 +344,7 @@ return; RKLogConfigureByName("RestKit/Network", RKLogLevelTrace); RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [mapping mapAttributes:@"firstname", @"lastname", @"email", nil]; + [mapping addAttributeMappingsFromArray:@[@"firstname", @"lastname", @"email"]]; RKObjectMapping *serializationMapping = [mapping inverseMapping]; RKObjectManager *objectManager = [RKTestFactory objectManager]; @@ -370,11 +370,11 @@ - (void)testShouldAllowYouToPOSTAnObjectOfOneTypeAndGetBackAnother { RKObjectMapping *sourceMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [sourceMapping mapAttributes:@"firstname", @"lastname", @"email", nil]; + [sourceMapping addAttributeMappingsFromArray:@[@"firstname", @"lastname", @"email"]]; RKObjectMapping *serializationMapping = [sourceMapping inverseMapping]; RKObjectMapping *targetMapping = [RKObjectMapping mappingForClass:[RKObjectLoaderTestResultModel class]]; - [targetMapping mapAttributes:@"ID", nil]; + [targetMapping addAttributeMappingsFromArray:@[@"ID"]]; RKObjectManager *objectManager = [RKTestFactory objectManager]; [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKTestComplexUser class] pathPattern:@"/notNestedUser" method:RKRequestMethodAny]]; @@ -407,11 +407,11 @@ - (void)testShouldAllowYouToPOSTAnObjectOfOneTypeAndGetBackAnotherViaURLConfiguration { RKObjectMapping *sourceMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [sourceMapping mapAttributes:@"firstname", @"lastname", @"email", nil]; + [sourceMapping addAttributeMappingsFromArray:@[@"firstname", @"lastname", @"email"]]; RKObjectMapping *serializationMapping = [sourceMapping inverseMapping]; RKObjectMapping *targetMapping = [RKObjectMapping mappingForClass:[RKObjectLoaderTestResultModel class]]; - [targetMapping mapAttributes:@"ID", nil]; + [targetMapping addAttributeMappingsFromArray:@[@"ID"]]; RKObjectManager *objectManager = [RKTestFactory objectManager]; [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKTestComplexUser class] pathPattern:@"/notNestedUser" method:RKRequestMethodAny]]; @@ -445,7 +445,7 @@ - (void)testShouldAllowYouToPOSTAnObjectAndMapBackNonNestedContentViapostObject { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [mapping mapAttributes:@"firstname", @"lastname", @"email", nil]; + [mapping addAttributeMappingsFromArray:@[@"firstname", @"lastname", @"email"]]; RKObjectMapping *serializationMapping = [mapping inverseMapping]; RKObjectManager *objectManager = [RKTestFactory objectManager]; @@ -472,7 +472,7 @@ { RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; userMapping.rootKeyPath = @"data.STUser"; - [userMapping mapAttributes:@"firstname", nil]; + [userMapping addAttributeMappingsFromArray:@[@"firstname"]]; RKTestComplexUser *user = [[RKTestComplexUser new] autorelease]; RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[RKTestFactory baseURL]]; @@ -494,7 +494,7 @@ { RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; userMapping.rootKeyPath = @"data.STUser"; - [userMapping mapAttributes:@"firstname", nil]; + [userMapping addAttributeMappingsFromArray:@[@"firstname"]]; RKTestComplexUser *user = [[RKTestComplexUser new] autorelease]; RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[RKTestFactory baseURL]]; @@ -520,7 +520,7 @@ { RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; userMapping.rootKeyPath = @"data.STUser"; - [userMapping mapAttributes:@"firstname", nil]; + [userMapping addAttributeMappingsFromArray:@[@"firstname"]]; RKTestComplexUser *user = [[RKTestComplexUser new] autorelease]; RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[RKTestFactory baseURL]]; @@ -553,7 +553,7 @@ RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; userMapping.rootKeyPath = @"data.STUser"; - [userMapping mapAttributes:@"firstname", nil]; + [userMapping addAttributeMappingsFromArray:@[@"firstname"]]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; RKObjectLoader *objectLoader = [objectManager loaderWithResourcePath:@"/humans/1234"]; objectLoader.delegate = responseLoader; @@ -576,7 +576,7 @@ RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; userMapping.rootKeyPath = @"data.STUser"; - [userMapping mapAttributes:@"firstname", nil]; + [userMapping addAttributeMappingsFromArray:@[@"firstname"]]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; RKObjectLoader *objectLoader = [RKObjectLoader loaderWithURL:[objectManager.baseURL URLByAppendingResourcePath:@"/humans/1234"] mappingProvider:objectManager.mappingProvider]; @@ -594,7 +594,7 @@ RKObjectManager *objectManager = [RKTestFactory objectManager]; RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; - [userMapping mapAttributes:@"firstname", nil]; + [userMapping addAttributeMappingsFromArray:@[@"firstname"]]; [objectManager.mappingProvider setMapping:userMapping forKeyPath:@"firstUser"]; [objectManager.mappingProvider setMapping:userMapping forKeyPath:@"secondUser"]; @@ -647,7 +647,7 @@ objectManager.client.requestQueue.concurrentRequestsLimit = 1; RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; userMapping.rootKeyPath = @"human"; - [userMapping mapAttributes:@"name", @"id", nil]; + [userMapping addAttributeMappingsFromArray:@[@"name", @"id"]]; // Suspend the Queue to block object mapping [objectManager.mappingQueue setSuspended:YES]; @@ -796,7 +796,7 @@ RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestComplexUser class]]; userMapping.rootKeyPath = @"data.STUser"; - [userMapping mapAttributes:@"firstname", nil]; + [userMapping addAttributeMappingsFromArray:@[@"firstname"]]; RKObjectLoader *objectLoader = [objectManager loaderWithResourcePath:@"/humans/1"]; objectLoader.objectMapping = userMapping; [objectLoader sendSynchronously]; diff --git a/Tests/Logic/ObjectMapping/RKObjectManagerTest.m b/Tests/Logic/ObjectMapping/RKObjectManagerTest.m index b7fd9a0d..caca191a 100644 --- a/Tests/Logic/ObjectMapping/RKObjectManagerTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectManagerTest.m @@ -45,36 +45,36 @@ NSError *error; [_objectManager.managedObjectStore resetPersistentStores:&error]; - RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; + NSMutableDictionary *mappingDictionary = [NSMutableDictionary dictionary]; RKEntityMapping *humanMapping = [RKEntityMapping mappingForEntityForName:@"RKHuman" inManagedObjectStore:_objectManager.managedObjectStore]; humanMapping.rootKeyPath = @"human"; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]]; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"nick-name" toKeyPath:@"nickName"]]; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"birthday" toKeyPath:@"birthday"]]; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"sex" toKeyPath:@"sex"]]; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"age" toKeyPath:@"age"]]; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"created-at" toKeyPath:@"createdAt"]]; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"updated-at" toKeyPath:@"updatedAt"]]; - [humanMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"nick-name" toKeyPath:@"nickName"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"birthday" toKeyPath:@"birthday"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"sex" toKeyPath:@"sex"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"age" toKeyPath:@"age"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"created-at" toKeyPath:@"createdAt"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"updated-at" toKeyPath:@"updatedAt"]]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; RKEntityMapping *catMapping = [RKEntityMapping mappingForEntityForName:@"RKCat" inManagedObjectStore:_objectManager.managedObjectStore]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"nick-name" toKeyPath:@"nickName"]]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"birthday" toKeyPath:@"birthday"]]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"sex" toKeyPath:@"sex"]]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"age" toKeyPath:@"age"]]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"created-at" toKeyPath:@"createdAt"]]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"updated-at" toKeyPath:@"updatedAt"]]; - [catMapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"nick-name" toKeyPath:@"nickName"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"birthday" toKeyPath:@"birthday"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"sex" toKeyPath:@"sex"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"age" toKeyPath:@"age"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"created-at" toKeyPath:@"createdAt"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"updated-at" toKeyPath:@"updatedAt"]]; + [catMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; - [catMapping addRelationshipMapping:[RKRelationshipMapping mappingFromKeyPath:@"cats" toKeyPath:@"cats" withMapping:catMapping]]; + [catMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"cats" toKeyPath:@"cats" withMapping:catMapping]]; - [provider setMapping:humanMapping forKeyPath:@"human"]; - [provider setMapping:humanMapping forKeyPath:@"humans"]; + [mappingsDictionary setObject:humanMapping forKey:@"human"]; + [mappingsDictionary setObject:humanMapping forKey:@"humans"]; RKObjectMapping *humanSerialization = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [humanSerialization addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]]; + [humanSerialization addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]]; [provider setSerializationMapping:humanSerialization forClass:[RKHuman class]]; _objectManager.mappingProvider = provider; [_objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKHuman class] pathPattern:@"/humans" method:RKRequestMethodPOST]]; @@ -111,7 +111,7 @@ RKHuman *temporaryHuman = [NSEntityDescription insertNewObjectForEntityForName:@"RKHuman" inManagedObjectContext:_objectManager.managedObjectStore.primaryManagedObjectContext]; temporaryHuman.name = @"My Name"; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [mapping mapAttributes:@"name", nil]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; NSString *resourcePath = @"/humans/fail"; @@ -131,7 +131,7 @@ RKHuman *temporaryHuman = [[RKHuman alloc] initWithEntity:[NSEntityDescription entityForName:@"RKHuman" inManagedObjectContext:_objectManager.managedObjectStore.primaryManagedObjectContext] insertIntoManagedObjectContext:_objectManager.managedObjectStore.primaryManagedObjectContext]; temporaryHuman.name = @"My Name"; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [mapping mapAttributes:@"name", nil]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; // Save it to suppress deletion [_objectManager.managedObjectStore.primaryManagedObjectContext save:nil]; @@ -190,7 +190,7 @@ RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; mapping.rootKeyPath = @"human"; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; [manager.mappingProvider setMapping:mapping forKeyPath:@"human"]; [manager.mappingProvider setSerializationMapping:mapping forClass:[RKObjectMapperTestModel class]]; @@ -213,7 +213,7 @@ [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKObjectMapperTestModel class] pathPattern:@"/humans/1" method:RKRequestMethodAny]]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; [objectManager.mappingProvider registerMapping:mapping withRootKeyPath:@"human"]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; @@ -236,7 +236,7 @@ [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKObjectMapperTestModel class] pathPattern:@"/humans/1" method:RKRequestMethodAny]]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; [objectManager.mappingProvider registerMapping:mapping withRootKeyPath:@"human"]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; @@ -259,7 +259,7 @@ { RKObjectManager *objectManager = [RKTestFactory objectManager]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; [objectManager.mappingProvider registerMapping:mapping withRootKeyPath:@"human"]; RKTestResponseLoader *responseLoader = [[RKTestResponseLoader responseLoader] retain]; @@ -277,7 +277,7 @@ RKObjectManager *objectManager = [RKTestFactory objectManager]; [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKObjectMapperTestModel class] pathPattern:@"/humans/2" method:RKRequestMethodAny]]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; [objectManager.mappingProvider registerMapping:mapping withRootKeyPath:@"human"]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; @@ -297,7 +297,7 @@ { RKObjectManager *objectManager = [RKTestFactory objectManager]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; [objectManager.mappingProvider registerMapping:mapping withRootKeyPath:@"human"]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; @@ -318,7 +318,7 @@ RKObjectManager *objectManager = [RKTestFactory objectManager]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; mapping.rootKeyPath = @"human"; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; RKObjectMapperTestModel *human = [[RKObjectMapperTestModel new] autorelease]; @@ -339,7 +339,7 @@ RKObjectManager *objectManager = [RKTestFactory objectManager]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; mapping.rootKeyPath = @"human"; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; RKObjectMapperTestModel *human = [[RKObjectMapperTestModel new] autorelease]; diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingNextGenTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingNextGenTest.m index df36496f..b087ca67 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingNextGenTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingNextGenTest.m @@ -27,18 +27,24 @@ #import "RKRelationshipMapping.h" #import "RKLog.h" #import "RKMapperOperation.h" -#import "RKObjectMapper_Private.h" +#import "RKMapperOperation_Private.h" #import "RKMappingErrors.h" #import "RKDynamicMappingModels.h" #import "RKTestAddress.h" #import "RKTestUser.h" #import "RKObjectMappingOperationDataSource.h" #import "RKManagedObjectMappingOperationDataSource.h" +#import "RKDynamicMapping.h" +#import "RKMIMETypeSerialization.h" // Managed Object Serialization Testific #import "RKHuman.h" #import "RKCat.h" +@interface RKObjectMapping () ++ (void)resetDefaultDateFormatters; +@end + @interface RKExampleGroupWithUserArray : NSObject { NSString *_name; NSArray *_users; @@ -121,15 +127,15 @@ - (void)testShouldDefineElementToPropertyMapping { - RKAttributeMapping *elementMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; + RKAttributeMapping *elementMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; assertThat(elementMapping.sourceKeyPath, is(equalTo(@"id"))); assertThat(elementMapping.destinationKeyPath, is(equalTo(@"userID"))); } - (void)testShouldDescribeElementMappings { - RKAttributeMapping *elementMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - assertThat([elementMapping description], is(equalTo(@"RKObjectKeyPathMapping: id => userID"))); + RKAttributeMapping *elementMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + assertThatBool([[elementMapping description] hasSuffix:@"id => userID>"], is(equalToBool(YES))); } #pragma mark - RKObjectMapping Tests @@ -137,16 +143,16 @@ - (void)testShouldDefineMappingFromAnElementToAProperty { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - [mapping addAttributeMapping:idMapping]; - assertThat([mapping mappingForKeyPath:@"id"], is(sameInstance(idMapping))); + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + assertThat(mapping.propertyMappingsBySourceKeyPath[@"id"], is(sameInstance(idMapping))); } - (void)testShouldAddMappingsToAttributeMappings { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - [mapping addAttributeMapping:idMapping]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; assertThatBool([mapping.propertyMappings containsObject:idMapping], is(equalToBool(YES))); assertThatBool([mapping.attributeMappings containsObject:idMapping], is(equalToBool(YES))); } @@ -154,8 +160,8 @@ - (void)testShouldAddMappingsToRelationshipMappings { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKRelationshipMapping *idMapping = [RKRelationshipMapping mappingFromKeyPath:@"id" toKeyPath:@"userID" withMapping:nil]; - [mapping addRelationshipMapping:idMapping]; + RKRelationshipMapping *idMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"id" toKeyPath:@"userID" withMapping:nil]; + [mapping addPropertyMapping:idMapping]; assertThatBool([mapping.propertyMappings containsObject:idMapping], is(equalToBool(YES))); assertThatBool([mapping.relationshipMappings containsObject:idMapping], is(equalToBool(YES))); } @@ -163,87 +169,60 @@ - (void)testShouldGenerateAttributeMappings { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - assertThat([mapping mappingForKeyPath:@"name"], is(nilValue())); - [mapping mapKeyPath:@"name" toAttribute:@"name"]; - assertThat([mapping mappingForKeyPath:@"name"], isNot(nilValue())); + assertThat(mapping.propertyMappingsBySourceKeyPath[@"name"], is(nilValue())); + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]]; + assertThat(mapping.propertyMappingsBySourceKeyPath[@"name"], isNot(nilValue())); } - (void)testShouldGenerateRelationshipMappings { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; RKObjectMapping *anotherMapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - assertThat([mapping mappingForKeyPath:@"another"], is(nilValue())); - [mapping mapRelationship:@"another" withMapping:anotherMapping]; - assertThat([mapping mappingForKeyPath:@"another"], isNot(nilValue())); + assertThat(mapping.propertyMappingsBySourceKeyPath[@"another"], is(nilValue())); + [mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"another" toKeyPath:@"another" withMapping:anotherMapping]]; + assertThat(mapping.propertyMappingsBySourceKeyPath[@"another"], isNot(nilValue())); } -- (void)testShouldRemoveMappings -{ - RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - [mapping addAttributeMapping:idMapping]; - assertThat(mapping.propertyMappings, hasItem(idMapping)); - [mapping removeMapping:idMapping]; - assertThat(mapping.propertyMappings, isNot(hasItem(idMapping))); -} - -- (void)testShouldRemoveMappingsByKeyPath -{ - RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - [mapping addAttributeMapping:idMapping]; - assertThat(mapping.propertyMappings, hasItem(idMapping)); - [mapping removeMappingForKeyPath:@"id"]; - assertThat(mapping.propertyMappings, isNot(hasItem(idMapping))); -} - -- (void)testShouldRemoveAllMappings -{ - RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - [mapping mapAttributes:@"one", @"two", @"three", nil]; - assertThat(mapping.propertyMappings, hasCountOf(3)); - [mapping removeAllMappings]; - assertThat(mapping.propertyMappings, is(empty())); -} - -- (void)testShouldGenerateAnInverseMappings -{ - RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - [mapping mapKeyPath:@"first_name" toAttribute:@"firstName"]; - [mapping mapAttributes:@"city", @"state", @"zip", nil]; - RKObjectMapping *otherMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - [otherMapping mapAttributes:@"street", nil]; - [mapping mapRelationship:@"address" withMapping:otherMapping]; - RKObjectMapping *inverse = [mapping inverseMapping]; - assertThat(inverse.objectClass, is(equalTo([NSMutableDictionary class]))); - assertThat([inverse mappingForKeyPath:@"firstName"], isNot(nilValue())); -} +// TODO: Decide about inverse... +//- (void)testShouldGenerateAnInverseMappings +//{ +// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +// [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"first_name" toKeyPath:@"firstName"]]; +// [mapping addAttributeMappingsFromArray:@[@"city", @"state", @"zip"]]; +// RKObjectMapping *otherMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; +// [otherMapping addAttributeMappingsFromArray:@[@"street"]]; +// [mapping mapRelationship:@"address" withMapping:otherMapping]; +// RKObjectMapping *inverse = [mapping inverseMapping]; +// assertThat(inverse.objectClass, is(equalTo([NSMutableDictionary class]))); +// assertThat([inverse mappingForKeyPath:@"firstName"], isNot(nilValue())); +//} - (void)testShouldLetYouRetrieveMappingsByAttribute { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKAttributeMapping *attributeMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"nameAttribute"]; - [mapping addAttributeMapping:attributeMapping]; - assertThat([mapping mappingForAttribute:@"nameAttribute"], is(equalTo(attributeMapping))); + RKAttributeMapping *attributeMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"nameAttribute"]; + [mapping addPropertyMapping:attributeMapping]; + assertThat(mapping.propertyMappingsByDestinationKeyPath[@"nameAttribute"], is(equalTo(attributeMapping))); } - (void)testShouldLetYouRetrieveMappingsByRelationship { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKRelationshipMapping *relationshipMapping = [RKRelationshipMapping mappingFromKeyPath:@"friend" toKeyPath:@"friendRelationship" withMapping:mapping]; - [mapping addRelationshipMapping:relationshipMapping]; - assertThat([mapping mappingForRelationship:@"friendRelationship"], is(equalTo(relationshipMapping))); + RKRelationshipMapping *relationshipMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"friend" toKeyPath:@"friendRelationship" withMapping:mapping]; + [mapping addPropertyMapping:relationshipMapping]; + assertThat(mapping.propertyMappingsByDestinationKeyPath[@"friendRelationship"], is(equalTo(relationshipMapping))); } -#pragma mark - RKObjectMapper Tests +#pragma mark - RKMapperOperation Tests +// TODO: Move these into RKMapperOperationTest.m - (void)testShouldPerformBasicMapping { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - [mapping addAttributeMapping:idMapping]; - RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; - [mapping addAttributeMapping:nameMapping]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; RKMapperOperation *mapper = [RKMapperOperation new]; mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; @@ -259,10 +238,10 @@ - (void)testShouldMapACollectionOfSimpleObjectDictionaries { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - [mapping addAttributeMapping:idMapping]; - RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; - [mapping addAttributeMapping:nameMapping]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; RKMapperOperation *mapper = [RKMapperOperation new]; mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; @@ -274,1848 +253,1781 @@ [mapper release]; } -//- (void)testShouldDetermineTheObjectMappingByConsultingTheMappingProviderWhenThereIsATargetObject -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// mapper.targetObject = [RKTestUser user]; -// [mapper performMapping]; -// -// [mockProvider verify]; -//} -// -//- (void)testShouldAddAnErrorWhenTheKeyPathMappingAndObjectClassDoNotAgree -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// mapper.targetObject = [NSDictionary new]; -// [mapper performMapping]; -// assertThatUnsignedInteger([mapper.errors count], is(equalToInt(1))); -//} +// TODO: This doesn't really test anything anymore... +- (void)testShouldDetermineTheObjectMappingByConsultingTheMappingProviderWhenThereIsATargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; -//- (void)testShouldMapToATargetObject -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// RKTestUser *user = [RKTestUser user]; -// mapper.targetObject = user; -// RKMappingResult *result = [mapper performMapping]; -// -// [mockProvider verify]; -// assertThat(result, isNot(nilValue())); -// assertThatBool([result asObject] == user, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldCreateANewInstanceOfTheAppropriateDestinationObjectWhenThereIsNoTargetObject -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// id mappingResult = [[mapper performMapping] asObject]; -// assertThatBool([mappingResult isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -//} + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + mapper.targetObject = [RKTestUser user]; + [mapper start]; +} -//- (void)testShouldDetermineTheMappingClassForAKeyPathByConsultingTheMappingProviderWhenMappingADictionaryWithoutATargetObject -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// [[mockProvider expect] valueForContext:RKObjectMappingProviderContextObjectsByKeyPath]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// [mapper performMapping]; -// [mockProvider verify]; -//} -// -//- (void)testShouldMapWithoutATargetMapping -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// RKTestUser *user = [[mapper performMapping] asObject]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} +- (void)testShouldAddAnErrorWhenTheKeyPathMappingAndObjectClassDoNotAgree +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:@{[NSNull null] : mapping}]; + mapper.targetObject = [NSDictionary new]; + [mapper start]; + assertThat(mapper.error, is(notNilValue())); + // TODO: Better check on the error type... +} -//- (void)testShouldMapACollectionOfObjects -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// RKMappingResult *result = [mapper performMapping]; -// NSArray *users = [result asCollection]; -// assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); -// assertThatUnsignedInteger([users count], is(equalToInt(3))); -// RKTestUser *user = [users objectAtIndex:0]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldMapACollectionOfObjectsWithDynamicKeys -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// mapping.forceCollectionMapping = YES; -// [mapping mapKeyOfNestedDictionaryToAttribute:@"name"]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"(name).id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@"users"]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeys.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// RKMappingResult *result = [mapper performMapping]; -// NSArray *users = [result asCollection]; -// assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); -// assertThatUnsignedInteger([users count], is(equalToInt(2))); -// RKTestUser *user = [users objectAtIndex:0]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"blake"))); -// user = [users objectAtIndex:1]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"rachit"))); -//} -// -//- (void)testShouldMapACollectionOfObjectsWithDynamicKeysAndRelationships -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// mapping.forceCollectionMapping = YES; -// [mapping mapKeyOfNestedDictionaryToAttribute:@"name"]; -// -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// [addressMapping mapAttributes:@"city", @"state", nil]; -// [mapping mapKeyPath:@"(name).address" toRelationship:@"address" withMapping:addressMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@"users"]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithRelationship.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// RKMappingResult *result = [mapper performMapping]; -// NSArray *users = [result asCollection]; -// assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); -// assertThatUnsignedInteger([users count], is(equalToInt(2))); -// RKTestUser *user = [users objectAtIndex:0]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"blake"))); -// user = [users objectAtIndex:1]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"rachit"))); -// assertThat(user.address, isNot(nilValue())); -// assertThat(user.address.city, is(equalTo(@"New York"))); -//} -// -//- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndArrayRelationships -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserArray class]]; -// [mapping mapAttributes:@"name", nil]; -// -// -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// userMapping.forceCollectionMapping = YES; -// [userMapping mapKeyOfNestedDictionaryToAttribute:@"name"]; -// [mapping mapKeyPath:@"users" toRelationship:@"users" withMapping:userMapping]; -// -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// [addressMapping mapAttributes: -// @"city", @"city", -// @"state", @"state", -// @"country", @"country", -// nil -// ]; -// [userMapping mapKeyPath:@"(name).address" toRelationship:@"address" withMapping:addressMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@"groups"]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithNestedRelationship.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// RKMappingResult *result = [mapper performMapping]; -// -// NSArray *groups = [result asCollection]; -// assertThatBool([groups isKindOfClass:[NSArray class]], is(equalToBool(YES))); -// assertThatUnsignedInteger([groups count], is(equalToInt(2))); -// -// RKExampleGroupWithUserArray *group = [groups objectAtIndex:0]; -// assertThatBool([group isKindOfClass:[RKExampleGroupWithUserArray class]], is(equalToBool(YES))); -// assertThat(group.name, is(equalTo(@"restkit"))); -// NSArray *users = group.users; -// RKTestUser *user = [users objectAtIndex:0]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"blake"))); -// user = [users objectAtIndex:1]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"rachit"))); -// assertThat(user.address, isNot(nilValue())); -// assertThat(user.address.city, is(equalTo(@"New York"))); -// -// group = [groups objectAtIndex:1]; -// assertThatBool([group isKindOfClass:[RKExampleGroupWithUserArray class]], is(equalToBool(YES))); -// assertThat(group.name, is(equalTo(@"others"))); -// users = group.users; -// assertThatUnsignedInteger([users count], is(equalToInt(1))); -// user = [users objectAtIndex:0]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"bjorn"))); -// assertThat(user.address, isNot(nilValue())); -// assertThat(user.address.city, is(equalTo(@"Gothenburg"))); -// assertThat(user.address.country, is(equalTo(@"Sweden"))); -//} -// -//- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndSetRelationships -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserSet class]]; -// [mapping mapAttributes:@"name", nil]; -// -// -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// userMapping.forceCollectionMapping = YES; -// [userMapping mapKeyOfNestedDictionaryToAttribute:@"name"]; -// [mapping mapKeyPath:@"users" toRelationship:@"users" withMapping:userMapping]; -// -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// [addressMapping mapAttributes: -// @"city", @"city", -// @"state", @"state", -// @"country", @"country", -// nil -// ]; -// [userMapping mapKeyPath:@"(name).address" toRelationship:@"address" withMapping:addressMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@"groups"]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithNestedRelationship.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// RKMappingResult *result = [mapper performMapping]; -// -// NSArray *groups = [result asCollection]; -// assertThatBool([groups isKindOfClass:[NSArray class]], is(equalToBool(YES))); -// assertThatUnsignedInteger([groups count], is(equalToInt(2))); -// -// RKExampleGroupWithUserSet *group = [groups objectAtIndex:0]; -// assertThatBool([group isKindOfClass:[RKExampleGroupWithUserSet class]], is(equalToBool(YES))); -// assertThat(group.name, is(equalTo(@"restkit"))); -// -// -// NSSortDescriptor *sortByName = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]; -// NSArray *descriptors = [NSArray arrayWithObject:sortByName];; -// NSArray *users = [group.users sortedArrayUsingDescriptors:descriptors]; -// RKTestUser *user = [users objectAtIndex:0]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"blake"))); -// user = [users objectAtIndex:1]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"rachit"))); -// assertThat(user.address, isNot(nilValue())); -// assertThat(user.address.city, is(equalTo(@"New York"))); -// -// group = [groups objectAtIndex:1]; -// assertThatBool([group isKindOfClass:[RKExampleGroupWithUserSet class]], is(equalToBool(YES))); -// assertThat(group.name, is(equalTo(@"others"))); -// users = [group.users sortedArrayUsingDescriptors:descriptors]; -// assertThatUnsignedInteger([users count], is(equalToInt(1))); -// user = [users objectAtIndex:0]; -// assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"bjorn"))); -// assertThat(user.address, isNot(nilValue())); -// assertThat(user.address.city, is(equalTo(@"Gothenburg"))); -// assertThat(user.address.country, is(equalTo(@"Sweden"))); -//} -// -// -//- (void)testShouldBeAbleToMapFromAUserObjectToADictionary -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"userID" toKeyPath:@"id"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// user.userID = [NSNumber numberWithInt:123]; -// -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:user mappingProvider:provider]; -// RKMappingResult *result = [mapper performMapping]; -// NSDictionary *userInfo = [result asObject]; -// assertThatBool([userInfo isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); -// assertThat([userInfo valueForKey:@"name"], is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldMapRegisteredSubKeyPathsOfAnUnmappableDictionaryAndReturnTheResults -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@"user"]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"nested_user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// NSDictionary *dictionary = [[mapper performMapping] asDictionary]; -// assertThatBool([dictionary isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); -// RKTestUser *user = [dictionary objectForKey:@"user"]; -// assertThat(user, isNot(nilValue())); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//#pragma mark Mapping Error States -// -//- (void)testShouldAddAnErrorWhenYouTryToMapAnArrayToATargetObject -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// mapper.targetObject = [RKTestUser user]; -// [mapper performMapping]; -// assertThatUnsignedInteger([mapper.errors count], is(equalToInt(1))); -// assertThatInteger([[mapper.errors objectAtIndex:0] code], is(equalToInt(RKMappingErrorTypeMismatch))); -//} -// -//- (void)testShouldAddAnErrorWhenAttemptingToMapADictionaryWithoutAnObjectMapping -//{ -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// [mapper performMapping]; -// assertThatUnsignedInteger([mapper.errors count], is(equalToInt(1))); -// assertThat([[mapper.errors objectAtIndex:0] localizedDescription], is(equalTo(@"Could not find an object mapping for keyPath: ''"))); -//} -// -//- (void)testShouldAddAnErrorWhenAttemptingToMapACollectionWithoutAnObjectMapping -//{ -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// [mapper performMapping]; -// assertThatUnsignedInteger([mapper.errors count], is(equalToInt(1))); -// assertThat([[mapper.errors objectAtIndex:0] localizedDescription], is(equalTo(@"Could not find an object mapping for keyPath: ''"))); -//} -// -//#pragma mark RKObjectMapperDelegate Tests -// -//- (void)testShouldInformTheDelegateWhenMappingBegins -//{ -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// [[mockDelegate expect] mapperWillBeginMapping:mapper]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldInformTheDelegateWhenMappingEnds -//{ -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// [[mockDelegate stub] mapperWillBeginMapping:mapper]; -// [[mockDelegate expect] mapperDidFinishMapping:mapper]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsSuccessful -//{ -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// [[mockDelegate expect] mapper:mapper didFindMappableObject:[OCMArg any] atKeyPath:@""withMapping:mapping]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsNotSuccessful -//{ -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// [provider setMapping:mapping forKeyPath:@"users"]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// [[mockDelegate expect] mapper:mapper didNotFindMappableObjectAtKeyPath:@"users"]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldInformTheDelegateOfError -//{ -// id mockProvider = [OCMockObject niceMockForClass:[RKObjectMappingProvider class]]; -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// [[mockDelegate expect] mapper:mapper didAddError:[OCMArg isNotNil]]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldNotifyTheDelegateWhenItWillMapAnObject -//{ -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// [provider setMapping:mapping forKeyPath:@""]; -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// [[mockDelegate expect] mapper:mapper willMapFromObject:userInfo toObject:[OCMArg any] atKeyPath:@"" usingMapping:mapping]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldNotifyTheDelegateWhenItDidMapAnObject -//{ -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// [[mockDelegate expect] mapper:mapper didMapFromObject:userInfo toObject:[OCMArg any] atKeyPath:@"" usingMapping:mapping]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockDelegate verify]; -//} -// -//- (BOOL)fakeValidateValue:(inout id *)ioValue forKeyPath:(NSString *)inKey error:(out NSError **)outError -//{ -// *outError = [NSError errorWithDomain:RKErrorDomain code:1234 userInfo:nil]; -// return NO; -//} -// -//- (void)testShouldNotifyTheDelegateWhenItFailedToMapAnObject -//{ -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:NSClassFromString(@"OCPartialMockObject")]; -// [mapping mapAttributes:@"name", nil]; -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:mapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// RKTestUser *exampleUser = [[RKTestUser new] autorelease]; -// id mockObject = [OCMockObject partialMockForObject:exampleUser]; -// [[[mockObject expect] andCall:@selector(fakeValidateValue:forKeyPath:error:) onObject:self] validateValue:[OCMArg anyPointer] forKeyPath:OCMOCK_ANY error:[OCMArg anyPointer]]; -// mapper.targetObject = mockObject; -// [[mockDelegate expect] mapper:mapper didFailMappingFromObject:userInfo toObject:[OCMArg any] withError:[OCMArg any] atKeyPath:@"" usingMapping:mapping]; -// mapper.delegate = mockDelegate; -// [mapper performMapping]; -// [mockObject verify]; -// [mockDelegate verify]; -//} -// -//#pragma mark - RKObjectMappingOperationTests -// -//- (void)testShouldBeAbleToMapADictionaryToAUser -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:123], @"id", @"Blake Watters", @"name", nil]; -// RKTestUser *user = [RKTestUser user]; -// -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// [operation performMapping:nil]; -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// assertThatInt([user.userID intValue], is(equalToInt(123))); -// [operation release]; -//} -// -//- (void)testShouldConsiderADictionaryContainingOnlyNullValuesForKeysMappable -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNull null], @"name", nil]; -// RKTestUser *user = [RKTestUser user]; -// -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// BOOL success = [operation performMapping:nil]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat(user.name, is(nilValue())); -// [operation release]; -//} -// -//- (void)testShouldBeAbleToMapAUserToADictionary -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"userID" toKeyPath:@"id"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// user.userID = [NSNumber numberWithInt:123]; -// -// NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:user destinationObject:dictionary mapping:mapping]; -// BOOL success = [operation performMapping:nil]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat([dictionary valueForKey:@"name"], is(equalTo(@"Blake Watters"))); -// assertThatInt([[dictionary valueForKey:@"id"] intValue], is(equalToInt(123))); -// [operation release]; -//} -// -//- (void)testShouldReturnNoWithoutErrorWhenGivenASourceObjectThatContainsNoMappableKeys -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; -// RKTestUser *user = [RKTestUser user]; -// -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// BOOL success = [operation performMapping:&error]; -// assertThatBool(success, is(equalToBool(NO))); -// assertThat(error, is(nilValue())); -// [operation release]; -//} -// -//- (void)testShouldInformTheDelegateOfAnErrorWhenMappingFailsBecauseThereIsNoMappableContent -//{ -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMappingOperationDelegate)]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; -// RKTestUser *user = [RKTestUser user]; -// -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// operation.delegate = mockDelegate; -// BOOL success = [operation performMapping:nil]; -// assertThatBool(success, is(equalToBool(NO))); -// [mockDelegate verify]; -//} -// -//- (void)testShouldSetTheErrorWhenMappingOperationFails -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// [mapping addAttributeMapping:idMapping]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"FAILURE", @"id", nil]; -// RKTestUser *user = [RKTestUser user]; -// id mockObject = [OCMockObject partialMockForObject:user]; -// [[[mockObject expect] andCall:@selector(fakeValidateValue:forKeyPath:error:) onObject:self] validateValue:[OCMArg anyPointer] forKeyPath:OCMOCK_ANY error:[OCMArg anyPointer]]; -// -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockObject mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// assertThat(error, isNot(nilValue())); -// [operation release]; -//} -// -//#pragma mark - Attribute Mapping -// -//- (void)testShouldMapAStringToADateAttribute -//{ -// [RKObjectMapping setDefaultDateFormatters:nil]; -// -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *birthDateMapping = [RKAttributeMapping mappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; -// [mapping addAttributeMapping:birthDateMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; -// dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; -// [dateFormatter setDateFormat:@"MM/dd/yyyy"]; -// assertThat([dateFormatter stringFromDate:user.birthDate], is(equalTo(@"11/27/1982"))); -//} -// -//- (void)testShouldMapStringToURL -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"website" toKeyPath:@"website"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThat(user.website, isNot(nilValue())); -// assertThatBool([user.website isKindOfClass:[NSURL class]], is(equalToBool(YES))); -// assertThat([user.website absoluteString], is(equalTo(@"http://restkit.org/"))); -//} -// -//- (void)testShouldMapAStringToANumberBool -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); -//} -// -//- (void)testShouldMapAShortTrueStringToANumberBool -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// RKTestUser *user = [RKTestUser user]; -// [dictionary setValue:@"T" forKey:@"is_developer"]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); -//} -// -//- (void)testShouldMapAShortFalseStringToANumberBool -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// RKTestUser *user = [RKTestUser user]; -// [dictionary setValue:@"f" forKey:@"is_developer"]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThatBool([[user isDeveloper] boolValue], is(equalToBool(NO))); -//} -// -//- (void)testShouldMapAYesStringToANumberBool -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// RKTestUser *user = [RKTestUser user]; -// [dictionary setValue:@"yes" forKey:@"is_developer"]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); -//} -// -//- (void)testShouldMapANoStringToANumberBool -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// RKTestUser *user = [RKTestUser user]; -// [dictionary setValue:@"NO" forKey:@"is_developer"]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThatBool([[user isDeveloper] boolValue], is(equalToBool(NO))); -//} -// -//- (void)testShouldMapAStringToANumber -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"luckyNumber"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThatInt([user.luckyNumber intValue], is(equalToInt(187))); -//} -// -//- (void)testShouldMapAStringToADecimalNumber -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"weight" toKeyPath:@"weight"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// NSDecimalNumber *weight = user.weight; -// assertThatBool([weight isKindOfClass:[NSDecimalNumber class]], is(equalToBool(YES))); -// assertThatInteger([weight compare:[NSDecimalNumber decimalNumberWithString:@"131.3"]], is(equalToInt(NSOrderedSame))); -//} -// -//- (void)testShouldMapANumberToAString -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"name"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThat(user.name, is(equalTo(@"187"))); -//} -// -//- (void)testShouldMapANumberToANSDecimalNumber -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *websiteMapping = [RKAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"weight"]; -// [mapping addAttributeMapping:websiteMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// NSDecimalNumber *weight = user.weight; -// assertThatBool([weight isKindOfClass:[NSDecimalNumber class]], is(equalToBool(YES))); -// assertThatInteger([weight compare:[NSDecimalNumber decimalNumberWithString:@"187"]], is(equalToInt(NSOrderedSame))); -//} -// -//- (void)testShouldMapANumberToADate -//{ -// NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; -// [dateFormatter setDateFormat:@"MM/dd/yyyy"]; -// NSDate *date = [dateFormatter dateFromString:@"11/27/1982"]; -// -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *birthDateMapping = [RKAttributeMapping mappingFromKeyPath:@"dateAsNumber" toKeyPath:@"birthDate"]; -// [mapping addAttributeMapping:birthDateMapping]; -// -// NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary setValue:[NSNumber numberWithInt:[date timeIntervalSince1970]] forKey:@"dateAsNumber"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThat([dateFormatter stringFromDate:user.birthDate], is(equalTo(@"11/27/1982"))); -//} -// -//- (void)testShouldMapANestedKeyPathToAnAttribute -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *countryMapping = [RKAttributeMapping mappingFromKeyPath:@"address.country" toKeyPath:@"country"]; -// [mapping addAttributeMapping:countryMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThat(user.country, is(equalTo(@"USA"))); -//} -// -//- (void)testShouldMapANestedArrayOfStringsToAnAttribute -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *countryMapping = [RKAttributeMapping mappingFromKeyPath:@"interests" toKeyPath:@"interests"]; -// [mapping addAttributeMapping:countryMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// NSArray *interests = [NSArray arrayWithObjects:@"Hacking", @"Running", nil]; -// assertThat(user.interests, is(equalTo(interests))); -//} -// -//- (void)testShouldMapANestedDictionaryToAnAttribute -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *countryMapping = [RKAttributeMapping mappingFromKeyPath:@"address" toKeyPath:@"addressDictionary"]; -// [mapping addAttributeMapping:countryMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// NSDictionary *address = [NSDictionary dictionaryWithKeysAndObjects: -// @"city", @"Carrboro", -// @"state", @"North Carolina", -// @"id", [NSNumber numberWithInt:1234], -// @"country", @"USA", nil]; -// assertThat(user.addressDictionary, is(equalTo(address))); -//} -// -//- (void)testShouldNotSetAPropertyWhenTheValueIsTheSame -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser reject] setName:OCMOCK_ANY]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -//} -// -//- (void)testShouldNotSetTheDestinationPropertyWhenBothAreNil -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary setValue:[NSNull null] forKey:@"name"]; -// RKTestUser *user = [RKTestUser user]; -// user.name = nil; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser reject] setName:OCMOCK_ANY]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -//} -// -//- (void)testShouldSetNilForNSNullValues -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary setValue:[NSNull null] forKey:@"name"]; -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser expect] setName:nil]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// [mockUser verify]; -//} -// -//- (void)testDelegateIsInformedWhenANilValueIsMappedForNSNullWithExistingValue -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary setValue:[NSNull null] forKey:@"name"]; -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKMappingOperationDelegate)]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// operation.delegate = mockDelegate; -// NSError *error = nil; -// [[mockDelegate expect] mappingOperation:operation didFindMapping:nameMapping forKeyPath:@"name"]; -// [[mockDelegate expect] mappingOperation:operation didSetValue:nil forKeyPath:@"name" usingMapping:nameMapping]; -// [operation performMapping:&error]; -// [mockDelegate verify]; -//} -// -//- (void)testDelegateIsInformedWhenUnchangedValueIsSkipped -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary setValue:@"Blake Watters" forKey:@"name"]; -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKMappingOperationDelegate)]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// operation.delegate = mockDelegate; -// NSError *error = nil; -// [[mockDelegate expect] mappingOperation:operation didFindMapping:nameMapping forKeyPath:@"name"]; -// [[mockDelegate expect] mappingOperation:operation didNotSetUnchangedValue:@"Blake Watters" forKeyPath:@"name" usingMapping:nameMapping]; -// [operation performMapping:&error]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldOptionallySetDefaultValueForAMissingKeyPath -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary removeObjectForKey:@"name"]; -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser expect] setName:nil]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// id mockMapping = [OCMockObject partialMockForObject:mapping]; -// BOOL returnValue = YES; -// [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] shouldSetDefaultValueForMissingAttributes]; -// NSError *error = nil; -// [operation performMapping:&error]; -// [mockUser verify]; -//} -// -//- (void)testShouldOptionallyIgnoreAMissingSourceKeyPath -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [mapping addAttributeMapping:nameMapping]; -// -// NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary removeObjectForKey:@"name"]; -// RKTestUser *user = [RKTestUser user]; -// user.name = @"Blake Watters"; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser reject] setName:nil]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// id mockMapping = [OCMockObject partialMockForObject:mapping]; -// BOOL returnValue = NO; -// [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] shouldSetDefaultValueForMissingAttributes]; -// NSError *error = nil; -// [operation performMapping:&error]; -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//#pragma mark - Relationship Mapping -// -//- (void)testShouldMapANestedObject -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// RKAttributeMapping *cityMapping = [RKAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; -// [addressMapping addAttributeMapping:cityMapping]; -// -// RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; -// [userMapping addRelationshipMapping:hasOneMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// assertThat(user.address, isNot(nilValue())); -//} -// -//- (void)testShouldMapANestedObjectToCollection -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// RKAttributeMapping *cityMapping = [RKAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; -// [addressMapping addAttributeMapping:cityMapping]; -// -// RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"friends" withMapping:addressMapping]; -// [userMapping addRelationshipMapping:hasOneMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// assertThat(user.friends, isNot(nilValue())); -// assertThatUnsignedInteger([user.friends count], is(equalToInt(1))); -//} -// -//- (void)testShouldMapANestedObjectToOrderedSetCollection -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// RKAttributeMapping *cityMapping = [RKAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; -// [addressMapping addAttributeMapping:cityMapping]; -// -// RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"friendsOrderedSet" withMapping:addressMapping]; -// [userMapping addRelationshipMapping:hasOneMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// assertThat(user.friendsOrderedSet, isNot(nilValue())); -// assertThatUnsignedInteger([user.friendsOrderedSet count], is(equalToInt(1))); -//} -// -//- (void)testShouldMapANestedObjectCollection -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// -// RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; -// [userMapping addRelationshipMapping:hasManyMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// assertThat(user.friends, isNot(nilValue())); -// assertThatUnsignedInteger([user.friends count], is(equalToInt(2))); -// NSArray *names = [NSArray arrayWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; -// assertThat([user.friends valueForKey:@"name"], is(equalTo(names))); -//} -// -//- (void)testShouldMapANestedArrayIntoASet -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// -// RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friendsSet" withMapping:userMapping]; -// [userMapping addRelationshipMapping:hasManyMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// assertThat(user.friendsSet, isNot(nilValue())); -// assertThatBool([user.friendsSet isKindOfClass:[NSSet class]], is(equalToBool(YES))); -// assertThatUnsignedInteger([user.friendsSet count], is(equalToInt(2))); -// NSSet *names = [NSSet setWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; -// assertThat([user.friendsSet valueForKey:@"name"], is(equalTo(names))); -//} -// -//- (void)testShouldMapANestedArrayIntoAnOrderedSet -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// -// RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friendsOrderedSet" withMapping:userMapping]; -// [userMapping addRelationshipMapping:hasManyMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -// assertThatBool(success, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// assertThat(user.friendsOrderedSet, isNot(nilValue())); -// assertThatBool([user.friendsOrderedSet isKindOfClass:[NSOrderedSet class]], is(equalToBool(YES))); -// assertThatUnsignedInteger([user.friendsOrderedSet count], is(equalToInt(2))); -// NSOrderedSet *names = [NSOrderedSet orderedSetWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; -// assertThat([user.friendsOrderedSet valueForKey:@"name"], is(equalTo(names))); -//} -// -//- (void)testShouldNotSetThePropertyWhenTheNestedObjectIsIdentical -//{ -// RKTestUser *user = [RKTestUser user]; -// RKTestAddress *address = [RKTestAddress address]; -// address.addressID = [NSNumber numberWithInt:1234]; -// user.address = address; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser reject] setAddress:OCMOCK_ANY]; -// -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; -// [addressMapping addAttributeMapping:idMapping]; -// -// RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; -// [userMapping addRelationshipMapping:hasOneMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -//} -// -//- (void)testSkippingOfIdenticalObjectsInformsDelegate -//{ -// RKTestUser *user = [RKTestUser user]; -// RKTestAddress *address = [RKTestAddress address]; -// address.addressID = [NSNumber numberWithInt:1234]; -// user.address = address; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser reject] setAddress:OCMOCK_ANY]; -// -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; -// [addressMapping addAttributeMapping:idMapping]; -// -// RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; -// [userMapping addRelationshipMapping:hasOneMapping]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKMappingOperation *operation = [RKMappingOperation mappingOperationFromObject:userInfo toObject:user withMapping:userMapping]; -// id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMappingOperationDelegate)]; -// [[mockDelegate expect] mappingOperation:operation didNotSetUnchangedValue:address forKeyPath:@"address" usingMapping:hasOneMapping]; -// operation.delegate = mockDelegate; -// [operation performMapping:nil]; -// [mockDelegate verify]; -//} -// -//- (void)testShouldNotSetThePropertyWhenTheNestedObjectCollectionIsIdentical -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:idMapping]; -// [userMapping addAttributeMapping:nameMapping]; -// -// RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; -// [userMapping addRelationshipMapping:hasManyMapping]; -// -// RKObjectMapper *mapper = [RKObjectMapper new]; -// mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// -// // Set the friends up -// RKTestUser *jeremy = [RKTestUser user]; -// jeremy.name = @"Jeremy Ellison"; -// jeremy.userID = [NSNumber numberWithInt:187]; -// RKTestUser *rachit = [RKTestUser user]; -// rachit.name = @"Rachit Shukla"; -// rachit.userID = [NSNumber numberWithInt:7]; -// user.friends = [NSArray arrayWithObjects:jeremy, rachit, nil]; -// -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser reject] setFriends:OCMOCK_ANY]; -// [mapper mapFromObject:userInfo toObject:mockUser atKeyPath:@"" usingMapping:userMapping]; -// [mapper release]; -// [mockUser verify]; -//} -// -//- (void)testShouldOptionallyNilOutTheRelationshipIfItIsMissing -//{ -// RKTestUser *user = [RKTestUser user]; -// RKTestAddress *address = [RKTestAddress address]; -// address.addressID = [NSNumber numberWithInt:1234]; -// user.address = address; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser expect] setAddress:nil]; -// -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; -// [addressMapping addAttributeMapping:idMapping]; -// RKRelationshipMapping *relationshipMapping = [RKRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; -// [userMapping addRelationshipMapping:relationshipMapping]; -// -// NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary removeObjectForKey:@"address"]; -// id mockMapping = [OCMockObject partialMockForObject:userMapping]; -// BOOL returnValue = YES; -// [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] setNilForMissingRelationships]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; -// -// NSError *error = nil; -// [operation performMapping:&error]; -// [mockUser verify]; -//} -// -//- (void)testShouldNotNilOutTheRelationshipIfItIsMissingAndCurrentlyNilOnTheTargetObject -//{ -// RKTestUser *user = [RKTestUser user]; -// user.address = nil; -// id mockUser = [OCMockObject partialMockForObject:user]; -// [[mockUser reject] setAddress:nil]; -// -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *nameMapping = [RKAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; -// [userMapping addAttributeMapping:nameMapping]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// RKAttributeMapping *idMapping = [RKAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; -// [addressMapping addAttributeMapping:idMapping]; -// RKRelationshipMapping *relationshipMapping = [RKRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; -// [userMapping addRelationshipMapping:relationshipMapping]; -// -// NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; -// [dictionary removeObjectForKey:@"address"]; -// id mockMapping = [OCMockObject partialMockForObject:userMapping]; -// BOOL returnValue = YES; -// [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] setNilForMissingRelationships]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; -// -// NSError *error = nil; -// [operation performMapping:&error]; -// [mockUser verify]; -//} -// -//#pragma mark - RKObjectMappingProvider -// -//- (void)testShouldRegisterRailsIdiomaticObjects -//{ -// RKObjectManager *objectManager = [RKTestFactory objectManager]; -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// [mapping mapAttributes:@"name", @"website", nil]; -// [mapping mapKeyPath:@"id" toAttribute:@"userID"]; -// -// [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKTestUser class] pathPattern:@"/humans/:userID" method:RKRequestMethodAny]]; -// [objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[RKTestUser class] pathPattern:@"/humans" method:RKRequestMethodPOST]]; -// [objectManager.mappingProvider registerMapping:mapping withRootKeyPath:@"human"]; -// -// RKTestUser *user = [RKTestUser new]; -// user.userID = [NSNumber numberWithInt:1]; -// -// RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; -// loader.timeout = 5; -// [objectManager getObject:user delegate:loader]; -// [loader waitForResponse]; -// assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -// -// [objectManager postObject:user delegate:loader]; -// [loader waitForResponse]; -// assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); -// assertThat(user.name, is(equalTo(@"My Name"))); -// assertThat(user.website, is(equalTo([NSURL URLWithString:@"http://restkit.org/"]))); -//} -// -//- (void)testShouldReturnAllMappingsForAClass -//{ -// RKObjectMapping *firstMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMapping *secondMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMapping *thirdMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMappingProvider *mappingProvider = [[RKObjectMappingProvider new] autorelease]; -// [mappingProvider addObjectMapping:firstMapping]; -// [mappingProvider addObjectMapping:secondMapping]; -// [mappingProvider setMapping:thirdMapping forKeyPath:@"third"]; -// assertThat([mappingProvider objectMappingsForClass:[RKTestUser class]], is(equalTo([NSArray arrayWithObjects:firstMapping, secondMapping, thirdMapping, nil]))); -//} -// -//- (void)testShouldReturnAllMappingsForAClassAndNotExplodeWithRegisteredDynamicMappings -//{ -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; -// [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; -// [provider setMapping:dynamicMapping forKeyPath:@"dynamic"]; -// RKObjectMapping *firstMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKObjectMapping *secondMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// [provider addObjectMapping:firstMapping]; -// [provider setMapping:secondMapping forKeyPath:@"second"]; -// NSException *exception = nil; -// NSArray *actualMappings = nil; -// @try { -// actualMappings = [provider objectMappingsForClass:[RKTestUser class]]; -// } -// @catch (NSException *e) { -// exception = e; -// } -// assertThat(exception, is(nilValue())); -// assertThat(actualMappings, is(equalTo([NSArray arrayWithObjects:firstMapping, secondMapping, nil]))); -//} -// -//#pragma mark - RKDynamicMapping -// -//- (void)testShouldMapASingleObjectDynamically -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { -// if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { -// return boyMapping; -// } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { -// return girlMapping; -// } -// -// return nil; -// }; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// Boy *user = [[mapper performMapping] asObject]; -// assertThat(user, is(instanceOf([Boy class]))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldMapASingleObjectDynamicallyWithADeclarativeMatcher -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; -// [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// Boy *user = [[mapper performMapping] asObject]; -// assertThat(user, is(instanceOf([Boy class]))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldACollectionOfObjectsDynamically -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; -// [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"mixed.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// NSArray *objects = [[mapper performMapping] asCollection]; -// assertThat(objects, hasCountOf(2)); -// assertThat([objects objectAtIndex:0], is(instanceOf([Boy class]))); -// assertThat([objects objectAtIndex:1], is(instanceOf([Girl class]))); -// Boy *boy = [objects objectAtIndex:0]; -// Girl *girl = [objects objectAtIndex:1]; -// assertThat(boy.name, is(equalTo(@"Blake Watters"))); -// assertThat(girl.name, is(equalTo(@"Sarah"))); -//} -// -//- (void)testShouldMapARelationshipDynamically -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; -// [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; -// [boyMapping mapKeyPath:@"friends" toRelationship:@"friends" withMapping:dynamicMapping]; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"friends.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// Boy *blake = [[mapper performMapping] asObject]; -// NSArray *friends = blake.friends; -// -// assertThat(friends, hasCountOf(2)); -// assertThat([friends objectAtIndex:0], is(instanceOf([Boy class]))); -// assertThat([friends objectAtIndex:1], is(instanceOf([Girl class]))); -// Boy *boy = [friends objectAtIndex:0]; -// Girl *girl = [friends objectAtIndex:1]; -// assertThat(boy.name, is(equalTo(@"John Doe"))); -// assertThat(girl.name, is(equalTo(@"Jane Doe"))); -//} -// -//- (void)testShouldBeAbleToDeclineMappingAnObjectByReturningANilObjectMapping -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { -// if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { -// return boyMapping; -// } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { -// // NO GIRLS ALLOWED(*$!)(* -// return nil; -// } -// -// return nil; -// }; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"mixed.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// NSArray *boys = [[mapper performMapping] asCollection]; -// assertThat(boys, hasCountOf(1)); -// Boy *user = [boys objectAtIndex:0]; -// assertThat(user, is(instanceOf([Boy class]))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldBeAbleToDeclineMappingObjectsInARelationshipByReturningANilObjectMapping -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { -// if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { -// return boyMapping; -// } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { -// // NO GIRLS ALLOWED(*$!)(* -// return nil; -// } -// -// return nil; -// }; -// [boyMapping mapKeyPath:@"friends" toRelationship:@"friends" withMapping:dynamicMapping]; -// -// RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// id mockProvider = [OCMockObject partialMockForObject:provider]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"friends.json"]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; -// Boy *blake = [[mapper performMapping] asObject]; -// assertThat(blake, is(notNilValue())); -// assertThat(blake.name, is(equalTo(@"Blake Watters"))); -// assertThat(blake, is(instanceOf([Boy class]))); -// NSArray *friends = blake.friends; -// -// assertThat(friends, hasCountOf(1)); -// assertThat([friends objectAtIndex:0], is(instanceOf([Boy class]))); -// Boy *boy = [friends objectAtIndex:0]; -// assertThat(boy.name, is(equalTo(@"John Doe"))); -//} -// -//- (void)testShouldMapATargetObjectWithADynamicMapping -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { -// if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { -// return boyMapping; -// } -// -// return nil; -// }; -// -// RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; -// Boy *blake = [[Boy new] autorelease]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// mapper.targetObject = blake; -// Boy *user = [[mapper performMapping] asObject]; -// assertThat(user, is(instanceOf([Boy class]))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldBeBackwardsCompatibleWithTheOldClassName -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKObjectDynamicMapping *dynamicMapping = (RKObjectDynamicMapping *)[RKObjectDynamicMapping dynamicMapping]; -// dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { -// if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { -// return boyMapping; -// } -// -// return nil; -// }; -// -// RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; -// Boy *blake = [[Boy new] autorelease]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// mapper.targetObject = blake; -// Boy *user = [[mapper performMapping] asObject]; -// assertThat(user, is(instanceOf([Boy class]))); -// assertThat(user.name, is(equalTo(@"Blake Watters"))); -//} -// -//- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsNil -//{ -// RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; -// [boyMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { -// return nil; -// }; -// -// RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; -// Boy *blake = [[Boy new] autorelease]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// mapper.targetObject = blake; -// Boy *user = [[mapper performMapping] asObject]; -// assertThat(user, is(nilValue())); -// assertThat(mapper.errors, hasCountOf(1)); -//} -// -//- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsTheIncorrectType -//{ -// RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; -// [girlMapping mapAttributes:@"name", nil]; -// RKDynamicMapping *dynamicMapping = [RKDynamicMapping dynamicMapping]; -// dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { -// if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { -// return girlMapping; -// } -// -// return nil; -// }; -// -// RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; -// [provider setMapping:dynamicMapping forKeyPath:@""]; -// -// id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"girl.json"]; -// Boy *blake = [[Boy new] autorelease]; -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; -// mapper.targetObject = blake; -// Boy *user = [[mapper performMapping] asObject]; -// assertThat(user, is(nilValue())); -// assertThat(mapper.errors, hasCountOf(1)); -//} -// -//#pragma mark - Date and Time Formatting -// -//- (void)testShouldAutoConfigureDefaultDateFormatters -//{ -// [RKObjectMapping setDefaultDateFormatters:nil]; -// NSArray *dateFormatters = [RKObjectMapping defaultDateFormatters]; -// assertThat(dateFormatters, hasCountOf(3)); -// assertThat([[dateFormatters objectAtIndex:0] dateFormat], is(equalTo(@"yyyy-MM-dd'T'HH:mm:ss'Z'"))); -// assertThat([[dateFormatters objectAtIndex:1] dateFormat], is(equalTo(@"MM/dd/yyyy"))); -// NSTimeZone *UTCTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; -// assertThat([[dateFormatters objectAtIndex:0] timeZone], is(equalTo(UTCTimeZone))); -// assertThat([[dateFormatters objectAtIndex:1] timeZone], is(equalTo(UTCTimeZone))); -//} -// -//- (void)testShouldLetYouSetTheDefaultDateFormatters -//{ -// NSDateFormatter *dateFormatter = [NSDateFormatter new]; -// NSArray *dateFormatters = [NSArray arrayWithObject:dateFormatter]; -// [RKObjectMapping setDefaultDateFormatters:dateFormatters]; -// assertThat([RKObjectMapping defaultDateFormatters], is(equalTo(dateFormatters))); -//} -// -//- (void)testShouldLetYouAppendADateFormatterToTheList -//{ -// [RKObjectMapping setDefaultDateFormatters:nil]; -// assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(3)); -// NSDateFormatter *dateFormatter = [NSDateFormatter new]; -// [RKObjectMapping addDefaultDateFormatter:dateFormatter]; -// assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(4)); -//} -// -//- (void)testShouldAllowNewlyAddedDateFormatterToRunFirst -//{ -// [RKObjectMapping setDefaultDateFormatters:nil]; -// NSDateFormatter *newDateFormatter = [[NSDateFormatter new] autorelease]; -// [newDateFormatter setDateFormat:@"dd/MM/yyyy"]; -// [RKObjectMapping addDefaultDateFormatter:newDateFormatter]; -// -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *birthDateMapping = [RKAttributeMapping mappingFromKeyPath:@"favorite_date" toKeyPath:@"favoriteDate"]; -// [mapping addAttributeMapping:birthDateMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; -// dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; -// [dateFormatter setDateFormat:@"MM/dd/yyyy"]; -// -// /* -// If RKObjectMappingOperation is using the date formatter set above, we're -// going to get a really wonky date, which is what we are testing for. -// */ -// assertThat([dateFormatter stringFromDate:user.favoriteDate], is(equalTo(@"01/03/2012"))); -//} -// -//- (void)testShouldLetYouConfigureANewDateFormatterFromAStringAndATimeZone -//{ -// [RKObjectMapping setDefaultDateFormatters:nil]; -// assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(3)); -// NSTimeZone *EDTTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"]; -// [RKObjectMapping addDefaultDateFormatterForString:@"mm/dd/YYYY" inTimeZone:EDTTimeZone]; -// assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(4)); -// NSDateFormatter *dateFormatter = [[RKObjectMapping defaultDateFormatters] objectAtIndex:0]; -// assertThat(dateFormatter.timeZone, is(equalTo(EDTTimeZone))); -//} -// -//- (void)testShouldReturnNilForEmptyDateValues -//{ -// RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// RKAttributeMapping *birthDateMapping = [RKAttributeMapping mappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; -// [mapping addAttributeMapping:birthDateMapping]; -// -// NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; -// NSMutableDictionary *mutableDictionary = [dictionary mutableCopy]; -// [mutableDictionary setValue:@"" forKey:@"birthdate"]; -// RKTestUser *user = [RKTestUser user]; -// RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:mutableDictionary destinationObject:user mapping:mapping]; -// [mutableDictionary release]; -// NSError *error = nil; -// [operation performMapping:&error]; -// -// assertThat(user.birthDate, is(equalTo(nil))); -//} -// -//- (void)testShouldConfigureANewDateFormatterInTheUTCTimeZoneIfPassedANilTimeZone -//{ -// [RKObjectMapping setDefaultDateFormatters:nil]; -// assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(3)); -// [RKObjectMapping addDefaultDateFormatterForString:@"mm/dd/YYYY" inTimeZone:nil]; -// assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(4)); -// NSDateFormatter *dateFormatter = [[RKObjectMapping defaultDateFormatters] objectAtIndex:0]; -// NSTimeZone *UTCTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; -// assertThat(dateFormatter.timeZone, is(equalTo(UTCTimeZone))); -//} -// -//#pragma mark - Object Serialization -//// TODO: Move to RKObjectSerializerTest -// -//- (void)testShouldSerializeHasOneRelatioshipsToJSON -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// [userMapping mapAttributes:@"name", nil]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// [addressMapping mapAttributes:@"city", @"state", nil]; -// [userMapping hasOne:@"address" withMapping:addressMapping]; -// -// RKTestUser *user = [RKTestUser new]; -// user.name = @"Blake Watters"; -// RKTestAddress *address = [RKTestAddress new]; -// address.state = @"North Carolina"; -// user.address = address; -// -// RKObjectMapping *serializationMapping = [userMapping inverseMapping]; -// RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:user mapping:serializationMapping]; -// NSError *error = nil; -// NSString *JSON = [serializer serializeObjectToMIMEType:RKMIMETypeJSON error:&error]; -// assertThat(error, is(nilValue())); -// assertThat(JSON, is(equalTo(@"{\"name\":\"Blake Watters\",\"address\":{\"state\":\"North Carolina\"}}"))); -//} -// -//- (void)testShouldSerializeHasManyRelationshipsToJSON -//{ -// RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; -// [userMapping mapAttributes:@"name", nil]; -// RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; -// [addressMapping mapAttributes:@"city", @"state", nil]; -// [userMapping hasMany:@"friends" withMapping:addressMapping]; -// -// RKTestUser *user = [RKTestUser new]; -// user.name = @"Blake Watters"; -// RKTestAddress *address1 = [RKTestAddress new]; -// address1.city = @"Carrboro"; -// RKTestAddress *address2 = [RKTestAddress new]; -// address2.city = @"New York City"; -// user.friends = [NSArray arrayWithObjects:address1, address2, nil]; -// -// -// RKObjectMapping *serializationMapping = [userMapping inverseMapping]; -// RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:user mapping:serializationMapping]; -// NSError *error = nil; -// NSString *JSON = [serializer serializeObjectToMIMEType:RKMIMETypeJSON error:&error]; -// assertThat(error, is(nilValue())); -// assertThat(JSON, is(equalTo(@"{\"name\":\"Blake Watters\",\"friends\":[{\"city\":\"Carrboro\"},{\"city\":\"New York City\"}]}"))); -//} -// -//- (void)testShouldSerializeManagedHasManyRelationshipsToJSON -//{ -// RKManagedObjectStore *managedObjectStore = [RKTestFactory managedObjectStore]; -// RKObjectMapping *humanMapping = [RKObjectMapping mappingForClass:[RKHuman class]]; -// [humanMapping mapAttributes:@"name", nil]; -// RKObjectMapping *catMapping = [RKObjectMapping mappingForClass:[RKCat class]]; -// [catMapping mapAttributes:@"name", nil]; -// [humanMapping hasMany:@"cats" withMapping:catMapping]; -// -// RKHuman *blake = [NSEntityDescription insertNewObjectForEntityForName:@"RKHuman" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; -// blake.name = @"Blake Watters"; -// RKCat *asia = [NSEntityDescription insertNewObjectForEntityForName:@"RKCat" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; -// asia.name = @"Asia"; -// RKCat *roy = [NSEntityDescription insertNewObjectForEntityForName:@"RKCat" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; -// roy.name = @"Roy"; -// blake.cats = [NSSet setWithObjects:asia, roy, nil]; -// -// RKObjectMapping *serializationMapping = [humanMapping inverseMapping]; -// RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:blake mapping:serializationMapping]; -// NSError *error = nil; -// NSString *JSON = [serializer serializeObjectToMIMEType:RKMIMETypeJSON error:&error]; -// NSDictionary *parsedJSON = [JSON performSelector:@selector(objectFromJSONString)]; -// assertThat(error, is(nilValue())); -// assertThat([parsedJSON valueForKey:@"name"], is(equalTo(@"Blake Watters"))); -// NSArray *catNames = [[parsedJSON valueForKeyPath:@"cats.name"] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; -// assertThat(catNames, is(equalTo([NSArray arrayWithObjects:@"Asia", @"Roy", nil]))); -//} -// -//- (void)testUpdatingArrayOfExistingCats -//{ -// RKManagedObjectStore *managedObjectStore = [RKTestFactory managedObjectStore]; -// NSArray *array = [RKTestFixture parsedObjectWithContentsOfFixture:@"ArrayOfHumans.json"]; -// RKEntityMapping *humanMapping = [RKEntityMapping mappingForEntityForName:@"RKHuman" inManagedObjectStore:managedObjectStore]; -// [humanMapping mapKeyPath:@"id" toAttribute:@"railsID"]; -// humanMapping.primaryKeyAttribute = @"railsID"; -// RKObjectMappingProvider *provider = [RKObjectMappingProvider mappingProvider]; -// [provider setObjectMapping:humanMapping forKeyPath:@"human"]; -// -// // Create instances that should match the fixture -// RKHuman *human1 = [NSEntityDescription insertNewObjectForEntityForName:@"RKHuman" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; -// human1.railsID = [NSNumber numberWithInt:201]; -// RKHuman *human2 = [NSEntityDescription insertNewObjectForEntityForName:@"RKHuman" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; -// human2.railsID = [NSNumber numberWithInt:202]; -// [managedObjectStore.primaryManagedObjectContext save:nil]; -// -// RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:array mappingProvider:provider]; -// RKFetchRequestManagedObjectCache *managedObjectCache = [[RKFetchRequestManagedObjectCache alloc] init]; -// mapper.mappingOperationDataSource = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:managedObjectStore.primaryManagedObjectContext -// cache:managedObjectCache]; -// RKMappingResult *result = [mapper performMapping]; -// assertThat(result, is(notNilValue())); -// -// NSArray *humans = [result asCollection]; -// assertThat(humans, hasCountOf(2)); -// assertThat([humans objectAtIndex:0], is(equalTo(human1))); -// assertThat([humans objectAtIndex:1], is(equalTo(human2))); -//} +- (void)testShouldMapToATargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:@{[NSNull null] : mapping}]; + RKTestUser *user = [RKTestUser user]; + mapper.targetObject = user; + [mapper start]; + RKMappingResult *result = mapper.mappingResult; + + assertThat(result, isNot(nilValue())); + assertThatBool([result firstObject] == user, is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldCreateANewInstanceOfTheAppropriateDestinationObjectWhenThereIsNoTargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + id mappingResult = [mapper.mappingResult firstObject]; + assertThatBool([mappingResult isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); +} + +- (void)testShouldMapWithoutATargetMapping +{ + RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace); + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + RKTestUser *user = [mapper.mappingResult firstObject]; + assertThat(user, is(notNilValue())); + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldMapACollectionOfObjects +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + NSArray *users = [mapper.mappingResult array]; + assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); + assertThatUnsignedInteger([users count], is(equalToInt(3))); + RKTestUser *user = [users objectAtIndex:0]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldMapACollectionOfObjectsWithDynamicKeys +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + mapping.forceCollectionMapping = YES; + [mapping mapKeyOfNestedDictionaryToAttribute:@"name"]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"(name).id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:@"users"]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeys.json"]; + + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + NSArray *users = [mapper.mappingResult array]; + assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); + assertThatUnsignedInteger([users count], is(equalToInt(2))); + RKTestUser *user = [users objectAtIndex:0]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"blake"))); + user = [users objectAtIndex:1]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"rachit"))); +} + +- (void)testShouldMapACollectionOfObjectsWithDynamicKeysAndRelationships +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + mapping.forceCollectionMapping = YES; + [mapping mapKeyOfNestedDictionaryToAttribute:@"name"]; + + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + [addressMapping addAttributeMappingsFromArray:@[@"city", @"state"]]; + [mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"(name).address" toKeyPath:@"address" withMapping:addressMapping]];; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:@"users"]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithRelationship.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + RKMappingResult *result = mapper.mappingResult; + NSArray *users = [result array]; + assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); + assertThatUnsignedInteger([users count], is(equalToInt(2))); + RKTestUser *user = [users objectAtIndex:0]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"blake"))); + user = [users objectAtIndex:1]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"rachit"))); + assertThat(user.address, isNot(nilValue())); + assertThat(user.address.city, is(equalTo(@"New York"))); +} + +- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndArrayRelationships +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserArray class]]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; + + + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + userMapping.forceCollectionMapping = YES; + [userMapping mapKeyOfNestedDictionaryToAttribute:@"name"]; + [mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"users" toKeyPath:@"users" withMapping:userMapping]];; + + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + [addressMapping addAttributeMappingsFromDictionary:@{ + @"city": @"city", + @"state": @"state", + @"country": @"country", + }]; + [userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"(name).address" toKeyPath:@"address" withMapping:addressMapping]];; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:@"groups"]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithNestedRelationship.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + RKMappingResult *result = mapper.mappingResult; + + NSArray *groups = [result array]; + assertThatBool([groups isKindOfClass:[NSArray class]], is(equalToBool(YES))); + assertThatUnsignedInteger([groups count], is(equalToInt(2))); + + RKExampleGroupWithUserArray *group = [groups objectAtIndex:0]; + assertThatBool([group isKindOfClass:[RKExampleGroupWithUserArray class]], is(equalToBool(YES))); + assertThat(group.name, is(equalTo(@"restkit"))); + NSArray *users = group.users; + RKTestUser *user = [users objectAtIndex:0]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"blake"))); + user = [users objectAtIndex:1]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"rachit"))); + assertThat(user.address, isNot(nilValue())); + assertThat(user.address.city, is(equalTo(@"New York"))); + + group = [groups objectAtIndex:1]; + assertThatBool([group isKindOfClass:[RKExampleGroupWithUserArray class]], is(equalToBool(YES))); + assertThat(group.name, is(equalTo(@"others"))); + users = group.users; + assertThatUnsignedInteger([users count], is(equalToInt(1))); + user = [users objectAtIndex:0]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"bjorn"))); + assertThat(user.address, isNot(nilValue())); + assertThat(user.address.city, is(equalTo(@"Gothenburg"))); + assertThat(user.address.country, is(equalTo(@"Sweden"))); +} + +- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndSetRelationships +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserSet class]]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; + + + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + userMapping.forceCollectionMapping = YES; + [userMapping mapKeyOfNestedDictionaryToAttribute:@"name"]; + [mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"users" toKeyPath:@"users" withMapping:userMapping]];; + + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + [addressMapping addAttributeMappingsFromDictionary:@{ + @"city": @"city", + @"state": @"state", + @"country": @"country", + }]; + [userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"(name).address" toKeyPath:@"address" withMapping:addressMapping]];; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:@"groups"]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithNestedRelationship.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + RKMappingResult *result = mapper.mappingResult; + + NSArray *groups = [result array]; + assertThatBool([groups isKindOfClass:[NSArray class]], is(equalToBool(YES))); + assertThatUnsignedInteger([groups count], is(equalToInt(2))); + + RKExampleGroupWithUserSet *group = [groups objectAtIndex:0]; + assertThatBool([group isKindOfClass:[RKExampleGroupWithUserSet class]], is(equalToBool(YES))); + assertThat(group.name, is(equalTo(@"restkit"))); + + + NSSortDescriptor *sortByName = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]; + NSArray *descriptors = [NSArray arrayWithObject:sortByName];; + NSArray *users = [group.users sortedArrayUsingDescriptors:descriptors]; + RKTestUser *user = [users objectAtIndex:0]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"blake"))); + user = [users objectAtIndex:1]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"rachit"))); + assertThat(user.address, isNot(nilValue())); + assertThat(user.address.city, is(equalTo(@"New York"))); + + group = [groups objectAtIndex:1]; + assertThatBool([group isKindOfClass:[RKExampleGroupWithUserSet class]], is(equalToBool(YES))); + assertThat(group.name, is(equalTo(@"others"))); + users = [group.users sortedArrayUsingDescriptors:descriptors]; + assertThatUnsignedInteger([users count], is(equalToInt(1))); + user = [users objectAtIndex:0]; + assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"bjorn"))); + assertThat(user.address, isNot(nilValue())); + assertThat(user.address.city, is(equalTo(@"Gothenburg"))); + assertThat(user.address.country, is(equalTo(@"Sweden"))); +} + + +- (void)testShouldBeAbleToMapFromAUserObjectToADictionary +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"userID" toKeyPath:@"id"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + user.userID = [NSNumber numberWithInt:123]; + + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:user mappingsDictionary:mappingsDictionary]; + [mapper start]; + RKMappingResult *result = mapper.mappingResult; + NSDictionary *userInfo = [result firstObject]; + assertThatBool([userInfo isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); + assertThat([userInfo valueForKey:@"name"], is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldMapRegisteredSubKeyPathsOfAnUnmappableDictionaryAndReturnTheResults +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:@"user"]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"nested_user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + NSDictionary *dictionary = [mapper.mappingResult dictionary]; + assertThatBool([dictionary isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); + RKTestUser *user = [dictionary objectForKey:@"user"]; + assertThat(user, isNot(nilValue())); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +#pragma mark Mapping Error States + +- (void)testShouldAddAnErrorWhenYouTryToMapAnArrayToATargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + mapper.targetObject = [RKTestUser user]; + [mapper start]; + assertThatInteger(mapper.error.code, is(equalToInt(RKMappingErrorTypeMismatch))); +} + +- (void)testShouldAddAnErrorWhenAttemptingToMapADictionaryWithoutAnObjectMapping +{ + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + assertThat([mapper.error localizedDescription], is(equalTo(@"Unable to find any mappings for the given content"))); +} + +- (void)testShouldAddAnErrorWhenAttemptingToMapACollectionWithoutAnObjectMapping +{ + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + assertThat([mapper.error localizedDescription], is(equalTo(@"Unable to find any mappings for the given content"))); +} + +#pragma mark RKMapperOperationDelegate Tests + +- (void)testShouldInformTheDelegateWhenMappingBegins +{ + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMapperOperationDelegate)]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [[mockDelegate expect] mapperWillStartMapping:mapper]; + mapper.delegate = mockDelegate; + [mapper start]; + [mockDelegate verify]; +} + +- (void)testShouldInformTheDelegateWhenMappingEnds +{ + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMapperOperationDelegate)]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [[mockDelegate stub] mapperWillStartMapping:mapper]; + [[mockDelegate expect] mapperDidFinishMapping:mapper]; + mapper.delegate = mockDelegate; + [mapper start]; + [mockDelegate verify]; +} + +- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsSuccessful +{ + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMapperOperationDelegate)]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [[mockDelegate expect] mapper:mapper didFindRespresentation:OCMOCK_ANY atKeyPath:nil]; + mapper.delegate = mockDelegate; + [mapper start]; + [mockDelegate verify]; +} + +- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsNotSuccessful +{ + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + [mappingsDictionary setObject:mapping forKey:@"users"]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMapperOperationDelegate)]; + [[mockDelegate expect] mapper:mapper didNotFindReprsentationAtKeyPath:@"users"]; + mapper.delegate = mockDelegate; + [mapper start]; + [mockDelegate verify]; +} + +- (void)testShouldNotifyTheDelegateWhenItDidMapAnObject +{ + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMapperOperationDelegate)]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [[mockDelegate expect] mapper:mapper didFinishMappingOperation:OCMOCK_ANY forKeyPath:nil]; + mapper.delegate = mockDelegate; + [mapper start]; + [mockDelegate verify]; +} + +- (BOOL)fakeValidateValue:(inout id *)ioValue forKeyPath:(NSString *)inKey error:(out NSError **)outError +{ + *outError = [NSError errorWithDomain:RKErrorDomain code:1234 userInfo:nil]; + return NO; +} + +- (void)testShouldNotifyTheDelegateWhenItFailedToMapAnObject +{ + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMapperOperationDelegate)]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:NSClassFromString(@"OCPartialMockObject")]; + [mapping addAttributeMappingsFromArray:@[@"name"]]; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:mapping forKey:[NSNull null]]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + RKTestUser *exampleUser = [[RKTestUser new] autorelease]; + id mockObject = [OCMockObject partialMockForObject:exampleUser]; + [[[mockObject expect] andCall:@selector(fakeValidateValue:forKeyPath:error:) onObject:self] validateValue:[OCMArg anyPointer] forKeyPath:OCMOCK_ANY error:[OCMArg anyPointer]]; + mapper.targetObject = mockObject; + [[mockDelegate expect] mapper:mapper didFailMappingOperation:OCMOCK_ANY forKeyPath:nil withError:OCMOCK_ANY]; + mapper.delegate = mockDelegate; + [mapper start]; + [mockObject verify]; + [mockDelegate verify]; +} + +#pragma mark - RKObjectMappingOperationTests + +- (void)testShouldBeAbleToMapADictionaryToAUser +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:123], @"id", @"Blake Watters", @"name", nil]; + RKTestUser *user = [RKTestUser user]; + + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + [operation start]; + assertThat(user.name, is(equalTo(@"Blake Watters"))); + assertThatInt([user.userID intValue], is(equalToInt(123))); + [operation release]; +} + +- (void)testShouldConsiderADictionaryContainingOnlyNullValuesForKeysMappable +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNull null], @"name", nil]; + RKTestUser *user = [RKTestUser user]; + + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + BOOL success = [operation performMapping:nil]; + assertThatBool(success, is(equalToBool(YES))); + assertThat(user.name, is(nilValue())); + [operation release]; +} + +- (void)testShouldBeAbleToMapAUserToADictionary +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"userID" toKeyPath:@"id"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + user.userID = [NSNumber numberWithInt:123]; + + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:user destinationObject:dictionary mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + BOOL success = [operation performMapping:nil]; + assertThatBool(success, is(equalToBool(YES))); + assertThat([dictionary valueForKey:@"name"], is(equalTo(@"Blake Watters"))); + assertThatInt([[dictionary valueForKey:@"id"] intValue], is(equalToInt(123))); + [operation release]; +} + +- (void)testShouldReturnNoWithoutErrorWhenGivenASourceObjectThatContainsNoMappableKeys +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; + RKTestUser *user = [RKTestUser user]; + + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + BOOL success = [operation performMapping:&error]; + assertThatBool(success, is(equalToBool(NO))); + assertThat(error, is(notNilValue())); + assertThatInteger(operation.error.code, is(equalToInteger(RKMappingErrorUnmappableContent))); +} + +- (void)testShouldInformTheDelegateOfAnErrorWhenMappingFailsBecauseThereIsNoMappableContent +{ + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMappingOperationDelegate)]; + + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; + RKTestUser *user = [RKTestUser user]; + + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + operation.delegate = mockDelegate; + BOOL success = [operation performMapping:nil]; + assertThatBool(success, is(equalToBool(NO))); + [mockDelegate verify]; +} + +- (void)testShouldSetTheErrorWhenMappingOperationFails +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + [mapping addPropertyMapping:idMapping]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"FAILURE", @"id", nil]; + RKTestUser *user = [RKTestUser user]; + id mockObject = [OCMockObject partialMockForObject:user]; + [[[mockObject expect] andCall:@selector(fakeValidateValue:forKeyPath:error:) onObject:self] validateValue:[OCMArg anyPointer] forKeyPath:OCMOCK_ANY error:[OCMArg anyPointer]]; + + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockObject mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + assertThat(error, isNot(nilValue())); + [operation release]; +} + +#pragma mark - Attribute Mapping + +- (void)testShouldMapAStringToADateAttribute +{ + [RKObjectMapping resetDefaultDateFormatters]; + + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *birthDateMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; + [mapping addPropertyMapping:birthDateMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; + dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; + [dateFormatter setDateFormat:@"MM/dd/yyyy"]; + assertThat([dateFormatter stringFromDate:user.birthDate], is(equalTo(@"11/27/1982"))); +} + +- (void)testShouldMapStringToURL +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"website" toKeyPath:@"website"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThat(user.website, isNot(nilValue())); + assertThatBool([user.website isKindOfClass:[NSURL class]], is(equalToBool(YES))); + assertThat([user.website absoluteString], is(equalTo(@"http://restkit.org/"))); +} + +- (void)testShouldMapAStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); +} + +- (void)testShouldMapAShortTrueStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; + [dictionary setValue:@"T" forKey:@"is_developer"]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); +} + +- (void)testShouldMapAShortFalseStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; + [dictionary setValue:@"f" forKey:@"is_developer"]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThatBool([[user isDeveloper] boolValue], is(equalToBool(NO))); +} + +- (void)testShouldMapAYesStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; + [dictionary setValue:@"yes" forKey:@"is_developer"]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); +} + +- (void)testShouldMapANoStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; + [dictionary setValue:@"NO" forKey:@"is_developer"]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThatBool([[user isDeveloper] boolValue], is(equalToBool(NO))); +} + +- (void)testShouldMapAStringToANumber +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"lucky_number" toKeyPath:@"luckyNumber"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThatInt([user.luckyNumber intValue], is(equalToInt(187))); +} + +- (void)testShouldMapAStringToADecimalNumber +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"weight" toKeyPath:@"weight"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + NSDecimalNumber *weight = user.weight; + assertThatBool([weight isKindOfClass:[NSDecimalNumber class]], is(equalToBool(YES))); + assertThatInteger([weight compare:[NSDecimalNumber decimalNumberWithString:@"131.3"]], is(equalToInt(NSOrderedSame))); +} + +- (void)testShouldMapANumberToAString +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"lucky_number" toKeyPath:@"name"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThat(user.name, is(equalTo(@"187"))); +} + +- (void)testShouldMapANumberToANSDecimalNumber +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *websiteMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"lucky_number" toKeyPath:@"weight"]; + [mapping addPropertyMapping:websiteMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + NSDecimalNumber *weight = user.weight; + assertThatBool([weight isKindOfClass:[NSDecimalNumber class]], is(equalToBool(YES))); + assertThatInteger([weight compare:[NSDecimalNumber decimalNumberWithString:@"187"]], is(equalToInt(NSOrderedSame))); +} + +- (void)testShouldMapANumberToADate +{ + NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; + [dateFormatter setDateFormat:@"MM/dd/yyyy"]; + NSDate *date = [dateFormatter dateFromString:@"11/27/1982"]; + + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *birthDateMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"dateAsNumber" toKeyPath:@"birthDate"]; + [mapping addPropertyMapping:birthDateMapping]; + + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary setValue:[NSNumber numberWithInt:[date timeIntervalSince1970]] forKey:@"dateAsNumber"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThat([dateFormatter stringFromDate:user.birthDate], is(equalTo(@"11/27/1982"))); +} + +- (void)testShouldMapANestedKeyPathToAnAttribute +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *countryMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"address.country" toKeyPath:@"country"]; + [mapping addPropertyMapping:countryMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + assertThat(user.country, is(equalTo(@"USA"))); +} + +- (void)testShouldMapANestedArrayOfStringsToAnAttribute +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *countryMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"interests" toKeyPath:@"interests"]; + [mapping addPropertyMapping:countryMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + NSArray *interests = [NSArray arrayWithObjects:@"Hacking", @"Running", nil]; + assertThat(user.interests, is(equalTo(interests))); +} + +- (void)testShouldMapANestedDictionaryToAnAttribute +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *countryMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"address" toKeyPath:@"addressDictionary"]; + [mapping addPropertyMapping:countryMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + + NSDictionary *address = @{ + @"city": @"Carrboro", + @"state": @"North Carolina", + @"id": [NSNumber numberWithInt:1234], + @"country": @"USA"}; + assertThat(user.addressDictionary, is(equalTo(address))); +} + +- (void)testShouldNotSetAPropertyWhenTheValueIsTheSame +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser reject] setName:OCMOCK_ANY]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; +} + +- (void)testShouldNotSetTheDestinationPropertyWhenBothAreNil +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary setValue:[NSNull null] forKey:@"name"]; + RKTestUser *user = [RKTestUser user]; + user.name = nil; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser reject] setName:OCMOCK_ANY]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; +} + +- (void)testShouldSetNilForNSNullValues +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary setValue:[NSNull null] forKey:@"name"]; + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser expect] setName:nil]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + NSError *error = nil; + [operation performMapping:&error]; + [mockUser verify]; +} + +- (void)testDelegateIsInformedWhenANilValueIsMappedForNSNullWithExistingValue +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary setValue:[NSNull null] forKey:@"name"]; + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKMappingOperationDelegate)]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + operation.delegate = mockDelegate; + NSError *error = nil; + [[mockDelegate expect] mappingOperation:operation didFindMapping:nameMapping forKeyPath:@"name"]; + [[mockDelegate expect] mappingOperation:operation didSetValue:nil forKeyPath:@"name" usingMapping:nameMapping]; + operation.dataSource = dataSource; + [operation performMapping:&error]; + [mockDelegate verify]; +} + +- (void)testDelegateIsInformedWhenUnchangedValueIsSkipped +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary setValue:@"Blake Watters" forKey:@"name"]; + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKMappingOperationDelegate)]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + operation.delegate = mockDelegate; + NSError *error = nil; + [[mockDelegate expect] mappingOperation:operation didFindMapping:nameMapping forKeyPath:@"name"]; + [[mockDelegate expect] mappingOperation:operation didNotSetUnchangedValue:@"Blake Watters" forKeyPath:@"name" usingMapping:nameMapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + [operation performMapping:&error]; + [mockDelegate verify]; +} + +- (void)testShouldOptionallySetDefaultValueForAMissingKeyPath +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary removeObjectForKey:@"name"]; + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser expect] setName:nil]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + id mockMapping = [OCMockObject partialMockForObject:mapping]; + BOOL returnValue = YES; + [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] shouldSetDefaultValueForMissingAttributes]; + NSError *error = nil; + [operation performMapping:&error]; + [mockUser verify]; +} + +- (void)testShouldOptionallyIgnoreAMissingSourceKeyPath +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [mapping addPropertyMapping:nameMapping]; + + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary removeObjectForKey:@"name"]; + RKTestUser *user = [RKTestUser user]; + user.name = @"Blake Watters"; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser reject] setName:nil]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + id mockMapping = [OCMockObject partialMockForObject:mapping]; + BOOL returnValue = NO; + [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] shouldSetDefaultValueForMissingAttributes]; + NSError *error = nil; + [operation performMapping:&error]; + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +#pragma mark - Relationship Mapping + +- (void)testShouldMapANestedObject +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKAttributeMapping *cityMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"city" toKeyPath:@"city"]; + [addressMapping addPropertyMapping:cityMapping]; + + RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + [userMapping addPropertyMapping:hasOneMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; + assertThatBool(success, is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); + assertThat(user.address, isNot(nilValue())); +} + +- (void)testShouldMapANestedObjectToCollection +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKAttributeMapping *cityMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"city" toKeyPath:@"city"]; + [addressMapping addPropertyMapping:cityMapping]; + + RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"friends" withMapping:addressMapping]; + [userMapping addPropertyMapping:hasOneMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; + assertThatBool(success, is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); + assertThat(user.friends, isNot(nilValue())); + assertThatUnsignedInteger([user.friends count], is(equalToInt(1))); +} + +- (void)testShouldMapANestedObjectToOrderedSetCollection +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKAttributeMapping *cityMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"city" toKeyPath:@"city"]; + [addressMapping addPropertyMapping:cityMapping]; + + RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"friendsOrderedSet" withMapping:addressMapping]; + [userMapping addPropertyMapping:hasOneMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; + assertThatBool(success, is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); + assertThat(user.friendsOrderedSet, isNot(nilValue())); + assertThatUnsignedInteger([user.friendsOrderedSet count], is(equalToInt(1))); +} + +- (void)testShouldMapANestedObjectCollection +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + + RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; + [userMapping addPropertyMapping:hasManyMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; + assertThatBool(success, is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); + assertThat(user.friends, isNot(nilValue())); + assertThatUnsignedInteger([user.friends count], is(equalToInt(2))); + NSArray *names = [NSArray arrayWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; + assertThat([user.friends valueForKey:@"name"], is(equalTo(names))); +} + +- (void)testShouldMapANestedArrayIntoASet +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + + RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"friends" toKeyPath:@"friendsSet" withMapping:userMapping]; + [userMapping addPropertyMapping:hasManyMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; + assertThatBool(success, is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); + assertThat(user.friendsSet, isNot(nilValue())); + assertThatBool([user.friendsSet isKindOfClass:[NSSet class]], is(equalToBool(YES))); + assertThatUnsignedInteger([user.friendsSet count], is(equalToInt(2))); + NSSet *names = [NSSet setWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; + assertThat([user.friendsSet valueForKey:@"name"], is(equalTo(names))); +} + +- (void)testShouldMapANestedArrayIntoAnOrderedSet +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + + RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"friends" toKeyPath:@"friendsOrderedSet" withMapping:userMapping]; + [userMapping addPropertyMapping:hasManyMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; + assertThatBool(success, is(equalToBool(YES))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); + assertThat(user.friendsOrderedSet, isNot(nilValue())); + assertThatBool([user.friendsOrderedSet isKindOfClass:[NSOrderedSet class]], is(equalToBool(YES))); + assertThatUnsignedInteger([user.friendsOrderedSet count], is(equalToInt(2))); + NSOrderedSet *names = [NSOrderedSet orderedSetWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; + assertThat([user.friendsOrderedSet valueForKey:@"name"], is(equalTo(names))); +} + +- (void)testShouldNotSetThePropertyWhenTheNestedObjectIsIdentical +{ + RKTestUser *user = [RKTestUser user]; + RKTestAddress *address = [RKTestAddress address]; + address.addressID = [NSNumber numberWithInt:1234]; + user.address = address; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser reject] setAddress:OCMOCK_ANY]; + + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + [addressMapping addPropertyMapping:idMapping]; + + RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + [userMapping addPropertyMapping:hasOneMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; +} + +- (void)testSkippingOfIdenticalObjectsInformsDelegate +{ + RKTestUser *user = [RKTestUser user]; + RKTestAddress *address = [RKTestAddress address]; + address.addressID = [NSNumber numberWithInt:1234]; + user.address = address; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser reject] setAddress:OCMOCK_ANY]; + + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + [addressMapping addPropertyMapping:idMapping]; + + RKRelationshipMapping *hasOneMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + [userMapping addPropertyMapping:hasOneMapping]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:userInfo destinationObject:user mapping:userMapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKMappingOperationDelegate)]; + [[mockDelegate expect] mappingOperation:operation didNotSetUnchangedValue:address forKeyPath:@"address" usingMapping:hasOneMapping]; + operation.delegate = mockDelegate; + [operation performMapping:nil]; + [mockDelegate verify]; +} + +- (void)testShouldNotSetThePropertyWhenTheNestedObjectCollectionIsIdentical +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"userID"]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:idMapping]; + [userMapping addPropertyMapping:nameMapping]; + + RKRelationshipMapping *hasManyMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; + [userMapping addPropertyMapping:hasManyMapping]; + + RKMapperOperation *mapper = [RKMapperOperation new]; + mapper.mappingOperationDataSource = [[RKObjectMappingOperationDataSource new] autorelease]; + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + + // Set the friends up + RKTestUser *jeremy = [RKTestUser user]; + jeremy.name = @"Jeremy Ellison"; + jeremy.userID = [NSNumber numberWithInt:187]; + RKTestUser *rachit = [RKTestUser user]; + rachit.name = @"Rachit Shukla"; + rachit.userID = [NSNumber numberWithInt:7]; + user.friends = [NSArray arrayWithObjects:jeremy, rachit, nil]; + + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser reject] setFriends:OCMOCK_ANY]; + [mapper mapFromObject:userInfo toObject:mockUser atKeyPath:@"" usingMapping:userMapping]; + [mapper release]; + [mockUser verify]; +} + +- (void)testShouldOptionallyNilOutTheRelationshipIfItIsMissing +{ + RKTestUser *user = [RKTestUser user]; + RKTestAddress *address = [RKTestAddress address]; + address.addressID = [NSNumber numberWithInt:1234]; + user.address = address; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser expect] setAddress:nil]; + + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + [addressMapping addPropertyMapping:idMapping]; + RKRelationshipMapping *relationshipMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + [userMapping addPropertyMapping:relationshipMapping]; + + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary removeObjectForKey:@"address"]; + id mockMapping = [OCMockObject partialMockForObject:userMapping]; + BOOL returnValue = YES; + [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] setNilForMissingRelationships]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + + NSError *error = nil; + [operation performMapping:&error]; + [mockUser verify]; +} + +- (void)testShouldNotNilOutTheRelationshipIfItIsMissingAndCurrentlyNilOnTheTargetObject +{ + RKTestUser *user = [RKTestUser user]; + user.address = nil; + id mockUser = [OCMockObject partialMockForObject:user]; + [[mockUser reject] setAddress:nil]; + + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *nameMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"name"]; + [userMapping addPropertyMapping:nameMapping]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKAttributeMapping *idMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + [addressMapping addPropertyMapping:idMapping]; + RKRelationshipMapping *relationshipMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + [userMapping addPropertyMapping:relationshipMapping]; + + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + [dictionary removeObjectForKey:@"address"]; + id mockMapping = [OCMockObject partialMockForObject:userMapping]; + BOOL returnValue = YES; + [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] setNilForMissingRelationships]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + + NSError *error = nil; + [operation performMapping:&error]; + [mockUser verify]; +} + +#pragma mark - RKDynamicMapping + +- (void)testShouldMapASingleObjectDynamically +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + [dynamicMapping setObjectMappingForDataBlock:^RKObjectMapping *(id mappableData) { + if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { + return boyMapping; + } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { + return girlMapping; + } + + return nil; + }]; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + Boy *user = [mapper.mappingResult firstObject]; + assertThat(user, is(instanceOf([Boy class]))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldMapASingleObjectDynamicallyWithADeclarativeMatcher +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; + [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + Boy *user = [mapper.mappingResult firstObject]; + assertThat(user, is(instanceOf([Boy class]))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldACollectionOfObjectsDynamically +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; + [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"mixed.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + NSArray *objects = [mapper.mappingResult array]; + assertThat(objects, hasCountOf(2)); + assertThat([objects objectAtIndex:0], is(instanceOf([Boy class]))); + assertThat([objects objectAtIndex:1], is(instanceOf([Girl class]))); + Boy *boy = [objects objectAtIndex:0]; + Girl *girl = [objects objectAtIndex:1]; + assertThat(boy.name, is(equalTo(@"Blake Watters"))); + assertThat(girl.name, is(equalTo(@"Sarah"))); +} + +- (void)testShouldMapARelationshipDynamically +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; + [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; + [boyMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:dynamicMapping]];; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"friends.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + Boy *blake = [mapper.mappingResult firstObject]; + NSArray *friends = blake.friends; + + assertThat(friends, hasCountOf(2)); + assertThat([friends objectAtIndex:0], is(instanceOf([Boy class]))); + assertThat([friends objectAtIndex:1], is(instanceOf([Girl class]))); + Boy *boy = [friends objectAtIndex:0]; + Girl *girl = [friends objectAtIndex:1]; + assertThat(boy.name, is(equalTo(@"John Doe"))); + assertThat(girl.name, is(equalTo(@"Jane Doe"))); +} + +- (void)testShouldBeAbleToDeclineMappingAnObjectByReturningANilObjectMapping +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { + if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { + return boyMapping; + } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { + // NO GIRLS ALLOWED(*$!)(* + return nil; + } + + return nil; + }; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"mixed.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + NSArray *boys = [mapper.mappingResult array]; + assertThat(boys, hasCountOf(1)); + Boy *user = [boys objectAtIndex:0]; + assertThat(user, is(instanceOf([Boy class]))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldBeAbleToDeclineMappingObjectsInARelationshipByReturningANilObjectMapping +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { + if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { + return boyMapping; + } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { + // NO GIRLS ALLOWED(*$!)(* + return nil; + } + + return nil; + }; + [boyMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:dynamicMapping]];; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"friends.json"]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + [mapper start]; + Boy *blake = [mapper.mappingResult firstObject]; + assertThat(blake, is(notNilValue())); + assertThat(blake.name, is(equalTo(@"Blake Watters"))); + assertThat(blake, is(instanceOf([Boy class]))); + NSArray *friends = blake.friends; + + assertThat(friends, hasCountOf(1)); + assertThat([friends objectAtIndex:0], is(instanceOf([Boy class]))); + Boy *boy = [friends objectAtIndex:0]; + assertThat(boy.name, is(equalTo(@"John Doe"))); +} + +- (void)testShouldMapATargetObjectWithADynamicMapping +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { + if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { + return boyMapping; + } + + return nil; + }; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; + Boy *blake = [[Boy new] autorelease]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + mapper.targetObject = blake; + [mapper start]; + Boy *user = [mapper.mappingResult firstObject]; + assertThat(user, is(instanceOf([Boy class]))); + assertThat(user.name, is(equalTo(@"Blake Watters"))); +} + +- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsNil +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; + [boyMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { + return nil; + }; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; + Boy *blake = [[Boy new] autorelease]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + mapper.targetObject = blake; + [mapper start]; + Boy *user = [mapper.mappingResult firstObject]; + assertThat(user, is(nilValue())); + assertThat(mapper.error, is(notNilValue())); +} + +- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsTheIncorrectType +{ + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + [girlMapping addAttributeMappingsFromArray:@[@"name"]]; + RKDynamicMapping *dynamicMapping = [RKDynamicMapping new]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { + if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { + return girlMapping; + } + + return nil; + }; + + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:dynamicMapping forKey:@""]; + + id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"girl.json"]; + Boy *blake = [[Boy new] autorelease]; + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:userInfo mappingsDictionary:mappingsDictionary]; + mapper.targetObject = blake; + [mapper start]; + Boy *user = [mapper.mappingResult firstObject]; + assertThat(user, is(nilValue())); + assertThat(mapper.error, is(notNilValue())); +} + +#pragma mark - Date and Time Formatting + +- (void)testShouldAutoConfigureDefaultDateFormatters +{ + [RKObjectMapping resetDefaultDateFormatters]; + NSArray *dateFormatters = [RKObjectMapping defaultDateFormatters]; + assertThat(dateFormatters, hasCountOf(4)); + assertThat([[dateFormatters objectAtIndex:0] dateFormat], is(equalTo(@"yyyy-MM-dd'T'HH:mm:ss'Z'"))); + assertThat([[dateFormatters objectAtIndex:1] dateFormat], is(equalTo(@"MM/dd/yyyy"))); + NSTimeZone *UTCTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; + assertThat([[dateFormatters objectAtIndex:0] timeZone], is(equalTo(UTCTimeZone))); + assertThat([[dateFormatters objectAtIndex:1] timeZone], is(equalTo(UTCTimeZone))); +} + +- (void)testShouldLetYouSetTheDefaultDateFormatters +{ + NSDateFormatter *dateFormatter = [NSDateFormatter new]; + NSArray *dateFormatters = [NSArray arrayWithObject:dateFormatter]; + [RKObjectMapping setDefaultDateFormatters:dateFormatters]; + assertThat([RKObjectMapping defaultDateFormatters], is(equalTo(dateFormatters))); +} + +- (void)testShouldLetYouAppendADateFormatterToTheList +{ + [RKObjectMapping resetDefaultDateFormatters]; + assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(4)); + NSDateFormatter *dateFormatter = [NSDateFormatter new]; + [RKObjectMapping addDefaultDateFormatter:dateFormatter]; + assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(5)); +} + +- (void)testShouldAllowNewlyAddedDateFormatterToRunFirst +{ + [RKObjectMapping setDefaultDateFormatters:nil]; + NSDateFormatter *newDateFormatter = [[NSDateFormatter new] autorelease]; + [newDateFormatter setDateFormat:@"dd/MM/yyyy"]; + [RKObjectMapping addDefaultDateFormatter:newDateFormatter]; + + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *birthDateMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"favorite_date" toKeyPath:@"favoriteDate"]; + [mapping addPropertyMapping:birthDateMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + [operation performMapping:&error]; + + NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; + dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; + [dateFormatter setDateFormat:@"MM/dd/yyyy"]; + + /* + If RKObjectMappingOperation is using the date formatter set above, we're + going to get a really wonky date, which is what we are testing for. + */ + assertThat([dateFormatter stringFromDate:user.favoriteDate], is(equalTo(@"01/03/2012"))); +} + +- (void)testShouldLetYouConfigureANewDateFormatterFromAStringAndATimeZone +{ + [RKObjectMapping resetDefaultDateFormatters]; + assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(4)); + NSTimeZone *EDTTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"]; + [RKObjectMapping addDefaultDateFormatterForString:@"mm/dd/YYYY" inTimeZone:EDTTimeZone]; + assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(5)); + NSDateFormatter *dateFormatter = [[RKObjectMapping defaultDateFormatters] objectAtIndex:0]; + assertThat(dateFormatter.timeZone, is(equalTo(EDTTimeZone))); +} + +- (void)testShouldReturnNilForEmptyDateValues +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKAttributeMapping *birthDateMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; + [mapping addPropertyMapping:birthDateMapping]; + + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + NSMutableDictionary *mutableDictionary = [dictionary mutableCopy]; + [mutableDictionary setValue:@"" forKey:@"birthdate"]; + RKTestUser *user = [RKTestUser user]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:mutableDictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new]; + operation.dataSource = dataSource; + [mutableDictionary release]; + NSError *error = nil; + [operation performMapping:&error]; + + assertThat(user.birthDate, is(equalTo(nil))); +} + +- (void)testShouldConfigureANewDateFormatterInTheUTCTimeZoneIfPassedANilTimeZone +{ + [RKObjectMapping resetDefaultDateFormatters]; + assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(4)); + [RKObjectMapping addDefaultDateFormatterForString:@"mm/dd/YYYY" inTimeZone:nil]; + assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(5)); + NSDateFormatter *dateFormatter = [[RKObjectMapping defaultDateFormatters] objectAtIndex:0]; + NSTimeZone *UTCTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; + assertThat(dateFormatter.timeZone, is(equalTo(UTCTimeZone))); +} + +#pragma mark - Object Serialization +// TODO: Move to RKObjectSerializerTest + +- (void)testShouldSerializeHasOneRelatioshipsToJSON +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + [userMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + [addressMapping addAttributeMappingsFromArray:@[@"city", @"state"]]; + [userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]]; + + RKTestUser *user = [RKTestUser new]; + user.name = @"Blake Watters"; + RKTestAddress *address = [RKTestAddress new]; + address.state = @"North Carolina"; + user.address = address; + + RKObjectMapping *serializationMapping = [userMapping inverseMapping]; + NSDictionary *params = [RKObjectParameterization parametersWithObject:user requestDescriptor:[RKRequestDescriptor requestDescriptorWithMapping:serializationMapping objectClass:[RKTestUser class] rootKeyPath:nil] error:nil]; + NSError *error = nil; + NSString *JSON = [[NSString alloc] initWithData:[RKMIMETypeSerialization dataFromObject:params MIMEType:RKMIMETypeJSON error:nil] encoding:NSUTF8StringEncoding]; + assertThat(error, is(nilValue())); + assertThat(JSON, is(equalTo(@"{\"name\":\"Blake Watters\",\"address\":{\"state\":\"North Carolina\"}}"))); +} + +- (void)testShouldSerializeHasManyRelationshipsToJSON +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + [userMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + [addressMapping addAttributeMappingsFromArray:@[@"city", @"state"]]; + [userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:addressMapping]]; + + RKTestUser *user = [RKTestUser new]; + user.name = @"Blake Watters"; + RKTestAddress *address1 = [RKTestAddress new]; + address1.city = @"Carrboro"; + RKTestAddress *address2 = [RKTestAddress new]; + address2.city = @"New York City"; + user.friends = [NSArray arrayWithObjects:address1, address2, nil]; + + + RKObjectMapping *serializationMapping = [userMapping inverseMapping]; + NSDictionary *params = [RKObjectParameterization parametersWithObject:user requestDescriptor:[RKRequestDescriptor requestDescriptorWithMapping:serializationMapping objectClass:[RKTestUser class] rootKeyPath:nil] error:nil]; + NSError *error = nil; + NSString *JSON = [[NSString alloc] initWithData:[RKMIMETypeSerialization dataFromObject:params MIMEType:RKMIMETypeJSON error:nil] encoding:NSUTF8StringEncoding]; + assertThat(error, is(nilValue())); + assertThat(JSON, is(equalTo(@"{\"name\":\"Blake Watters\",\"friends\":[{\"city\":\"Carrboro\"},{\"city\":\"New York City\"}]}"))); +} + +- (void)testShouldSerializeManagedHasManyRelationshipsToJSON +{ + RKManagedObjectStore *managedObjectStore = [RKTestFactory managedObjectStore]; + RKObjectMapping *humanMapping = [RKObjectMapping mappingForClass:[RKHuman class]]; + [humanMapping addAttributeMappingsFromArray:@[@"name"]]; + RKObjectMapping *catMapping = [RKObjectMapping mappingForClass:[RKCat class]]; + [catMapping addAttributeMappingsFromArray:@[@"name"]]; + [humanMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"cats" toKeyPath:@"cats" withMapping:catMapping]]; + + RKHuman *blake = [NSEntityDescription insertNewObjectForEntityForName:@"RKHuman" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; + blake.name = @"Blake Watters"; + RKCat *asia = [NSEntityDescription insertNewObjectForEntityForName:@"RKCat" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; + asia.name = @"Asia"; + RKCat *roy = [NSEntityDescription insertNewObjectForEntityForName:@"RKCat" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; + roy.name = @"Roy"; + blake.cats = [NSSet setWithObjects:asia, roy, nil]; + + RKObjectMapping *serializationMapping = [humanMapping inverseMapping]; + + NSDictionary *params = [RKObjectParameterization parametersWithObject:blake requestDescriptor:[RKRequestDescriptor requestDescriptorWithMapping:serializationMapping objectClass:[RKHuman class] rootKeyPath:nil] error:nil]; + NSError *error = nil; + NSDictionary *parsedJSON = [NSJSONSerialization JSONObjectWithData:[RKMIMETypeSerialization dataFromObject:params MIMEType:RKMIMETypeJSON error:nil] options:0 error:nil]; + assertThat(error, is(nilValue())); + assertThat([parsedJSON valueForKey:@"name"], is(equalTo(@"Blake Watters"))); + NSArray *catNames = [[parsedJSON valueForKeyPath:@"cats.name"] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; + assertThat(catNames, is(equalTo([NSArray arrayWithObjects:@"Asia", @"Roy", nil]))); +} + +- (void)testUpdatingArrayOfExistingCats +{ + RKManagedObjectStore *managedObjectStore = [RKTestFactory managedObjectStore]; + NSArray *array = [RKTestFixture parsedObjectWithContentsOfFixture:@"ArrayOfHumans.json"]; + RKEntityMapping *humanMapping = [RKEntityMapping mappingForEntityForName:@"RKHuman" inManagedObjectStore:managedObjectStore]; + [humanMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; + humanMapping.primaryKeyAttribute = @"railsID"; + NSMutableDictionary *mappingsDictionary = [NSMutableDictionary dictionary]; + [mappingsDictionary setObject:humanMapping forKey:@"human"]; + + // Create instances that should match the fixture + RKHuman *human1 = [NSEntityDescription insertNewObjectForEntityForName:@"RKHuman" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; + human1.railsID = [NSNumber numberWithInt:201]; + RKHuman *human2 = [NSEntityDescription insertNewObjectForEntityForName:@"RKHuman" inManagedObjectContext:managedObjectStore.primaryManagedObjectContext]; + human2.railsID = [NSNumber numberWithInt:202]; + [managedObjectStore.primaryManagedObjectContext save:nil]; + + RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithObject:array mappingsDictionary:mappingsDictionary]; + RKFetchRequestManagedObjectCache *managedObjectCache = [[RKFetchRequestManagedObjectCache alloc] init]; + mapper.mappingOperationDataSource = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:managedObjectStore.primaryManagedObjectContext + cache:managedObjectCache]; + + [mapper start]; + RKMappingResult *result = mapper.mappingResult; + assertThat(result, is(notNilValue())); + + NSArray *humans = [result array]; + assertThat(humans, hasCountOf(2)); + assertThat([humans objectAtIndex:0], is(equalTo(human1))); + assertThat([humans objectAtIndex:1], is(equalTo(human2))); +} @end diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m index 9fb1d3be..673ff8eb 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m @@ -77,7 +77,7 @@ - (void)testShouldNotUpdateEqualURLProperties { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"url", nil]; + [mapping addAttributeMappingsFromArray:@[@"url"]]; NSURL *url1 = [NSURL URLWithString:@"http://www.restkit.org"]; NSURL *url2 = [NSURL URLWithString:@"http://www.restkit.org"]; assertThatBool(url1 == url2, is(equalToBool(NO))); @@ -86,7 +86,8 @@ NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:url2, @"url", nil]; RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - BOOL success = [operation performMapping:nil]; + [operation start]; + BOOL success = (operation.error == nil); assertThatBool(success, is(equalToBool(YES))); assertThatBool(object.url == url1, is(equalToBool(YES))); [operation release]; @@ -95,14 +96,15 @@ - (void)testShouldSuccessfullyMapBoolsToStrings { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"boolString", nil]; + [mapping addAttributeMappingsFromArray:@[@"boolString"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; - id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; - id data = [parser objectFromString:@"{\"boolString\":true}" error:nil]; + NSData *data = [@"{\"boolString\":true}" dataUsingEncoding:NSUTF8StringEncoding]; + id deserializedObject = [RKMIMETypeSerialization objectFromData:data MIMEType:RKMIMETypeJSON error:nil]; - RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; - BOOL success = [operation performMapping:nil]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:deserializedObject destinationObject:object mapping:mapping]; + [operation start]; + BOOL success = (operation.error == nil); assertThatBool(success, is(equalToBool(YES))); assertThat(object.boolString, is(equalTo(@"true"))); [operation release]; @@ -111,14 +113,15 @@ - (void)testShouldSuccessfullyMapTrueBoolsToNSNumbers { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"boolNumber", nil]; + [mapping addAttributeMappingsFromArray:@[@"boolNumber"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; - id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; - id data = [parser objectFromString:@"{\"boolNumber\":true}" error:nil]; + NSData *data = [@"{\"boolNumber\":true}" dataUsingEncoding:NSUTF8StringEncoding]; + id deserializedObject = [RKMIMETypeSerialization objectFromData:data MIMEType:RKMIMETypeJSON error:nil]; - RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; - BOOL success = [operation performMapping:nil]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:deserializedObject destinationObject:object mapping:mapping]; + [operation start]; + BOOL success = (operation.error == nil); assertThatBool(success, is(equalToBool(YES))); assertThatInt([object.boolNumber intValue], is(equalToInt(1))); [operation release]; @@ -127,14 +130,15 @@ - (void)testShouldSuccessfullyMapFalseBoolsToNSNumbers { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"boolNumber", nil]; + [mapping addAttributeMappingsFromArray:@[@"boolNumber"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; + + NSData *data = [@"{\"boolNumber\":false}" dataUsingEncoding:NSUTF8StringEncoding]; + id deserializedObject = [RKMIMETypeSerialization objectFromData:data MIMEType:RKMIMETypeJSON error:nil]; - id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; - id data = [parser objectFromString:@"{\"boolNumber\":false}" error:nil]; - - RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; - BOOL success = [operation performMapping:nil]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:deserializedObject destinationObject:object mapping:mapping]; + [operation start]; + BOOL success = (operation.error == nil); assertThatBool(success, is(equalToBool(YES))); assertThatInt([object.boolNumber intValue], is(equalToInt(0))); [operation release]; @@ -143,14 +147,15 @@ - (void)testShouldSuccessfullyMapNumbersToStrings { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapKeyPath:@"number" toAttribute:@"boolString"]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"number" toKeyPath:@"boolString"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; - id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; - id data = [parser objectFromString:@"{\"number\":123}" error:nil]; + NSData *data = [@"{\"number\":123}" dataUsingEncoding:NSUTF8StringEncoding]; + id deserializedObject = [RKMIMETypeSerialization objectFromData:data MIMEType:RKMIMETypeJSON error:nil]; - RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; - BOOL success = [operation performMapping:nil]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:deserializedObject destinationObject:object mapping:mapping]; + [operation start]; + BOOL success = (operation.error == nil); assertThatBool(success, is(equalToBool(YES))); assertThat(object.boolString, is(equalTo(@"123"))); [operation release]; @@ -159,13 +164,13 @@ - (void)testShouldSuccessfullyMapArraysToOrderedSets { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapKeyPath:@"numbers" toAttribute:@"orderedSet"]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"numbers" toKeyPath:@"orderedSet"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; + + NSData *data = [@"{\"numbers\":[1, 2, 3]}" dataUsingEncoding:NSUTF8StringEncoding]; + id deserializedObject = [RKMIMETypeSerialization objectFromData:data MIMEType:RKMIMETypeJSON error:nil]; - id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; - id data = [parser objectFromString:@"{\"numbers\":[1, 2, 3]}" error:nil]; - - RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; + RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:deserializedObject destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); NSOrderedSet *expectedSet = [NSOrderedSet orderedSetWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil]; @@ -176,7 +181,7 @@ - (void)testShouldSuccessfullyMapOrderedSetsToArrays { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapKeyPath:@"orderedSet" toAttribute:@"array"]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"orderedSet" toKeyPath:@"array"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; TestMappable *data = [[[TestMappable alloc] init] autorelease]; @@ -193,7 +198,7 @@ - (void)testShouldFailTheMappingOperationIfKeyValueValidationSetsAnError { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"boolString", nil]; + [mapping addAttributeMappingsFromArray:@[@"boolString"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"FAIL" forKey:@"boolString"]; RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; @@ -207,7 +212,7 @@ - (void)testShouldNotSetTheAttributeIfKeyValueValidationReturnsNo { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"boolString", nil]; + [mapping addAttributeMappingsFromArray:@[@"boolString"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"should not change"; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"REJECT" forKey:@"boolString"]; @@ -222,7 +227,7 @@ - (void)testModifyingValueWithinKeyValueValidationIsRespected { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"boolString", nil]; + [mapping addAttributeMappingsFromArray:@[@"boolString"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"MODIFY" forKey:@"boolString"]; RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; @@ -238,7 +243,7 @@ - (void)testShouldMapAUTCDateWithoutChangingTheTimeZone { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"date", nil]; + [mapping addAttributeMappingsFromArray:@[@"date"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"2011-07-07T04:35:28Z" forKey:@"date"]; RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; @@ -253,7 +258,7 @@ - (void)testShouldMapAUnixTimestampStringAppropriately { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"date", nil]; + [mapping addAttributeMappingsFromArray:@[@"date"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"457574400" forKey:@"date"]; RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; @@ -268,7 +273,7 @@ - (void)testShouldMapASimpleDateStringAppropriately { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"date", nil]; + [mapping addAttributeMappingsFromArray:@[@"date"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"08/09/2011" forKey:@"date"]; RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; @@ -283,7 +288,7 @@ - (void)testShouldMapAISODateStringAppropriately { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"date", nil]; + [mapping addAttributeMappingsFromArray:@[@"date"]]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"2011-08-09T00:00Z" forKey:@"date"]; RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; @@ -302,7 +307,7 @@ dateFormatter.dateFormat = @"MM-dd-yyyy"; dateFormatter.timeZone = EDTTimeZone; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapAttributes:@"date", nil]; + [mapping addAttributeMappingsFromArray:@[@"date"]]; mapping.dateFormatters = [NSArray arrayWithObject:dateFormatter]; TestMappable *object = [[[TestMappable alloc] init] autorelease]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"11-27-1982" forKey:@"date"]; @@ -319,7 +324,7 @@ - (void)testShouldMapADateToAStringUsingThePreferredDateFormatter { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; - [mapping mapKeyPath:@"date" toAttribute:@"boolString"]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"date" toKeyPath:@"boolString"]]; NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; dateFormatter.dateFormat = @"MM-dd-yyyy"; dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; @@ -337,7 +342,7 @@ - (void)testShouldGenerateAnUnknownKeyPathExceptionWhenIgnoreUnknownKeyPathsIsNO { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [mapping mapAttributes:@"invalid", @"boolString", nil]; + [mapping addAttributeMappingsFromArray:@[@"invalid", @"boolString"]]; mapping.ignoreUnknownKeyPaths = NO; TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"test"; @@ -361,7 +366,7 @@ - (void)testShouldOptionallyIgnoreUnknownKeyPathAttributes { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [mapping mapAttributes:@"invalid", @"boolString", nil]; + [mapping addAttributeMappingsFromArray:@[@"invalid", @"boolString"]]; mapping.ignoreUnknownKeyPaths = YES; TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"test"; @@ -386,8 +391,8 @@ - (void)testShouldOptionallyIgnoreUnknownKeyPathRelationships { RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [mapping mapAttributes:@"boolString", nil]; - [mapping mapRelationship:@"invalid" withMapping:[RKObjectMapping mappingForClass:[TestMappable class]]]; + [mapping addAttributeMappingsFromArray:@[@"boolString"]]; + [mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"invalid" toKeyPath:@"invalid" withMapping:[RKObjectMapping mappingForClass:[TestMappable class]]]]; mapping.ignoreUnknownKeyPaths = YES; TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"test"; @@ -415,10 +420,10 @@ // Use keyPath to traverse to the collection and target a hasMany id data = [RKTestFixture parsedObjectWithContentsOfFixture:@"ArrayOfNestedDictionaries.json"]; RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[RKMappableObject class]]; - [objectMapping mapKeyPath:@"name" toAttribute:@"stringTest"]; + [objectMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"name" toKeyPath:@"stringTest"]]; RKObjectMapping *relationshipMapping = [RKObjectMapping mappingForClass:[RKMappableAssociation class]]; - [relationshipMapping mapKeyPath:@"title" toAttribute:@"testString"]; - [objectMapping mapKeyPath:@"mediaGroups.contents" toRelationship:@"hasMany" withMapping:relationshipMapping]; + [relationshipMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"title" toKeyPath:@"testString"]]; + [objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"mediaGroups.contents" toKeyPath:@"hasMany" withMapping:relationshipMapping]];; RKMappableObject *targetObject = [[RKMappableObject new] autorelease]; RKLogToComponentWithLevelWhileExecutingBlock(lcl_cRestKitObjectMapping, RKLogLevelDebug, ^ { RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:data diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m index f405e50f..86d1f13f 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m @@ -51,7 +51,7 @@ RKManagedObjectStore *managedObjectStore = [RKTestFactory managedObjectStore]; RKEntityMapping *humanMapping = [RKEntityMapping mappingForEntityForName:@"RKHuman" inManagedObjectStore:managedObjectStore]; assertThat(humanMapping, isNot(equalTo(nil))); - [humanMapping mapAttributes:@"name", nil]; + [humanMapping addAttributeMappingsFromArray:@[@"name"]]; [_objectManager.mappingProvider addObjectMapping:humanMapping]; RKMapping *returnedMapping = [_objectManager.mappingProvider objectMappingForClass:[RKHuman class]]; assertThat(returnedMapping, isNot(equalTo(nil))); @@ -63,7 +63,7 @@ RKManagedObjectStore *managedObjectStore = [RKTestFactory managedObjectStore]; RKEntityMapping *catMapping = [RKEntityMapping mappingForEntityForName:@"RKCat" inManagedObjectStore:managedObjectStore]; assertThat(catMapping, isNot(equalTo(nil))); - [catMapping mapAttributes:@"name", nil]; + [catMapping addAttributeMappingsFromArray:@[@"name"]]; [_objectManager.mappingProvider setMapping:catMapping forKeyPath:@"cat"]; RKMapping *returnedMapping = [_objectManager.mappingProvider mappingForKeyPath:@"cat"]; assertThat(returnedMapping, isNot(equalTo(nil))); @@ -76,7 +76,7 @@ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKEntityMapping *catMapping = [RKEntityMapping mappingForEntityForName:@"RKCat" inManagedObjectStore:managedObjectStore]; assertThat(catMapping, isNot(equalTo(nil))); - [catMapping mapAttributes:@"name", nil]; + [catMapping addAttributeMappingsFromArray:@[@"name"]]; [mappingProvider setMapping:catMapping forKeyPath:@"cat"]; RKMapping *returnedMapping = [mappingProvider mappingForKeyPath:@"cat"]; assertThat(returnedMapping, isNot(equalTo(nil))); diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m index 66c43a59..147a81ad 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m @@ -30,9 +30,9 @@ - (void)testShouldNotCrashWhenAsObjectIsInvokedOnAnEmptyResult { NSException *exception = nil; - RKMappingResult *result = [RKMappingResult mappingResultWithDictionary:[NSDictionary dictionary]]; + RKMappingResult *result = [[RKMappingResult alloc] initWithDictionary:[NSDictionary dictionary]]; @try { - [result asObject]; + [result firstObject]; } @catch (NSException *e) { exception = e; @@ -44,15 +44,15 @@ - (void)testShouldReturnNilForAnEmptyCollectionCoercedToAsObject { - RKMappingResult *result = [RKMappingResult mappingResultWithDictionary:[NSDictionary dictionary]]; - assertThat([result asObject], is(equalTo(nil))); + RKMappingResult *result = [[RKMappingResult alloc] initWithDictionary:[NSDictionary dictionary]]; + assertThat([result firstObject], is(equalTo(nil))); } - (void)testShouldReturnTheFirstObjectInTheCollectionWhenCoercedToAsObject { NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"one", @"one", @"two", @"two", nil]; - RKMappingResult *result = [RKMappingResult mappingResultWithDictionary:dictionary]; - assertThat([result asObject], is(equalTo(@"one"))); + RKMappingResult *result = [[RKMappingResult alloc] initWithDictionary:dictionary]; + assertThat([result firstObject], is(equalTo(@"one"))); } @end diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingTest.m index fb5fafdf..61efb06c 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingTest.m @@ -49,9 +49,9 @@ - (void)testThatTwoMappingsForTheSameObjectClassContainingIdenticalAttributeMappingsAreConsideredEqual { RKObjectMapping *mapping1 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping1 mapKeyPath:@"this" toAttribute:@"that"]; + [mapping1 addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"this" toKeyPath:@"that"]]; RKObjectMapping *mapping2 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping2 mapKeyPath:@"this" toAttribute:@"that"]; + [mapping2 addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"this" toKeyPath:@"that"]]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(YES))); } @@ -59,9 +59,9 @@ - (void)testThatTwoMappingsForTheSameObjectClassContainingDifferingAttributeMappingsAreNotConsideredEqual { RKObjectMapping *mapping1 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping1 mapKeyPath:@"this" toAttribute:@"that"]; + [mapping1 addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"this" toKeyPath:@"that"]]; RKObjectMapping *mapping2 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping2 mapKeyPath:@"different" toAttribute:@"that"]; + [mapping2 addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"different" toKeyPath:@"that"]]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(NO))); } @@ -72,9 +72,9 @@ RKObjectMapping *relationshipMapping2 = [RKObjectMapping mappingForClass:[NSSet class]]; RKObjectMapping *mapping1 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping1 mapKeyPath:@"this" toRelationship:@"that" withMapping:relationshipMapping1]; + [mapping1 addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]];; RKObjectMapping *mapping2 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping2 mapKeyPath:@"this" toRelationship:@"that" withMapping:relationshipMapping2]; + [mapping2 addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]];; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(YES))); } @@ -85,9 +85,9 @@ RKObjectMapping *relationshipMapping2 = [RKObjectMapping mappingForClass:[NSNumber class]]; RKObjectMapping *mapping1 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping1 mapKeyPath:@"this" toRelationship:@"that" withMapping:relationshipMapping1]; + [mapping1 addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]];; RKObjectMapping *mapping2 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping2 mapKeyPath:@"this" toRelationship:@"that" withMapping:relationshipMapping2]; + [mapping2 addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]];; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(NO))); } @@ -98,9 +98,9 @@ RKObjectMapping *relationshipMapping2 = [RKObjectMapping mappingForClass:[NSSet class]]; RKObjectMapping *mapping1 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping1 mapKeyPath:@"this" toRelationship:@"that" withMapping:relationshipMapping1]; + [mapping1 addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]];; RKObjectMapping *mapping2 = [RKObjectMapping mappingForClass:[NSString class]]; - [mapping2 mapKeyPath:@"this" toRelationship:@"different" withMapping:relationshipMapping2]; + [mapping2 addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"different" withMapping:relationshipMapping2]];; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(NO))); } diff --git a/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m b/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m index b0f5b134..0b78734b 100644 --- a/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m @@ -159,12 +159,12 @@ static NSString * const RKObjectPaginatorTestResourcePathPattern = @"/paginate?p - (RKObjectMappingProvider *)paginationMappingProvider { RKObjectMapping *paginationMapping = [RKObjectMapping mappingForClass:[RKObjectPaginator class]]; - [paginationMapping mapKeyPath:@"current_page" toAttribute:@"currentPage"]; - [paginationMapping mapKeyPath:@"per_page" toAttribute:@"perPage"]; - [paginationMapping mapKeyPath:@"total_entries" toAttribute:@"objectCount"]; + [paginationMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"current_page" toKeyPath:@"currentPage"]]; + [paginationMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"per_page" toKeyPath:@"perPage"]]; + [paginationMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"total_entries" toKeyPath:@"objectCount"]]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKObjectMapperTestModel class]]; - [mapping mapAttributes:@"name", @"age", nil]; + [mapping addAttributeMappingsFromArray:@[@"name", @"age"]]; RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; mappingProvider.paginationMapping = paginationMapping; [mappingProvider setObjectMapping:mapping forKeyPath:@"entries"]; diff --git a/Tests/Logic/ObjectMapping/RKObjectParametersTest.m b/Tests/Logic/ObjectMapping/RKObjectParametersTest.m index a2d21a26..61147376 100644 --- a/Tests/Logic/ObjectMapping/RKObjectParametersTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectParametersTest.m @@ -19,7 +19,8 @@ // #import "RKTestEnvironment.h" -#import "RKObjectSerializer.h" +#import "RKObjectParameterization.h" +#import "RKMIMETypeSerialization.h" #import "RKMappableObject.h" @interface RKObjectSerializerTest : RKTestCase { @@ -33,32 +34,31 @@ { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + + // URL Encode + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeFormURLEncoded error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"key2-form-name=value2&key1-form-name=value1"))); + assertThat(string, is(equalTo(@"key2-form-name=value2&key1-form-name=value1"))); } - (void)testShouldSerializeADateToFormEncodedData { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"key1-form-name=value1&date-form-name=1970-01-01 00:00:00 +0000"))); + assertThat(parameters[@"date-form-name"], is(equalTo(@"key1-form-name=value1&date-form-name=1970-01-01 00:00:00 +0000"))); } - (void)testShouldSerializeADateToAStringUsingThePreferredDateFormatter @@ -69,53 +69,53 @@ dateFormatter.dateFormat = @"MM/dd/yyyy"; dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; mapping.preferredDateFormatter = dateFormatter; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeFormURLEncoded error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"key1-form-name=value1&date-form-name=01/01/1970"))); + assertThat(string, is(equalTo(@"key1-form-name=value1&date-form-name=01/01/1970"))); } - (void)testShouldSerializeADateToJSON { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"{\"key1-form-name\":\"value1\",\"date-form-name\":\"1970-01-01 00:00:00 +0000\"}"))); + assertThat(string, is(equalTo(@"{\"key1-form-name\":\"value1\",\"date-form-name\":\"1970-01-01 00:00:00 +0000\"}"))); } - (void)testShouldSerializeNSDecimalNumberAttributesToJSON { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDecimalNumber decimalNumberWithString:@"18274191731731.4557723623"], @"number", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"number" toKeyPath:@"number-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"number" toKeyPath:@"number-form-name"]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"{\"key1-form-name\":\"value1\",\"number-form-name\":\"18274191731731.4557723623\"}"))); + assertThat(string, is(equalTo(@"{\"key1-form-name\":\"value1\",\"number-form-name\":\"18274191731731.4557723623\"}"))); } - (void)testShouldSerializeRelationshipsToo @@ -128,22 +128,23 @@ nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"relationship1.relatioship1Key1" toKeyPath:@"relationship1-form-name[r1k1]"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"relationship2.subKey1" toKeyPath:@"relationship2-form-name[subKey1]"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"relationship1.relatioship1Key1" toKeyPath:@"relationship1-form-name[r1k1]"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"relationship2.subKey1" toKeyPath:@"relationship2-form-name[subKey1]"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeFormURLEncoded error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); #if TARGET_OS_IPHONE - assertThat(data, is(equalTo(@"key1-form-name=value1&relationship1-form-name[r1k1][]=relationship1Value1&relationship1-form-name[r1k1][]=relationship1Value2&key2-form-name=value2&relationship2-form-name[subKey1]=subValue1"))); + assertThat(string, is(equalTo(@"key1-form-name=value1&relationship1-form-name[r1k1][]=relationship1Value1&relationship1-form-name[r1k1][]=relationship1Value2&key2-form-name=value2&relationship2-form-name[subKey1]=subValue1"))); #else - assertThat(data, is(equalTo(@"relationship1-form-name[r1k1][]=relationship1Value1&relationship1-form-name[r1k1][]=relationship1Value2&key2-form-name=value2&key1-form-name=value1&relationship2-form-name[subKey1]=subValue1"))); + assertThat(string, is(equalTo(@"relationship1-form-name[r1k1][]=relationship1Value1&relationship1-form-name[r1k1][]=relationship1Value2&key2-form-name=value2&key1-form-name=value1&relationship2-form-name[subKey1]=subValue1"))); #endif } @@ -151,28 +152,31 @@ { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"{\"key2-form-name\":\"value2\",\"key1-form-name\":\"value1\"}"))); + assertThat(string, is(equalTo(@"{\"key2-form-name\":\"value2\",\"key1-form-name\":\"value1\"}"))); } - (void)testShouldSetReturnNilIfItDoesNotFindAnythingToSerialize { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key12123" toKeyPath:@"key1-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key12123" toKeyPath:@"key1-form-name"]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; - assertThat(serialization, is(nilValue())); + assertThat(parameters, is(nilValue())); } - (void)testShouldSerializeNestedObjectsContainingDatesToJSON @@ -185,25 +189,23 @@ // Setup object mappings RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [objectMapping mapAttributes:@"stringTest", nil]; + [objectMapping addAttributeMappingsFromArray:@[ @"stringTest" ]]; RKObjectMapping *relationshipMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [relationshipMapping mapAttributes:@"date", nil]; - [objectMapping mapRelationship:@"hasOne" withMapping:relationshipMapping]; - - // Serialize - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:objectMapping]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - assertThat(error, is(nilValue())); - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [relationshipMapping addAttributeMappingsFromArray:@[ @"date" ]]; + [objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"hasOne" toKeyPath:@"hasOne" withMapping:relationshipMapping]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:objectMapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // Encodes differently on iOS / OS X #if TARGET_OS_IPHONE - assertThat(data, is(equalTo(@"{\"stringTest\":\"The string\",\"hasOne\":{\"date\":\"1970-01-01 00:00:00 +0000\"}}"))); + assertThat(string, is(equalTo(@"{\"stringTest\":\"The string\",\"hasOne\":{\"date\":\"1970-01-01 00:00:00 +0000\"}}"))); #else - assertThat(data, is(equalTo(@"{\"hasOne\":{\"date\":\"1970-01-01 00:00:00 +0000\"},\"stringTest\":\"The string\"}"))); + assertThat(string, is(equalTo(@"{\"hasOne\":{\"date\":\"1970-01-01 00:00:00 +0000\"},\"stringTest\":\"The string\"}"))); #endif } @@ -211,16 +213,15 @@ { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; - RKObjectSerializer *serializer = [[RKObjectSerializer alloc] initWithObject:object mapping:mapping rootKeyPath:@"stuff"]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - - assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"stuff[key2-form-name]=value2&stuff[key1-form-name]=value1"))); + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:@"stuff"]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + assertThat(parameters[@"stuff"][@"key2-form-name"], is(equalTo(@"value2"))); + assertThat(parameters[@"stuff"][@"key1-form-name"], is(equalTo(@"value1"))); } - (void)testShouldSerializeToManyRelationships @@ -233,38 +234,36 @@ // Setup object mappings RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [objectMapping mapAttributes:@"stringTest", nil]; + [objectMapping addAttributeMappingsFromArray:@[@"stringTest"]]; RKObjectMapping *relationshipMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - [relationshipMapping mapAttributes:@"date", nil]; - [objectMapping mapRelationship:@"hasMany" withMapping:relationshipMapping]; + [relationshipMapping addAttributeMappingsFromArray:@[@"date"]]; + [objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"hasMany" toKeyPath:@"hasMany" withMapping:relationshipMapping]]; // Serialize - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:objectMapping]; - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - assertThat(error, is(nilValue())); - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - assertThat(data, is(equalTo(@"{\"hasMany\":[{\"date\":\"1970-01-01 00:00:00 +0000\"}],\"stringTest\":\"The string\"}"))); + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:objectMapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + assertThat(string, is(equalTo(@"{\"hasMany\":[{\"date\":\"1970-01-01 00:00:00 +0000\"}],\"stringTest\":\"The string\"}"))); } - (void)testShouldSerializeAnNSNumberContainingABooleanToTrueFalseIfRequested { NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSNumber numberWithBool:YES], @"boolean", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - RKAttributeMapping *attributeMapping = [RKAttributeMapping mappingFromKeyPath:@"boolean" toKeyPath:@"boolean-value"]; - [mapping addAttributeMapping:attributeMapping]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + RKAttributeMapping *attributeMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"boolean" toKeyPath:@"boolean-value"]; + [mapping addPropertyMapping:attributeMapping]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"{\"boolean-value\":true}"))); + assertThat(string, is(equalTo(@"{\"boolean-value\":true}"))); } - (void)testShouldSerializeANSOrderedSetToJSON @@ -273,18 +272,17 @@ [NSOrderedSet orderedSetWithObjects:@"setElementOne", @"setElementTwo", @"setElementThree", nil], @"set", nil]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; - [mapping addAttributeMapping:[RKAttributeMapping mappingFromKeyPath:@"set" toKeyPath:@"set-form-name"]]; - RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - - NSError *error = nil; - id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - - NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; - data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; + [mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"set" toKeyPath:@"set-form-name"]]; + + NSError *error; + RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:mapping objectClass:[NSDictionary class] rootKeyPath:nil]; + NSDictionary *parameters = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:&error]; + NSData *data = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error]; + NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); - assertThat(data, is(equalTo(@"{\"key1-form-name\":\"value1\",\"set-form-name\":[\"setElementOne\",\"setElementTwo\",\"setElementThree\"]}"))); + assertThat(string, is(equalTo(@"{\"key1-form-name\":\"value1\",\"set-form-name\":[\"setElementOne\",\"setElementTwo\",\"setElementThree\"]}"))); } @end diff --git a/Tests/Logic/ObjectMapping/RKObjectRelationshipMappingTest.m b/Tests/Logic/ObjectMapping/RKObjectRelationshipMappingTest.m index 7f030522..cbf9b464 100644 --- a/Tests/Logic/ObjectMapping/RKObjectRelationshipMappingTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectRelationshipMappingTest.m @@ -16,16 +16,16 @@ - (void)testThatRelationshipMappingsWithTheSameSourceAndDestinationKeyPathAreConsideredEqual { - RKRelationshipMapping *mapping1 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:nil]; - RKRelationshipMapping *mapping2 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:nil]; + RKRelationshipMapping *mapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:nil]; + RKRelationshipMapping *mapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:nil]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(YES))); } - (void)testThatRelationshipMappingsWithDifferingKeyPathsAreNotConsideredEqual { - RKRelationshipMapping *mapping1 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:nil]; - RKRelationshipMapping *mapping2 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"the other" withMapping:nil]; + RKRelationshipMapping *mapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:nil]; + RKRelationshipMapping *mapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"the other" withMapping:nil]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(NO))); } @@ -35,8 +35,8 @@ RKObjectMapping *relationshipMapping1 = [RKObjectMapping mappingForClass:[NSSet class]]; RKObjectMapping *relationshipMapping2 = [RKObjectMapping mappingForClass:[NSSet class]]; - RKRelationshipMapping *mapping1 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; - RKRelationshipMapping *mapping2 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; + RKRelationshipMapping *mapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; + RKRelationshipMapping *mapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(YES))); } @@ -46,8 +46,8 @@ RKObjectMapping *relationshipMapping1 = [RKObjectMapping mappingForClass:[NSSet class]]; RKObjectMapping *relationshipMapping2 = [RKObjectMapping mappingForClass:[NSNumber class]]; - RKRelationshipMapping *mapping1 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; - RKRelationshipMapping *mapping2 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; + RKRelationshipMapping *mapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; + RKRelationshipMapping *mapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(NO))); } @@ -57,8 +57,8 @@ RKObjectMapping *relationshipMapping1 = [RKObjectMapping mappingForClass:[NSSet class]]; RKObjectMapping *relationshipMapping2 = [RKObjectMapping mappingForClass:nil]; - RKRelationshipMapping *mapping1 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; - RKRelationshipMapping *mapping2 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; + RKRelationshipMapping *mapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; + RKRelationshipMapping *mapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(NO))); } @@ -68,8 +68,8 @@ RKObjectMapping *relationshipMapping1 = [RKObjectMapping mappingForClass:nil]; RKObjectMapping *relationshipMapping2 = [RKObjectMapping mappingForClass:nil]; - RKRelationshipMapping *mapping1 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; - RKRelationshipMapping *mapping2 = [RKRelationshipMapping mappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; + RKRelationshipMapping *mapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping1]; + RKRelationshipMapping *mapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"this" toKeyPath:@"that" withMapping:relationshipMapping2]; assertThatBool([mapping1 isEqualToMapping:mapping2], is(equalToBool(YES))); } diff --git a/Tests/Logic/ObjectMapping/RKParserRegistryTest.m b/Tests/Logic/ObjectMapping/RKParserRegistryTest.m index fe9906dc..86ed35df 100644 --- a/Tests/Logic/ObjectMapping/RKParserRegistryTest.m +++ b/Tests/Logic/ObjectMapping/RKParserRegistryTest.m @@ -19,76 +19,89 @@ // #import "RKTestEnvironment.h" -#import "RKParserRegistry.h" -#import "RKJSONParserJSONKit.h" -#import "RKXMLParserXMLReader.h" +#import "RKMIMETypeSerialization.h" +#import "RKNSJSONSerialization.h" -@interface RKParserRegistryTest : RKTestCase { +@interface RKMIMETypeSerialization () +@property (nonatomic, strong) NSMutableArray *registrations; + ++ (RKMIMETypeSerialization *)sharedSerialization; +- (void)addRegistrationsForKnownSerializations; +@end + +@interface RKParserRegistryTest : RKTestCase +@end + +@interface RKTestSerialization : NSObject +@end + +@implementation RKTestSerialization + ++ (id)objectFromData:(NSData *)data error:(NSError **)error +{ + return nil; +} + ++ (NSData *)dataFromObject:(id)object error:(NSError **)error +{ + return nil; } @end @implementation RKParserRegistryTest -- (void)testShouldEnableRegistrationFromMIMETypeToParserClasses +- (void)setUp { - RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; - [registry setParserClass:[RKJSONParserJSONKit class] forMIMEType:RKMIMETypeJSON]; - Class parserClass = [registry parserClassForMIMEType:RKMIMETypeJSON]; - assertThat(NSStringFromClass(parserClass), is(equalTo(@"RKJSONParserJSONKit"))); + [RKMIMETypeSerialization sharedSerialization].registrations = [NSMutableArray array]; } -- (void)testShouldInstantiateParserObjects +- (void)testShouldEnableRegistrationFromMIMETypeToParserClasses { - RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; - [registry setParserClass:[RKJSONParserJSONKit class] forMIMEType:RKMIMETypeJSON]; - id parser = [registry parserForMIMEType:RKMIMETypeJSON]; - assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); + [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:RKMIMETypeJSON]; + Class parserClass = [RKMIMETypeSerialization serializationClassForMIMEType:RKMIMETypeJSON]; + assertThat(NSStringFromClass(parserClass), is(equalTo(@"RKNSJSONSerialization"))); } - (void)testShouldAutoconfigureBasedOnReflection { - RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; - [registry autoconfigure]; - id parser = [registry parserForMIMEType:RKMIMETypeJSON]; - assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); - parser = [registry parserForMIMEType:RKMIMETypeXML]; - assertThat(parser, is(instanceOf([RKXMLParserXMLReader class]))); + [[RKMIMETypeSerialization sharedSerialization] addRegistrationsForKnownSerializations]; + Class parserClass = [RKMIMETypeSerialization serializationClassForMIMEType:RKMIMETypeJSON]; + assertThat(NSStringFromClass(parserClass), is(equalTo(@"RKNSJSONSerialization"))); } - (void)testRetrievalOfExactStringMatchForMIMEType { - RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; - [registry setParserClass:[RKJSONParserJSONKit class] forMIMEType:RKMIMETypeJSON]; - id parser = [registry parserForMIMEType:RKMIMETypeJSON]; - assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); + [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:RKMIMETypeJSON]; + Class parserClass = [RKMIMETypeSerialization serializationClassForMIMEType:RKMIMETypeJSON]; + assertThat(NSStringFromClass(parserClass), is(equalTo(@"RKNSJSONSerialization"))); } - (void)testRetrievalOfRegularExpressionMatchForMIMEType { - RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"application/xml\\+\\w+" options:0 error:&error]; - [registry setParserClass:[RKJSONParserJSONKit class] forMIMETypeRegularExpression:regex]; - id parser = [registry parserForMIMEType:@"application/xml+whatever"]; - assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); + + [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:regex]; + Class serializationClass = [RKMIMETypeSerialization serializationClassForMIMEType:@"application/xml+whatever"]; + assertThat(NSStringFromClass(serializationClass), is(equalTo(@"RKNSJSONSerialization"))); } - (void)testRetrievalOfExactStringMatchIsFavoredOverRegularExpression { - RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"application/xml\\+\\w+" options:0 error:&error]; - [registry setParserClass:[RKJSONParserJSONKit class] forMIMETypeRegularExpression:regex]; - [registry setParserClass:[RKXMLParserXMLReader class] forMIMEType:@"application/xml+whatever"]; + + [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:regex]; + [RKMIMETypeSerialization registerClass:[RKTestSerialization class] forMIMEType:@"application/xml+whatever"]; // Exact match - id exactParser = [registry parserForMIMEType:@"application/xml+whatever"]; - assertThat(exactParser, is(instanceOf([RKXMLParserXMLReader class]))); + Class exactMatch = [RKMIMETypeSerialization serializationClassForMIMEType:@"application/xml+whatever"]; + assertThat(exactMatch, is(equalTo([RKTestSerialization class]))); // Fallback to regex - id regexParser = [registry parserForMIMEType:@"application/xml+different"]; - assertThat(regexParser, is(instanceOf([RKJSONParserJSONKit class]))); + Class regexMatch = [RKMIMETypeSerialization serializationClassForMIMEType:@"application/xml+different"]; + assertThat(regexMatch, is(equalTo([RKNSJSONSerialization class]))); } @end diff --git a/Tests/Logic/Support/NSArray+RKAdditionsTest.m b/Tests/Logic/Support/NSArray+RKAdditionsTest.m deleted file mode 100644 index 4c376a26..00000000 --- a/Tests/Logic/Support/NSArray+RKAdditionsTest.m +++ /dev/null @@ -1,86 +0,0 @@ -// -// NSArray+RKAdditionsTest.m -// RestKit -// -// Created by Blake Watters on 4/10/12. -// Copyright (c) 2012 RestKit. All rights reserved. -// - -#import "RKTestEnvironment.h" -#import "NSArray+RKAdditions.h" -#import "RKTestUser.h" - -@interface NSArray_RKAdditionsTest : RKTestCase -@end - -@implementation NSArray_RKAdditionsTest - -#pragma mark - sectionsGroupedByKeyPath Tests - -- (void)testReturnsEmptyArrayWhenGroupingEmptyArray -{ - NSArray *objects = [NSArray array]; - assertThat([objects sectionsGroupedByKeyPath:@"whatever"], is(empty())); -} - -- (void)testReturnsSingleSectionWhenGroupingSingleObject -{ - RKTestUser *user = [RKTestUser new]; - user.name = @"Blake"; - user.country = @"USA"; - NSArray *users = [NSArray arrayWithObject:user]; - - NSArray *sections = [users sectionsGroupedByKeyPath:@"country"]; - assertThat(sections, hasCountOf(1)); -} - -- (void)testReturnsTwoSectionsWhenGroupingThreeObjectsWithTwoUniqueValues -{ - RKTestUser *user1 = [RKTestUser new]; - user1.name = @"Blake"; - user1.country = @"USA"; - - RKTestUser *user2 = [RKTestUser new]; - user2.name = @"Colin"; - user2.country = @"USA"; - - RKTestUser *user3 = [RKTestUser new]; - user3.name = @"Pepe"; - user3.country = @"Spain"; - - NSArray *users = [NSArray arrayWithObjects:user1, user2, user3, nil]; - - NSArray *sections = [users sectionsGroupedByKeyPath:@"country"]; - assertThat(sections, hasCountOf(2)); - assertThat([sections objectAtIndex:0], contains(user1, user2, nil)); - assertThat([sections objectAtIndex:1], contains(user3, nil)); -} - -- (void)testCreationOfSingleSectionForNullValues -{ - RKTestUser *user1 = [RKTestUser new]; - user1.name = @"Blake"; - user1.country = @"USA"; - - RKTestUser *user2 = [RKTestUser new]; - user2.name = @"Expatriate"; - user2.country = nil; - - RKTestUser *user3 = [RKTestUser new]; - user3.name = @"John Doe"; - user3.country = nil; - - RKTestUser *user4 = [RKTestUser new]; - user4.name = @"Pepe"; - user4.country = @"Spain"; - - NSArray *users = [NSArray arrayWithObjects:user1, user2, user3, user4, nil]; - - NSArray *sections = [users sectionsGroupedByKeyPath:@"country"]; - assertThat(sections, hasCountOf(3)); - assertThat([sections objectAtIndex:0], contains(user1, nil)); - assertThat([sections objectAtIndex:1], contains(user2, user3, nil)); - assertThat([sections objectAtIndex:2], contains(user4, nil)); -} - -@end diff --git a/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m b/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m index 729be477..5b57db47 100644 --- a/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m +++ b/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m @@ -19,29 +19,22 @@ // #import "RKTestEnvironment.h" -#import "NSDictionary+RKRequestSerialization.h" -#import "NSDictionary+RKAdditions.h" +#import "RKURLEncodedSerialization.h" @interface NSDictionary_RKRequestSerializationTest : RKTestCase { } @end +// TODO: Moves to RKURLEncodedSerializationTest.m @implementation NSDictionary_RKRequestSerializationTest -- (void)testShouldHaveKeysAndValuesDictionaryInitializer -{ - NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value", @"key", @"value2", @"key2", nil]; - NSDictionary *dictionary2 = [NSDictionary dictionaryWithKeysAndObjects:@"key", @"value", @"key2", @"value2", nil]; - assertThat(dictionary2, is(equalTo(dictionary1))); -} - - (void)testShouldEncodeUnicodeStrings { NSString *unicode = [NSString stringWithFormat:@"%CNo ser ni%Co, ser b%Cfalo%C%C", (unichar)0x00A1, (unichar)0x00F1, (unichar)0x00FA, (unichar)0x2026, (unichar)0x0021]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:unicode forKey:@"utf8"]; NSString *validUnicode = @"utf8=%C2%A1No%20ser%20ni%C3%B1o%2C%20ser%20b%C3%BAfalo%E2%80%A6%21"; - assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validUnicode))); + assertThat(RKURLEncodedStringFromDictionaryWithEncoding(dictionary, NSUTF8StringEncoding), is(equalTo(validUnicode))); } - (void)testShouldEncodeURLStrings @@ -49,7 +42,7 @@ NSString *url = @"http://some.server.com/path/action?subject=\"That thing I sent\"&email=\"me@me.com\""; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:url forKey:@"url"]; NSString *validURL = @"url=http%3A%2F%2Fsome.server.com%2Fpath%2Faction%3Fsubject%3D%22That%20thing%20I%20sent%22%26email%3D%22me%40me.com%22"; - assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validURL))); + assertThat(RKURLEncodedStringFromDictionaryWithEncoding(dictionary, NSUTF8StringEncoding), is(equalTo(validURL))); } - (void)testShouldEncodeArrays @@ -57,7 +50,7 @@ NSArray *array = [NSArray arrayWithObjects:@"item1", @"item2", nil]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:array forKey:@"anArray"]; NSString *validArray = @"anArray[]=item1&anArray[]=item2"; - assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validArray))); + assertThat(RKURLEncodedStringFromDictionaryWithEncoding(dictionary, NSUTF8StringEncoding), is(equalTo(validArray))); } - (void)testShouldEncodeDictionaries @@ -65,19 +58,19 @@ NSDictionary *subDictionary = [NSDictionary dictionaryWithObject:@"value1" forKey:@"key1"]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:subDictionary forKey:@"aDictionary"]; NSString *validDictionary = @"aDictionary[key1]=value1"; - assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validDictionary))); + assertThat(RKURLEncodedStringFromDictionaryWithEncoding(dictionary, NSUTF8StringEncoding), is(equalTo(validDictionary))); } - (void)testShouldEncodeArrayOfDictionaries { - NSDictionary *dictA = [NSDictionary dictionaryWithKeysAndObjects:@"a", @"x", @"b", @"y", nil]; - NSDictionary *dictB = [NSDictionary dictionaryWithKeysAndObjects:@"a", @"1", @"b", @"2", nil]; + NSDictionary *dictA = @{@"a": @"x", @"b": @"y"}; + NSDictionary *dictB = @{@"a": @"1", @"b": @"2"}; NSArray *array = [NSArray arrayWithObjects:dictA, dictB, nil]; - NSDictionary *dictRoot = [NSDictionary dictionaryWithKeysAndObjects:@"root", array, nil]; + NSDictionary *dictRoot = @{@"root" : array}; NSString *validString = @"root[][a]=x&root[][b]=y&root[][a]=1&root[][b]=2"; - assertThat([dictRoot stringWithURLEncodedEntries], is(equalTo(validString))); + assertThat(RKURLEncodedStringFromDictionaryWithEncoding(dictRoot, NSUTF8StringEncoding), is(equalTo(validString))); } - (void)testShouldEncodeRecursiveArrays @@ -87,7 +80,7 @@ NSArray *recursiveArray1 = [NSArray arrayWithObject:recursiveArray2]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:recursiveArray1 forKey:@"recursiveArray"]; NSString *validRecursion = @"recursiveArray[]=%28%0A%20%20%20%20%20%20%20%20%28%0A%20%20%20%20%20%20%20%20item1%2C%0A%20%20%20%20%20%20%20%20item2%0A%20%20%20%20%29%0A%29"; - assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validRecursion))); + assertThat(RKURLEncodedStringFromDictionaryWithEncoding(dictionary, NSUTF8StringEncoding), is(equalTo(validRecursion))); } @end diff --git a/Tests/Logic/Support/NSStringRestKitTest.m b/Tests/Logic/Support/NSStringRestKitTest.m index 73112c8e..6ca1dcdd 100755 --- a/Tests/Logic/Support/NSStringRestKitTest.m +++ b/Tests/Logic/Support/NSStringRestKitTest.m @@ -19,8 +19,9 @@ // #import "RKTestEnvironment.h" -#import "NSString+RKAdditions.h" +#import "RKPathUtilities.h" #import "RKObjectMapperTestModel.h" +#import "RKURLEncodedSerialization.h" @interface NSStringRestKitTest : RKTestCase @@ -28,27 +29,12 @@ @implementation NSStringRestKitTest -- (void)testShouldAppendQueryParameters -{ - NSString *resourcePath = @"/controller/objects/"; - NSDictionary *queryParams = [NSDictionary dictionaryWithObjectsAndKeys: - @"ascend", @"sortOrder", - @"name", @"groupBy", nil]; - NSString *resultingPath = [resourcePath stringByAppendingQueryParameters:queryParams]; - assertThat(resultingPath, isNot(equalTo(nil))); - NSString *expectedPath1 = @"/controller/objects/?sortOrder=ascend&groupBy=name"; - NSString *expectedPath2 = @"/controller/objects/?groupBy=name&sortOrder=ascend"; - BOOL isValidPath = ( [resultingPath isEqualToString:expectedPath1] || - [resultingPath isEqualToString:expectedPath2] ); - assertThatBool(isValidPath, is(equalToBool(YES))); -} - - (void)testShouldInterpolateObjects { RKObjectMapperTestModel *person = [[[RKObjectMapperTestModel alloc] init] autorelease]; person.name = @"CuddleGuts"; person.age = [NSNumber numberWithInt:6]; - NSString *interpolatedPath = [@"/people/:name/:age" interpolateWithObject:person]; + NSString *interpolatedPath = RKPathFromPatternWithObject(@"/people/:name/:age", person); assertThat(interpolatedPath, isNot(equalTo(nil))); NSString *expectedPath = @"/people/CuddleGuts/6"; assertThat(interpolatedPath, is(equalTo(expectedPath))); @@ -59,39 +45,32 @@ RKObjectMapperTestModel *person = [[[RKObjectMapperTestModel alloc] init] autorelease]; person.name = @"CuddleGuts"; person.age = [NSNumber numberWithInt:6]; - NSString *interpolatedPath = [@"/people/(name)/(age)" interpolateWithObject:person]; + NSString *interpolatedPath = RKPathFromPatternWithObject(@"/people/(name)/(age)", person); assertThat(interpolatedPath, isNot(equalTo(nil))); NSString *expectedPath = @"/people/CuddleGuts/6"; assertThat(interpolatedPath, is(equalTo(expectedPath))); } +// TODO: Moves to RKURLEncodedSerializationTest.m - (void)testShouldParseQueryParameters { NSString *resourcePath = @"/views/thing/?keyA=valA&keyB=valB"; - NSDictionary *queryParams = [resourcePath queryParametersUsingEncoding:NSASCIIStringEncoding]; - assertThat(queryParams, isNot(empty())); - assertThat(queryParams, hasCountOf(2)); - assertThat(queryParams, hasEntries(@"keyA", @"valA", @"keyB", @"valB", nil)); + NSDictionary *queryParameters = RKDictionaryFromURLEncodedStringWithEncoding(resourcePath, NSUTF8StringEncoding); + assertThat(queryParameters, isNot(empty())); + assertThat(queryParameters, hasCountOf(2)); + assertThat(queryParameters, hasEntries(@"keyA", @"valA", @"keyB", @"valB", nil)); } - (void)testReturningTheMIMETypeForAPathWithXMLExtension { - NSString *MIMEType = [@"/path/to/file.xml" MIMETypeForPathExtension]; + NSString *MIMEType = RKMIMETypeFromPathExtension(@"/path/to/file.xml"); assertThat(MIMEType, is(equalTo(@"application/xml"))); } - (void)testReturningTheMIMETypeForAPathWithJSONExtension { - NSString *MIMEType = [@"/path/to/file.json" MIMETypeForPathExtension]; + NSString *MIMEType = RKMIMETypeFromPathExtension(@"/path/to/file.json"); assertThat(MIMEType, is(equalTo(@"application/json"))); } -- (void)testShouldKnowIfTheReceiverContainsAnIPAddress -{ - assertThatBool([@"127.0.0.1" isIPAddress], equalToBool(YES)); - assertThatBool([@"173.45.234.197" isIPAddress], equalToBool(YES)); - assertThatBool([@"google.com" isIPAddress], equalToBool(NO)); - assertThatBool([@"just some random text" isIPAddress], equalToBool(NO)); -} - @end diff --git a/Tests/Logic/Support/RKDotNetDateFormatterTest.m b/Tests/Logic/Support/RKDotNetDateFormatterTest.m index 06601077..4a01135e 100644 --- a/Tests/Logic/Support/RKDotNetDateFormatterTest.m +++ b/Tests/Logic/Support/RKDotNetDateFormatterTest.m @@ -17,13 +17,12 @@ - (void)testShouldInstantiateAFormatterWithDefaultGMTTimeZone { - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; assertThat(formatter, isNot(equalTo(nil))); assertThat(formatter.timeZone, is(equalTo(timeZone))); } - - (void)testShouldInstantiateAFormatterWithATimeZone { NSTimeZone *timeZoneCST = [NSTimeZone timeZoneWithAbbreviation:@"CST"]; @@ -35,7 +34,7 @@ - (void)testShouldCreateADateFromDotNetThatWithAnOffset { NSString *dotNetString = @"/Date(1000212360000-0400)/"; - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSDate *date = [formatter dateFromString:dotNetString]; assertThat([date description], is(equalTo(@"2001-09-11 12:46:00 +0000"))); } @@ -43,7 +42,7 @@ - (void)testShouldCreateADateFromDotNetWithoutAnOffset { NSString *dotNetString = @"/Date(1112715000000)/"; - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSDate *date = [formatter dateFromString:dotNetString]; assertThat([date description], is(equalTo(@"2005-04-05 15:30:00 +0000"))); } @@ -51,14 +50,14 @@ - (void)testShouldCreateADateFromDotNetBefore1970WithoutAnOffset { NSString *dotNetString = @"/Date(-864000000000)/"; - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSDate *date = [formatter dateFromString:dotNetString]; assertThat([date description], is(equalTo(@"1942-08-16 00:00:00 +0000"))); } - (void)testShouldFailToCreateADateFromInvalidStrings { - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSDate *date = [formatter dateFromString:nil]; assertThat(date, is(equalTo(nil))); date = [formatter dateFromString:@"(null)"]; @@ -79,7 +78,7 @@ - (void)testShouldCreateADotNetStringFromADateBefore1970WithoutAnOffset { - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSDate *referenceDate = [NSDate dateWithTimeIntervalSince1970:-1000212360]; NSString *string = [formatter stringFromDate:referenceDate]; assertThat(string, is(equalTo(@"/Date(-1000212360000+0000)/"))); @@ -87,7 +86,7 @@ - (void)testShouldCreateADateWithGetObjectValueForString { - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSString *dotNetString = @"/Date(1000212360000-0400)/"; NSDate *date = nil; @@ -108,7 +107,7 @@ } - (void)testShouldCreateADotNetStringWithStringForObjectValueFromADateBefore1970WithoutAnOffset { - RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; + RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter new]; NSDate *referenceDate = [NSDate dateWithTimeIntervalSince1970:-1000212360]; NSString *string = [formatter stringForObjectValue:referenceDate]; assertThat(string, is(equalTo(@"/Date(-1000212360000+0000)/"))); diff --git a/Tests/Logic/Support/RKJSONParserJSONKitTest.m b/Tests/Logic/Support/RKJSONParserJSONKitTest.m deleted file mode 100644 index 94245375..00000000 --- a/Tests/Logic/Support/RKJSONParserJSONKitTest.m +++ /dev/null @@ -1,39 +0,0 @@ -// -// RKJSONParserJSONKitTest.m -// RestKit -// -// Created by Blake Watters on 7/6/11. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKJSONParserJSONKit.h" - -@interface RKJSONParserJSONKitTest : RKTestCase - -@end - -@implementation RKJSONParserJSONKitTest - -- (void)testShouldParseEmptyResults -{ - NSError *error = nil; - RKJSONParserJSONKit *parser = [[RKJSONParserJSONKit new] autorelease]; - id parsingResult = [parser objectFromString:nil error:&error]; - assertThat(parsingResult, is(equalTo(nil))); - assertThat(error, is(equalTo(nil))); -} - -@end diff --git a/Tests/Logic/Support/RKMutableBlockDictionaryTest.m b/Tests/Logic/Support/RKMutableBlockDictionaryTest.m deleted file mode 100644 index 3ba9d9e5..00000000 --- a/Tests/Logic/Support/RKMutableBlockDictionaryTest.m +++ /dev/null @@ -1,40 +0,0 @@ -// -// RKMutableBlockDictionaryTest.m -// RestKit -// -// Created by Blake Watters on 8/22/11. -// Copyright (c) 2009-2012 RestKit. All rights reserved. -// - -#import "RKTestEnvironment.h" -#import "RKMutableBlockDictionary.h" - -@interface RKMutableBlockDictionaryTest : RKTestCase - -@end - -@implementation RKMutableBlockDictionaryTest - -- (void)testLetYouAssignABlockToTheDictionary -{ - RKMutableBlockDictionary *blockDictionary = [[RKMutableBlockDictionary new] autorelease]; - [blockDictionary setValueWithBlock:^id{ return @"Value from the block!"; } forKey:@"theKey"]; - assertThat([blockDictionary valueForKey:@"theKey"], is(equalTo(@"Value from the block!"))); -} - -- (void)testLetYouUseKVC -{ - RKMutableBlockDictionary *blockDictionary = [[RKMutableBlockDictionary new] autorelease]; - [blockDictionary setValue:@"a value" forKey:@"a key"]; - assertThat([blockDictionary valueForKey:@"a key"], is(equalTo(@"a value"))); -} - -- (void)testLetYouAccessABlockValueUsingAKeyPath -{ - RKMutableBlockDictionary *blockDictionary = [[RKMutableBlockDictionary new] autorelease]; - [blockDictionary setValueWithBlock:^id{ return @"Value from the block!"; } forKey:@"theKey"]; - NSDictionary *otherDictionary = [NSDictionary dictionaryWithObject:blockDictionary forKey:@"dictionary"]; - assertThat([otherDictionary valueForKeyPath:@"dictionary.theKey"], is(equalTo(@"Value from the block!"))); -} - -@end diff --git a/Tests/Logic/Support/RKPathMatcherTest.m b/Tests/Logic/Support/RKPathMatcherTest.m index f572906e..1a343c5e 100755 --- a/Tests/Logic/Support/RKPathMatcherTest.m +++ b/Tests/Logic/Support/RKPathMatcherTest.m @@ -93,7 +93,7 @@ NSDictionary *person = [NSDictionary dictionaryWithObjectsAndKeys: @"CuddleGuts", @"name", [NSNumber numberWithInt:6], @"age", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/people/:name/:age"]; - NSString *interpolatedPath = [matcher pathFromObject:person]; + NSString *interpolatedPath = [matcher pathFromObject:person addingEscapes:YES]; assertThat(interpolatedPath, isNot(equalTo(nil))); NSString *expectedPath = @"/people/CuddleGuts/6"; assertThat(interpolatedPath, is(equalTo(expectedPath))); @@ -104,7 +104,7 @@ NSDictionary *person = [NSDictionary dictionaryWithObjectsAndKeys: @"CuddleGuts", @"name", [NSNumber numberWithInt:6], @"age", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/people/(name)/(age)"]; - NSString *interpolatedPath = [matcher pathFromObject:person]; + NSString *interpolatedPath = [matcher pathFromObject:person addingEscapes:YES]; assertThat(interpolatedPath, isNot(equalTo(nil))); NSString *expectedPath = @"/people/CuddleGuts/6"; assertThat(interpolatedPath, is(equalTo(expectedPath))); @@ -115,7 +115,7 @@ NSDictionary *person = [NSDictionary dictionaryWithObjectsAndKeys: @"JUICE|BOX&121", @"password", @"Joe Bob Briggs", @"name", [NSNumber numberWithInt:15], @"group", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/people/:group/:name?password=:password"]; - NSString *interpolatedPath = [matcher pathFromObject:person]; + NSString *interpolatedPath = [matcher pathFromObject:person addingEscapes:YES]; assertThat(interpolatedPath, isNot(equalTo(nil))); NSString *expectedPath = @"/people/15/Joe%20Bob%20Briggs?password=JUICE%7CBOX%26121"; assertThat(interpolatedPath, is(equalTo(expectedPath))); @@ -136,11 +136,10 @@ { NSDictionary *arguments = [NSDictionary dictionaryWithObjectsAndKeys:@"Resources", @"filename", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/directory/:filename\\.json"]; - NSString *interpolatedPath = [matcher pathFromObject:arguments]; + NSString *interpolatedPath = [matcher pathFromObject:arguments addingEscapes:YES]; assertThat(interpolatedPath, isNot(equalTo(nil))); NSString *expectedPath = @"/directory/Resources.json"; assertThat(interpolatedPath, is(equalTo(expectedPath))); } - @end diff --git a/Tests/Logic/Support/RKXMLParserTest.m b/Tests/Logic/Support/RKXMLParserTest.m deleted file mode 100644 index 7725f85d..00000000 --- a/Tests/Logic/Support/RKXMLParserTest.m +++ /dev/null @@ -1,248 +0,0 @@ -// -// RKXMLParserTest.m -// RestKit -// -// Created by Jeremy Ellison on 3/29/11. -// Copyright (c) 2009-2012 RestKit. 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. -// - -#import "RKTestEnvironment.h" -#import "RKXMLParserXMLReader.h" - -// See Tests/Fixtures/XML/tab_data.xml -@interface RKTestTabData : NSObject { - NSString *_title; - NSString *_summary; -} - -@property (nonatomic, retain) NSString *title; -@property (nonatomic, retain) NSString *summary; - -@end - -@implementation RKTestTabData - -@synthesize title = _title; -@synthesize summary = _summary; - -@end - -@interface RKXMLParserTest : RKTestCase { - -} - -@end - -@implementation RKXMLParserTest - -- (void)testShouldMapASingleXMLObjectPayloadToADictionary -{ - NSString *data = @"\n\n 2.4\n string\n 1\n\n"; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - id result = [parser objectFromString:data error:&error]; - assertThat(result, is(instanceOf([NSDictionary class]))); - assertThatFloat([[[result valueForKeyPath:@"hash.float"] valueForKey:@"text"] floatValue], is(equalToFloat(2.4f))); - assertThatInt([[[result valueForKeyPath:@"hash.number"] valueForKey:@"text"] intValue], is(equalToInt(1))); - assertThat([result valueForKeyPath:@"hash.string"], is(equalTo(@"string"))); -} - -- (void)testShouldMapMultipleObjectsToAnArray -{ - NSString *data = @"\n\n \n 2.4\n string\n 1\n \n \n 1\n \n\n"; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - id result = [parser objectFromString:data error:&error]; - NSArray *records = (NSArray *)[result valueForKeyPath:@"records.record"]; - assertThatUnsignedInteger([records count], is(equalToInt(2))); - id result1 = [records objectAtIndex:0]; - assertThat(result, is(instanceOf([NSDictionary class]))); - assertThatFloat([[[result1 valueForKeyPath:@"float"] valueForKey:@"text"] floatValue], is(equalToFloat(2.4f))); - assertThatInt([[[result1 valueForKeyPath:@"number"] valueForKey:@"text"] intValue], is(equalToInt(1))); - assertThat([result1 valueForKeyPath:@"string"], is(equalTo(@"string"))); - id result2 = [records objectAtIndex:1]; - assertThatInt([[[result2 valueForKeyPath:@"another-number"] valueForKey:@"text"] intValue], is(equalToInt(1))); -} - -- (void)testShouldMapXML -{ - RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestTabData class]]; - [mapping mapAttributes:@"title", @"summary", nil]; - RKObjectMappingProvider *provider = [[RKObjectMappingProvider alloc] init]; - id data = [RKTestFixture parsedObjectWithContentsOfFixture:@"tab_data.xml"]; - assertThat([data valueForKeyPath:@"tabdata.item"], is(instanceOf([NSArray class]))); - [provider setMapping:mapping forKeyPath:@"tabdata.item"]; - RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:data mappingProvider:provider]; - RKMappingResult *result = [mapper performMapping]; - assertThatUnsignedInteger([[result asCollection] count], is(equalToInt(2))); - assertThatUnsignedInteger([[data valueForKeyPath:@"tabdata.title"] count], is(equalToInt(2))); - assertThatUnsignedInteger([[data valueForKeyPath:@"tabdata.item"] count], is(equalToInt(2))); -} - -- (void)testShouldParseXMLWithAttributes -{ - NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"container_attributes.xml"]; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - NSDictionary *result = [parser objectFromString:XML error:&error]; - assertThat(result, is(instanceOf([NSDictionary class]))); - NSArray *elements = [[result objectForKey:@"elements"] objectForKey:@"element"]; - assertThat(elements, isNot(nilValue())); - assertThat(elements, is(instanceOf([NSArray class]))); - assertThat(elements, hasCountOf(2)); - NSDictionary *firstElement = [elements objectAtIndex:0]; - assertThat([firstElement objectForKey:@"attribute"], is(equalTo(@"1"))); - assertThat([firstElement objectForKey:@"subelement"], is(equalTo(@"text"))); - NSDictionary *secondElement = [elements objectAtIndex:1]; - assertThat([secondElement objectForKey:@"attribute"], is(equalTo(@"2"))); - assertThat([secondElement objectForKey:@"subelement"], is(equalTo(@"text2"))); -} - -- (void)testShouldParseXMLWithAttributesInTextNodes -{ - NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"attributes_without_text_content.xml"]; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - NSDictionary *result = [parser objectFromString:XML error:&error]; - NSDictionary *exchangeRate = [result objectForKey:@"exchange_rate"]; - assertThat(exchangeRate, is(notNilValue())); - assertThat([exchangeRate objectForKey:@"type"], is(equalTo(@"XML_RATE_TYPE_EBNK_MIDDLE"))); - assertThat([exchangeRate objectForKey:@"valid_from"], is(equalTo(@"2011-08-03 00:00:00.0"))); - assertThat([exchangeRate objectForKey:@"name"], nilValue()); // This is to test for bug in parsing - NSArray *currency = [exchangeRate objectForKey:@"currency"]; - assertThat(currency, hasCountOf(3)); - NSDictionary *firstCurrency = [currency objectAtIndex:0]; - assertThat(firstCurrency, is(instanceOf([NSDictionary class]))); - assertThat([firstCurrency objectForKey:@"name"], is(equalTo(@"AUD"))); - assertThat([firstCurrency objectForKey:@"quota"], is(equalTo(@"1"))); - assertThat([firstCurrency objectForKey:@"rate"], is(equalTo(@"18.416"))); - - NSDictionary *secondCurrency = [currency objectAtIndex:1]; - assertThat(secondCurrency, is(instanceOf([NSDictionary class]))); - assertThat([secondCurrency objectForKey:@"name"], is(equalTo(@"HRK"))); - assertThat([secondCurrency objectForKey:@"quota"], is(equalTo(@"1"))); - assertThat([secondCurrency objectForKey:@"rate"], is(equalTo(@"3.25017"))); - - NSDictionary *thirdCurrency = [currency objectAtIndex:2]; - assertThat(thirdCurrency, is(instanceOf([NSDictionary class]))); - assertThat([thirdCurrency objectForKey:@"name"], is(equalTo(@"DKK"))); - assertThat([thirdCurrency objectForKey:@"quota"], is(equalTo(@"1"))); - assertThat([thirdCurrency objectForKey:@"rate"], is(equalTo(@"3.251"))); -} - -- (void)testShouldNotCrashWhileParsingOrdersXML -{ - NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"orders.xml"]; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - NSException *exception = nil; - @try { - [parser objectFromString:XML error:&error];; - } - @catch (NSException *e) { - exception = e; - } - @finally { - assertThat(exception, is(nilValue())); - } -} - -- (void)testShouldParseXMLWithCDATA -{ - NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"zend.xml"]; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - NSDictionary *output = [parser objectFromString:XML error:&error]; - NSArray *map = [output valueForKeyPath:@"Api.getList.map"]; - assertThat(map, isNot(nilValue())); - assertThat(map, hasCountOf(4)); - assertThat([[map objectAtIndex:0] valueForKey:@"title"], is(equalTo(@"Main World Map"))); - assertThat([[map objectAtIndex:1] valueForKey:@"title"], is(equalTo(@"Section Map: Narshe Village"))); - assertThat([[map objectAtIndex:2] valueForKey:@"subtitle"], is(equalTo(@"Kary lives here."))); -} - -- (void)testShouldConsiderASingleCloseTagAnEmptyContainer -{ - NSString *XML = @""; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - NSDictionary *output = [parser objectFromString:XML error:&error]; - NSDictionary *users = [output valueForKey:@"users"]; - NSLog(@"%@", output); - assertThat(users, is(notNilValue())); - assertThatBool([users isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); -} - -- (void)testShouldParseRelativelyComplexXML -{ - NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"national_weather_service.xml"]; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - NSException *exception = nil; - @try { - [parser objectFromString:XML error:&error]; - } - @catch (NSException *e) { - exception = e; - } - @finally { - assertThat(exception, is(nilValue())); - } -} - -- (void)testShouldParseXMLElementsAndAttributesProperly -{ - - NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"channels.xml"]; - NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; - NSDictionary *result = [parser objectFromString:XML error:&error]; - - NSLog(@"result : %@", result); - - NSDictionary *channel = [[result objectForKey:@"Channels"] objectForKey:@"Channel"]; - assertThat(channel, is(notNilValue())); - - // Check to see if the Channel attributes are properly parsed - assertThat([channel objectForKey:@"Identifier"], is(equalTo(@"1172"))); - assertThat([channel objectForKey:@"Title"], is(equalTo(@"MySpecialTitle"))); - assertThat([channel objectForKey:@"Position"], is(equalTo(@"2234"))); - - NSLog(@"channel: %@", channel); - - // Check to see if the Channel elements are properly parsed - assertThat([channel objectForKey:@"Languages"], is(equalTo(@"it"))); - - assertThat([[channel objectForKey:@"Stream"] objectForKey:@"text"], is(equalTo(@"MySpecialTitle"))); - assertThat([[channel objectForKey:@"Stream"] objectForKey:@"Identifier"], is(equalTo(@"MySpecialTitle"))); - assertThat([[channel objectForKey:@"Stream"] objectForKey:@"Index"], is(equalTo(@"0"))); - - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:0] objectForKey:@"Identifier"], is(equalTo(@"42883461"))); - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:0] objectForKey:@"Start"], is(equalTo(@"2011-12-19 20:00:00Z"))); - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:0] objectForKey:@"End"], is(equalTo(@"2011-12-19 21:00:00Z"))); - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:0] objectForKey:@"Title"], is(equalTo(@"Program Title 1"))); - - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:1] objectForKey:@"Identifier"], is(equalTo(@"42883471"))); - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:1] objectForKey:@"Start"], is(equalTo(@"2011-12-19 21:00:00Z"))); - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:1] objectForKey:@"End"], is(equalTo(@"2011-12-19 23:00:00Z"))); - assertThat([[[channel objectForKey:@"Program"] objectAtIndex:1] objectForKey:@"Title"], is(equalTo(@"Program Title"))); - - assertThat([[channel objectForKey:@"Image"] objectAtIndex:0], is(equalTo(@"http://domain.com/Images/MySpecialTitle.png"))); - assertThat([[[channel objectForKey:@"Image"] objectAtIndex:1] objectForKey:@"text"], is(equalTo(@"http://domain.com/Images/65x35/2234.png"))); - assertThat([[[channel objectForKey:@"Image"] objectAtIndex:1] objectForKey:@"Width"], is(equalTo(@"65"))); - assertThat([[[channel objectForKey:@"Image"] objectAtIndex:1] objectForKey:@"Height"], is(equalTo(@"35"))); -} - -@end diff --git a/Tests/Models/RKHuman.m b/Tests/Models/RKHuman.m index 38f3963a..374c10e9 100644 --- a/Tests/Models/RKHuman.m +++ b/Tests/Models/RKHuman.m @@ -20,7 +20,6 @@ #import "RKHuman.h" -#import "NSDictionary+RKAdditions.h" @implementation RKHuman diff --git a/Tests/Models/RKMappableObject.m b/Tests/Models/RKMappableObject.m index 5dd9a9af..b37805d4 100644 --- a/Tests/Models/RKMappableObject.m +++ b/Tests/Models/RKMappableObject.m @@ -19,7 +19,6 @@ // #import "RKMappableObject.h" -#import "NSDictionary+RKAdditions.h" @implementation RKMappableObject