github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/protocol/vm/assemble_test.go (about)

     1  package vm
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/hex"
     6  	"testing"
     7  
     8  	"github.com/bytom/bytom/errors"
     9  )
    10  
    11  func TestAssemble(t *testing.T) {
    12  	cases := []struct {
    13  		plain   string
    14  		want    []byte
    15  		wantErr error
    16  	}{
    17  		{"2 3 ADD 5 NUMEQUAL", mustDecodeHex("525393559c"), nil},
    18  		{"0x02 3 ADD 5 NUMEQUAL", mustDecodeHex("01025393559c"), nil},
    19  		{"19 14 SUB 5 NUMEQUAL", mustDecodeHex("01135e94559c"), nil},
    20  		{"'Hello' 'WORLD' CAT 'HELLOWORLD' EQUAL", mustDecodeHex("0548656c6c6f05574f524c447e0a48454c4c4f574f524c4487"), nil},
    21  		{`'H\'E' 'W' CAT 'H\'EW' EQUAL`, mustDecodeHex("0348274501577e044827455787"), nil},
    22  		{`'HELLO '  'WORLD' CAT 'HELLO WORLD' EQUAL`, mustDecodeHex("0648454c4c4f2005574f524c447e0b48454c4c4f20574f524c4487"), nil},
    23  		{`0x1`, nil, hex.ErrLength},
    24  		{`BADTOKEN`, nil, ErrToken},
    25  		{`'Unterminated quote`, nil, ErrToken},
    26  	}
    27  
    28  	for _, c := range cases {
    29  		got, gotErr := Assemble(c.plain)
    30  		if errors.Root(gotErr) != c.wantErr {
    31  			t.Errorf("Compile(%s) err = %v want %v", c.plain, errors.Root(gotErr), c.wantErr)
    32  			continue
    33  		}
    34  
    35  		if c.wantErr != nil {
    36  			continue
    37  		}
    38  
    39  		if !bytes.Equal(got, c.want) {
    40  			t.Errorf("Compile(%s) = %x want %x", c.plain, got, c.want)
    41  		}
    42  	}
    43  }
    44  
    45  func TestDisassemble(t *testing.T) {
    46  	cases := []struct {
    47  		raw     []byte
    48  		want    string
    49  		wantErr error
    50  	}{
    51  		{mustDecodeHex("525393559c"), "0x02 0x03 ADD 0x05 NUMEQUAL", nil},
    52  		{mustDecodeHex("01135e94559c"), "0x13 0x0e SUB 0x05 NUMEQUAL", nil},
    53  		{mustDecodeHex("6300000000"), "$alpha JUMP:$alpha", nil},
    54  		{[]byte{0xff}, "NOPxff", nil},
    55  	}
    56  
    57  	for _, c := range cases {
    58  		got, gotErr := Disassemble(c.raw)
    59  
    60  		if errors.Root(gotErr) != c.wantErr {
    61  			t.Errorf("Decompile(%x) err = %v want %v", c.raw, errors.Root(gotErr), c.wantErr)
    62  			continue
    63  		}
    64  
    65  		if c.wantErr != nil {
    66  			continue
    67  		}
    68  
    69  		if got != c.want {
    70  			t.Errorf("Decompile(%x) = %s want %s", c.raw, got, c.want)
    71  		}
    72  	}
    73  }
    74  
    75  func mustDecodeHex(h string) []byte {
    76  	bits, err := hex.DecodeString(h)
    77  	if err != nil {
    78  		panic(err)
    79  	}
    80  	return bits
    81  }