code_test.go 1.7 KB

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