forked from FreeRTOS/coreSNTP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore_sntp_client_utest.c
1387 lines (1212 loc) · 72.2 KB
/
core_sntp_client_utest.c
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
/*
* coreSNTP v1.3.1
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Standard includes. */
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
/* Unity include. */
#include "unity.h"
/*#define SNTP_DO_NOT_USE_CUSTOM_CONFIG 1 */
/* coreSNTP Client API include */
#include "core_sntp_client.h"
/* Include mock header of Serializer API of coreSNTP. */
#include "mock_core_sntp_serializer.h"
/* Test IPv4 address for time server. */
#define TEST_SERVER_ADDR ( 0xAABBCCDD )
/* Test server response timeout (in ms). */
#define TEST_RESPONSE_TIMEOUT ( 500 )
/* Test block time for calls to Sntp_ReceiveTimeResponse API. */
#define TEST_RECV_BLOCK_TIME ( TEST_RESPONSE_TIMEOUT / 2 )
/* Test values for the "last request time" state of the SNTP context. */
#define LAST_REQUEST_TIME_SECS 10
#define LAST_REQUEST_TIME_MS 100
/* Test block time for the Sntp_SendRequestTime API.
* This serves as the timeout value for send operations. */
#define SEND_TIMEOUT_MS 10
/* Utility to convert milliseconds to fractions value in
* SNTP timestamp. */
#define CONVERT_MS_TO_FRACTIONS( MS ) \
( MS * 1000 * SNTP_FRACTION_VALUE_PER_MICROSECOND )
/* Test definition of NetworkContext_t structure. */
typedef struct NetworkContext
{
int udpSocket;
} NetworkContext_t;
/* Test definition of SntpAuthContext_t structure. */
typedef struct SntpAuthContext
{
uint32_t keyId;
} SntpAuthContext_t;
/* Global variables common to test cases. */
static SntpContext_t context;
static uint8_t testBuffer[ 100 ];
static SntpServerInfo_t testServers[] =
{
{
"my.ntp.server.1",
strlen( "my.ntp.server.1" ),
SNTP_DEFAULT_SERVER_PORT
},
{
"my.ntp.server.2",
strlen( "my.ntp.server.2" ),
SNTP_DEFAULT_SERVER_PORT
}
};
static UdpTransportInterface_t transportIntf;
static NetworkContext_t netContext;
static SntpAuthenticationInterface_t authIntf;
static SntpAuthContext_t authContext;
/* Variables for configuring behavior of interface functions. */
static bool dnsResolveRetCode = true;
static uint32_t dnsResolveAddr = TEST_SERVER_ADDR;
static SntpTimestamp_t currentTimeList[ 4 ];
static uint8_t currentTimeIndex;
static size_t expectedBytesToSend = SNTP_PACKET_BASE_SIZE;
static int32_t udpSendRetCodes[ 2 ];
static uint8_t currentUdpSendCodeIndex;
static int32_t udpRecvRetCodes[ 3 ];
static uint8_t currentUdpRecvCodeIndex;
static size_t expectedBytesToRecv = SNTP_PACKET_BASE_SIZE;
static SntpStatus_t generateClientAuthRetCode = SntpSuccess;
static uint16_t authCodeSize;
static SntpStatus_t validateServerAuthRetCode = SntpSuccess;
/* Output parameter for mock of Sntp_DeserializeResponse API. */
static SntpResponseData_t mockResponseData =
{
.clockOffsetMs = 1000,
.leapSecondType = NoLeapSecond,
.rejectedResponseCode = SNTP_KISS_OF_DEATH_CODE_NONE,
.serverTime =
{
.seconds = 0xAABBCCDD,
.fractions = 0x11223344
}
};
/* ========================= Helper Functions ============================ */
/* Test definition of the @ref SntpResolveDns_t interface. */
static bool dnsResolve( const SntpServerInfo_t * pServerAddr,
uint32_t * pIpV4Addr )
{
TEST_ASSERT_NOT_NULL( pServerAddr );
TEST_ASSERT_NOT_NULL( pIpV4Addr );
*pIpV4Addr = TEST_SERVER_ADDR;
return dnsResolveRetCode;
}
/* Test definition of the @ref SntpGetTime_t interface. */
static void getTime( SntpTimestamp_t * pCurrentTime )
{
TEST_ASSERT_NOT_NULL( pCurrentTime );
/* Set the current time output parameter based on index
* in the time list. */
pCurrentTime->seconds = currentTimeList[ currentTimeIndex ].seconds;
pCurrentTime->fractions = currentTimeList[ currentTimeIndex ].fractions;
/* Increment the index to point to the next in the list. */
currentTimeIndex = ( currentTimeIndex + 1 ) %
( sizeof( currentTimeList ) / sizeof( SntpTimestamp_t ) );
}
/* Test definition of the @ref SntpSetTime_t interface. */
static void setTime( const SntpServerInfo_t * pTimeServer,
const SntpTimestamp_t * pServerTime,
int64_t clockOffsetMs,
SntpLeapSecondInfo_t leapSecondInfo )
{
TEST_ASSERT_NOT_NULL( pTimeServer );
TEST_ASSERT_NOT_NULL( pServerTime );
TEST_ASSERT_EQUAL( mockResponseData.clockOffsetMs, clockOffsetMs );
TEST_ASSERT_EQUAL( mockResponseData.leapSecondType, leapSecondInfo );
TEST_ASSERT_EQUAL_MEMORY( &mockResponseData.serverTime, pServerTime, sizeof( SntpTimestamp_t ) );
}
/* Test definition of the @ref UdpTransportSendTo_t interface. */
static int32_t UdpSendTo( NetworkContext_t * pNetworkContext,
uint32_t serverAddr,
uint16_t serverPort,
const void * pBuffer,
uint16_t bytesToSend )
{
TEST_ASSERT_EQUAL_PTR( &netContext, pNetworkContext );
TEST_ASSERT_NOT_NULL( pBuffer );
TEST_ASSERT_EQUAL( dnsResolveAddr, serverAddr );
TEST_ASSERT_EQUAL( SNTP_DEFAULT_SERVER_PORT, serverPort );
TEST_ASSERT_EQUAL( expectedBytesToSend, bytesToSend );
int32_t retCode = udpSendRetCodes[ currentUdpSendCodeIndex ];
/* Increment the index in the return code list to the next. */
currentUdpSendCodeIndex = ( currentUdpSendCodeIndex + 1 ) %
( sizeof( udpSendRetCodes ) / sizeof( int32_t ) );
return retCode;
}
/* Test definition of the @ref UdpTransportRecvFrom_t interface. */
static int32_t UdpRecvFrom( NetworkContext_t * pNetworkContext,
uint32_t serverAddr,
uint16_t serverPort,
void * pBuffer,
uint16_t bytesToRecv )
{
TEST_ASSERT_EQUAL_PTR( &netContext, pNetworkContext );
TEST_ASSERT_NOT_NULL( pBuffer );
TEST_ASSERT_EQUAL( context.currentServerAddr, serverAddr );
TEST_ASSERT_EQUAL( SNTP_DEFAULT_SERVER_PORT, serverPort );
TEST_ASSERT_EQUAL( expectedBytesToRecv, bytesToRecv );
int32_t retCode = udpRecvRetCodes[ currentUdpRecvCodeIndex ];
/* Increment the index in the return code list to the next. */
currentUdpRecvCodeIndex = ( currentUdpRecvCodeIndex + 1 ) %
( sizeof( udpRecvRetCodes ) / sizeof( int32_t ) );
return retCode;
}
/* Test definition for @ref SntpGenerateAuthCode_t interface. */
static SntpStatus_t generateClientAuth( SntpAuthContext_t * pContext,
const SntpServerInfo_t * pTimeServer,
void * pBuffer,
size_t bufferSize,
uint16_t * pAuthCodeSize )
{
TEST_ASSERT_EQUAL_PTR( &authContext, pContext );
TEST_ASSERT_NOT_NULL( pTimeServer );
TEST_ASSERT_EQUAL_PTR( testBuffer, pBuffer );
TEST_ASSERT_NOT_NULL( pAuthCodeSize );
TEST_ASSERT_EQUAL( context.bufferSize, bufferSize );
TEST_ASSERT_GREATER_OR_EQUAL( SNTP_PACKET_BASE_SIZE, bufferSize );
*pAuthCodeSize = authCodeSize;
return generateClientAuthRetCode;
}
/* Test definition for @ref SntpValidateServerAuth_t interface. */
static SntpStatus_t validateServerAuth( SntpAuthContext_t * pContext,
const SntpServerInfo_t * pTimeServer,
const void * pResponseData,
uint16_t responseSize )
{
TEST_ASSERT_EQUAL_PTR( &authContext, pContext );
TEST_ASSERT_NOT_NULL( pTimeServer );
TEST_ASSERT_EQUAL_PTR( testBuffer, pResponseData );
TEST_ASSERT_GREATER_OR_EQUAL( SNTP_PACKET_BASE_SIZE, responseSize );
TEST_ASSERT_EQUAL( context.sntpPacketSize, responseSize );
return validateServerAuthRetCode;
}
/* Enumeration for the API functions of the SNTP Client layer. */
enum SntpClientApiType
{
ApiInvalid,
ApiSendTimeRequest,
ApiReceiveTimeResponse
};
/* Common function for testing all scenarios of invalid context. */
static void testApiForInvalidContextCases( enum SntpClientApiType api )
{
#define SELECT_API_AND_TEST_INVALID_CONTEXT( api, context ) \
do { \
if( api == ApiSendTimeRequest ) \
{ \
TEST_ASSERT_EQUAL( SntpErrorContextNotInitialized, Sntp_SendTimeRequest( &context, \
rand() % UINT32_MAX, \
SEND_TIMEOUT_MS ) ); \
} \
else \
{ \
TEST_ASSERT_EQUAL( SntpErrorContextNotInitialized, Sntp_ReceiveTimeResponse( &context, 0 ) ); \
} \
} while( 0 )
/* Start with a non-initialized context. */
SntpContext_t testContext;
memset( &testContext, 0, sizeof( SntpContext_t ) );
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Now fully initialize context and then test all scenarios with only one member being invalid. */
TEST_ASSERT_EQUAL( SntpSuccess,
Sntp_Init( &testContext,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
&authIntf ) );
/* Test with invalid servers in the context. */
testContext.pTimeServers = NULL;
testContext.numOfServers = 0;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
testContext.pTimeServers = testServers;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Reset the server list to be valid. */
testContext.pTimeServers = testServers;
testContext.numOfServers = sizeof( testServers ) / sizeof( SntpServerInfo_t );
/* Test with invalid network buffer and/or buffer size in the context. */
testContext.pNetworkBuffer = NULL;
testContext.bufferSize = 0;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
testContext.pNetworkBuffer = testBuffer;
testContext.bufferSize = SNTP_PACKET_BASE_SIZE - 1;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Reset the network buffer and size to be valid in the context. */
testContext.pNetworkBuffer = testBuffer;
testContext.bufferSize = sizeof( testBuffer );
/* Test with invalid DNS Resolution interface function. */
testContext.resolveDnsFunc = NULL;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Reset the DNS Resolution function pointer to be valid. */
testContext.resolveDnsFunc = dnsResolve;
/* Test with invalid SntpGetTime_t interface function. */
testContext.getTimeFunc = NULL;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Reset the SntpGetTime_t function pointer to be valid. */
testContext.getTimeFunc = getTime;
/* Test with invalid SntpSetTime_t interface function. */
testContext.setTimeFunc = NULL;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Reset the SntpSetTime_t function pointer to be valid. */
testContext.setTimeFunc = setTime;
/* Test with invalid SntpSetTime_t interface function. */
testContext.networkIntf.recvFrom = NULL;
testContext.networkIntf.sendTo = NULL;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
testContext.networkIntf.sendTo = UdpSendTo;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
testContext.networkIntf.sendTo = NULL;
testContext.networkIntf.recvFrom = UdpRecvFrom;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Reset the network interface function pointers to be valid. */
testContext.networkIntf.sendTo = UdpSendTo;
testContext.networkIntf.recvFrom = UdpRecvFrom;
/* Test cases when only one of the authentication interface functions is set,
* instead of both. */
testContext.authIntf.generateClientAuth = NULL;
testContext.authIntf.validateServerAuth = validateServerAuth;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
testContext.authIntf.generateClientAuth = generateClientAuth;
testContext.authIntf.validateServerAuth = NULL;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
/* Test with invalid value of the sntpPacketSize member of the context. */
testContext.sntpPacketSize = SNTP_PACKET_BASE_SIZE - 1;
SELECT_API_AND_TEST_INVALID_CONTEXT( api, testContext );
}
/* Helper function to set values in the currentTimeList that is used in the
* test implementation of the SntpGetTime_t interface. */
static void setSystemTimeAtIndex( size_t index,
uint32_t seconds,
uint32_t milliseconds )
{
currentTimeList[ index ].seconds = seconds;
currentTimeList[ index ].fractions = CONVERT_MS_TO_FRACTIONS( milliseconds );
}
/* ============================ UNITY FIXTURES ============================ */
/* Called before each test method. */
void setUp()
{
/* Reset the global variables. */
dnsResolveRetCode = true;
dnsResolveAddr = TEST_SERVER_ADDR;
generateClientAuthRetCode = SntpSuccess;
validateServerAuthRetCode = SntpSuccess;
currentTimeIndex = 0;
authCodeSize = 0;
expectedBytesToSend = SNTP_PACKET_BASE_SIZE;
expectedBytesToRecv = SNTP_PACKET_BASE_SIZE;
/* Reset array of UDP I/O functions return codes. */
memset( udpSendRetCodes, 0, sizeof( udpSendRetCodes ) );
currentUdpSendCodeIndex = 0;
memset( udpRecvRetCodes, 0, sizeof( udpRecvRetCodes ) );
currentUdpRecvCodeIndex = 0;
/* Reset the current time list for the SntpGetTime_t
* interface function. */
memset( currentTimeList, 0, sizeof( currentTimeList ) );
/* Set the transport interface object. */
transportIntf.pUserContext = &netContext;
transportIntf.sendTo = UdpSendTo;
transportIntf.recvFrom = UdpRecvFrom;
/* Set the auth interface object. */
authIntf.pAuthContext = &authContext;
authIntf.generateClientAuth = generateClientAuth;
authIntf.validateServerAuth = validateServerAuth;
/* Clear the network buffer. */
memset( &testBuffer, 0, sizeof( testBuffer ) );
/* Initialize context. */
TEST_ASSERT_EQUAL( SntpSuccess,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
&authIntf ) );
/* Update the "Last Request Time" state of the context to a non-zero value to
* check that it gets cleared by the library only AFTER receiving a valid SNTP response. */
context.lastRequestTime.seconds = LAST_REQUEST_TIME_SECS;
context.lastRequestTime.fractions = CONVERT_MS_TO_FRACTIONS( LAST_REQUEST_TIME_MS );
}
/* Called at the beginning of the whole suite. */
void suiteSetUp()
{
}
/* Called at the end of the whole suite. */
int suiteTearDown( int numFailures )
{
return numFailures;
}
/* ========================================================================== */
/**
* @brief Test @ref Sntp_Init with invalid parameters.
*/
void test_Init_InvalidParams( void )
{
/* Pass invalid context memory. */
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( NULL,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
NULL ) );
/* Pass invalid list of time servers. */
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
NULL,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
NULL ) );
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
0,
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
NULL ) );
/* Pass invalid network buffer. */
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
NULL,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
NULL ) );
TEST_ASSERT_EQUAL( SntpErrorBufferTooSmall,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
SNTP_PACKET_BASE_SIZE / 2,
dnsResolve,
getTime,
setTime,
&transportIntf,
NULL ) );
/* Pass invalid required interface definitions. */
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
NULL,
getTime,
setTime,
&transportIntf,
NULL ) );
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
NULL,
setTime,
&transportIntf,
NULL ) );
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
NULL,
&transportIntf,
NULL ) );
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
NULL,
NULL ) );
/* Pass valid transport interface object but invalid members. */
transportIntf.recvFrom = NULL;
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
NULL ) );
transportIntf.recvFrom = UdpRecvFrom;
transportIntf.sendTo = NULL;
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
NULL ) );
/* Set the transport interface object to be valid for next test. */
transportIntf.sendTo = UdpSendTo;
/* Pass valid authentication interface object but invalid members. */
authIntf.generateClientAuth = NULL;
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
&authIntf ) );
authIntf.generateClientAuth = generateClientAuth;
authIntf.validateServerAuth = NULL;
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_Init( &context,
testServers,
sizeof( testServers ) / sizeof( SntpServerInfo_t ),
TEST_RESPONSE_TIMEOUT,
testBuffer,
sizeof( testBuffer ),
dnsResolve,
getTime,
setTime,
&transportIntf,
&authIntf ) );
}
/**
* @brief Test @ref Sntp_Init API correctly initializes a context.
*/
void test_Init_Nominal( void )
{
#define TEST_SNTP_INIT_SUCCESS( pAuthIntf ) \
do { \
/* Call the API under test. */ \
TEST_ASSERT_EQUAL( SntpSuccess, \
Sntp_Init( &context, \
testServers, \
sizeof( testServers ) / sizeof( SntpServerInfo_t ), \
TEST_RESPONSE_TIMEOUT, \
testBuffer, \
sizeof( testBuffer ), \
dnsResolve, \
getTime, \
setTime, \
&transportIntf, \
pAuthIntf ) ); \
\
/* Make sure that the passed parameters have been set in the context. */ \
TEST_ASSERT_EQUAL( testServers, context.pTimeServers ); \
TEST_ASSERT_EQUAL( sizeof( testServers ) / sizeof( SntpServerInfo_t ), context.numOfServers ); \
TEST_ASSERT_EQUAL_PTR( testBuffer, context.pNetworkBuffer ); \
TEST_ASSERT_EQUAL( TEST_RESPONSE_TIMEOUT, context.responseTimeoutMs ); \
TEST_ASSERT_EQUAL( sizeof( testBuffer ), context.bufferSize ); \
TEST_ASSERT_EQUAL_PTR( dnsResolve, context.resolveDnsFunc ); \
TEST_ASSERT_EQUAL_PTR( getTime, context.getTimeFunc ); \
TEST_ASSERT_EQUAL_PTR( setTime, context.setTimeFunc ); \
TEST_ASSERT_EQUAL_MEMORY( &transportIntf, \
&context.networkIntf, \
sizeof( UdpTransportInterface_t ) ); \
if( pAuthIntf == NULL ) \
{ \
TEST_ASSERT_NULL( context.authIntf.pAuthContext ); \
TEST_ASSERT_NULL( context.authIntf.generateClientAuth ); \
TEST_ASSERT_NULL( context.authIntf.validateServerAuth ); \
} \
else \
{ \
TEST_ASSERT_EQUAL_MEMORY( &authIntf, &context.authIntf, sizeof( SntpAuthenticationInterface_t ) ); \
} \
\
/* Validate the initialization of the state members of the context. */ \
TEST_ASSERT_EQUAL( 0, context.currentServerIndex ); \
TEST_ASSERT_EQUAL( 0, context.currentServerAddr ); \
TEST_ASSERT_EQUAL( 0, context.lastRequestTime.seconds ); \
TEST_ASSERT_EQUAL( 0, context.lastRequestTime.fractions ); \
TEST_ASSERT_EQUAL( SNTP_PACKET_BASE_SIZE, context.sntpPacketSize ); \
} while( 0 )
/* Test when an authentication interface is not passed. */
TEST_SNTP_INIT_SUCCESS( NULL );
/* Reset the context memory. */
memset( &context, 0, sizeof( SntpContext_t ) );
/* Test with a valid authentication interface. */
TEST_SNTP_INIT_SUCCESS( &authIntf );
}
/**
* @brief Validate the behavior of @ref Sntp_SendTimeRequest for invalid
* parameters
*/
void test_Sntp_SendTimeRequest_InvalidParams()
{
/* Test with NULL context parameter. */
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_SendTimeRequest( NULL, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
/* Test all cases of context with invalid members. */
testApiForInvalidContextCases( ApiSendTimeRequest );
/* Reset the context member for current server to a valid value. */
context.currentServerIndex = 0U;
}
/**
* @brief Validate the behavior of @ref Sntp_SendTimeRequest when the DNS resolution
* of time server fails.
*/
void test_Sntp_SendTimeRequest_Dns_Failure()
{
/* Test case when DNS resolution of server fails. */
dnsResolveRetCode = false;
TEST_ASSERT_EQUAL( SntpErrorDnsFailure,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
}
/**
* @brief Validate the behavior of @ref Sntp_SendTimeRequest when authentication
* interface returns error of the request buffer being insufficient in size for
* adding authentication data.
*/
void test_Sntp_SendTimeRequest_Auth_Failure_BufferTooSmall()
{
/* Set the behavior of the serializer function dependency to always return
* success. */
Sntp_SerializeRequest_IgnoreAndReturn( SntpSuccess );
/* Test case when authentication interface call for adding client authentication
* fails. */
generateClientAuthRetCode = SntpErrorBufferTooSmall;
TEST_ASSERT_EQUAL( SntpErrorBufferTooSmall,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
}
/**
* @brief Validate the behavior of @ref Sntp_SendTimeRequest when failure from
* the authentication interface function, that generates client authentication,
* returning failure.
*/
void test_Sntp_SendTimeRequest_Auth_Failure_InternalError()
{
/* Set the behavior of the serializer function dependency to always return
* success. */
Sntp_SerializeRequest_IgnoreAndReturn( SntpSuccess );
generateClientAuthRetCode = SntpErrorAuthFailure;
TEST_ASSERT_EQUAL( SntpErrorAuthFailure,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
}
/**
* @brief Validate that @ref Sntp_SendTimeRequest returns failure when the authentication
* data size returned by the @ref SntpGenerateAuthCode_t function of authentication interface
* is invalid, i.e. the size exceeds the buffer capacity for holding authentication data.
*/
void test_Sntp_SendTimeRequest_Auth_Failure_InvalidOutputParam()
{
/* Set the behavior of the serializer function dependency to always return
* success. */
Sntp_SerializeRequest_IgnoreAndReturn( SntpSuccess );
/* Test when authentication interface returns an invalid authentication data
* size.*/
authCodeSize = sizeof( testBuffer ) - SNTP_PACKET_BASE_SIZE + 1; /* 1 byte more than buffer can
* take for holding auth data. */
TEST_ASSERT_EQUAL( SntpErrorAuthFailure,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
}
/**
* @brief Validate the behavior of @ref Sntp_SendTimeRequest when transport send operation
* fails in the first try.
*/
void test_Sntp_SendTimeRequest_Transport_Send_Failure_ErrorOnFirstTry()
{
/* Set the behavior of the serializer function dependency to always return
* success. */
Sntp_SerializeRequest_IgnoreAndReturn( SntpSuccess );
/* Test case when transport send fails with negative error code sent in the first
* call to transport interface send function. */
udpSendRetCodes[ currentUdpSendCodeIndex ] = -2;
TEST_ASSERT_EQUAL( SntpErrorNetworkFailure,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
}
/**
* @brief Validate the behavior of @ref Sntp_SendTimeRequest when transport send operation
* fails in a retry attempt.
*/
void test_Sntp_SendTimeRequest_Transport_Send_Failure_ErrorOnRetry()
{
/* Set the behavior of the serializer function dependency to always return
* success. */
Sntp_SerializeRequest_IgnoreAndReturn( SntpSuccess );
/* Test case when transport send fails with negative error code sent after some
* calls to transport interface send function. */
udpSendRetCodes[ 0 ] = 0; /* 1st call sending 0 bytes.*/
udpSendRetCodes[ 1 ] = -1; /* 2nd call returning error.*/
TEST_ASSERT_EQUAL( SntpErrorNetworkFailure,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
/* Reset the index in the current time list. */
currentTimeIndex = 0;
currentUdpSendCodeIndex = 0;
}
/**
* @brief Validate the behavior of @ref Sntp_SendTimeRequest when retries time
* out for transport send operation.
*/
void test_Sntp_SendTimeRequest_Transport_Send_Error_RetryTimeout()
{
/* Set the behavior of the serializer function dependency to always return
* success. */
Sntp_SerializeRequest_IgnoreAndReturn( SntpSuccess );
/* Test case when transport send operation times out due to no data being
* sent for #SEND_TIMEOUT_MS duration. */
udpSendRetCodes[ 0 ] = 0;
udpSendRetCodes[ 1 ] = 0;
currentTimeList[ 1 ].fractions = 0; /* SntpGetTime_t call before the loop in sendSntpPacket. */
currentTimeList[ 2 ].fractions = CONVERT_MS_TO_FRACTIONS( SEND_TIMEOUT_MS / 2 ); /* SntpGetTime_t call in 1st iteration of loop. */
currentTimeList[ 3 ].fractions = CONVERT_MS_TO_FRACTIONS( ( SEND_TIMEOUT_MS + 1 ) ); /* SntpGetTime_t call in 2nd iteration of loop. */
TEST_ASSERT_EQUAL( SntpErrorSendTimeout,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
}
/**
* @brief Validate that the @ref Sntp_SendTimeRequest API treats partial data being sent
* by the UDP transport interface as an error because UDP does not support partial sends.
*/
void test_Sntp_SendTimeRequest_Transport_Send_Error_PartialSend()
{
/* Set the behavior of the serializer function dependency to always return
* success. */
Sntp_SerializeRequest_IgnoreAndReturn( SntpSuccess );
/* Test case when transport send returns partial number of bytes sent. This is
* incorrect as UDP protocol does not support partial writes. */
udpSendRetCodes[ 0 ] = 0; /* 1st call sending 0 bytes.*/
udpSendRetCodes[ 1 ] = expectedBytesToSend / 2; /* 2nd call returning partial bytes.*/
TEST_ASSERT_EQUAL( SntpErrorNetworkFailure,
Sntp_SendTimeRequest( &context, rand() % UINT32_MAX, SEND_TIMEOUT_MS ) );
}
/**
* @brief Validate behavior of @ref Sntp_SendTimeRequest in success cases.
*/
void test_SendTimeRequest_Nominal( void )
{
uint32_t randNum = ( rand() % UINT32_MAX );
/* Set the size of authentication data within the SNTP packet. */
authCodeSize = sizeof( testBuffer ) - SNTP_PACKET_BASE_SIZE;
#define TEST_SUCCESS_CASE( packetSize, timeBeforeLoop, timeIn1stIteration ) \
do { \
/* Reset indices to lists controlling behavior of interface functions. */ \
currentTimeIndex = 0; \
currentUdpSendCodeIndex = 0; \
\
/* Set the parameter expectations and behavior of call to serializer function .*/ \
Sntp_SerializeRequest_ExpectAndReturn( &context.lastRequestTime, randNum, \
testBuffer, sizeof( testBuffer ), SntpSuccess ); \
\
/* Update the global variable of expected number of bytes to send with network send function. */ \
expectedBytesToSend = packetSize; \
\
/* Set the behavior of the transport send and get time interface functions. */ \
udpSendRetCodes[ 0 ] = 0; /* 1st return value for no data send. */ \
udpSendRetCodes[ 1 ] = expectedBytesToSend; /* 2nd return value for the packet send. */ \
currentTimeList[ 1 ].seconds = timeBeforeLoop.seconds; /* Time call in before loop in sendSntpPacket. */ \
currentTimeList[ 1 ].fractions = timeBeforeLoop.fractions; /* Time call in before loop in sendSntpPacket loop. */ \
currentTimeList[ 2 ].seconds = timeIn1stIteration.seconds; /* Time call in 1st iteration of sendSntpPacket loop. */ \
currentTimeList[ 2 ].fractions = timeIn1stIteration.fractions; /* Time call in 1st iteration of sendSntpPacket loop. */ \
TEST_ASSERT_EQUAL( SntpSuccess, Sntp_SendTimeRequest( &context, randNum, SEND_TIMEOUT_MS ) ); \
} while( 0 )
SntpTimestamp_t beforeLoopTime;
SntpTimestamp_t inLoopTime;
beforeLoopTime.seconds = 0;
beforeLoopTime.fractions = 0;
inLoopTime.seconds = 0;
inLoopTime.fractions = CONVERT_MS_TO_FRACTIONS( SEND_TIMEOUT_MS / 2 );
/* Test when no authentication interface is provided. */
context.authIntf.generateClientAuth = NULL;
context.authIntf.validateServerAuth = NULL;
TEST_SUCCESS_CASE( SNTP_PACKET_BASE_SIZE, beforeLoopTime, inLoopTime );
/* Test when an authentication interface is provided. */
context.authIntf.generateClientAuth = generateClientAuth;
context.authIntf.validateServerAuth = validateServerAuth;
TEST_SUCCESS_CASE( SNTP_PACKET_BASE_SIZE + authCodeSize, beforeLoopTime, inLoopTime );
/* Test edge case when SNTP time overflows (i.e. at 7 Feb 2036 6h 28m 16s UTC )
* during the send operation. */
beforeLoopTime.seconds = UINT32_MAX;
beforeLoopTime.fractions = UINT32_MAX; /* Last time in SNTP era 0. */
inLoopTime.seconds = 0; /* Time in SNTP era 1. */
inLoopTime.fractions = CONVERT_MS_TO_FRACTIONS( SEND_TIMEOUT_MS / 2 );
/* Test when an authentication interface is provided. */
TEST_SUCCESS_CASE( SNTP_PACKET_BASE_SIZE + authCodeSize, beforeLoopTime, inLoopTime );
}
/**
* @brief Validate the behavior of @ref Sntp_ReceiveTimeResponse API for all error cases.
*/
void test_Sntp_ReceiveTimeResponse_InvalidParams()
{
/* Test with NULL context parameter. */
TEST_ASSERT_EQUAL( SntpErrorBadParameter,
Sntp_ReceiveTimeResponse( NULL, TEST_RESPONSE_TIMEOUT ) );
/* Test all cases of context with invalid members. */
testApiForInvalidContextCases( ApiReceiveTimeResponse );
}
/**
* @brief Validate the behavior of @ref Sntp_ReceiveTimeResponse API for the case
* when the transport receive operation returns error in the first read attempt within
* the receive loop of the API.
*/
void test_ReceiveTimeResponse_Transport_Read_Failures_NoRetry( void )
{
/* Test case when transport receive fails in the first byte read attempt. */
udpRecvRetCodes[ 0 ] = -1; /* 1st read call. No data read.*/
TEST_ASSERT_EQUAL( SntpErrorNetworkFailure,
Sntp_ReceiveTimeResponse( &context, TEST_RECV_BLOCK_TIME ) );
/* Ensure that the "last request time" state of the context was not modified from network error. */
TEST_ASSERT_EQUAL( LAST_REQUEST_TIME_SECS, context.lastRequestTime.seconds );
TEST_ASSERT_EQUAL( CONVERT_MS_TO_FRACTIONS( LAST_REQUEST_TIME_MS ), context.lastRequestTime.fractions );
}
/**
* @brief Validate the behavior of @ref Sntp_ReceiveTimeResponse API for cases
* when the transport receive operation returns error in a read retry attempt within
* the receive loop of the API.
*/
void test_ReceiveTimeResponse_Transport_Read_Failures_AfterRetries( void )
{
/* Set the times to be returned by SntpGetTime_t function to be within the server response timeout
* as well as block time windows. */
setSystemTimeAtIndex( 0, LAST_REQUEST_TIME_SECS, LAST_REQUEST_TIME_MS );
setSystemTimeAtIndex( 1, LAST_REQUEST_TIME_SECS, LAST_REQUEST_TIME_MS + TEST_RECV_BLOCK_TIME / 2 );
setSystemTimeAtIndex( 2, LAST_REQUEST_TIME_SECS, LAST_REQUEST_TIME_MS + ( 2 * TEST_RECV_BLOCK_TIME / 3 ) );
/* Test cases when transport receive fail in the retry attempts. */
udpRecvRetCodes[ 0 ] = 0; /* 1st read call. No data read.*/
udpRecvRetCodes[ 1 ] = -1; /* Encounter error in 2nd call to receive remaining packet.*/
TEST_ASSERT_EQUAL( SntpErrorNetworkFailure,
Sntp_ReceiveTimeResponse( &context, TEST_RECV_BLOCK_TIME ) );
/* Ensure that the "last request time" state of the context was not modified from network error. */
TEST_ASSERT_EQUAL( LAST_REQUEST_TIME_SECS, context.lastRequestTime.seconds );
TEST_ASSERT_EQUAL( CONVERT_MS_TO_FRACTIONS( LAST_REQUEST_TIME_MS ), context.lastRequestTime.fractions );
/* Reset the receive code index. */
currentUdpRecvCodeIndex = 0;
currentTimeIndex = 0;
udpRecvRetCodes[ 0 ] = 0; /* 1st read call. No data read.*/
udpRecvRetCodes[ 1 ] = 0; /* 2nd call also reading zero bytes .*/
udpRecvRetCodes[ 2 ] = -1; /* Encounter error in 3rd call.*/
TEST_ASSERT_EQUAL( SntpErrorNetworkFailure,
Sntp_ReceiveTimeResponse( &context, TEST_RECV_BLOCK_TIME ) );
/* Ensure that the "last request time" state of the context was not modified from network error. */
TEST_ASSERT_EQUAL( LAST_REQUEST_TIME_SECS, context.lastRequestTime.seconds );
TEST_ASSERT_EQUAL( CONVERT_MS_TO_FRACTIONS( LAST_REQUEST_TIME_MS ), context.lastRequestTime.fractions );
}
/**
* @brief Validate that the @ref Sntp_ReceiveTimeResponse API returns error when the transport
* read interface returns code representing partial read, which is not supported by UDP.
* UDP only supports either a complete packet read or read of no packet.
*/
void test_Sntp_ReceiveTimeResponse_Read_Failure_PartialRead()
{
/* Test case when transport interface reads partial data. */
udpRecvRetCodes[ 0 ] = SNTP_PACKET_BASE_SIZE / 2; /* 1st read call returning partial data which is invalid for UDP reads. */
TEST_ASSERT_EQUAL( SntpErrorNetworkFailure, Sntp_ReceiveTimeResponse( &context, TEST_RECV_BLOCK_TIME ) );
/* Ensure that the "last request time" state of the context was not modified from network error. */
TEST_ASSERT_EQUAL( LAST_REQUEST_TIME_SECS, context.lastRequestTime.seconds );
TEST_ASSERT_EQUAL( CONVERT_MS_TO_FRACTIONS( LAST_REQUEST_TIME_MS ), context.lastRequestTime.fractions );
}
/**
* @brief Validate that the @ref Sntp_ReceiveTimeResponse API returns error when the transport
* read interface returns code representing more number of bytes read from the network than asked for
* by the library.
*/
void test_Sntp_ReceiveTimeResponse_Read_Failure_LargerPacketThanExpected()
{
/* Test cases when transport read returns more than expected number of bytes read. */