github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/marshal_test.go (about) 1 package runtime 2 3 import ( 4 "bytes" 5 "io" 6 "reflect" 7 "testing" 8 ) 9 10 func TestMarshalConst(t *testing.T) { 11 type args struct { 12 c Value 13 budget uint64 14 } 15 tests := []struct { 16 name string 17 args args 18 wantUsed uint64 19 // wantW string 20 wantErr bool 21 }{ 22 { 23 name: "marshal the wrong type", 24 args: args{ 25 c: FunctionValue(nil), 26 }, 27 wantErr: true, 28 }, 29 { 30 name: "use the budget", 31 args: args{ 32 c: IntValue(123456), 33 budget: 1, 34 }, 35 wantUsed: 1, 36 }, 37 { 38 name: "within budget", 39 args: args{ 40 c: IntValue(1234566), 41 budget: 10, 42 }, 43 wantUsed: 9, 44 }, 45 } 46 for _, tt := range tests { 47 t.Run(tt.name, func(t *testing.T) { 48 w := &bytes.Buffer{} 49 gotUsed, err := MarshalConst(w, tt.args.c, tt.args.budget) 50 if (err != nil) != tt.wantErr { 51 t.Errorf("MarshalConst() error = %v, wantErr %v", err, tt.wantErr) 52 return 53 } 54 if gotUsed != tt.wantUsed { 55 t.Errorf("MarshalConst() = %v, want %v", gotUsed, tt.wantUsed) 56 } 57 // if gotW := w.String(); gotW != tt.wantW { 58 // t.Errorf("MarshalConst() = %v, want %v", gotW, tt.wantW) 59 // } 60 }) 61 } 62 } 63 64 func TestUnmarshalConst(t *testing.T) { 65 type args struct { 66 r io.Reader 67 budget uint64 68 } 69 tests := []struct { 70 name string 71 args args 72 wantV Value 73 wantUsed uint64 74 wantErr bool 75 }{ 76 { 77 name: "consume the budget", 78 args: args{ 79 r: bytes.NewBuffer([]byte{6, 0, 4, byte(StringType), 1, 1, 1, 1, 1, 1, 1, 1}), // would be very long 80 budget: 1000, 81 }, 82 wantUsed: 1000, 83 }, 84 { 85 name: "wrong prefix", 86 args: args{ 87 r: bytes.NewBuffer([]byte{6, 1, 4, byte(StringType), 1, 1, 1, 1, 1, 1, 1, 1}), // would be very long 88 budget: 1000, 89 }, 90 wantErr: true, 91 }, 92 93 { 94 name: "read wrong type", 95 args: args{ 96 r: bytes.NewBuffer([]byte{6, 0, 4, byte(FunctionType)}), 97 }, 98 wantErr: true, 99 }, 100 } 101 for _, tt := range tests { 102 t.Run(tt.name, func(t *testing.T) { 103 gotV, gotUsed, err := UnmarshalConst(tt.args.r, tt.args.budget) 104 if (err != nil) != tt.wantErr { 105 t.Errorf("UnmarshalConst() error = %v, wantErr %v", err, tt.wantErr) 106 return 107 } 108 if !reflect.DeepEqual(gotV, tt.wantV) { 109 t.Errorf("UnmarshalConst() gotV = %v, want %v", gotV, tt.wantV) 110 } 111 if gotUsed != tt.wantUsed { 112 t.Errorf("UnmarshalConst() gotUsed = %v, want %v", gotUsed, tt.wantUsed) 113 } 114 }) 115 } 116 }