-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_Payloads.py
2451 lines (2047 loc) · 105 KB
/
test_Payloads.py
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
from unittest import TestCase
from AISDictionary import AISDictionaries
import Payloads
import random
import logging
import math
from GlobalDefinitions import Global
class TestBinary_addressed_message(TestCase):
pass
class TestBinary_acknowledge(TestCase):
pass
class TestBinary_broadcast_message(TestCase):
pass
class TestUTC_date_enquiry(TestCase):
pass
class TestUTC_date_response(TestCase):
pass
class TestSafety_related_acknowledgement(TestCase):
pass
class TestInterrogation(TestCase):
pass
class TestDGNS_broadcast_binaty_message(TestCase):
pass
class TestClassB_position_report(TestCase):
pass
class TestExtende_ClassB_position_report(TestCase):
pass
class TestData_link_management_message(TestCase):
pass
class Test_aid_to_navigation_report(TestCase):
pass
class TestChannel_management(TestCase):
pass
class TestGroup_assigment_command(TestCase):
pass
class TestSingle_slot_binary_message(TestCase):
pass
class TestMultiple_slot_binary_message(TestCase):
pass
class TestFragments(TestCase):
def test_put_frag_in_dict(self):
# __init__(self, binary_payload: str, fragment_count: int, fragment_number: int, message_id: int):
# we need to define at least two fragments
# the first with frag count = 2, frag_number = 1, message_id = 0
# thge second with frag_count = 2, frag_number = 2, message_id= 0
# and try and put both of these in dictionary
# print('**********************************************************************************************')
# print("entering test put frag in dict")
# print('8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888')
fragcnt = random.randint(1, 4)
messid = []
message_memory = []
# produce a list of tuples (message_id, Number of Fragments)
# create random number of fragments with varied message ids and varied number of fragments
# if you can put them into the Fragdict and then recover them to match with a local fragment memory
# we have success
for i in range(0, 10):
messid.append((random.randint(0, 999), random.randint(1, 4)))
# print(messid)
current = 0
maxno = 10
for j in range(0, maxno):
# print(messid[j])
current += 1
for k in range(0, maxno):
if messid[k][1] > j:
# create a random payload
payload = '{:20b}'.format(random.randint(0, 999999))
message_memory.append((messid[k][0], current, payload))
# print(messid[k][0], current, payload)
m = Payloads.Fragments(payload, messid[k][1], current, messid[k][0])
m.put_frag_in_dict()
for data in message_memory:
# print(data[0], data[1], data[2], Global.FragDict[str(data[0]) + ',' + str(data[1])][2])
self.assertEqual(data[2], Payloads.Fragments.FragDict[str(data[0]) + ',' + str(data[1])][2], "Failed")
def test_match_fragments(self):
# first a simple test - produce two fragments with same message id, fragment counts 1 and 2
# possibly extend to three fragments once proven with two
print("Testing match fragments")
fragements = [(3, 1, '000000111111000000111111000000'),
(3, 2, '111111000000111111000000111111'),
(3, 3, '1011010101000000111111000000111111')]
expected = fragements[0][2] + fragements[1][2] + fragements[2][2]
m = Payloads.Fragments(fragements[0][2], 3, 1, 4)
m.put_frag_in_dict(False)
m = Payloads.Fragments(fragements[1][2], 3, 2, 4)
m.put_frag_in_dict(False)
m = Payloads.Fragments(fragements[2][2], 3, 3, 4)
m.put_frag_in_dict(False)
# now try merging - this normally would come out of put_frag_in_dict but for testing will do it seperately
# there is little validation done in the fragments object
success, newpayload = m.match_fragments('4,3')
# print('After merge ', success)
if success:
# print(expected)
# print(newpayload)
self.assertEqual(expected, newpayload,
'Failed in matching fragments test sequence does not match sequence retrurned')
# set of fragments produced in testing put_frag_in_dict as test data
messid = []
message_memory = []
for i in range(0, 10):
messid.append((random.randint(0, 999), random.randint(1, 4)))
# print(messid)
current = 0
maxno = 10
for j in range(0, maxno):
# print(messid[j])
current += 1
for k in range(0, maxno):
if messid[k][1] > j:
# create a random payload
payload = '{:20b}'.format(random.randint(0, 999999))
message_memory.append((messid[k][0], current, payload))
# print(messid[k][0], current, payload)
m = Payloads.Fragments(payload, messid[k][1], current, messid[k][0])
m.put_frag_in_dict(False) # dont attempt to invoke match_fragments as would be normal
# print(Global.FragDict)
# now take message_id from list messid and see if we can do matches
# yje list of tuples in message memory contains the message_id, the number of fragments and the portions of
# "fragmented"payload. Now work down the list presenting message id , when success flag is returned TRUE
# aggregate the fragmented payloads tresented and compare to the aggregate payload returned
#
for m_id, fc in messid:
# collect the presented payloads on a per message_id basis
expected = ''
for mm_id, fn, pload in message_memory:
if m_id == mm_id:
expected = expected + pload
# now have an expected payload to compare
# call match_fragements with a key ['m_id,fc']
key = str(m_id) + ',' + str(fc)
# print('calling match frags key = ', key)
success, newpayload = m.match_fragments(key)
# print('returned {}\n{}\n{}'.format(success,expected, newpayload))
if success:
self.assertEqual(expected, newpayload,
"Failed in random fragment matching\n {} \n {}vs".format(expected, newpayload))
else:
print("Failed matching fragments for {}\n ".format(m_id))
class TestPayload(TestCase):
def initialise(self):
logging.basicConfig(level=logging.CRITICAL, filename='logfile.log')
diction = AISDictionaries()
# the stream offered here is valid but the mystream.payload , mypayload.payload
# and/or mystream.binary_payload will be overwritten during testing
mystream = Payloads.AISStream('!AIVDM,1,1,,A,404kS@P000Htt<tSF0l4Q@100pAg,0*05')
return diction, mystream
def test_create_mmsi(self):
diction, mystream = self.initialise()
print('Testing create mmsi')
smmsi_list: list = [
'850312345', '503543210', '050398765', '005037651', '111504678',
'998761234', '984135432', '970654987', '972654321', '974765432',
'999999999'
]
# the mmsi field is bits 8-37 of the binary payload string
# so split the mystream.binary_payload generated in the initialiastion into three parts
# bits 0-7, bits 38-end and substitute the 30 bits that are the mmsi field
header: str = '00010000'
trailer: str = mystream.binary_payload[38:]
for ssm in smmsi_list:
sm: str = ssm
mmsibits = '{:030b}'.format(int(sm))
mypayload = Payloads.Payload(header + mmsibits + trailer)
try:
mypayload.payload = header + mmsibits + trailer
mypayload.create_mmsi()
ommsi: str = mypayload.create_mmsi()
self.assertEqual(sm, ommsi, "Failed in create mmsi integer form")
except:
pass
def test_extract_int(self):
'''
Produces random number in rage 0 to 999999999 and sets up fake binary_payload string
then extracts that binary number from the string using AIS_Data.Binary_item
effectively same test as for Binary_item
'''
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
print("Testing extract_int")
# Create fake AIS payload with a random binary number in bits 8 to 37
for i in range(10):
fakestream: str = '00010000'
faketail: str = '000000000000000000000000000000'
testnumber: int = random.randint(0, 999999999)
strnumber: str = "{:030b}".format(testnumber)
# print('strnumber = ', strnumber)
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
# print('fakestream ', fakestream)
intmmsi = mypayload.extract_int(8, 30)
self.assertEqual(testnumber, intmmsi, "In Payload - Failed in test_extract_int")
def test_extract_string(self):
'''
Create dummy binary payload including some test strings use Extract_String to recover text
:return:
string text to be compared
'''
print("Testing ExtractString")
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
fakestream: str = '00010000'
faketail: str = '11111111111111111111'
testtext: str = 'ABCDEFGHIJKLMNOPQRSTUVWabcdefghijklmnopqrstuvw01234567890:;<>=?@@AB'
for _ in range(10):
for ik in range(len(testtext)):
fakestream = diction.makebinpayload(fakestream, testtext[ik])
fakestream = fakestream + faketail
# set this as "binary_payload" in AIS_Data and set its length as 6 times the text length plus
# additional head/tail bits (28)
mypayload.payload = fakestream
# nominal start of text stream
basepos: int = 8
rndstrt = random.randint(0, len(testtext) - 1)
# can pick out any random portion no more than 30chars size
# then check if the combination of start posn plus length will not exceed binary_payload length
rndlen = random.randint(1, 30)
while rndstrt * 6 + rndlen * 6 > len(testtext) * 6:
rndlen = random.randint(1, 30)
# then extract the text segment we will be recovering from the binary_payload
rndtext = testtext[rndstrt:rndstrt + rndlen]
blklen = rndlen * 6
logging.debug("DEBUG binary_payload from which string will be extracted\n{}"
.format(mystream.binary_payload))
outstr = mypayload.extract_string(rndstrt * 6 + 8, rndlen * 6)
logging.debug('Extracted string {}'.format( outstr))
self.assertEqual(rndtext, outstr, "In Payload - Failed in Extract_String")
def test_binary_item(self):
'''
Produces random number in rage 0 to 999999999 and sets up fake binary_payload string
then extracts that binary number from the string using AIS_Data.Binary_item
'''
print("Testing ExtractString")
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
print("Testing Binary_item")
# Create fake binary payload with a random binary number in bits 8 to 37
for i in range(10):
fakestream: str = '00010000'
faketail: str = '000000000000000000000000000000'
testnumber: int = random.randint(0, 999999999)
strnumber: str = "{:030b}".format(testnumber)
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
intmmsi = mypayload.binary_item(8, 30)
self.assertEqual(testnumber, intmmsi, "FAiled in test_binary_item")
def test_m_to_int(self):
'''
m_to_int takes in single armoured (encoded) character and returns a binary value
:return:
binary value as per Dictionaries.payload_armour
'''
print("Testing m_to_int")
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
for char, str_val in diction.payload_armour.items():
# print('character, string value', char, str_val )
bin_val = int(str_val, 2)
ret_val = mypayload.m_to_int(char)
self.assertEqual(bin_val, ret_val, 'In Payload.m_to_int - returned binary does not match encoded char')
def test_remove_at(self):
'''
remove_at strips trailing @ from string values
:return:
string without trailing @
'''
print("Testing remove_at")
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
teststring = 'ABC'
for i in range(1, 10):
out_string = mypayload.remove_at(teststring)
self.assertEqual('ABC', out_string,
"In Payload.remove_at - the returned string has not had trailing @ removed ")
teststring = teststring + '@'
def test_remove_space(self):
'''
remove_at strips trailing spaces from string values
:return:
string without trailing spaces
'''
print("Testing remove_space")
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
teststring = 'ABC'
for i in range(1, 10):
out_string = mypayload.remove_space(teststring)
self.assertEqual('ABC', out_string,
"In Payload.remove_at - the returned string has not had trailing spaces removed ")
teststring = teststring + ' '
def test_signd_bin_lat_long(self):
'''
signed_binary_item takes in a set of parameters start position, number of bits (blength)
and extracts string of bits from the binary_payload.
if MSBit is 1 the negetive. Do twos complement arithmetic to return a signed integer
:return:
signed integer value which will need scaling if necessary
'''
print("Testing signed binary item")
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
# zero degrees
fakestream: str = '00010000'
faketail: str = '000000000000000000000000000000'
# testnumber: int = random.randint(0, 999999999)
strnumber: str = "{:028b}".format(0)
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
intmmsi = mypayload.signed_binary_item(8, 28)
self.assertEqual(0, intmmsi, "In Payload.signed_binary_int - Offered 0 but got non zero")
# longitude
mypayload.payload = fakestream
mypayload.get_longitude(8, 28)
self.assertEqual(0.0, mypayload.longitude, "In Payload testing signed int, longitude\n" +
'Entered for zero degrees got non zero back')
# latitude
strnumber: str = "{:027b}".format(0)
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.get_latitude(8, 27)
self.assertEqual(0.0, mypayload.latitude, "In Payload testing signed int, latitude\n" +
'Entered for zero degrees got non zero back')
# 1 degree
strnumber: str = "{:028b}".format(1)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
intmmsi = mypayload.signed_binary_item(8, 28)
self.assertEqual(1, intmmsi, "In Payload.signed_binary_int - Offered 1 but got not 1")
# longitude
strnumber: str = "{:028b}".format(1 * 600000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.payload = fakestream
mypayload.get_longitude(8, 28)
self.assertEqual(1.0, mypayload.longitude, "In Payload testing signed int, longitude\n" +
'Entered for one degrees one did not return')
# latitude
strnumber: str = "{:027b}".format(1 * 600000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.get_latitude(8, 27)
self.assertEqual(1.0, mypayload.latitude, "In Payload testing signed int, latitude\n" +
'Entered for zero degrees one did not return')
# minus 1 degree
strnumber: str = "{:028b}".format(-1)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
intmmsi = mypayload.signed_binary_item(8, 28)
self.assertEqual(-1, intmmsi, "In Payload.signed_binary_int - Offered -1 but got not -1")
# longitude
strnumber: str = "{:028b}".format(-1 * 600000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.payload = fakestream
mypayload.get_longitude(8, 28)
self.assertEqual(-1.0, mypayload.longitude, "In Payload testing signed int, longitude\n" +
'Entered for minus one did not return')
# latitude
strnumber: str = "{:027b}".format(-1 * 600000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.get_latitude(8, 27)
self.assertEqual(-1.0, mypayload.latitude, "In Payload testing signed int, latitude\n" +
'Entered for minus one did not return')
# 181 degrees - indicates not available
mynumb = 181 * 600000
strnumber: str = "{:028b}".format(mynumb)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
intmmsi = mypayload.signed_binary_item(8, 28)
self.assertEqual(181 * 600000, intmmsi, "In Payload.signed_binary_int - Offered 181 but got not 181")
# longitude
mypayload.payload = fakestream
mypayload.get_longitude(8, 28)
self.assertEqual(181.0, mypayload.longitude, "In Payload testing signed int, longitude\n" +
'Entered for 181 did not return 181.0')
# latitude
# 91 degrees - indicates not available
strnumber: str = "{:027b}".format(91 * 600000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.get_latitude(8, 27)
self.assertEqual(91.0, mypayload.latitude, "In Payload testing signed int, latitude\n" +
'Entered for minus one did not return')
# minus 180 degrees
strnumber: str = "{:028b}".format(-180 * 600000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
intmmsi = mypayload.signed_binary_item(8, 28)
self.assertEqual(-180 * 600000, intmmsi, "In Payload.signed_binary_int - Offered -180 but got not -180")
# longitude
mypayload.payload = fakestream
mypayload.get_longitude(8, 28)
self.assertEqual(-180.0, mypayload.longitude, "In Payload testing signed int, longitude\n" +
'Entered for -180 did not return -180.0')
# latitude
# 91 degrees - indicates not available
strnumber: str = "{:027b}".format(91 * 600000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.get_latitude(8, 27)
self.assertEqual(91.0, mypayload.latitude, "In Payload testing signed int, latitude\n" +
'Entered for -90 degrees did not return -90.0')
# test for a non zero decimal degrees
# longitude
strnumber: str = "{:028b}".format(-45 * 600000 + 300000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.payload = fakestream
mypayload.get_longitude(8, 28)
self.assertEqual(-44.5, mypayload.longitude, "In Payload testing signed int, longitude\n" +
'Entered for -44.5 did not return -44.5')
# latitude
# 31.1 - indicates not available
strnumber: str = "{:027b}".format(31 * 600000 + 60000)
fakestream: str = '00010000'
fakestream = fakestream + strnumber + faketail
mypayload.payload = fakestream
mypayload.get_latitude(8, 27)
self.assertEqual(31.1, mypayload.latitude, "In Payload testing signed int, latitude\n" +
'Entered for 31.1 degrees did not return 31.1')
# for i in range(100):
# fakestream: str = '00010000'
# faketail: str = '000000000000000000000000000000'
#
# #testnumber: int = random.randint(0, 999999999)
# strnumber: str = "{:030b}".format(testnumber)
# fakestream = fakestream + strnumber + faketail
# mypayload.payload = fakestream
# intmmsi = mypayload.binary_item(8, 30)
def test_get_raimflag(self):
'''
The RAIM flag indicates whether Receiver Autonomous Integrity Monitoring is being used
to check the performance if the EPFD.
0 = RAIM not in use (default),
1 = RAIM in use.
See [RAIM] for a detailed description of this flag.
at bit position 148 in CNB, Base Station
:return:
sets Payload.RAIMflag
'''
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
print('Testing get_RAIMflag')
fakestream: str = '00010000'
faketail: str = '000000000000000000000000000000'
teststring = fakestream + '1' + faketail
mypayload.payload = teststring
mypayload.getRAIMflag(8)
self.assertEqual(True, mypayload.raim_flag, "In Payload.RAIMflag looking for True got other")
teststring = fakestream + '0' + faketail
mypayload.payload = teststring
mypayload.getRAIMflag(8)
self.assertEqual(False, mypayload.raim_flag, "In Payload.RAIMflag looking for False got other")
mypayload.payload = teststring
def test_get_fix(self):
'''
The position accuracy flag indicates the accuracy of the fix.
A value of 1 indicates a DGPS-quality fix with an accuracy of < 10ms.
0, the default, indicates an unaugmented GNSS fix with accuracy > 10m.
:return:
sets payload.fixquality
'''
# some necessary preconfig
diction, mystream = self.initialise()
mypayload = Payloads.Payload(mystream.binary_payload)
print('Testing get_fixquality')
fakestream: str = '00010000'
faketail: str = '000000000000000000000000000000'
teststring = fakestream + '1' + faketail
mypayload.payload = teststring
mypayload.getfix(8)
self.assertEqual(True, mypayload.fix_quality, "In Payload.fixquality looking for True got other")
teststring = fakestream + '0' + faketail
mypayload.payload = teststring
mypayload.getfix(8)
self.assertEqual(False, mypayload.fix_quality, "In Payload.fixquality looking for False got other")
mypayload.payload = teststring
class TestCNB(TestCase):
def initialise(self):
logging.basicConfig(level=logging.CRITICAL, filename='logfile.log')
diction = AISDictionaries()
# the stream offered here is valid but the mystream.payload , mypayload.payload
# and/or mystream.binary_payload will be overwritten during testing
mystream = Payloads.AISStream('!AIVDM,1,1,,A,404kS@P000Htt<tSF0l4Q@100pAg,0*05')
# mystream = Payloads.AISStream('!AIVDM,1,1,,B,177Q0U0wBO:`jk5apbs2q2@>00SG,0*1F')
mycnb = Payloads.CNB(mystream.binary_payload)
return diction, mystream, mycnb
def make_stream(self, preamlen: int, testbits: str):
# creates a fake binary payload to allow testing
# preamble is number number of bits needed to fill up to beginning of testbits
# testbits is the binary stream representing the area of thge domain under test
# a couple of 'constants'
fakehead: str = '00010000'
faketail: str = '000000000000000000000000000000'
# prefill the preamble with message type 4
preamble: str = fakehead
# fillcount is number of required prefill with allowance for the 8 bit header
fillcount = preamlen - 8
while fillcount > 0:
preamble = preamble + '1'
fillcount -= 1
# print('in make_stream nr bits needed, nr bits offered', preamlen, len(preamble))
return preamble + testbits + faketail
def test_get_nav_status(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_nav_status")
for i in range(0, 15):
testbits = '{:04b}'.format(i)
diction.make_stream(38, testbits)
mycnb.payload = diction.make_stream(38, testbits)
mycnb.get_CNB_nav_status()
self.assertEqual(i, mycnb.navigation_status, "In CNB.get_nav_status - value expected not returned")
def test_get_rot(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_ROT")
# int(round(4.733 * math.sqrt(708), 0)) gives 126
# valid entries are -127 to 128
fvalue: float = 0.0
for fvalue in [0, 1.0, -1.0, 90.0, -90.0, 708.0, -708.0]:
if fvalue >= 0:
testbits = '{:08b}'.format(int(round(4.733 * math.sqrt(fvalue), 0)))
else:
testbits = '{:08b}'.format(-int(round(4.733 * math.sqrt(abs(fvalue)), 0)))
mycnb.payload = diction.make_stream(42, testbits)
mycnb.get_ROT()
self.assertTrue(fvalue - 1 <= mycnb.rate_of_turn <= fvalue + 1,
"In CNB.get_rot value returned does not match value set " + '{:f}'.format(fvalue))
# special cases
testbits = "{:08b}".format(127)
mycnb.payload = diction.make_stream(42, testbits)
mycnb.get_ROT()
self.assertEqual(1005.0, mycnb.rate_of_turn,
"In CNB.get_rot value returned does not match value set " + '{:f}'.format(1005.0))
testbits = "{:08b}".format(-127)
mycnb.payload = diction.make_stream(42, testbits)
mycnb.get_ROT()
self.assertEqual(-1005.0, mycnb.rate_of_turn,
"In CNB.get_rot value returned does not match value set " + '{:f}'.format(-1005.0))
testbits = "{:08b}".format(128)
mycnb.payload = diction.make_stream(42, testbits)
mycnb.get_ROT()
self.assertEqual(1000.0, mycnb.rate_of_turn,
"In CNB.get_rot value returned does not match value set " + '{:f}'.format(1000))
def test_get_sog(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_SOG")
# initially check for values 0, 0.5 1,102
for i in [0, 0.5, 1, 102, 102.2]:
i = int(i * 10)
testbits = '{:010b}'.format(i)
mycnb.payload = diction.make_stream(50, testbits)
mycnb.getCNB_SOG()
self.assertEqual(float(i) / 10.0, mycnb.speed_over_ground,
"In getSOG value returned does not match value offered")
for _ in range(100):
i = random.randint(0, 1022)
testbits = '{:010b}'.format(i)
mycnb.payload = diction.make_stream(50, testbits)
mycnb.getCNB_SOG()
self.assertEqual(float(i) / 10.0, mycnb.speed_over_ground,
"In getSOG value returned does not match value offered")
def test_get_cog(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_COG")
# initially check for values 0, 0.5 1,359, 360 and value outside valid range
for i in [0, 0.5, 1, 90, 359, 360, 361]:
i = i * 10
testbits = '{:012b}'.format(i)
mycnb.payload = diction.make_stream(116, testbits)
try:
mycnb.getCNB_COG()
self.assertEqual(float(i) / 10.0, mycnb.course_over_ground,
"In get_COG value returned does not offered value " + '{:d}'.format(i))
except ValueError:
self.assertFalse(mycnb.valid_item, "In get_COG module did not detect invalid parameter")
# and for completeness a random set of values
for _ in range(100):
i = random.randint(0, 3600)
testbits = '{:012b}'.format(i)
mycnb.payload = diction.make_stream(116, testbits)
try:
mycnb.getCNB_COG()
self.assertEqual(float(i) / 10.0, mycnb.course_over_ground,
"In get_COG value returned does not offered value " + '{:d}'.format(i))
except ValueError:
self.assertFalse(mycnb.valid_item, "In get_COG module did not detect invalid parameter")
def test_get_CNBtru_head(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_truhead")
# initially check for values 0, 1,359, 360 and value outside valid range
for i in [0, 1, 90, 259, 359, 511, 360]:
testbits = '{:09b}'.format(i)
mycnb.payload = diction.make_stream(128, testbits)
try:
mycnb.getCNB_tru_head()
self.assertEqual(i, mycnb.true_heading,
"In get_CNBtru_head value returned does not match value offered")
except ValueError:
self.assertFalse(mycnb.valid_item, "In get_CNBtru_head module did not detect invalid parameter")
# and again a random selection
for _ in range(100):
i = random.randint(0, 360)
testbits = '{:09b}'.format(i)
mycnb.payload = diction.make_stream(128, testbits)
try:
mycnb.getCNB_tru_head()
self.assertEqual(i, mycnb.true_heading,
"In get_COG value returned does not match value offered")
except ValueError:
self.assertFalse(mycnb.valid_item, "In CNB.get_tru_hed invalid value not flagged")
def test_get_pos_accuracy(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_pos_accuracy")
mycnb = Payloads.CNB(mystream.binary_payload)
teststring = diction.make_stream(60, '1')
mycnb.payload = teststring
mycnb.get_pos_accuracy()
self.assertEqual(True, mycnb.position_accuracy,
"In CNB.get_pos_accuracy looking for True got other")
teststring = diction.make_stream(60, '0')
mycnb.payload = teststring
mycnb.get_pos_accuracy()
self.assertEqual(False, mycnb.position_accuracy,
"In CNB.get_pos_accuracy looking for False got other")
def test_get_timestamp(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_timestamp")
# valid entries are 0-63, by virtue of only 6 bits cannot go outside range
for i in [0, 1, 30, 59, 60, 61, 62, 63]:
testbits = '{:06b}'.format(i)
mycnb.payload = diction.make_stream(137, testbits)
mycnb.getCNB_timestamp()
self.assertEqual(i, mycnb.time_stamp,
"In get_timestamp value returned does not match value offered" + '{:d}'.format(i))
def test_get_man_indic(self):
diction, mystream, mycnb = self.initialise()
print("Testing get_man_indic")
# valid entries are 0-2 but can have an invalid 3 appear
for i in [0, 1, 2, 3]:
testbits = '{:02b}'.format(i)
mycnb.payload = diction.make_stream(143, testbits)
try:
mycnb.get_man_indic()
self.assertEqual(i, mycnb.maneouver_indicator,
"In get_man_indic value returned does not offered value " + '{:d}'.format(i))
except ValueError:
self.assertFalse(mycnb.valid_item, "In get_man_indic module did not detect invalid parameter")
def test_repr(self):
diction, mystream, mycnb = self.initialise()
print('Testing CNB __repr__')
print(mycnb)
class TestBasestation(TestCase):
def initialise(self):
logging.basicConfig(level=logging.CRITICAL, filename='logfile.log')
diction = AISDictionaries()
# the stream offered here is valid but the mystream.payload , mypayload.payload
# and/or mystream.binary_payload will be overwritten during testing
psuedo_AIS = '!AIVDM,1,1,,A,404kS@P000Htt<tSF0l4Q@100pAg,0*05'
mystream = Payloads.AISStream(psuedo_AIS)
mybase = Payloads.Basestation(mystream.binary_payload)
return diction, mystream, mybase
def test_get_year(self):
print('Testing Base.get_year')
# Bits 38-51 length 14 Year (UTC) year UTC, 1-9999, 0 = N/A (default)
diction, mystream, mybase = self.initialise()
# first check for edge conditions, some normal values and a non=-valid
for yval in [0, 9999, 1, 2023, 11000]:
mybase.payload = diction.make_stream(38, '{:014b}'.format(yval))
try:
mybase.get_year()
self.assertEqual(yval, mybase.year, "In Base.get_year - value returned does match value set")
except ValueError:
self.assertFalse(mybase.valid_item, "In Base.get_year - module does not flag invalid value")
def test_get_month(self):
print('Testing Base.get_month')
# Bits 52-55 length 4 Month (UTC) month 1-12; 0 = N/A (default)
diction, mystream, mybase = self.initialise()
# first check for edge conditions, some normal values and a non=-valid
for yval in [0, 12, 1, 13]:
mybase.payload = diction.make_stream(52, '{:04b}'.format(yval))
try:
mybase.get_month()
self.assertEqual(yval, mybase.month, "In Base.get_month - value returned does match value set")
except ValueError:
self.assertFalse(mybase.valid_item, "In Base.get_month - module does not flag invalid value")
def test_get_day(self):
print('Testing Base.get_day')
# Bits 56-60 length 5 Day (UTC) day 1-31; 0 = N/A (default)
diction, mystream, mybase = self.initialise()
# first check for edge conditions, some normal values and a non=-valid
for yval in [0, 31, 1]:
mybase.payload = diction.make_stream(56, '{:05b}'.format(yval))
# put in dummy year 2023, dummy month 1
dyear = '{:014b}'.format(2023)
dmonth = '{:04b}'.format(1)
mybase.payload = mybase.payload[0:38] + dyear + dmonth + mybase.payload[56:]
try:
mybase.get_day()
self.assertEqual(yval, mybase.day, "In Base.get_day - value returned does match value set")
except ValueError:
self.assertFalse(mybase.valid_item, "In Base.get_day - module does not flag invalid value")
# now setup some weird invalid conditions
leap = '{:014b}'.format(2004)
month = '{:04b}'.format(2)
day = '{:05b}'.format(30)
leap_year_stream = mybase.payload[0:38] + leap + month + day + mybase.payload[78:]
mybase.payload = leap_year_stream
try:
mybase.get_day()
self.fail("In Base.day - module does not flag invalid day for leap_year")
except ValueError:
self.assertFalse(mybase.valid_item,
"In Base.day - module does not flag invalid day for leap_year")
nonleap = '{:014b}'.format(2003)
month = '{:04b}'.format(2)
day = '{:05b}'.format(29)
nonleap_year_stream = mybase.payload[0:38] + nonleap + month + day + mybase.payload[78:]
mybase.payload = leap_year_stream
mybase.payload = nonleap_year_stream
try:
mybase.get_day()
self.fail("In Base.day - module does not flag invalid day for nonleap_year")
except ValueError:
self.assertFalse(mybase.valid_item,
"In Base.day - module does not flag invalid day for nonleap_year")
for imonth in [4, 6, 9, 11]:
nonleap = '{:014b}'.format(2003)
month = '{:04b}'.format(imonth)
day = '{:05b}'.format(31)
mybase.payload = diction.make_stream(56, '{:05b}'.format(31))
nonleap_year_stream = mybase.payload[0:38] + nonleap + month + day + mybase.payload[78:]
mybase.payload = nonleap_year_stream
try:
mybase.get_day()
self.fail("In Base.day - module does not flag invalid day for 30 day months")
except ValueError:
self.assertFalse(mybase.valid_item,
"In Base.day - module does not flag invalid day for 30 day months")
def test_get_hour(self):
print('Testing Base.get_hour')
# Bits 61-65 length 5 Hour (UTC) hour 0-23; 24 = N/A (default)
diction, mystream, mybase = self.initialise()
# first check for edge conditions, some normal values and a non=-valid
for yval in [0, 23, 1, 24, 25]:
mybase.payload = diction.make_stream(61, '{:05b}'.format(yval))
try:
mybase.get_hour()
self.assertEqual(yval, mybase.hour, "In Base.get_hour - value returned does match value set")
except ValueError:
self.assertFalse(mybase.valid_item, "In Base.get_hour - module does not flag invalid value")
def test_get_minute(self):
print('Testing Base.get_minute')
# Bits 66-71 length 6 Minute (UTC) minute 0-59; 60 = N/A (default)
diction, mystream, mybase = self.initialise()
# first check for edge conditions, some normal values and a non=-valid
for yval in [0, 59, 60, 61]:
mybase.payload = diction.make_stream(66, '{:06b}'.format(yval))
try:
mybase.get_minute()
self.assertEqual(yval, mybase.minute, "In Base.get_minute - value returned does match value set")
except ValueError:
self.assertFalse(mybase.valid_item, "In Base.get_minute - module does not flag invalid value")
def test_get_second(self):
print('Testing Base.get_second')
# Bits 72-77 length 6 Second (UTC) second 0-59; 60 = N/A (default)
diction, mystream, mybase = self.initialise()
# first check for edge conditions, some normal values and a non=-valid
for yval in [0, 59, 60, 61]:
mybase.payload = diction.make_stream(72, '{:06b}'.format(yval))
try:
mybase.get_second(72)
self.assertEqual(yval, mybase.second, "In Base.get_second - value returned does match value set")
except ValueError:
self.assertFalse(mybase.valid_item, "In Base.get_second - module does not flag invalid value")
def test_get_epfd(self):
print('Testing Base.get_EPFD')
# Bits 134-137 length 4 Type of EPFD epfd See "EPFD Fix Types" in Dictionary
# valid 0-8 15 not uncommen, values 9-14 returned as 0 and object still validated
diction, mystream, mybase = self.initialise()
# first check for edge conditions, some normal values and a non=-valid
for yval in [0, 8, 1, 15, 10]:
mybase.payload = diction.make_stream(134, '{:04b}'.format(yval))
try:
mybase.get_Base_EPFD()
if 0 <= yval <= 8 or yval == 15:
self.assertEqual(yval, mybase.EPFD_type,
"In Base.get_EPFD - value returned does match value set")
else:
yval = 0
self.assertEqual(yval, mybase.EPFD_type,
"In Base.get_EPFD - value returned does match default substitution 9-14")
except:
self.assertFalse(mybase.valid_item,
"In Base.get_EPFD - somethings very wrong should not get here")
def test_repr(self):
diction, mystream, mybase = self.initialise()
print("testing Base __repr__")
print(mybase)
class TestAISStream(TestCase):
mytestdata = [