summaryrefslogtreecommitdiff
path: root/SmartDeviceLinkTests/DevAPISpecs/SDLFileManagerSpec.m
blob: 8a7a0db7811da5ab0446d4ad586f6a9658b1da45 (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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
#import <Quick/Quick.h>
#import <Nimble/Nimble.h>

#import "SDLDeleteFileResponse.h"
#import "SDLError.h"
#import "SDLFile.h"
#import "SDLFileManager.h"
#import "SDLFileType.h"
#import "SDLListFiles.h"
#import "SDLListFilesOperation.h"
#import "SDLListFilesResponse.h"
#import "SDLNotificationConstants.h"
#import "SDLPutFile.h"
#import "SDLPutFileResponse.h"
#import "SDLRPCResponse.h"
#import "TestConnectionManager.h"
#import "TestMultipleFilesConnectionManager.h"
#import "TestProgressResponse.h"
#import "TestResponse.h"

typedef NSString SDLFileManagerState;
SDLFileManagerState *const SDLFileManagerStateShutdown = @"Shutdown";
SDLFileManagerState *const SDLFileManagerStateFetchingInitialList = @"FetchingInitialList";
SDLFileManagerState *const SDLFileManagerStateReady = @"Ready";

@interface SDLFileManager ()
@property (strong, nonatomic) NSOperationQueue *transactionQueue;
@property (strong, nonatomic) NSMutableSet<SDLFileName *> *uploadedEphemeralFileNames;
@end

QuickSpecBegin(SDLFileManagerSpec)

describe(@"SDLFileManager", ^{
    __block TestConnectionManager *testConnectionManager = nil;
    __block SDLFileManager *testFileManager = nil;
    __block NSUInteger initialSpaceAvailable = 250;

    beforeEach(^{
        testConnectionManager = [[TestConnectionManager alloc] init];
        testFileManager = [[SDLFileManager alloc] initWithConnectionManager:testConnectionManager];
        testFileManager.suspended = YES;
    });

    describe(@"before starting", ^{
        it(@"should be in the shutdown state", ^{
            expect(testFileManager.currentState).to(match(SDLFileManagerStateShutdown));
        });

        it(@"bytesAvailable should be 0", ^{
            expect(@(testFileManager.bytesAvailable)).to(equal(@0));
        });

        it(@"remoteFileNames should be empty", ^{
            expect(testFileManager.remoteFileNames).to(beEmpty());
        });

        it(@"should have no pending operations", ^{
            expect(testFileManager.pendingTransactions).to(beEmpty());
        });
    });

    describe(@"after receiving a start message", ^{
        __block BOOL startupSuccess = NO;
        __block NSError *startupError = nil;

        beforeEach(^{
            [testFileManager startWithCompletionHandler:^(BOOL success, NSError * _Nullable error) {
                startupSuccess = success;
                startupError = error;
            }];

            testFileManager.suspended = NO;

            [NSThread sleepForTimeInterval:0.1];
        });

        it(@"should have queued a ListFiles request", ^{
            expect(testFileManager.pendingTransactions).to(haveCount(@1));
            expect(testFileManager.pendingTransactions.firstObject).to(beAnInstanceOf([SDLListFilesOperation class]));
        });

        it(@"should be in the fetching initial list state", ^{
            expect(testFileManager.currentState).to(match(SDLFileManagerStateFetchingInitialList));
        });

        describe(@"after going to the shutdown state and receiving a ListFiles response", ^{
            __block SDLListFilesResponse *testListFilesResponse = nil;
            __block NSSet<NSString *> *testInitialFileNames = nil;

            beforeEach(^{
                testInitialFileNames = [NSSet setWithArray:@[@"testFile1", @"testFile2", @"testFile3"]];

                testListFilesResponse = [[SDLListFilesResponse alloc] init];
                testListFilesResponse.success = @YES;
                testListFilesResponse.spaceAvailable = @(initialSpaceAvailable);
                testListFilesResponse.filenames = [NSArray arrayWithArray:[testInitialFileNames allObjects]];

                [testFileManager stop];
                [testConnectionManager respondToLastRequestWithResponse:testListFilesResponse];
            });

            it(@"should remain in the stopped state after receiving the response if disconnected", ^{

                expect(testFileManager.currentState).toEventually(match(SDLFileManagerStateShutdown));
            });
        });

        describe(@"after receiving a ListFiles response", ^{
            __block SDLListFilesResponse *testListFilesResponse = nil;
            __block NSSet<NSString *> *testInitialFileNames = nil;

            beforeEach(^{
                testInitialFileNames = [NSSet setWithArray:@[@"testFile1", @"testFile2", @"testFile3"]];

                testListFilesResponse = [[SDLListFilesResponse alloc] init];
                testListFilesResponse.success = @YES;
                testListFilesResponse.spaceAvailable = @(initialSpaceAvailable);
                testListFilesResponse.filenames = [NSArray arrayWithArray:[testInitialFileNames allObjects]];
                [testConnectionManager respondToLastRequestWithResponse:testListFilesResponse];
            });

            it(@"the file manager should be in the correct state", ^{
                [testConnectionManager respondToLastRequestWithResponse:testListFilesResponse];

                expect(testFileManager.currentState).toEventually(match(SDLFileManagerStateReady));
                expect(testFileManager.remoteFileNames).toEventually(equal(testInitialFileNames));
                expect(@(testFileManager.bytesAvailable)).toEventually(equal(@(initialSpaceAvailable)));
            });

            describe(@"deleting a file", ^{
                __block BOOL completionSuccess = NO;
                __block NSUInteger completionBytesAvailable = 0;
                __block NSError *completionError = nil;

                context(@"when the file is unknown", ^{
                    beforeEach(^{
                        NSString *someUnknownFileName = @"Some Unknown File Name";
                        [testFileManager deleteRemoteFileWithName:someUnknownFileName completionHandler:^(BOOL success, NSUInteger bytesAvailable, NSError * _Nullable error) {
                            completionSuccess = success;
                            completionBytesAvailable = bytesAvailable;
                            completionError = error;
                        }];

                        [NSThread sleepForTimeInterval:0.1];
                    });

                    it(@"should return the correct data", ^{
                        expect(@(completionSuccess)).toEventually(equal(@NO));
                        expect(@(completionBytesAvailable)).toEventually(equal(@250));
                        expect(completionError).toEventually(equal([NSError sdl_fileManager_noKnownFileError]));
                    });

                    it(@"should not have deleted any files in the file manager", ^{
                        expect(testFileManager.remoteFileNames).toEventually(haveCount(@(testInitialFileNames.count)));
                    });
                });

                context(@"when the file is known", ^{
                    __block NSUInteger newSpaceAvailable = 600;
                    __block NSString *someKnownFileName = nil;
                    __block BOOL completionSuccess = NO;
                    __block NSUInteger completionBytesAvailable = 0;
                    __block NSError *completionError = nil;

                    beforeEach(^{
                        someKnownFileName = [testInitialFileNames anyObject];
                        [testFileManager deleteRemoteFileWithName:someKnownFileName completionHandler:^(BOOL success, NSUInteger bytesAvailable, NSError * _Nullable error) {
                            completionSuccess = success;
                            completionBytesAvailable = bytesAvailable;
                            completionError = error;
                        }];

                        SDLDeleteFileResponse *deleteResponse = [[SDLDeleteFileResponse alloc] init];
                        deleteResponse.success = @YES;
                        deleteResponse.spaceAvailable = @(newSpaceAvailable);

                        [NSThread sleepForTimeInterval:0.1];

                        [testConnectionManager respondToLastRequestWithResponse:deleteResponse];
                    });

                    it(@"should return the correct data", ^{
                        expect(@(completionSuccess)).to(equal(@YES));
                        expect(@(completionBytesAvailable)).to(equal(@(newSpaceAvailable)));
                        expect(@(testFileManager.bytesAvailable)).to(equal(@(newSpaceAvailable)));
                        expect(completionError).to(beNil());
                    });

                    it(@"should have removed the file from the file manager", ^{
                        expect(testFileManager.remoteFileNames).toNot(contain(someKnownFileName));
                    });
                });
            });

            describe(@"uploading a new file", ^{
                __block NSString *testFileName = nil;
                __block SDLFile *testUploadFile = nil;
                __block BOOL completionSuccess = NO;
                __block NSUInteger completionBytesAvailable = 0;
                __block NSError *completionError = nil;

                __block SDLPutFile *sentPutFile = nil;
                __block NSData *testFileData = nil;

                context(@"when there is a remote file named the same thing", ^{
                    beforeEach(^{
                        testFileName = [testInitialFileNames anyObject];
                        testFileData = [@"someData" dataUsingEncoding:NSUTF8StringEncoding];
                        testUploadFile = [SDLFile fileWithData:testFileData name:testFileName fileExtension:@"bin"];
                    });

                    context(@"when the file's overwrite property is YES", ^{
                        beforeEach(^{
                            testUploadFile.overwrite = YES;

                            [testFileManager uploadFile:testUploadFile completionHandler:^(BOOL success, NSUInteger bytesAvailable, NSError * _Nullable error) {
                                completionSuccess = success;
                                completionBytesAvailable = bytesAvailable;
                                completionError = error;
                            }];

                            [NSThread sleepForTimeInterval:0.1];

                            sentPutFile = testConnectionManager.receivedRequests.lastObject;
                        });

                        it(@"should set the file manager state to be waiting", ^{
                            expect(testFileManager.currentState).to(match(SDLFileManagerStateReady));
                            expect(testFileManager.uploadedEphemeralFileNames).to(beEmpty());
                        });

                        it(@"should create a putfile with the correct data", ^{
                            expect(sentPutFile.length).to(equal(@(testFileData.length)));
                            expect(sentPutFile.bulkData).to(equal(testFileData));
                            expect(sentPutFile.fileType).to(match(SDLFileTypeBinary));
                        });

                        context(@"when the response returns without error", ^{
                            __block SDLPutFileResponse *testResponse = nil;
                            __block NSNumber *testResponseSuccess = nil;
                            __block NSNumber *testResponseBytesAvailable = nil;

                            beforeEach(^{
                                testResponseBytesAvailable = @750;
                                testResponseSuccess = @YES;

                                testResponse = [[SDLPutFileResponse alloc] init];
                                testResponse.success = testResponseSuccess;
                                testResponse.spaceAvailable = testResponseBytesAvailable;

                                [testConnectionManager respondToLastRequestWithResponse:testResponse];
                            });

                            it(@"should set the file manager data correctly", ^{
                                expect(@(testFileManager.bytesAvailable)).toEventually(equal(testResponseBytesAvailable));
                                expect(testFileManager.currentState).toEventually(match(SDLFileManagerStateReady));
                                expect(testFileManager.remoteFileNames).toEventually(contain(testFileName));
                                expect(testFileManager.uploadedEphemeralFileNames).toEventually(contain(testFileName));
                            });

                            it(@"should call the completion handler with the correct data", ^{
                                expect(@(completionBytesAvailable)).toEventually(equal(testResponseBytesAvailable));
                                expect(@(completionSuccess)).toEventually(equal(@YES));
                                expect(completionError).to(beNil());
                            });
                        });

                        context(@"when the connection returns failure", ^{
                            __block SDLPutFileResponse *testResponse = nil;
                            __block NSNumber *testResponseBytesAvailable = nil;
                            __block NSNumber *testResponseSuccess = nil;

                            beforeEach(^{
                                testResponseBytesAvailable = @750;
                                testResponseSuccess = @NO;

                                testResponse = [[SDLPutFileResponse alloc] init];
                                testResponse.spaceAvailable = testResponseBytesAvailable;
                                testResponse.success = testResponseSuccess;

                                [testConnectionManager respondToLastRequestWithResponse:testResponse];
                            });

                            it(@"should set the file manager data correctly", ^{
                                expect(@(testFileManager.bytesAvailable)).toEventually(equal(@(initialSpaceAvailable)));
                                expect(testFileManager.remoteFileNames).toEventually(contain(testFileName));
                                expect(testFileManager.currentState).toEventually(match(SDLFileManagerStateReady));
                                expect(testFileManager.uploadedEphemeralFileNames).to(beEmpty());
                            });

                            it(@"should call the completion handler with the correct data", ^{
                                expect(@(completionBytesAvailable)).to(equal(@0));
                                expect(@(completionSuccess)).to(equal(testResponseSuccess));
                                expect(completionError).toEventually(beNil());
                            });
                        });

                        context(@"when the connection errors without a response", ^{
                            beforeEach(^{
                                [testConnectionManager respondToLastRequestWithResponse:nil error:[NSError sdl_lifecycle_notReadyError]];
                            });

                            it(@"should have the correct file manager state", ^{
                                expect(testFileManager.remoteFileNames).to(contain(testFileName));
                                expect(testFileManager.currentState).to(match(SDLFileManagerStateReady));
                            });

                            it(@"should call the completion handler with correct data", ^{
                                expect(completionError).toEventually(equal([NSError sdl_lifecycle_notReadyError]));
                            });
                        });
                    });

                    context(@"when allow overwrite is NO", ^{
                        __block SDLRPCRequest *lastRequest = nil;

                        beforeEach(^{
                            testUploadFile.overwrite = NO;

                            [testFileManager uploadFile:testUploadFile completionHandler:^(BOOL success, NSUInteger bytesAvailable, NSError * _Nullable error) {
                                completionSuccess = success;
                                completionBytesAvailable = bytesAvailable;
                                completionError = error;
                            }];

                            [NSThread sleepForTimeInterval:0.1];

                            lastRequest = testConnectionManager.receivedRequests.lastObject;
                        });

                        it(@"should have called the completion handler with correct data", ^{
                            expect(lastRequest).toNot(beAnInstanceOf([SDLPutFile class]));
                            expect(@(completionSuccess)).to(equal(@NO));
                            expect(@(completionBytesAvailable)).to(equal(@(testFileManager.bytesAvailable)));
                            expect(completionError).to(equal([NSError sdl_fileManager_cannotOverwriteError]));
                        });
                    });
                });

                context(@"when there is not a remote file named the same thing", ^{
                    beforeEach(^{
                        testFileName = @"not a test file";
                        testFileData = [@"someData" dataUsingEncoding:NSUTF8StringEncoding];
                        testUploadFile = [SDLFile fileWithData:testFileData name:testFileName fileExtension:@"bin"];

                        [testFileManager uploadFile:testUploadFile completionHandler:^(BOOL success, NSUInteger bytesAvailable, NSError * _Nullable error) {
                            completionSuccess = success;
                            completionBytesAvailable = bytesAvailable;
                            completionError = error;
                        }];

                        [NSThread sleepForTimeInterval:0.1];

                        sentPutFile = (SDLPutFile *)testConnectionManager.receivedRequests.lastObject;
                    });

                    it(@"should not have testFileName in the files set", ^{
                        expect(testInitialFileNames).toNot(contain(testFileName));
                    });

                    context(@"when the connection returns without error", ^{
                        __block SDLPutFileResponse *testResponse = nil;
                        __block NSNumber *testResponseSuccess = nil;
                        __block NSNumber *testResponseBytesAvailable = nil;

                        beforeEach(^{
                            testResponseBytesAvailable = @750;
                            testResponseSuccess = @YES;

                            testResponse = [[SDLPutFileResponse alloc] init];
                            testResponse.success = testResponseSuccess;
                            testResponse.spaceAvailable = testResponseBytesAvailable;

                            [testConnectionManager respondToLastRequestWithResponse:testResponse];
                        });

                        it(@"should set the file manager state correctly", ^{
                            expect(@(testFileManager.bytesAvailable)).toEventually(equal(testResponseBytesAvailable));
                            expect(testFileManager.remoteFileNames).toEventually(contain(testFileName));
                            expect(testFileManager.uploadedEphemeralFileNames).toEventually(contain(testUploadFile.name));
                            expect(testFileManager.currentState).toEventually(match(SDLFileManagerStateReady));
                        });

                        it(@"should call the completion handler with the correct data", ^{
                            expect(@(completionBytesAvailable)).toEventually(equal(testResponseBytesAvailable));
                            expect(@(completionSuccess)).toEventually(equal(@YES));
                            expect(completionError).to(beNil());
                        });
                    });

                    context(@"when the connection returns failure", ^{
                        __block SDLPutFileResponse *testResponse = nil;
                        __block NSNumber *testResponseBytesAvailable = nil;
                        __block NSNumber *testResponseSuccess = nil;

                        beforeEach(^{
                            testResponseBytesAvailable = @750;
                            testResponseSuccess = @NO;

                            testResponse = [[SDLPutFileResponse alloc] init];
                            testResponse.spaceAvailable = testResponseBytesAvailable;
                            testResponse.success = testResponseSuccess;

                            testFileManager.accessibilityHint = @"This doesn't matter";

                            [testConnectionManager respondToLastRequestWithResponse:testResponse];
                        });

                        it(@"should set the file manager state correctly", ^{
                            expect(@(testFileManager.bytesAvailable)).toEventually(equal(@(initialSpaceAvailable)));
                            expect(testFileManager.remoteFileNames).toEventuallyNot(contain(testFileName));
                            expect(testFileManager.uploadedEphemeralFileNames).toEventuallyNot(contain(testUploadFile.name));
                            expect(testFileManager.currentState).toEventually(match(SDLFileManagerStateReady));
                        });

                        it(@"should call the completion handler with the correct data", ^{
                            expect(@(completionBytesAvailable)).to(equal(@0));
                            expect(@(completionSuccess)).to(equal(testResponseSuccess));
                            expect(completionError).toEventually(beNil());
                        });
                    });

                    context(@"when the connection errors without a response", ^{
                        beforeEach(^{
                            [testConnectionManager respondToLastRequestWithResponse:nil error:[NSError sdl_lifecycle_notReadyError]];
                        });

                        it(@"should set the file manager state correctly", ^{
                            expect(testFileManager.remoteFileNames).toNot(contain(testFileName));
                            expect(testFileManager.currentState).to(match(SDLFileManagerStateReady));
                        });

                        it(@"should call the completion handler with nil error", ^{
                            expect(completionError).toEventually(equal([NSError sdl_lifecycle_notReadyError]));
                        });
                    });
                });
            });
        });

        afterEach(^{
            expect(testFileManager.transactionQueue.maxConcurrentOperationCount).to(equal(@(1)));
        });
    });
});

describe(@"SDLFileManager uploading/deleting multiple files", ^{
    __block TestMultipleFilesConnectionManager *testConnectionManager;
    __block SDLFileManager *testFileManager;
    __block NSUInteger initialSpaceAvailable;

    beforeEach(^{
        testConnectionManager = [[TestMultipleFilesConnectionManager alloc] init];
        testFileManager = [[SDLFileManager alloc] initWithConnectionManager:testConnectionManager];
        initialSpaceAvailable = 66666;
    });

    context(@"When the file manager is passed multiple files to upload", ^{
        __block SDLListFilesResponse *testListFilesResponse;
        __block NSMutableArray<SDLFile *> *testSDLFiles;
        __block NSMutableArray *expectedSuccessfulFileNames;
        __block NSNumber *expectedSpaceLeft;
        __block SDLPutFileResponse *failedResponse;
        __block SDLPutFileResponse *successfulResponse;

        beforeEach(^{
            testSDLFiles = [NSMutableArray array];
            expectedSuccessfulFileNames = [NSMutableArray array];
            expectedSpaceLeft = @(initialSpaceAvailable);

            testListFilesResponse = [[SDLListFilesResponse alloc] init];
            testListFilesResponse.success = @YES;
            testListFilesResponse.spaceAvailable = @(initialSpaceAvailable);
            testListFilesResponse.filenames = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil];

            failedResponse = [[SDLPutFileResponse alloc] init];
            failedResponse.success = @NO;
            failedResponse.spaceAvailable = @(initialSpaceAvailable);

            successfulResponse = [[SDLPutFileResponse alloc] init];
            successfulResponse.success = @YES;
            successfulResponse.spaceAvailable = @(initialSpaceAvailable);

            waitUntilTimeout(10, ^(void (^done)(void)){
                [testFileManager startWithCompletionHandler:^(BOOL success, NSError * _Nullable error) {
                    done();
                }];

                // Need to wait state machine transitions to complete before sending testListFilesResponse
                [NSThread sleepForTimeInterval:0.3];

                [testConnectionManager respondToLastRequestWithResponse:testListFilesResponse];
            });
        });

        context(@"and all files are uploaded successfully", ^{
            __block NSError *successfulResponseError = nil;
            __block NSMutableDictionary *testConnectionManagerResponses = [[NSMutableDictionary alloc] init];

            it(@"should not return an error when one small file is uploaded from memory", ^{
                NSString *testFileName = [NSString stringWithFormat:@"TestSmallFileMemory%d", 0];
                SDLFile *testSDLFile = [SDLFile fileWithData:[@"someTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                testSDLFile.overwrite = true;
                [testSDLFiles addObject:testSDLFile];

                [expectedSuccessfulFileNames addObject:testFileName];
                testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:successfulResponseError];
                testConnectionManager.responses = testConnectionManagerResponses;
            });

            it(@"should not return an error when one large file is uploaded from disk", ^{
                NSString *testFileName = [NSString stringWithFormat:@"TestLargeFileDisk%d", 0];
                SDLFile *testSDLFile = [SDLFile fileAtFileURL: [[NSURL alloc] initFileURLWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"testImagePNG" ofType:@"png"]] name:testFileName];
                testSDLFile.overwrite = true;
                [testSDLFiles addObject:testSDLFile];

                [expectedSuccessfulFileNames addObject:testFileName];
                testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:successfulResponseError];
                testConnectionManager.responses = testConnectionManagerResponses;
            });

            it(@"should not return an error when multiple small files are uploaded from memory", ^{
                NSInteger testSpaceAvailable = initialSpaceAvailable;
                for(int i = 0; i < 5; i += 1) {
                    NSString *testFileName = [NSString stringWithFormat:@"TestSmallFilesMemory%d", i];
                    SDLFile *testSDLFile = [SDLFile fileWithData:[@"someTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                    testSDLFile.overwrite = true;
                    [testSDLFiles addObject:testSDLFile];

                    successfulResponse.spaceAvailable = @(testSpaceAvailable -= 5);

                    [expectedSuccessfulFileNames addObject:testFileName];
                    testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:successfulResponseError];
                }
                expectedSpaceLeft = @(testSpaceAvailable);
                testConnectionManager.responses = testConnectionManagerResponses;
            });

            it(@"should not return an error when a large number of small files are uploaded from memory", ^{
                NSInteger testSpaceAvailable = initialSpaceAvailable;
                for(int i = 0; i < 500; i += 1) {
                    NSString *testFileName = [NSString stringWithFormat:@"Test500FilesMemory%d", i];
                    SDLFile *testSDLFile = [SDLFile fileWithData:[@"someTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                    testSDLFile.overwrite = true;
                    [testSDLFiles addObject:testSDLFile];

                    successfulResponse.spaceAvailable = @(testSpaceAvailable -= 4);

                    [expectedSuccessfulFileNames addObject:testFileName];
                    testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:successfulResponseError];
                }
                expectedSpaceLeft = @(testSpaceAvailable);
                testConnectionManager.responses = testConnectionManagerResponses;
            });

            it(@"should not return an error when multiple small files are uploaded from disk", ^{
                NSInteger testSpaceAvailable = initialSpaceAvailable;
                for(int i = 0; i < 5; i += 1) {
                    NSString *testFileName = [NSString stringWithFormat:@"TestMultipleSmallFilesDisk%d", i];
                    SDLFile *testSDLFile = [SDLFile fileAtFileURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"testImagePNG" ofType:@"png"]] name:testFileName];
                    testSDLFile.overwrite = true;
                    [testSDLFiles addObject:testSDLFile];

                    successfulResponse.spaceAvailable = @(testSpaceAvailable -= 3);

                    [expectedSuccessfulFileNames addObject:testFileName];
                    testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:successfulResponseError];
                }
                expectedSpaceLeft = @(testSpaceAvailable);
                testConnectionManager.responses = testConnectionManagerResponses;
            });

            it(@"should not return an error when multiple files are uploaded from both memory and disk", ^{
                NSInteger testSpaceAvailable = initialSpaceAvailable;
                for(int i = 0; i < 10; i += 1) {
                    NSString *testFileName = [NSString stringWithFormat:@"TestMultipleFilesDiskAndMemory%d", i];
                    SDLFile *testSDLFile;
                    if (i < 5) {
                        testSDLFile = [SDLFile fileAtFileURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"testImagePNG" ofType:@"png"]] name:testFileName];
                    } else {
                        testSDLFile = [SDLFile fileWithData:[@"someTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                    }
                    testSDLFile.overwrite = true;
                    [testSDLFiles addObject:testSDLFile];

                    successfulResponse.spaceAvailable = @(testSpaceAvailable -= 2);

                    [expectedSuccessfulFileNames addObject:testFileName];
                    testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:successfulResponseError];
                }
                expectedSpaceLeft = @(testSpaceAvailable);
                testConnectionManager.responses = testConnectionManagerResponses;
            });

            afterEach(^{
                waitUntilTimeout(10, ^(void (^done)(void)){
                    [testFileManager uploadFiles:testSDLFiles completionHandler:^(NSError * _Nullable error) {
                        expect(error).to(beNil());
                        expect(testFileManager.bytesAvailable).to(equal(expectedSpaceLeft));
                        done();
                    }];
                });
            });
        });

        context(@"and all files are not uploaded successfully", ^{
            __block NSMutableDictionary *testConnectionManagerResponses;
            __block NSMutableDictionary *expectedFailedUploads;
            __block NSError *expectedError;
            __block int testTotalFileCount;
            __block NSString *testFileNameBase;
            __block int testFailureIndexStart;
            __block int testFailureIndexEnd;

            beforeEach(^{
                testConnectionManagerResponses = [[NSMutableDictionary alloc] init];
                expectedFailedUploads = [[NSMutableDictionary alloc] init];
                expectedError = nil;
            });

            context(@"When the file manager receives a notification from the remote that a file upload failed", ^{
                beforeEach(^{
                    testFailureIndexStart = -1;
                    testFailureIndexEnd = INT8_MAX;
                });

                it(@"should return an error when all files fail", ^{
                    testTotalFileCount = 5;
                    testFileNameBase = @"TestAllFilesUnsuccessful";
                    testFailureIndexStart = testTotalFileCount;
                });

                it(@"should return an error when the first file fails to upload", ^{
                    testTotalFileCount = 5;
                    testFileNameBase = @"TestFirstFileUnsuccessful";
                    testFailureIndexStart = 0;
                });

                it(@"should return an error when the last file fails to upload", ^{
                    testTotalFileCount = 100;
                    testFileNameBase = @"TestLastFileUnsuccessful";
                    testFailureIndexEnd = (testTotalFileCount - 1);
                });

                afterEach(^{
                    NSInteger testSpaceAvailable = initialSpaceAvailable;
                    for(int i = 0; i < testTotalFileCount; i += 1) {
                        NSString *testFileName = [NSString stringWithFormat:@"%@%d", testFileNameBase, i];
                        SDLFile *testSDLFile = [SDLFile fileWithData:[@"someTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                        testSDLFile.overwrite = true;
                        [testSDLFiles addObject:testSDLFile];

                        SDLPutFileResponse *response = [[SDLPutFileResponse alloc] init];
                        NSError *responseError = nil;
                        if (i <= testFailureIndexStart || i >= testFailureIndexEnd) {
                            // Failed response
                            response = failedResponse;
                            response.spaceAvailable = @(testSpaceAvailable);
                            responseError = [NSError sdl_lifecycle_unknownRemoteErrorWithDescription:[NSString stringWithFormat:@"file upload failed: %d", i] andReason:[NSString stringWithFormat:@"some error reason: %d", i]];
                            expectedFailedUploads[testFileName] = responseError;
                        } else {
                            // Successful response
                            response = successfulResponse;
                            response.spaceAvailable = @(testSpaceAvailable -= 1);
                            responseError = nil;
                            [expectedSuccessfulFileNames addObject:testFileName];
                        }

                        testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:response error:responseError];;
                    }

                    testConnectionManager.responses = testConnectionManagerResponses;
                    expectedError = [NSError sdl_fileManager_unableToUpload_ErrorWithUserInfo:expectedFailedUploads];
                    expectedSpaceLeft = @(testSpaceAvailable);
                });
            });

            afterEach(^{
                waitUntilTimeout(10, ^(void (^done)(void)){
                    [testFileManager uploadFiles:testSDLFiles completionHandler:^(NSError * _Nullable error) {
                        expect(error).to(equal(expectedError));
                        expect(testFileManager.bytesAvailable).to(equal(expectedSpaceLeft));
                        done();
                    }];
                });
            });
        });

        context(@"and all files are uploaded successfully while expecting a progress response for each file", ^{
            __block NSMutableDictionary *testFileManagerResponses;
            __block NSMutableDictionary *testFileManagerProgressResponses;
            __block int testTotalFileCount;
            __block NSString *testFileNameBase;

            beforeEach(^{
                testFileManagerResponses = [[NSMutableDictionary alloc] init];
                testFileManagerProgressResponses = [[NSMutableDictionary alloc] init];
            });

            context(@"A progress handler should be returned for each file", ^{
                it(@"should upload 1 small file from memory without error", ^{
                    testTotalFileCount = 1;
                    testFileNameBase = @"TestProgressHandlerOneSmallFileMemory";
                });

                it(@"should upload a large number of small files from memory without error", ^{
                    testTotalFileCount = 200;
                    testFileNameBase = @"TestProgressHandlerMultipleSmallFileMemory";
                });

                afterEach(^{
                    NSData *testFileData = [@"someTextData" dataUsingEncoding:NSUTF8StringEncoding];
                    float testTotalBytesToUpload = testTotalFileCount * testFileData.length;
                    float testTotalBytesUploaded = 0.0;

                    NSInteger testSpaceAvailable = initialSpaceAvailable;
                    for(int i = 0; i < testTotalFileCount; i += 1) {
                        NSString *testFileName = [NSString stringWithFormat:@"%@%d", testFileNameBase, i];
                        SDLFile *testSDLFile = [SDLFile fileWithData:testFileData name:testFileName fileExtension:@"bin"];
                        testSDLFile.overwrite = true;
                        [testSDLFiles addObject:testSDLFile];

                        successfulResponse.spaceAvailable = @(testSpaceAvailable -= 10);
                        [expectedSuccessfulFileNames addObject:testFileName];
                        testFileManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:nil];

                        testTotalBytesUploaded += testSDLFile.fileSize;
                        testFileManagerProgressResponses[testFileName] = [[TestProgressResponse alloc] initWithFileName:testFileName testUploadPercentage:testTotalBytesUploaded / testTotalBytesToUpload error:nil];
                    }
                    expectedSpaceLeft = @(testSpaceAvailable);
                    testConnectionManager.responses = testFileManagerResponses;
                });
            });

            afterEach(^{
                waitUntilTimeout(10, ^(void (^done)(void)){
                    [testFileManager uploadFiles:testSDLFiles progressHandler:^BOOL(SDLFileName * _Nonnull fileName, float uploadPercentage, NSError * _Nullable error) {
                        TestProgressResponse *testProgressResponse = testFileManagerProgressResponses[fileName];
                        expect(fileName).to(equal(testProgressResponse.testFileName));
                        expect(uploadPercentage).to(equal(testProgressResponse.testUploadPercentage));
                        expect(error).to(testProgressResponse.testError == nil ? beNil() : equal(testProgressResponse.testError));
                        return YES;
                    } completionHandler:^(NSError * _Nullable error) {
                        expect(error).to(beNil());
                        expect(testFileManager.bytesAvailable).to(equal(expectedSpaceLeft));
                        done();
                    }];
                });
            });
        });

        context(@"When an upload is canceled while in progress by the cancel parameter of the progress handler", ^{
            __block NSMutableDictionary *testResponses;
            __block NSMutableDictionary *testProgressResponses;
            __block NSString *testFileNameBase;
            __block int testFileCount = 0;
            __block int testCancelIndex = 0;
            __block NSError *expectedError;

            beforeEach(^{
                testResponses = [[NSMutableDictionary alloc] init];
                testProgressResponses = [[NSMutableDictionary alloc] init];
            });

            it(@"should cancel the remaining files if cancel is triggered after first upload", ^{
                testFileCount = 11;
                testCancelIndex = 0;
                testFileNameBase = @"TestUploadFilesCancelAfterFirst";
                expectedError = [NSError sdl_fileManager_unableToUpload_ErrorWithUserInfo:testResponses];
            });

            it(@"should cancel the remaining files if cancel is triggered after half of the files are uploaded", ^{
                testFileCount = 30;
                testCancelIndex = testFileCount / 2;
                testFileNameBase = @"TestUploadFilesCancelInMiddle";
                expectedError = [NSError sdl_fileManager_unableToUpload_ErrorWithUserInfo:testResponses];
            });

            it(@"should not fail if there are no more files to cancel", ^{
                testFileCount = 20;
                testCancelIndex = (testFileCount - 1);
                testFileNameBase = @"TestUploadFilesCancelAtEnd";
                expectedError = nil;
            });

            afterEach(^{
                for(int i = 0; i < testFileCount; i += 1) {
                    NSString *testFileName = [NSString stringWithFormat:@"%@%d", testFileNameBase, i];
                    SDLFile *testSDLFile = [SDLFile fileWithData:[@"someTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                    testSDLFile.overwrite = true;
                    [testSDLFiles addObject:testSDLFile];

                    if (i <= testCancelIndex) {
                        [expectedSuccessfulFileNames addObject:testFileName];
                    }

                    testResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:nil];
                    testProgressResponses[testFileName] = [[TestProgressResponse alloc] initWithFileName:testFileName testUploadPercentage:0.0 error:nil];
                }
                testConnectionManager.responses = testResponses;

                waitUntilTimeout(10, ^(void (^done)(void)){
                    [testFileManager uploadFiles:testSDLFiles progressHandler:^(NSString * _Nonnull fileName, float uploadPercentage, NSError * _Nullable error) {
                        // Once operations are canceled, the order in which the operations complete is random, so the upload percentage and the error message can vary. This means we can not test the error message or upload percentage it will be different every test run.
                        TestProgressResponse *testProgressResponse = testProgressResponses[fileName];
                        expect(fileName).to(equal(testProgressResponse.testFileName));

                        NSString *cancelFileName = [NSString stringWithFormat:@"%@%d", testFileNameBase, testCancelIndex];
                        if ([fileName isEqual:cancelFileName]) {
                            return NO;
                        }
                        return YES;
                    } completionHandler:^(NSError * _Nullable error) {
                        if (expectedError != nil) {
                            expect(error.code).to(equal(SDLFileManagerMultipleFileUploadTasksFailed));
                        } else {
                            expect(error).to(beNil());
                        }
                        done();
                    }];
                });
            });
        });

        context(@"When an upload is canceled it should only cancel files that were passed with the same file array", ^{
            // When canceled is called in this test group, the rest of the files should be canceled
            __block NSMutableDictionary *testResponses;
            __block NSMutableDictionary *testProgressResponses;
            __block NSString *testFileNameBase;
            __block int testFileCount = 0;
            __block int testCancelIndex = 0;
            __block NSError *expectedError;

            // Another group of uploads. These uploads should not be canceled when the other files are canceled
            __block NSMutableArray<SDLFile *> *testOtherSDLFiles;
            __block NSString *testOtherFileNameBase;
            __block int testOtherFileCount = 0;
            __block NSError *expectedOtherError;

            beforeEach(^{
                testResponses = [[NSMutableDictionary alloc] init];
                testProgressResponses = [[NSMutableDictionary alloc] init];

                testOtherSDLFiles = [[NSMutableArray alloc] init];
            });

            it(@"should only cancel the remaining files that were passed with the same file. Other files in the queue that were not passed in the same array should not be canceled", ^{
                testFileCount = 11;
                testCancelIndex = 0;
                testFileNameBase = @"TestUploadFilesCancelGroupOnly";
                expectedError = [NSError sdl_fileManager_unableToUpload_ErrorWithUserInfo:testResponses];

                testOtherFileNameBase = @"TestOtherUploadFilesCancelGroupOnly";
                testOtherFileCount = 22;
                expectedOtherError = nil;
            });

            it(@"should not fail if no files are canceled", ^{
                testFileCount = 1;
                testCancelIndex = 0;
                testFileNameBase = @"TestUploadFilesCancelGroupOnlyOneFile";
                expectedError = nil;

                testOtherFileNameBase = @"TestOtherUploadFilesCancelGroupOnlyOneFile";
                testOtherFileCount = 2;
                expectedOtherError = nil;
            });

            afterEach(^{
                for(int i = 0; i < testFileCount; i += 1) {
                    NSString *testFileName = [NSString stringWithFormat:@"%@%d", testFileNameBase, i];
                    SDLFile *testSDLFile = [SDLFile fileWithData:[@"someTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                    testSDLFile.overwrite = true;
                    [testSDLFiles addObject:testSDLFile];

                    if (i <= testCancelIndex) {
                        [expectedSuccessfulFileNames addObject:testFileName];
                    }

                    testResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:nil];
                    testProgressResponses[testFileName] = [[TestProgressResponse alloc] initWithFileName:testFileName testUploadPercentage:0.0 error:nil];
                }

                for(int i = 0; i < testOtherFileCount; i += 1) {
                    NSString *testFileName = [NSString stringWithFormat:@"%@%d", testOtherFileNameBase, i];
                    SDLFile *testSDLFile = [SDLFile fileWithData:[@"someOtherTextData" dataUsingEncoding:NSUTF8StringEncoding] name:testFileName fileExtension:@"bin"];
                    testSDLFile.overwrite = true;
                    [testOtherSDLFiles addObject:testSDLFile];

                    [expectedSuccessfulFileNames addObject:testFileName];

                    testResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulResponse error:nil];
                }

                testConnectionManager.responses = testResponses;

                waitUntilTimeout(10, ^(void (^done)(void)){
                    [testFileManager uploadFiles:testSDLFiles progressHandler:^(NSString * _Nonnull fileName, float uploadPercentage, NSError * _Nullable error) {
                        // Once operations are canceled, the order in which the operations complete is random, so the upload percentage and the error message can vary. This means we can not test the error message or upload percentage it will be different every test run.
                        TestProgressResponse *testProgressResponse = testProgressResponses[fileName];
                        expect(fileName).to(equal(testProgressResponse.testFileName));

                        NSString *cancelFileName = [NSString stringWithFormat:@"%@%d", testFileNameBase, testCancelIndex];
                        if ([fileName isEqual:cancelFileName]) {
                            return NO;
                        }
                        return YES;
                    } completionHandler:^(NSError * _Nullable error) {
                        if (expectedError != nil) {
                            expect(error.code).to(equal(SDLFileManagerMultipleFileUploadTasksFailed));
                        } else {
                            expect(error).to(beNil());
                        }
                    }];

                    [testFileManager uploadFiles:testOtherSDLFiles completionHandler:^(NSError * _Nullable error) {
                        expect(error).to(beNil());
                        // Since the queue is serial, we know that these files will finish after the first uploadFiles() batch.
                        done();
                    }];
                });
            });
        });

        afterEach(^{
            for(int i = 0; i < expectedSuccessfulFileNames.count; i += 1) {
                expect(testFileManager.remoteFileNames).to(contain(expectedSuccessfulFileNames[i]));
            }
        });
    });

    context(@"When the file manager is passed multiple files to delete", ^{
        __block SDLListFilesResponse *testListFilesResponse;
        __block NSArray<NSString *> *testRemoteFileNames;
        __block NSMutableArray<NSString *> *expectedRemoteFileNames;
        __block NSNumber *expectedSpaceLeft;
        __block NSMutableArray *testDeleteFileNames;
        __block SDLDeleteFileResponse *failedDeleteResponse;
        __block SDLDeleteFileResponse *successfulDeleteResponse;
        __block NSError *expectedError = nil;

        beforeEach(^{
            testRemoteFileNames = [[NSArray alloc] initWithObjects:@"AA", @"BB", @"CC", @"DD", @"EE", @"FF", nil];
            expectedRemoteFileNames = [[NSMutableArray alloc] init];

            testListFilesResponse = [[SDLListFilesResponse alloc] init];
            testListFilesResponse.success = @YES;
            testListFilesResponse.spaceAvailable = @(initialSpaceAvailable);
            testListFilesResponse.filenames = testRemoteFileNames;

            // Failed delete response
            failedDeleteResponse = [[SDLDeleteFileResponse alloc] init];
            failedDeleteResponse.spaceAvailable = @10;
            failedDeleteResponse.success = @NO;

            // Successful delete response
            successfulDeleteResponse = [[SDLDeleteFileResponse alloc] init];
            successfulDeleteResponse.spaceAvailable = @9;
            successfulDeleteResponse.success = @YES;

            waitUntilTimeout(10, ^(void (^done)(void)){
                [testFileManager startWithCompletionHandler:^(BOOL success, NSError * _Nullable error) {
                    done();
                }];

                // Need to wait state machine transitions to complete before sending testListFilesResponse
                [NSThread sleepForTimeInterval:0.3];

                [testConnectionManager respondToLastRequestWithResponse:testListFilesResponse];
            });
        });

        context(@"and all files are deleted successfully", ^{
            __block NSMutableDictionary *testResponses;
            __block int testFileCount = 0;

            beforeEach(^{
                testResponses = [[NSMutableDictionary alloc] init];
                testDeleteFileNames = [[NSMutableArray alloc] init];
            });

            context(@"When the file manager receives a successful notification for each deleted file", ^{
                it(@"should not return an error when one remote file is deleted", ^{
                    testFileCount = 1;
                });

                it(@"should not return an error when all remote files are deleted", ^{
                    testFileCount = (int)testRemoteFileNames.count;
                });

                afterEach(^{
                    NSInteger testSpaceAvailable = initialSpaceAvailable;
                    for(int i = 0; i < testFileCount; i += 1) {
                        NSString *testFileName = [testRemoteFileNames objectAtIndex:i];
                        successfulDeleteResponse.spaceAvailable = @(testSpaceAvailable += 91);
                        testResponses[testFileName] = [[TestResponse alloc] initWithResponse:successfulDeleteResponse error:nil];
                        [testDeleteFileNames addObject:testFileName];
                    }
                    expectedSpaceLeft = @(testSpaceAvailable);
                    [expectedRemoteFileNames removeAllObjects];
                    testConnectionManager.responses = testResponses;
                });
            });
        });

        context(@"and all files are not deleted successfully", ^{
            __block NSMutableDictionary *testConnectionManagerResponses;
            __block NSMutableDictionary *expectedFailedDeletes;

            beforeEach(^{
                testConnectionManagerResponses = [[NSMutableDictionary alloc] init];
                testDeleteFileNames = [[NSMutableArray alloc] init];
                expectedFailedDeletes = [[NSMutableDictionary alloc] init];
            });

            context(@"When the file manager receives a unsuccessful notification for a deleted file", ^{
                __block int testFailureIndexStart;
                __block int testFailureIndexEnd;

                beforeEach(^{
                    testFailureIndexStart = -1;
                    testFailureIndexEnd = INT8_MAX;
                });

                it(@"should return an error if the first remote file fails to delete", ^{
                    testFailureIndexStart = 0;
                });

                it(@"should return an error if the last remote file fails to delete", ^{
                    testFailureIndexEnd = (int)testRemoteFileNames.count - 1;
                });

                it(@"should return an error if all files fail to delete", ^{
                    testFailureIndexStart = (int)testRemoteFileNames.count;
                });

                afterEach(^{
                    NSInteger testSpaceAvailable = initialSpaceAvailable;
                    for(int i = 0; i < testRemoteFileNames.count; i += 1) {
                        NSString *testFileName = [testRemoteFileNames objectAtIndex:i];

                        SDLDeleteFileResponse *response;
                        NSError *responseError;
                        if (i <= testFailureIndexStart || i >= testFailureIndexEnd) {
                            failedDeleteResponse.spaceAvailable = @(testSpaceAvailable);
                            response = failedDeleteResponse;
                            responseError = [NSError sdl_lifecycle_unknownRemoteErrorWithDescription:[NSString stringWithFormat:@"file upload failed: %d", i] andReason: [NSString stringWithFormat:@"some error reason: %d", i]];
                            expectedFailedDeletes[testFileName] = responseError;
                            [expectedRemoteFileNames addObject:testFileName];
                        } else {
                            successfulDeleteResponse.spaceAvailable = @(testSpaceAvailable += 891);
                            response = successfulDeleteResponse;
                            responseError = nil;
                        }

                        testConnectionManagerResponses[testFileName] = [[TestResponse alloc] initWithResponse:response error:responseError];
                        [testDeleteFileNames addObject:testFileName];
                    }

                    testConnectionManager.responses = testConnectionManagerResponses;
                    expectedError = [NSError sdl_fileManager_unableToDelete_ErrorWithUserInfo:expectedFailedDeletes];
                    expectedSpaceLeft = @(testSpaceAvailable);
                });
            });
        });

        afterEach(^{
            waitUntilTimeout(10, ^(void (^done)(void)){
                [testFileManager deleteRemoteFilesWithNames:testDeleteFileNames completionHandler:^(NSError * _Nullable error) {
                    expect(error).to(expectedError == nil ? beNil() : equal(expectedError));
                    expect(testFileManager.bytesAvailable).to(equal(expectedSpaceLeft));
                    done();
                }];
            });

            for(int i = 0; i < expectedRemoteFileNames.count; i += 1) {
                expect(testFileManager.remoteFileNames).to(contain(expectedRemoteFileNames[i]));
            }
        });
    });

    context(@"The file manager should handle exceptions correctly", ^{
        beforeEach(^{
            SDLListFilesResponse *testListFilesResponse = [[SDLListFilesResponse alloc] init];
            testListFilesResponse.success = @YES;
            testListFilesResponse.spaceAvailable = @(initialSpaceAvailable);
            testListFilesResponse.filenames = [[NSArray alloc] initWithObjects:@"AA", nil];

            waitUntilTimeout(10, ^(void (^done)(void)){
                [testFileManager startWithCompletionHandler:^(BOOL success, NSError * _Nullable error) {
                    done();
                }];
                
                // Need to wait state machine transitions to complete before sending testListFilesResponse
                [NSThread sleepForTimeInterval:0.3];
                
                [testConnectionManager respondToLastRequestWithResponse:testListFilesResponse];
            });
        });
        
        it(@"should throw an exception when the upload function is passed an empty array", ^{
            expectAction(^{
                [testFileManager uploadFiles:[NSArray array] completionHandler:nil];
            }).to(raiseException().named([NSException sdl_missingFilesException].name));
        });
        
        it(@"should throw an exception when the upload function with a progress handler is passed an empty array", ^{
            expectAction(^{
                [testFileManager uploadFiles:[NSArray array] progressHandler:nil completionHandler:nil];
            }).to(raiseException().named([NSException sdl_missingFilesException].name));
        });
        
        it(@"should throw an exception when the delete function is passed an empty array", ^{
            expectAction(^{
                [testFileManager deleteRemoteFilesWithNames:[NSArray array] completionHandler:nil];
            }).to(raiseException().named([NSException sdl_missingFilesException].name));
        });
    });
});

QuickSpecEnd