1% SDNV library tests 2 3############ 4############ 5+ Test SDNV encoding/decoding 6 7= Load SDNVUtil 8 9# Explicit to load SDNVUtil 10load_contrib("sdnv") 11 12= Define utils 13 14def doTestVector(vec): 15 # Test numbers individually 16 for n in vec: 17 ba = SDNVUtil.encode(n) 18 (num, sdnvLen) = SDNVUtil.decode(ba, 0) 19 if num != n: 20 print("Error encoding/decoding", n) 21 return False 22 # Encode them all in a bunch 23 ba = bytearray() 24 for n in vec: 25 temp = SDNVUtil.encode(n) 26 ba = ba + temp 27 offset = 0 28 outNums = [] 29 for n in vec: 30 (num, sdnvLen) = SDNVUtil.decode(ba, offset) 31 outNums.append(num) 32 offset += sdnvLen 33 if outNums != vec: 34 print("Failed on multi-number encode/decode") 35 return False 36 return True 37 38= Vector tests: small ints 39 40ba = bytearray() 41theNums = [0, 1, 2, 5, 126, 127, 128, 129, 42 130, 150, 190, 220, 254, 255, 256] 43assert doTestVector(theNums) 44 45= Vector tests: big ints 46 47theNums = [0, 1, 0, 1, 0, 128, 32765, 48 SDNVUtil.maxValue - 10, 4, 32766, 32767, 32768, 32769] 49assert doTestVector(theNums) 50 51= 100 random vector tests 52 53import random 54 55def doRandomTestVector(howMany): 56 vec = [] 57 for i in range(0, howMany): 58 vec.append(random.randint(0, SDNVUtil.maxValue)) 59 result = doTestVector(vec) 60 return result 61 62assert doRandomTestVector(100) 63 64= SDVN tests 65 66# Tests using the SDNV class 67s = SDNV(30) 68b = s.encode(17) 69theNums = [0, 4, 20, 29, 30, 31, 33] 70not_enc = [] 71for n in theNums: 72 try: 73 b = s.encode(n) 74 except SDNVValueError as e: 75 print("Could not encode", n, "-- maximum value is:", e.maxValue) 76 not_enc.append(n) 77 78not_enc.sort() 79assert not_enc == [31, 33]