code_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package code
  2. import "testing"
  3. func TestMake(t *testing.T) {
  4. tests := []struct {
  5. op Opcode
  6. operands []int
  7. expected []byte
  8. }{
  9. {OpConstant, []int{65534}, []byte{byte(OpConstant), 0xFF, 0xFE}},
  10. {OpAdd, []int{}, []byte{byte(OpAdd)}},
  11. }
  12. for _, tt := range tests {
  13. instruction := Make(tt.op, tt.operands...)
  14. if len(instruction) != len(tt.expected) {
  15. t.Errorf("instruction has wrong length. want=%d, got=%d", len(tt.expected), len(instruction))
  16. }
  17. for i, b := range tt.expected {
  18. if instruction[i] != tt.expected[i] {
  19. t.Errorf("wrong byte at pos %d. want=%d, got=%d", i, b, instruction[i])
  20. }
  21. }
  22. }
  23. }
  24. func TestInstructionsString(t *testing.T) {
  25. instructions := []Instructions{
  26. Make(OpAdd),
  27. Make(OpConstant, 2),
  28. Make(OpConstant, 65535),
  29. }
  30. expected := `0000 OpAdd
  31. 0001 OpConstant 2
  32. 0004 OpConstant 65535
  33. `
  34. concatted := Instructions{}
  35. for _, ins := range instructions {
  36. concatted = append(concatted, ins...)
  37. }
  38. if concatted.String() != expected {
  39. t.Errorf("instructions wrong formatted.\nwant=%q\n got=%q", expected, concatted.String())
  40. }
  41. }
  42. func TestReadOperands(t *testing.T) {
  43. tests := []struct {
  44. op Opcode
  45. operands []int
  46. bytesRead int
  47. }{
  48. {OpConstant, []int{65535}, 2},
  49. }
  50. for _, tt := range tests {
  51. instruction := Make(tt.op, tt.operands...)
  52. def, err := Lookup(byte(tt.op))
  53. if err != nil {
  54. t.Fatalf("definition not found: %g\n", err)
  55. }
  56. operandsRead, n := ReadOperands(def, instruction[1:])
  57. if n != tt.bytesRead {
  58. t.Fatalf("n wrong. want=%d, got=%d", tt.bytesRead, n)
  59. }
  60. for i, want := range tt.operands {
  61. if operandsRead[i] != want {
  62. t.Errorf("operand wrong. want=%d, got=%d", want, operandsRead[i])
  63. }
  64. }
  65. }
  66. }