| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package code
- import "testing"
- func TestMake(t *testing.T) {
- tests := []struct {
- op Opcode
- operands []int
- expected []byte
- }{
- {OpConstant, []int{65534}, []byte{byte(OpConstant), 0xFF, 0xFE}},
- {OpAdd, []int{}, []byte{byte(OpAdd)}},
- }
- for _, tt := range tests {
- instruction := Make(tt.op, tt.operands...)
- if len(instruction) != len(tt.expected) {
- t.Errorf("instruction has wrong length. want=%d, got=%d", len(tt.expected), len(instruction))
- }
- for i, b := range tt.expected {
- if instruction[i] != tt.expected[i] {
- t.Errorf("wrong byte at pos %d. want=%d, got=%d", i, b, instruction[i])
- }
- }
- }
- }
- func TestInstructionsString(t *testing.T) {
- instructions := []Instructions{
- Make(OpAdd),
- Make(OpConstant, 2),
- Make(OpConstant, 65535),
- }
- expected := `0000 OpAdd
- 0001 OpConstant 2
- 0004 OpConstant 65535
- `
- concatted := Instructions{}
- for _, ins := range instructions {
- concatted = append(concatted, ins...)
- }
- if concatted.String() != expected {
- t.Errorf("instructions wrong formatted.\nwant=%q\n got=%q", expected, concatted.String())
- }
- }
- func TestReadOperands(t *testing.T) {
- tests := []struct {
- op Opcode
- operands []int
- bytesRead int
- }{
- {OpConstant, []int{65535}, 2},
- }
- for _, tt := range tests {
- instruction := Make(tt.op, tt.operands...)
- def, err := Lookup(byte(tt.op))
- if err != nil {
- t.Fatalf("definition not found: %g\n", err)
- }
- operandsRead, n := ReadOperands(def, instruction[1:])
- if n != tt.bytesRead {
- t.Fatalf("n wrong. want=%d, got=%d", tt.bytesRead, n)
- }
- for i, want := range tt.operands {
- if operandsRead[i] != want {
- t.Errorf("operand wrong. want=%d, got=%d", want, operandsRead[i])
- }
- }
- }
- }
|