summaryrefslogtreecommitdiff
path: root/platform/ios/Integration Tests/Snapshotter Tests/MGLMapSnapshotterTest.m
blob: ca7462f1601b6c4b631194e38860ed4b366f4373 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#import "MGLMapViewIntegrationTest.h"

@interface MGLMapSnapshotter ()
@property (nonatomic) BOOL cancelled;
@end


@interface MGLMapSnapshotterTest : MGLMapViewIntegrationTest
@end

// Convenience func to create snapshotter
MGLMapSnapshotter* snapshotterWithCoordinates(CLLocationCoordinate2D coordinates, CGSize size) {
    // Create snapshot options
    MGLMapCamera* mapCamera    = [[MGLMapCamera alloc] init];
    mapCamera.pitch            = 20;
    mapCamera.centerCoordinate = coordinates;
    MGLMapSnapshotOptions* options = [[MGLMapSnapshotOptions alloc] initWithStyleURL:[MGLStyle satelliteStreetsStyleURL]
                                                                              camera:mapCamera
                                                                                size:size];
    options.zoomLevel = 10;

    // Create and start the snapshotter
    MGLMapSnapshotter* snapshotter = [[MGLMapSnapshotter alloc] initWithOptions:options];
    return snapshotter;
}

@implementation MGLMapSnapshotterTest

- (void)testMultipleSnapshotsWithASingleSnapshotter {
    if (![self validAccessToken]) {
        return;
    }

    CGSize size = self.mapView.bounds.size;

    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshots"];
    expectation.expectedFulfillmentCount = 2;
    expectation.assertForOverFulfill = YES;

    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(30.0, 30.0);

    MGLMapSnapshotter *snapshotter = snapshotterWithCoordinates(coord, size);
    XCTAssertNotNil(snapshotter);

    [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
        [expectation fulfill];
    }];

    @try {
        [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
            XCTFail(@"Should not be called - but should it?");
        }];
        XCTFail(@"Should not be called");
    }
    @catch (NSException *exception) {
        XCTAssert(exception.name == NSInternalInconsistencyException);
        [expectation fulfill];
    }

    [self waitForExpectations:@[expectation] timeout:10.0];
}

- (void)testDeallocatingSnapshotterDuringSnapshot {
    // See also https://github.com/mapbox/mapbox-gl-native/issues/12336
    if (![self validAccessToken]) {
        return;
    }

    NSTimeInterval timeout         = 5.0;
    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshot"];
    CGSize size                    = self.mapView.bounds.size;
    CLLocationCoordinate2D coord   = CLLocationCoordinate2DMake(30.0, 30.0);

    // Test triggering to main queue
    dispatch_queue_t backgroundQueue = dispatch_get_main_queue();
//  dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    __weak __typeof__(self) weakself = self;

    dispatch_async(backgroundQueue, ^{

        dispatch_group_t dg = dispatch_group_create();
        dispatch_group_enter(dg);

        dispatch_async(dispatch_get_main_queue(), ^{
            MGLMapSnapshotter *snapshotter = snapshotterWithCoordinates(coord, size);
            __weak MGLMapSnapshotter *weakSnapshotter = snapshotter;
            
            [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
                // We expect this completion block to be called with an error
                __typeof__(self) strongself = weakself;

                MGLTestAssertNil(strongself, snapshot);
                MGLTestAssert(strongself,
                              ([error.domain isEqualToString:MGLErrorDomain] && error.code == MGLErrorCodeSnapshotFailed),
                              @"Should have errored");
                MGLTestAssertNil(strongself, weakSnapshotter, @"Snapshotter should have been deallocated");

                dispatch_group_leave(dg);
            }];
        });

        dispatch_group_notify(dg, dispatch_get_main_queue(), ^{
            [expectation fulfill];
        });
    });

    [self waitForExpectations:@[expectation] timeout:timeout];
}

- (void)testSnapshotterUsingNestedDispatchQueues {
    // This is the opposite pair to the above test `testDeallocatingSnapshotterDuringSnapshot`
    // The only significant difference is that the snapshotter is a `__block` variable, so
    // its lifetime should continue until it's set to nil in the completion block.
    // See also https://github.com/mapbox/mapbox-gl-native/issues/12336

    if (![self validAccessToken]) {
        return;
    }

    NSTimeInterval timeout         = 5.0;
    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshot"];
    CGSize size                    = self.mapView.bounds.size;
    CLLocationCoordinate2D coord   = CLLocationCoordinate2DMake(30.0, 30.0);

    // Test triggering to main queue
    dispatch_queue_t backgroundQueue = dispatch_get_main_queue();
    //  dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    __weak __typeof__(self) weakself = self;

    dispatch_async(backgroundQueue, ^{

        dispatch_group_t dg = dispatch_group_create();
        dispatch_group_enter(dg);

        dispatch_async(dispatch_get_main_queue(), ^{

            __block MGLMapSnapshotter *snapshotter = snapshotterWithCoordinates(coord, size);

            [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
                // We expect this completion block to be called with an error
                __typeof__(self) strongself = weakself;
                MGLTestAssertNotNil(strongself, snapshot);
                MGLTestAssertNil(strongself, error, @"Snapshotter should have completed");
                dispatch_group_leave(dg);
                snapshotter = nil;
            }];
        });

        dispatch_group_notify(dg, dispatch_get_main_queue(), ^{
            [expectation fulfill];
        });
    });

    [self waitForExpectations:@[expectation] timeout:timeout];
}

- (void)testCancellingSnapshot {
    if (![self validAccessToken]) {
        return;
    }

    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshots"];
    expectation.assertForOverFulfill = YES;
    expectation.expectedFulfillmentCount = 1;

    CGSize size                    = self.mapView.bounds.size;
    CLLocationCoordinate2D coord   = CLLocationCoordinate2DMake(30.0, 30.0);

    MGLMapSnapshotter *snapshotter = snapshotterWithCoordinates(coord, size);

    __weak __typeof__(self) weakself = self;

    [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
        // We expect this completion block to be called with an error
        __typeof__(self) strongself = weakself;

        MGLTestAssertNil(strongself, snapshot);
        MGLTestAssert(strongself,
                      ([error.domain isEqualToString:MGLErrorDomain] && error.code == MGLErrorCodeSnapshotFailed),
                      @"Should have been cancelled");
        MGLTestAssert(strongself, snapshotter.cancelled, @"Should have been cancelled");
        [expectation fulfill];
    }];

    [snapshotter cancel];

    [self waitForExpectations:@[expectation] timeout:0.5];
}

- (void)testAllocatingSnapshotOnBackgroundQueue {
    if (![self validAccessToken]) {
        return;
    }

    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshots"];

    CGSize size                  = self.mapView.bounds.size;
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(30.0, 30.0);

    dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, QOS_MIN_RELATIVE_PRIORITY);
    dispatch_queue_t backgroundQueue = dispatch_queue_create(__PRETTY_FUNCTION__, attr);

    dispatch_async(backgroundQueue, ^{

        // Create the snapshotter - DO NOT START.
        MGLMapSnapshotter* snapshotter = snapshotterWithCoordinates(coord, size);

        dispatch_group_t group = dispatch_group_create();
        dispatch_group_enter(group);

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_group_leave(group);
        });

        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

        snapshotter = nil;

        dispatch_sync(dispatch_get_main_queue(), ^{
            [expectation fulfill];
        });
    });

    [self waitForExpectations:@[expectation] timeout:2.0];
}

- (void)testSnapshotterFromBackgroundQueueShouldFail {
    if (![self validAccessToken]) {
        return;
    }

    CGSize size = self.mapView.bounds.size;
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(30.0, 30.0);

    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshots"];
    expectation.expectedFulfillmentCount = 1;
    expectation.assertForOverFulfill = YES;

    __weak __typeof__(self) weakself = self;

    dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, QOS_MIN_RELATIVE_PRIORITY); // also for concurrent
    dispatch_queue_t backgroundQueue = dispatch_queue_create(__PRETTY_FUNCTION__, attr);

    // Use dispatch_group to keep the backgroundQueue block around (and
    // so also the MGLMapSnapshotter
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);

    dispatch_async(backgroundQueue, ^{

        MGLMapSnapshotter *snapshotter = snapshotterWithCoordinates(coord, size);
        XCTAssertNotNil(snapshotter);

        MGLMapSnapshotCompletionHandler completion = ^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
            // The completion block should not be called
            MGLTestFail(weakself);
            dispatch_group_leave(group);
        };

        @try {
            [snapshotter startWithCompletionHandler:completion];
            MGLTestFail(weakself, @"startWithCompletionHandler: should raise an exception");
        }
        @catch (NSException *exception) {
            MGLTestAssert(weakself, exception.name == NSInvalidArgumentException);
            dispatch_group_leave(group);
        }

        // Wait for the snapshot to complete
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

        snapshotter = nil;

        dispatch_sync(dispatch_get_main_queue(), ^{
            [expectation fulfill];
        });
    });

    [self waitForExpectations:@[expectation] timeout:60.0];
}

- (void)testMultipleSnapshottersPENDING {

    if (![self validAccessToken]) {
        return;
    }

    NSUInteger numSnapshots = 8;
    CGSize size = self.mapView.bounds.size;

    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshots"];
    expectation.expectedFulfillmentCount = numSnapshots;
    expectation.assertForOverFulfill = YES;

    __weak __typeof__(self) weakself = self;

    for (size_t run = 0; run < numSnapshots; run++) {

        float ratio = (float)run/(float)numSnapshots;
        float lon = (ratio*120.0) + ((1.0-ratio)*54.0);
        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(57.0, lon);

        __block MGLMapSnapshotter *snapshotter;

        // Allocate from an autorelease pool here, to avoid having
        // snapshotter retained for longer than we'd like to test.
        @autoreleasepool {
            snapshotter = snapshotterWithCoordinates(coord, size);
            XCTAssertNotNil(snapshotter);
        }

        [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {

            // This should be the main queue
            __typeof__(self) strongself = weakself;

            MGLTestAssertNotNil(strongself, strongself);

            MGLTestAssertNotNil(strongself, snapshot);
            MGLTestAssertNotNil(strongself, snapshot.image);
            MGLTestAssertNil(strongself, error, @"Snapshot should not error with: %@", error);

            // Change this to XCTAttachmentLifetimeKeepAlways to be able to look at the snapshots after running
            XCTAttachment *attachment = [XCTAttachment attachmentWithImage:snapshot.image];
            attachment.lifetime = XCTAttachmentLifetimeDeleteOnSuccess;
            [strongself addAttachment:attachment];

            // Dealloc the snapshotter (by having this line in the block, we
            // also retained the snapshotter. Setting to nil should release, as
            // this block should be the only thing retaining it (since it was
            // allocated from the above autorelease pool)
            snapshotter = nil;

            [expectation fulfill];
        }];
    } // end for loop

    [self waitForExpectations:@[expectation] timeout:60.0];
}

- (void)testSnapshotPointConversion {
    if (![self validAccessToken]) {
        return;
    }

    CGSize size = self.mapView.bounds.size;

    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshot"];
    expectation.expectedFulfillmentCount = 1;
    expectation.assertForOverFulfill = YES;

    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(30.0, 30.0);

    MGLMapSnapshotter *snapshotter = snapshotterWithCoordinates(coord, size);
    XCTAssertNotNil(snapshotter);

    __weak __typeof__(self) weakself = self;

    [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {

        __typeof__(self) myself = weakself;

        MGLTestAssertNotNil(myself, snapshot);

        CGPoint point = [snapshot pointForCoordinate:coord];

        CGFloat epsilon = 0.000001;

        MGLTestAssertEqualWithAccuracy(myself, point.x, size.width/2.0, epsilon);
        MGLTestAssertEqualWithAccuracy(myself, point.y, size.height/2.0, epsilon);

        CLLocationCoordinate2D coord2 = [snapshot coordinateForPoint:point];

        MGLTestAssertEqualWithAccuracy(myself, coord.latitude, coord2.latitude, epsilon);
        MGLTestAssertEqualWithAccuracy(myself, coord.longitude, coord2.longitude, epsilon);

        [expectation fulfill];
    }];

    [self waitForExpectations:@[expectation] timeout:5.0];
}

- (void)testSnapshotPointConversionCoordinateOrdering {
    if (![self validAccessToken]) {
        return;
    }

    CGSize size = self.mapView.bounds.size;

    XCTestExpectation *expectation = [self expectationWithDescription:@"snapshot"];
    expectation.expectedFulfillmentCount = 1;
    expectation.assertForOverFulfill = YES;

    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(30.0, 30.0);

    MGLMapSnapshotter *snapshotter = snapshotterWithCoordinates(coord, size);
    XCTAssertNotNil(snapshotter);

    __weak __typeof__(self) weakself = self;

    [snapshotter startWithCompletionHandler:^(MGLMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {

        __typeof__(self) myself = weakself;

        CGFloat epsilon = 0.000001;

        MGLTestAssertNotNil(myself, snapshot);

        CLLocationCoordinate2D coordTL = [snapshot coordinateForPoint:CGPointZero];

        MGLTestAssert(myself, coordTL.longitude < coord.longitude);
        MGLTestAssert(myself, coordTL.latitude > coord.latitude);

        // And check point
        CGPoint tl = [snapshot pointForCoordinate:coordTL];
        MGLTestAssertEqualWithAccuracy(myself, tl.x, 0.0, epsilon);
        MGLTestAssertEqualWithAccuracy(myself, tl.y, 0.0, epsilon);

        CLLocationCoordinate2D coordBR = [snapshot coordinateForPoint:CGPointMake(size.width, size.height)];

        MGLTestAssert(myself, coordBR.longitude > coord.longitude);
        MGLTestAssert(myself, coordBR.latitude < coord.latitude);

        [expectation fulfill];
    }];

    [self waitForExpectations:@[expectation] timeout:5.0];
}


@end