github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/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  
    31  		if errors.Root(gotErr) != c.wantErr {
    32  			t.Errorf("Compile(%s) err = %v want %v", c.plain, errors.Root(gotErr), c.wantErr)
    33  			continue
    34  		}
    35  
    36  		if c.wantErr != nil {
    37  			continue
    38  		}
    39  
    40  		if !bytes.Equal(got, c.want) {
    41  			t.Errorf("Compile(%s) = %x want %x", c.plain, got, c.want)
    42  		}
    43  	}
    44  }
    45  
    46  func TestDisassemble(t *testing.T) {
    47  	cases := []struct {
    48  		raw     []byte
    49  		want    string
    50  		wantErr error
    51  	}{
    52  		{mustDecodeHex("525393559c"), "0x02 0x03 ADD 0x05 NUMEQUAL", nil},
    53  		{mustDecodeHex("01135e94559c"), "0x13 0x0e SUB 0x05 NUMEQUAL", nil},
    54  		{mustDecodeHex("6300000000"), "$alpha JUMP:$alpha", nil},
    55  		{[]byte{0xff}, "NOPxff", nil},
    56  	}
    57  
    58  	for _, c := range cases {
    59  		got, gotErr := Disassemble(c.raw)
    60  
    61  		if errors.Root(gotErr) != c.wantErr {
    62  			t.Errorf("Decompile(%x) err = %v want %v", c.raw, errors.Root(gotErr), c.wantErr)
    63  			continue
    64  		}
    65  
    66  		if c.wantErr != nil {
    67  			continue
    68  		}
    69  
    70  		if got != c.want {
    71  			t.Errorf("Decompile(%x) = %s want %s", c.raw, got, c.want)
    72  		}
    73  	}
    74  }
    75  
    76  func mustDecodeHex(h string) []byte {
    77  	bits, err := hex.DecodeString(h)
    78  	if err != nil {
    79  		panic(err)
    80  	}
    81  	return bits
    82  }