summaryrefslogtreecommitdiff
path: root/SmartDeviceLinkTests/DevAPISpecs/SDLLifecycleManagerSpec.m
blob: 8d2cf9dbc61338b7dd846da316e4539091e07bc6 (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
#import <Quick/Quick.h>
#import <Nimble/Nimble.h>
#import <OCMock/OCMock.h>

#import "SDLLifecycleManager.h"

#import "SDLAppServiceData.h"
#import "SDLChangeRegistration.h"
#import "SDLConfiguration.h"
#import "SDLConnectionManagerType.h"
#import "SDLEncryptionConfiguration.h"
#import "SDLEncryptionLifecycleManager.h"
#import "SDLError.h"
#import "SDLFileManagerConfiguration.h"
#import "SDLFileManager.h"
#import "SDLGlobals.h"
#import "SDLHMILevel.h"
#import "SDLLifecycleConfiguration.h"
#import "SDLLifecycleProtocolHandler.h"
#import "SDLLockScreenConfiguration.h"
#import "SDLLockScreenManager.h"
#import "SDLLogConfiguration.h"
#import "SDLManagerDelegate.h"
#import "SDLNotificationDispatcher.h"
#import "SDLOnAppInterfaceUnregistered.h"
#import "SDLOnAppServiceData.h"
#import "SDLOnHashChange.h"
#import "SDLOnHMIStatus.h"
#import "SDLPerformAppServiceInteractionResponse.h"
#import "SDLPermissionManager.h"
#import "SDLProtocol.h"
#import "SDLRegisterAppInterface.h"
#import "SDLRegisterAppInterfaceResponse.h"
#import "SDLResult.h"
#import "SDLRPCNotificationNotification.h"
#import "SDLSecondaryTransportManager.h"
#import "SDLShow.h"
#import "SDLStateMachine.h"
#import "SDLStreamingMediaConfiguration.h"
#import "SDLStreamingMediaManager.h"
#import "SDLSystemCapabilityManager.h"
#import "SDLTextAlignment.h"
#import "SDLTTSChunk.h"
#import "SDLUnregisterAppInterface.h"
#import "SDLUnregisterAppInterfaceResponse.h"
#import "SDLVersion.h"
#import "SDLVideoStreamingState.h"


@interface SDLStreamingMediaManager ()

@property (strong, nonatomic, nullable) SDLSecondaryTransportManager *secondaryTransportManager;
- (void)startSecondaryTransportWithProtocol:(SDLProtocol *)protocol;

@end

@interface SDLLifecycleManager ()
// this private property is used for testing
@property (copy, nonatomic) dispatch_queue_t lifecycleQueue;
@property (assign, nonatomic) int32_t lastCorrelationId;
@property (strong, nonatomic) SDLLanguage currentVRLanguage;
@property (strong, nonatomic, nullable) SDLSecondaryTransportManager *secondaryTransportManager;
@property (strong, nonatomic) SDLEncryptionLifecycleManager *encryptionLifecycleManager;
@property (strong, nonatomic, nullable) SDLLifecycleProtocolHandler *protocolHandler;
@end

@interface SDLGlobals ()
@property (copy, nonatomic, readwrite) SDLVersion *protocolVersion;
@end

QuickConfigurationBegin(SendingRPCsConfiguration)

+ (void)configure:(Configuration *)configuration {
    sharedExamples(@"unable to send an RPC", ^(QCKDSLSharedExampleContext exampleContext) {
        it(@"cannot publicly send RPCs", ^{
            SDLLifecycleManager *testManager = exampleContext()[@"manager"];
            SDLShow *testShow = [[SDLShow alloc] initWithMainField1:@"test" mainField2:nil mainField3:nil mainField4:nil alignment:nil statusBar:nil mediaTrack:nil graphic:nil secondaryGraphic:nil softButtons:nil customPresets:nil metadataTags:nil templateTitle:nil windowID:nil templateConfiguration:nil];

            [testManager sendRequest:testShow withResponseHandler:^(__kindof SDLRPCRequest * _Nullable request, __kindof SDLRPCResponse * _Nullable response, NSError * _Nullable error) {
                expect(error).to(equal([NSError sdl_lifecycle_notReadyError]));
            }];
        });
    });
}

QuickConfigurationEnd


QuickSpecBegin(SDLLifecycleManagerSpec)

describe(@"a lifecycle manager", ^{
    __block SDLLifecycleManager *testManager = nil;
    __block SDLConfiguration *testConfig = nil;
    __block id protocolMock = nil;
    __block id sdlManagerDelegateProtocolMock = nil;
    __block id lockScreenManagerMock = nil;
    __block id fileManagerMock = nil;
    __block id permissionManagerMock = nil;
    __block id streamingManagerMock = nil;
    __block id systemCapabilityMock = nil;
    __block id secondaryTransportManagerMock = nil;
    __block id encryptionManagerMock = nil;

    void (^transitionToState)(SDLState *) = ^(SDLState *state) {
        dispatch_sync(testManager.lifecycleQueue, ^{
            [testManager.lifecycleStateMachine transitionToState:state];
        });
    };

    void (^setToStateWithEnterTransition)(SDLState *, SDLState *) = ^(SDLState *oldState, SDLState *newState) {
        dispatch_sync(testManager.lifecycleQueue, ^{
            [testManager.lifecycleStateMachine setToState:newState fromOldState:oldState callEnterTransition:YES];
        });
    };

    beforeEach(^{
        protocolMock = OCMClassMock([SDLProtocol class]);
        sdlManagerDelegateProtocolMock = OCMProtocolMock(@protocol(SDLManagerDelegate));
        lockScreenManagerMock = OCMClassMock([SDLLockScreenManager class]);
        fileManagerMock = OCMClassMock([SDLFileManager class]);
        permissionManagerMock = OCMClassMock([SDLPermissionManager class]);
        streamingManagerMock = OCMClassMock([SDLStreamingMediaManager class]);
        systemCapabilityMock = OCMClassMock([SDLSystemCapabilityManager class]);
        secondaryTransportManagerMock = OCMClassMock([SDLSecondaryTransportManager class]);
        encryptionManagerMock = OCMClassMock([SDLEncryptionLifecycleManager class]);

        SDLLifecycleConfiguration *testLifecycleConfig = [SDLLifecycleConfiguration defaultConfigurationWithAppName:@"Test App" fullAppId:@"TestFullAppID"];
        testLifecycleConfig.shortAppName = @"Short Name";
        testLifecycleConfig.appType = SDLAppHMITypeNavigation;
        
        testConfig = [[SDLConfiguration alloc] initWithLifecycle:testLifecycleConfig lockScreen:[SDLLockScreenConfiguration disabledConfiguration] logging:[SDLLogConfiguration defaultConfiguration] streamingMedia:[SDLStreamingMediaConfiguration insecureConfiguration] fileManager:[SDLFileManagerConfiguration defaultConfiguration] encryption:[SDLEncryptionConfiguration defaultConfiguration]];
        testConfig.lifecycleConfig.languagesSupported = @[SDLLanguageEnUs, SDLLanguageEnGb];
        testConfig.lifecycleConfig.language = SDLLanguageEnUs;
        testConfig.lifecycleConfig.minimumProtocolVersion = [SDLVersion versionWithMajor:2 minor:0 patch:0];
        testConfig.lifecycleConfig.minimumRPCVersion = [SDLVersion versionWithMajor:2 minor:0 patch:0];
        testManager = [[SDLLifecycleManager alloc] initWithConfiguration:testConfig delegate:sdlManagerDelegateProtocolMock];
        testManager.lockScreenManager = lockScreenManagerMock;
        testManager.fileManager = fileManagerMock;
        testManager.permissionManager = permissionManagerMock;
        testManager.streamManager = streamingManagerMock;
        testManager.systemCapabilityManager = systemCapabilityMock;
        testManager.secondaryTransportManager = secondaryTransportManagerMock;
        testManager.encryptionLifecycleManager = encryptionManagerMock;

        [SDLGlobals sharedGlobals].protocolVersion = [SDLVersion versionWithMajor:3 minor:0 patch:0];
        [SDLGlobals sharedGlobals].rpcVersion = [SDLVersion versionWithMajor:3 minor:0 patch:0];
    });
    
    it(@"should initialize properties", ^{
        expect(testManager.configuration).toNot(equal(testConfig)); // This is copied
        expect(testManager.delegate).toNot(beNil());
        expect(testManager.lifecycleState).to(match(SDLLifecycleStateStopped));
        expect(@(testManager.lastCorrelationId)).to(equal(@0));
        expect(testManager.fileManager).toNot(beNil());
        expect(testManager.permissionManager).toNot(beNil());
        expect(testManager.streamManager).toNot(beNil());
        expect(testManager.registerResponse).to(beNil());
        expect(testManager.lockScreenManager).toNot(beNil());
        expect(testManager.notificationDispatcher).toNot(beNil());
        expect(testManager.responseDispatcher).toNot(beNil());
        expect(testManager.streamManager).toNot(beNil());
        expect(testManager.systemCapabilityManager).toNot(beNil());
        expect(testManager.rpcOperationQueue).toNot(beNil());
        expect(@([testManager conformsToProtocol:@protocol(SDLConnectionManagerType)])).to(equal(@YES));
        expect(testManager.authToken).to(beNil());
        expect(testManager.currentVRLanguage).toNot(beNil());
    });
    
    itBehavesLike(@"unable to send an RPC", ^{ return @{ @"manager": testManager }; });
    
    describe(@"after receiving an HMI Status", ^{
        __block SDLOnHMIStatus *testHMIStatus = nil;
        __block SDLHMILevel testHMILevel = nil;
        
        beforeEach(^{
            testHMIStatus = [[SDLOnHMIStatus alloc] init];
        });
        
        context(@"a non-none hmi level", ^{
            beforeEach(^{
                testHMILevel = SDLHMILevelNone;
                testHMIStatus.hmiLevel = testHMILevel;
                
                [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];
            });
            
            it(@"should set the hmi level", ^{
                expect(testManager.hmiLevel).toEventually(equal(testHMILevel));
            });
        });
        
        context(@"a non-full, non-none hmi level", ^{
            beforeEach(^{
                testHMILevel = SDLHMILevelBackground;
                testHMIStatus.hmiLevel = testHMILevel;
                
                [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];
            });
            
            it(@"should set the hmi level", ^{
                expect(testManager.hmiLevel).toEventually(equal(testHMILevel));
            });
        });
        
        context(@"a full hmi level", ^{
            beforeEach(^{
                testHMILevel = SDLHMILevelFull;
                testHMIStatus.hmiLevel = testHMILevel;
                
                [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];
            });
            
            it(@"should set the hmi level", ^{
                expect(testManager.hmiLevel).toEventually(equal(testHMILevel));
            });
        });
    });
    
    describe(@"calling stop", ^{
        beforeEach(^{
            [testManager stop];
        });
        
        it(@"should do nothing", ^{
            expect(testManager.lifecycleState).to(match(SDLLifecycleStateStopped));
            expect(testManager.lifecycleState).toEventuallyNot(match(SDLLifecycleStateStarted));
        });
    });
    
    describe(@"when started", ^{
        __block BOOL readyHandlerSuccess = NO;
        __block NSError *readyHandlerError = nil;

        beforeEach(^{
            readyHandlerSuccess = NO;
            readyHandlerError = nil;

            [testManager startWithReadyHandler:^(BOOL success, NSError * _Nullable error) {
                readyHandlerSuccess = success;
                readyHandlerError = error;
            }];

            testManager.protocolHandler.protocol = protocolMock;
        });
        
        it(@"should initialize enter the started state and start the secondary transport", ^{
            expect(testManager.lifecycleState).to(match(SDLLifecycleStateStarted));

            expect(testManager.secondaryTransportManager).toNot(beNil());
        });

        describe(@"after receiving a connect notification", ^{
            beforeEach(^{
                // When we connect, we should be creating an sending an RAI
                OCMExpect([protocolMock sendRPC:[OCMArg isKindOfClass:[SDLRegisterAppInterface class]]]);
                
                [testManager.notificationDispatcher postNotificationName:SDLRPCServiceDidConnect infoObject:nil];
            });
            
            it(@"should send a register app interface request and be in the connected state", ^{
                OCMVerifyAllWithDelay(protocolMock, 1.0);
                expect(testManager.lifecycleState).toEventually(equal(SDLLifecycleStateConnected));
            });
            
            itBehavesLike(@"unable to send an RPC", ^{ return @{ @"manager": testManager }; });
            
            describe(@"after receiving a disconnect notification", ^{
                beforeEach(^{
                    [testManager.notificationDispatcher postNotificationName:SDLTransportDidDisconnect infoObject:nil];
                    [NSThread sleepForTimeInterval:0.1];
                });
                
                it(@"should be in the started state", ^{
                    expect(testManager.lifecycleState).to(equal(SDLLifecycleStateReconnecting));
                });
            });
            
            describe(@"stopping the manager", ^{
                it(@"should simply stop", ^{
                    [testManager stop];
                    
                    expect(testManager.lifecycleState).toEventually(equal(SDLLifecycleStateStopped));
                });
            });
        });

        describe(@"in the connected state when the minimum protocol version is in effect", ^{
            beforeEach(^{
                [SDLGlobals sharedGlobals].protocolVersion = [SDLVersion versionWithMajor:1 minor:0 patch:0];

                OCMExpect([protocolMock endServiceWithType:SDLServiceTypeRPC]);
                [testManager.lifecycleStateMachine setToState:SDLLifecycleStateConnected fromOldState:nil callEnterTransition:YES];
            });

            it(@"should disconnect", ^{
                OCMVerifyAll(protocolMock);
            });
        });
        
        describe(@"in the connected state", ^{
            beforeEach(^{
                [testManager.lifecycleStateMachine setToState:SDLLifecycleStateConnected fromOldState:nil callEnterTransition:NO];
            });

             describe(@"after receiving a register app interface response", ^{
                it(@"should eventually reach the ready state", ^{
                    NSError *fileManagerStartError = [NSError errorWithDomain:@"testDomain" code:0 userInfo:nil];
                    NSError *permissionManagerStartError = [NSError errorWithDomain:@"testDomain" code:0 userInfo:nil];

                    OCMStub([fileManagerMock startWithCompletionHandler:([OCMArg invokeBlockWithArgs:@(YES), fileManagerStartError, nil])]);
                    OCMStub([permissionManagerMock startWithCompletionHandler:([OCMArg invokeBlockWithArgs:@(YES), permissionManagerStartError, nil])]);

                    // Make sure we have an HMI status to move the lifecycle forward
                    testManager.hmiLevel = SDLHMILevelFull;
                    transitionToState(SDLLifecycleStateRegistered);

                    expect(testManager.lifecycleState).toEventually(equal(SDLLifecycleStateReady));
                    OCMVerify([(SDLLockScreenManager *)lockScreenManagerMock start]);
                    OCMVerify([(SDLSystemCapabilityManager *)systemCapabilityMock start]);
                    OCMVerify([fileManagerMock startWithCompletionHandler:[OCMArg any]]);
                    OCMVerify([permissionManagerMock startWithCompletionHandler:[OCMArg any]]);
                    OCMVerify([encryptionManagerMock startWithProtocol:[OCMArg any]]);
                });

                itBehavesLike(@"unable to send an RPC", ^{ return @{ @"manager": testManager }; });
            });
            
            describe(@"after receiving a disconnect notification", ^{
                beforeEach(^{
                    OCMStub([protocolMock stopWithCompletionHandler:[OCMArg invokeBlock]]);
                    OCMStub([secondaryTransportManagerMock stopWithCompletionHandler:[OCMArg invokeBlock]]);
                    [testManager.notificationDispatcher postNotificationName:SDLTransportDidDisconnect infoObject:nil];
                    [NSThread sleepForTimeInterval:1.0];
                });
                
                it(@"should enter the started state", ^{
                    expect(testManager.lifecycleState).toEventually(equal(SDLLifecycleStateStarted));
                });
            });
            
            describe(@"stopping the manager", ^{
                beforeEach(^{
                    [testManager stop];
                });
                
                it(@"should enter the stopped state", ^{
                    expect(testManager.lifecycleState).to(equal(SDLLifecycleStateStopped));
                });
            });
        });

        describe(@"transitioning to the registered state when the minimum RPC version is in effect", ^{
            beforeEach(^{
                [SDLGlobals sharedGlobals].rpcVersion = [SDLVersion versionWithMajor:1 minor:0 patch:0];

                [testManager.lifecycleStateMachine setToState:SDLLifecycleStateRegistered fromOldState:nil callEnterTransition:YES];
            });

            it(@"should disconnect", ^{
                expect(testManager.lifecycleState).to(equal(SDLLifecycleStateUnregistering));
            });
        });
        
        describe(@"transitioning to the Setting Up HMI state", ^{
            context(@"before register response is a success", ^{
                it(@"ready handler should not be called yet", ^{
                    SDLRegisterAppInterfaceResponse *response = [[SDLRegisterAppInterfaceResponse alloc] init];
                    response.resultCode = SDLResultSuccess;
                    testManager.registerResponse = response;
                    
                    setToStateWithEnterTransition(nil, SDLLifecycleStateSettingUpHMI);

                    expect(@(readyHandlerSuccess)).to(equal(@NO));
                    expect(readyHandlerError).to(beNil());
                });
            });
            
            context(@"assume hmi status is nil", ^{
                it(@"mock notification and ensure state changes to ready", ^{
                    __block SDLOnHMIStatus *testHMIStatus = nil;
                    __block SDLHMILevel testHMILevel = nil;
                    testHMIStatus = [[SDLOnHMIStatus alloc] init];
                    
                    SDLRegisterAppInterfaceResponse *response = [[SDLRegisterAppInterfaceResponse alloc] init];
                    response.resultCode = SDLResultSuccess;
                    testManager.registerResponse = response;
                    
                    setToStateWithEnterTransition(nil, SDLLifecycleStateSettingUpHMI);
                    
                    testHMILevel = SDLHMILevelFull;
                    testHMIStatus.hmiLevel = testHMILevel;
                    
                    [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];

                    expect(testManager.lifecycleState).toEventually(equal(SDLLifecycleStateReady));
                    expect(@(readyHandlerSuccess)).toEventually(equal(@YES));
                    expect(readyHandlerError).toEventually(beNil());
                });
            });
        });

        describe(@"transitioning to the ready state", ^{
            beforeEach(^{
                [testManager.lifecycleStateMachine setToState:SDLLifecycleStateRegistered fromOldState:nil callEnterTransition:NO];
            });

            context(@"when the register response is a success", ^{
                it(@"should call the ready handler with success", ^{
                    SDLRegisterAppInterfaceResponse *response = [[SDLRegisterAppInterfaceResponse alloc] init];
                    response.resultCode = SDLResultSuccess;
                    testManager.registerResponse = response;
                    
                    setToStateWithEnterTransition(nil, SDLLifecycleStateReady);

                    expect(@(readyHandlerSuccess)).toEventually(equal(@YES));
                    expect(readyHandlerError).toEventually(beNil());
                });
            });

            context(@"when the register response is a warning", ^{
                it(@"should call the ready handler with success but error", ^{
                    SDLRegisterAppInterfaceResponse *response = [[SDLRegisterAppInterfaceResponse alloc] init];
                    response.resultCode = SDLResultWarnings;
                    response.info = @"some info";
                    testManager.registerResponse = response;

                    setToStateWithEnterTransition(nil, SDLLifecycleStateReady);

                    expect(@(readyHandlerSuccess)).toEventually(equal(@YES));
                    expect(readyHandlerError).toEventuallyNot(beNil());
                    expect(@(readyHandlerError.code)).toEventually(equal(@(SDLManagerErrorRegistrationSuccessWithWarning)));
                    expect(readyHandlerError.userInfo[NSLocalizedFailureReasonErrorKey]).toEventually(match(response.info));
                });
            });
            
            context(@"when the register response returns different language than the one passed with the lifecycle configuration", ^{
                it(@"should should update the configuration when the app supports the head unit language", ^{
                    SDLRegisterAppInterfaceResponse *registerAppInterfaceResponse = [[SDLRegisterAppInterfaceResponse alloc] init];
                    registerAppInterfaceResponse.success = @YES;
                    registerAppInterfaceResponse.resultCode = SDLResultWrongLanguage;
                    registerAppInterfaceResponse.info = @"Language mismatch";
                    registerAppInterfaceResponse.language = SDLLanguageEnGb;
                    registerAppInterfaceResponse.hmiDisplayLanguage = SDLLanguageEnGb;
                    testManager.registerResponse = registerAppInterfaceResponse;

                    SDLLifecycleConfigurationUpdate *update = [[SDLLifecycleConfigurationUpdate alloc] initWithAppName:@"EnGb" shortAppName:@"E" ttsName:[SDLTTSChunk textChunksFromString:@"EnGb ttsName"] voiceRecognitionCommandNames:@[@"EnGb", @"Gb"]];
                    OCMStub([testManager.delegate managerShouldUpdateLifecycleToLanguage:[OCMArg any] hmiLanguage:[OCMArg any]]).andReturn(update);

                    OCMExpect([protocolMock sendRPC:[OCMArg checkWithBlock:^BOOL(id value) {
                        SDLChangeRegistration *changeRegistration = (SDLChangeRegistration *)value;
                        expect(changeRegistration.appName).to(equal(update.appName));
                        expect(changeRegistration.ngnMediaScreenAppName).to(equal(update.shortAppName));
                        expect(changeRegistration.ttsName).to(equal(update.ttsName));
                        expect(changeRegistration.vrSynonyms).to(equal(@[@"EnGb", @"Gb"]));
                        return [value isKindOfClass:[SDLChangeRegistration class]];
                    }]]);

                    setToStateWithEnterTransition(SDLLifecycleStateRegistered, SDLLifecycleStateUpdatingConfiguration);

                    OCMVerifyAllWithDelay(protocolMock, 0.5);

                    expect(testManager.configuration.lifecycleConfig.language).toEventually(equal(SDLLanguageEnGb));
                    expect(testManager.currentVRLanguage).toEventually(equal(SDLLanguageEnGb));
                    expect(testManager.configuration.lifecycleConfig.appName).toEventually(equal(@"EnGb"));
                    expect(testManager.configuration.lifecycleConfig.shortAppName).toEventually(equal(@"E"));
                    expect(testManager.configuration.lifecycleConfig.ttsName).toEventually(equal([SDLTTSChunk textChunksFromString:@"EnGb ttsName"]));
                });

                it(@"should not update the configuration when the app does not support the head unit language or display language", ^{
                    SDLRegisterAppInterfaceResponse *registerAppInterfaceResponse = [[SDLRegisterAppInterfaceResponse alloc] init];
                    registerAppInterfaceResponse.success = @YES;
                    registerAppInterfaceResponse.resultCode = SDLResultWrongLanguage;
                    registerAppInterfaceResponse.info = @"Language mismatch";
                    registerAppInterfaceResponse.language = SDLLanguageDeDe;
                    registerAppInterfaceResponse.hmiDisplayLanguage = SDLLanguageDeDe;
                    testManager.registerResponse = registerAppInterfaceResponse;

                    OCMStub([testManager.delegate managerShouldUpdateLifecycleToLanguage:[OCMArg any] hmiLanguage:[OCMArg any]]).andReturn(nil);

                    setToStateWithEnterTransition(SDLLifecycleStateRegistered, SDLLifecycleStateUpdatingConfiguration);

                    OCMVerifyAllWithDelay(protocolMock, 0.5);

                    expect(testManager.configuration.lifecycleConfig.language).toEventually(equal(SDLLanguageEnUs));
                    expect(testManager.currentVRLanguage).toEventually(equal(SDLLanguageEnUs));
                    expect(testManager.configuration.lifecycleConfig.appName).toEventually(equal(@"Test App"));
                    expect(testManager.configuration.lifecycleConfig.shortAppName).toEventually(equal(@"Short Name"));
                    expect(testManager.configuration.lifecycleConfig.ttsName).toEventually(beNil());
                });

                it(@"should update when the app supports the head unit display language", ^{
                    SDLRegisterAppInterfaceResponse *registerAppInterfaceResponse = [[SDLRegisterAppInterfaceResponse alloc] init];
                    registerAppInterfaceResponse.success = @YES;
                    registerAppInterfaceResponse.resultCode = SDLResultWrongLanguage;
                    registerAppInterfaceResponse.info = @"Language mismatch";
                    registerAppInterfaceResponse.language = SDLLanguageEnUs;
                    registerAppInterfaceResponse.hmiDisplayLanguage = SDLLanguageEnGb;
                    testManager.registerResponse = registerAppInterfaceResponse;

                    SDLLifecycleConfigurationUpdate *update = [[SDLLifecycleConfigurationUpdate alloc] initWithAppName:@"EnGb" shortAppName:@"Gb" ttsName:nil voiceRecognitionCommandNames:nil];
                    OCMStub([testManager.delegate managerShouldUpdateLifecycleToLanguage:registerAppInterfaceResponse.language hmiLanguage:registerAppInterfaceResponse.hmiDisplayLanguage]).andReturn(update);

                    transitionToState(SDLLifecycleStateUpdatingConfiguration);

                    OCMExpect([protocolMock sendRPC:[OCMArg checkWithBlock:^BOOL(id value) {
                        SDLChangeRegistration *changeRegistration = (SDLChangeRegistration *)value;
                        expect(changeRegistration.appName).to(equal(update.appName));
                        expect(changeRegistration.ngnMediaScreenAppName).to(equal(update.shortAppName));
                        expect(changeRegistration.ttsName).to(beNil());
                        expect(changeRegistration.vrSynonyms).to(beNil());
                        return [value isKindOfClass:[SDLChangeRegistration class]];
                    }]]);

                    setToStateWithEnterTransition(SDLLifecycleStateRegistered, SDLLifecycleStateUpdatingConfiguration);

                    OCMVerifyAllWithDelay(protocolMock, 0.5);

                    expect(testManager.configuration.lifecycleConfig.language).toEventually(equal(SDLLanguageEnGb));
                    expect(testManager.currentVRLanguage).toEventually(equal(SDLLanguageEnUs));
                    expect(testManager.configuration.lifecycleConfig.appName).toEventually(equal(@"EnGb"));
                    expect(testManager.configuration.lifecycleConfig.shortAppName).toEventually(equal(@"Gb"));
                    expect(testManager.configuration.lifecycleConfig.ttsName).toEventually(beNil());
                });
            });
        });
        
        describe(@"in the ready state", ^{
            beforeEach(^{
                [testManager.lifecycleStateMachine setToState:SDLLifecycleStateReady fromOldState:nil callEnterTransition:NO];
            });

            it(@"can send an RPC of type Request", ^{
                SDLShow *testShow = [[SDLShow alloc] initWithMainField1:@"test" mainField2:nil mainField3:nil mainField4:nil alignment:nil statusBar:nil mediaTrack:nil graphic:nil secondaryGraphic:nil softButtons:nil customPresets:nil metadataTags:nil templateTitle:nil windowID:nil templateConfiguration:nil];
                OCMExpect([protocolMock sendRPC:testShow]);
                [testManager sendRPC:testShow];

                OCMVerifyAllWithDelay(protocolMock, 0.1);
            });

            it(@"can send an RPC of type Response", ^{
                SDLPerformAppServiceInteractionResponse *testResponse = [[SDLPerformAppServiceInteractionResponse alloc] init];
                OCMExpect([protocolMock sendRPC:testResponse]);
                [testManager sendRPC:testResponse];
                testResponse.correlationID = @(2);
                testResponse.success = @(true);
                testResponse.resultCode = SDLResultSuccess;
                testResponse.info = @"testResponse info";

                OCMVerifyAllWithDelay(protocolMock, 0.1);
            });

            it(@"can send an RPC of type Notification", ^{
                SDLOnAppServiceData *testNotification = [[SDLOnAppServiceData alloc] initWithServiceData:[[SDLAppServiceData alloc] init]];
                OCMExpect([protocolMock sendRPC:testNotification]);
                [testManager sendRPC:testNotification];

                OCMVerifyAllWithDelay(protocolMock, 0.1);
            });

            it(@"should throw an exception if the RPC is not of type `Request`, `Response` or `Notification`", ^{
                SDLRPCMessage *testMessage = [[SDLRPCMessage alloc] init];
                expectAction(^{
                    [testManager sendRPC:testMessage];
                }).to(raiseException());
            });
            
            describe(@"stopping the manager on certain SDLAppInterfaceUnregisteredReason", ^{
                it(@"should attempt to stop the manager when a PROTOCOL_VIOLATION notification is recieved", ^{

                    SDLOnAppInterfaceUnregistered *unreg = [[SDLOnAppInterfaceUnregistered alloc] init];
                    unreg.reason = SDLAppInterfaceUnregisteredReasonProtocolViolation;
                    
                    SDLRPCNotificationNotification *notification = [[SDLRPCNotificationNotification alloc] initWithName:SDLDidReceiveAppUnregisteredNotification object:testManager.notificationDispatcher rpcNotification:unreg];
                    
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                    expect(testManager.lifecycleState).toEventually(equal(SDLLifecycleStateStopped));
                });
       
                it(@"should attempt to stop the manager when an APP_UNAUTHORIZED notification is recieved", ^{
                    
                    SDLOnAppInterfaceUnregistered *unreg = [[SDLOnAppInterfaceUnregistered alloc] init];
                    unreg.reason = SDLAppInterfaceUnregisteredReasonAppUnauthorized;
                    
                    SDLRPCNotificationNotification *notification = [[SDLRPCNotificationNotification alloc] initWithName:SDLDidReceiveAppUnregisteredNotification object:testManager.notificationDispatcher rpcNotification:unreg];
                    
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                    expect(testManager.lifecycleState).toEventually(equal(SDLLifecycleStateStopped));
                });
            });
            
            
            describe(@"stopping the manager", ^{
                beforeEach(^{
                    [testManager stop];
                });
                
                it(@"should attempt to unregister", ^{
                    OCMVerify([protocolMock sendRPC:[OCMArg isKindOfClass:[SDLUnregisterAppInterface class]]]);
                    expect(testManager.lifecycleState).toEventually(match(SDLLifecycleStateUnregistering));
                });
                
                describe(@"when receiving an unregister response", ^{
                    __block SDLUnregisterAppInterfaceResponse *testUnregisterResponse = nil;
                    
                    beforeEach(^{
                        testUnregisterResponse = [[SDLUnregisterAppInterfaceResponse alloc] init];
                        testUnregisterResponse.success = @YES;
                        testUnregisterResponse.correlationID = @(testManager.lastCorrelationId);
                        
                        // This should run on `com.sdl.rpcProcessingQueue` to simulate the real case.
                        [testManager.notificationDispatcher postRPCResponseNotification:SDLDidReceiveUnregisterAppInterfaceResponse response:testUnregisterResponse];
                    });
                    
                    it(@"should stop", ^{
                        expect(testManager.lifecycleState).toEventually(match(SDLLifecycleStateStopped));
                    });
                });
            });
            
            describe(@"receiving an HMI level change", ^{
                __block SDLOnHMIStatus *testHMIStatus = nil;
                __block SDLHMILevel testHMILevel = nil;
                __block SDLHMILevel oldHMILevel = nil;
                
                beforeEach(^{
                    oldHMILevel = testManager.hmiLevel;
                    testHMIStatus = [[SDLOnHMIStatus alloc] init];
                });
                
                context(@"a full hmi level", ^{
                    beforeEach(^{
                        testHMILevel = SDLHMILevelFull;
                        testHMIStatus.hmiLevel = testHMILevel;
                        
                        [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];
                    });
                    
                    it(@"should set the hmi level", ^{
                        expect(testManager.hmiLevel).toEventually(equal(testHMILevel));
                    });
                    
                    it(@"should call the delegate", ^{
                        // Since notifications are sent to SDLManagerDelegate observers on the main thread, force the block to execute manually on the main thread. If this is not done, the test case may fail.
                        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
                        OCMVerify([testManager.delegate hmiLevel:[OCMArg any] didChangeToLevel:[OCMArg any]]);
                    });
                });
            });
            
            describe(@"receiving an audio state change", ^{
                __block SDLOnHMIStatus *testHMIStatus = nil;
                __block SDLAudioStreamingState testAudioStreamingState = nil;
                __block SDLAudioStreamingState oldAudioStreamingState = nil;
                
                beforeEach(^{
                    oldAudioStreamingState = testManager.audioStreamingState;
                    testHMIStatus = [[SDLOnHMIStatus alloc] init];
                });
                
                context(@"a not audible audio state", ^{
                    beforeEach(^{
                        testAudioStreamingState = SDLAudioStreamingStateNotAudible;
                        testHMIStatus.audioStreamingState = testAudioStreamingState;
                        
                        [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];
                    });
                    
                    it(@"should set the audio state", ^{
                        expect(testManager.audioStreamingState).toEventually(equal(testAudioStreamingState));
                    });
                    
                    it(@"should call the delegate", ^{
                        // Since notifications are sent to SDLManagerDelegate observers on the main thread, force the block to execute manually on the main thread. If this is not done, the test case may fail.
                        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];

                        OCMVerify([testManager.delegate audioStreamingState:oldAudioStreamingState didChangeToState:testAudioStreamingState]);
                    });
                });
            });

            describe(@"receiving a video state change", ^{
                __block SDLOnHMIStatus *testHMIStatus = nil;
                __block SDLVideoStreamingState testVideoStreamingState = nil;
                __block SDLAudioStreamingState oldVideoStreamingState = nil;

                beforeEach(^{
                    oldVideoStreamingState = testManager.videoStreamingState;
                    testHMIStatus = [[SDLOnHMIStatus alloc] init];
                });

                context(@"a not audible audio state", ^{
                    beforeEach(^{
                        testVideoStreamingState = SDLVideoStreamingStateNotStreamable;
                        testHMIStatus.videoStreamingState = testVideoStreamingState;

                        [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];
                    });

                    it(@"should set the audio state", ^{
                        expect(testManager.videoStreamingState).toEventually(equal(testVideoStreamingState));
                    });

                    it(@"should call the delegate", ^{
                        // Since notifications are sent to SDLManagerDelegate observers on the main thread, force the block to execute manually on the main thread. If this is not done, the test case may fail.
                        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];

                        OCMVerify([testManager.delegate videoStreamingState:oldVideoStreamingState didChangetoState:testVideoStreamingState]);
                    });
                });
            });
            
            describe(@"receiving a system context change", ^{
                __block SDLOnHMIStatus *testHMIStatus = nil;
                __block SDLSystemContext testSystemContext = nil;
                __block SDLSystemContext oldSystemContext = nil;

                beforeEach(^{
                    oldSystemContext = testManager.systemContext;
                    testHMIStatus = [[SDLOnHMIStatus alloc] init];
                });
                
                context(@"a alert system context state", ^{
                    beforeEach(^{
                        expect(testManager.lifecycleStateMachine.currentState).to(equal(SDLLifecycleStateReady));
                        expect(testManager.systemContext).to(beNil());

                        testSystemContext = SDLSystemContextAlert;
                        testHMIStatus.systemContext = testSystemContext;
                        
                        [testManager.notificationDispatcher postRPCNotificationNotification:SDLDidChangeHMIStatusNotification notification:testHMIStatus];
                    });
                    
                    it(@"should set the system context", ^{
                        expect(testManager.systemContext).toEventually(equal(testSystemContext));
                    });
                    
                    it(@"should call the delegate", ^{
                        // Since notifications are sent to SDLManagerDelegate observers on the main thread, force the block to execute manually on the main thread. If this is not done, the test case may fail.
                        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
                        OCMVerify([testManager.delegate systemContext:[OCMArg any] didChangeToContext:[OCMArg any]]);
                    });

                    afterEach(^{
                        expect(testManager.delegate).toNot(beNil());
                    });
                });
            });
         });
    });

    describe(@"configuring the lifecycle manager", ^{
        __block SDLLifecycleConfiguration *lifecycleConfig = nil;
        __block SDLLifecycleManager *testManager = nil;

        beforeEach(^{
            lifecycleConfig = [SDLLifecycleConfiguration defaultConfigurationWithAppName:@"Test app" fullAppId:@"Test ID"];
        });

        context(@"if secondary transport is not allowed", ^{
            beforeEach(^{
                lifecycleConfig.allowedSecondaryTransports = SDLSecondaryTransportsNone;
                SDLConfiguration *config = [[SDLConfiguration alloc] initWithLifecycle:lifecycleConfig lockScreen:[SDLLockScreenConfiguration disabledConfiguration] logging:[SDLLogConfiguration defaultConfiguration] fileManager:[SDLFileManagerConfiguration defaultConfiguration] encryption:[SDLEncryptionConfiguration defaultConfiguration]];
                testManager = [[SDLLifecycleManager alloc] initWithConfiguration:config delegate:nil];
                [testManager.lifecycleStateMachine setToState:SDLLifecycleStateStarted fromOldState:nil callEnterTransition:YES];
            });

            it(@"should not create a secondary transport manager", ^{
                expect(testManager.secondaryTransportManager).to(beNil());
            });
        });

        context(@"if a secondary transport is allowed but app is NOT a navigation or projection app", ^{
            beforeEach(^{
                 lifecycleConfig.allowedSecondaryTransports = SDLSecondaryTransportsTCP;
                 lifecycleConfig.appType = SDLAppHMITypeSocial;
                 SDLConfiguration *config = [[SDLConfiguration alloc] initWithLifecycle:lifecycleConfig lockScreen:[SDLLockScreenConfiguration disabledConfiguration] logging:[SDLLogConfiguration defaultConfiguration] fileManager:[SDLFileManagerConfiguration defaultConfiguration] encryption:[SDLEncryptionConfiguration defaultConfiguration]];
                 testManager = [[SDLLifecycleManager alloc] initWithConfiguration:config delegate:nil];
                 [testManager.lifecycleStateMachine setToState:SDLLifecycleStateStarted fromOldState:nil callEnterTransition:YES];
            });

             it(@"should not create a secondary transport manager", ^{
                 expect(testManager.secondaryTransportManager).to(beNil());
             });
        });

        context(@"if a secondary transport is allowed and app is a navigation or projection app", ^{
            beforeEach(^{
                lifecycleConfig.allowedSecondaryTransports = SDLSecondaryTransportsTCP;
                lifecycleConfig.appType = SDLAppHMITypeProjection;
                SDLConfiguration *config = [[SDLConfiguration alloc] initWithLifecycle:lifecycleConfig lockScreen:[SDLLockScreenConfiguration disabledConfiguration] logging:[SDLLogConfiguration defaultConfiguration] streamingMedia:[SDLStreamingMediaConfiguration insecureConfiguration] fileManager:[SDLFileManagerConfiguration defaultConfiguration] encryption:[SDLEncryptionConfiguration defaultConfiguration]];
                testManager = [[SDLLifecycleManager alloc] initWithConfiguration:config delegate:nil];

                [testManager.lifecycleStateMachine setToState:SDLLifecycleStateStarted fromOldState:nil callEnterTransition:YES];
            });

            it(@"should create a secondary transport manager", ^{
                expect(testManager.streamManager).toNot(beNil());
                expect(testManager.secondaryTransportManager).toNot(beNil());
            });
        });
    });
});

QuickSpecEnd