Slide 1

Slide 1 text

Consuming Web APIs, the TDD way

Slide 2

Slide 2 text

Luis Solano @luisobo

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

Good practices for networking code Quick intro to Test-driven development Tackle real life testing scenarios Underlaying principles of TDD Error handling

Slide 5

Slide 5 text

API Client design

Slide 6

Slide 6 text

Sockets HTTP Business logic Application

Slide 7

Slide 7 text

Sockets HTTP Business logic Application

Slide 8

Slide 8 text

Sockets HTTP Business logic Application API Client Abstraction

Slide 9

Slide 9 text

API Client Abstraction HTTP Content type negotiation HTTP error handling Authentication Parsing Caching Background Business error handling Business logic Retries State

Slide 10

Slide 10 text

Test-driven development

Slide 11

Slide 11 text

Test Implementation Refactor

Slide 12

Slide 12 text

Design tool Tests are a nice side effect of TDD Short feedback loop Enable us to modify our code

Slide 13

Slide 13 text

GET /dogs.json { "dogs": [{ "name": "perro", "color": "brown" },{ "name": "tomas", "color": "black" }] }

Slide 14

Slide 14 text

Our first test

Slide 15

Slide 15 text

it(@"retrieves dogs", ^{ ! ! ! ! ! ! ! ! ! }); ! [[LSBDogCare new] allDogs:^(NSArray *dogs) { ! } failure:^(NSError *error) { }]; [[expectFutureValue(capturedDogs) shouldEventually] equal:@[@{@"name":@"perro",@"color":@"brown"}, @{@"name":@"tomas",@"color":@"black"} ]]; __block NSArray *capturedDogs = nil; ! capturedDogs = dogs;

Slide 16

Slide 16 text

@implementation LSBDogCare ! - (void)allDogs:(void(^)(NSArray *dogs))success failure:(void(^)(NSError *error))failure { ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! } ! @end NSURL *url = [NSURL URLWithString:@"http://api.example.com/dogs.json"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; AFJSONRequestOperation *op; op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary *JSON) { ! ! } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *requestError, id JSON) { }]; success(JSON[@"dogs"]); [op start];

Slide 17

Slide 17 text

it(@"retrieves dogs", ^{ ! __block NSArray *capturedDogs = nil; [[LSBDogCare new] allDogs:^(NSArray *dogs) { capturedDogs = dogs; } failure:^(NSError *error) { }]; [[expectFutureValue(capturedDogs) shouldEventually] equal:@[@{@"name":@"perro",@"color":@"brown"}, @{@"name":@"tomas",@"color":@"black"} ]]; ! });

Slide 18

Slide 18 text

Isolate tests from undeterministic and slow depencencies.

Slide 19

Slide 19 text

it(@"retrieves dogs", ^{ ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! __block NSArray *capturedDogs = nil; [[LSBDogCare new] allDogs:^(NSArray *dogs) { capturedDogs = dogs; } failure:^(NSError *error) { ! }]; ! [[expectFutureValue(capturedDogs) shouldEventually] equal:@[@{@"name":@"perro",@"color":@"brown"}]]; ! }); AFJSONRequestOperation *mockOp = [AFJSONRequestOperation mock]; [AFJSONRequestOperation stub:@selector(JSONRequestOperationWithRequest:success:failure:) withBlock:^id(NSArray *params) { ! ! return mockOp; }]; [mockOp stub:@selector(start) withBlock:^id(NSArray *params) { capturedSuccess(capturedRequest, [NSHTTPURLResponse mock], @{@"dogs":@[@{@"name":@"perro",@"color":@"brown"}]}); return nil; }]; __block NSURLRequest *capturedRequest; __block void (^capturedSuccess)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON); capturedRequest = params[0]; capturedSuccess = params[1];

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

Don’t couple test with implementation details

Slide 22

Slide 22 text

Tests exist to let us modify our code.

Slide 23

Slide 23 text

Test Implementation Refactor What my coworkers think I do

Slide 24

Slide 24 text

Test Implementation Refactor Change a test Change implementation Shit I forgot to stub that What I actually do

Slide 25

Slide 25 text

$ git reset --hard

Slide 26

Slide 26 text

Don’t modify test and implementation at the same time

Slide 27

Slide 27 text

it(@"retrieves dogs", ^{ ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! __block NSArray *capturedDogs = nil; [[LSBDogCare new] allDogs:^(NSArray *dogs) { capturedDogs = dogs; } failure:^(NSError *error) { ! }]; ! [[expectFutureValue(capturedDogs) shouldEventually] equal:@[@{@"name":@"perro",@"color":@"brown"}]]; ! }); AFJSONRequestOperation *mockOp = [AFJSONRequestOperation mock]; [AFJSONRequestOperation stub:@selector(JSONRequestOperationWithRequest:success:failure:) withBlock:^id(NSArray *params) { ! ! return mockOp; }]; [mockOp stub:@selector(start) withBlock:^id(NSArray *params) { capturedSuccess(capturedRequest, [NSHTTPURLResponse mock], @{@"dogs":@[@{@"name":@"perro",@"color":@"brown"}]}); return nil; }]; __block NSURLRequest *capturedRequest; __block void (^capturedSuccess)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON); capturedRequest = params[0]; capturedSuccess = params[1];

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

it(@"retrieves dogs", ^{ ! ! ! ! ! ! __block NSArray *capturedDogs = nil; [[LSBDogCare new] allDogs:^(NSArray *dogs) { capturedDogs = dogs; } failure:^(NSError *error) { ! }]; ! [[expectFutureValue(capturedDogs) shouldEventually] equal:@[@{@"name":@"perro",@"color":@"brown"}, @{@"name":@"tomas",@"color":@"black"}]]; }); stubRequest(@"GET", @"http://api.example.com/dogs.json") .andReturn(200) .withHeaders(@{ @"Content-Type": @"application/json;charset=utf-8" }) .withBody([@{@"dogs":@[ @{@"name":@"perro",@"color":@"brown"}, @{@"name":@"tomas",@"color":@"black"}] } JSONString]);

Slide 30

Slide 30 text

context(@"when retrieving dogs fail because access was revoked", ^{ it(@"reports an error", ^{ ! ! ! ! ! ! ! ! ! ! ! ! ! }); }); __block NSError *capturedError; [[LSBDogCare new] allDogs:^(NSArray *dogs) { } failure:^(NSError *error) { capturedError = error; }]; [[expectFutureValue(capturedError) shouldEventually] equal:[NSError errorWithDomain:@"com.luisobo.dogcare" code:23 userInfo:@{ NSLocalizedDescriptionKey: @"uh uh uh, you didn't say the magic word" }]]; stubRequest(@"GET", @"http://api.example.com/dogs.json") .andReturn(401);

Slide 31

Slide 31 text

- (void)allDogs:(void(^)(NSArray *dogs))success failure:(void(^)(NSError *error))failure { ! // ... op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary *JSON) { success(JSON[@"dogs"]); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { ! ! ! ! ! ! ! ! ! ! ! ! }]; ! [op start]; } if (response.statusCode == 401) { error = [NSError errorWithDomain:@"com.luisobo.dogcare" code:23 userInfo:@{ NSLocalizedDescriptionKey: @"uh uh uh, you didn't say the magic word" }]; } failure(error);

Slide 32

Slide 32 text

context(@"when the request fails because there is no internet", ^{ it(@"reports an error", ^{ ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! }); }); __block NSError *capturedError; [[LSBDogCare new] allDogs:^(NSArray *dogs) { } failure:^(NSError *error) { capturedError = error; }]; [[expectFutureValue(capturedError) shouldEventually] equal:[NSError errorWithDomain:@"com.luisobo.dogcare" code:446 userInfo:@{ NSLocalizedDescriptionKey: @"eeeer, check your internet dumbass" }]]; stubRequest(@"GET", @"http://api.example.com/dogs.json") .andFailWithError([NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotConnectToHost userInfo:nil]);

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

Test Implementation Refactor

Slide 35

Slide 35 text

https://github.com/luisobo/Nocilla

Slide 36

Slide 36 text

Error handling The operation could not be completed. (com.facebook.sdk error 2)

Slide 37

Slide 37 text

NSError = domain + code

Slide 38

Slide 38 text

1.Developer screw-ups 2.Automatic recoverable errors (e.g. reauthorize) 3.User recoverable errors (e.g. validation, ask for more permissions) 4.Known non-recoverable errors. (e.g. server is down, rate limiting) 5.“How the hell did I get here?” errors

Slide 39

Slide 39 text

Group errors based on how the client is going to recover from them

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

No content

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

@interface NSError (FacebookAPI) ! ! ! ! ! ! ! @end + (instancetype)facebookAPIErrorWithResponse:(NSDictionary *)response; ! - (BOOL)isFacebookAPIError; // com.facebook.api ? ! - (BOOL)shouldRecoverByReauthorizing; - (BOOL)shouldRecoverByRequestingMorePermissions; - (BOOL)shouldRecoverByNotifyingUser;

Slide 46

Slide 46 text

failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { ! ! ! ! ! ! ! ! ! ! } NSError *facebookError = [NSError facebookAPIErrorWithResponse:JSON]; if ([facebookError shouldRecoverByReauthorizing]) { // Reauthorize } else if ([facebookError shouldRecoverByRequestingMorePermissions]) { // Request more permissions } else if ([facebookError shouldRecoverByNotifyingUser]) { }

Slide 47

Slide 47 text

@interface NSError (FacebookSDK) + (instancetype)facebookSDKErrorWithError:(NSError *)error; ! - (BOOL)isFacebookSDKError; // com.facebook.sdk ? ! // ... Same deal @end

Slide 48

Slide 48 text

HTTP Business logic com.facebook.api com.facebook.sdk request like POST /likes

Slide 49

Slide 49 text

failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { ! ! ! ! ! ! ! ! ! ! ! ! } NSError *facebookError = [NSError facebookAPIErrorWithResponse:JSON]; if ([facebookError shouldRecoverByReauthorizing]) { // Reauthorize } else if ([facebookError shouldRecoverByRequestingMorePermissions]) { // Request more permissions } else if ([facebookError shouldRecoverByNotifyingUser]) { } else { failure([NSError genericError]); } failure([NSError facebookSDKErrorWithError:error]); // Ensure consistent state // Log facebookError in a remote service

Slide 50

Slide 50 text

Build an abstraction on top of of an stateless wrapper Isolate test from undeterministic and slow dependencies. Don’t modify implementation and tests at the same time. Don’t couple test with implementation details Group errors by recover strategy

Slide 51

Slide 51 text

Thanks Say hi @luisobo