main_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package at
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "kitty/tools/crypto"
  7. "kitty/tools/utils"
  8. "testing"
  9. )
  10. func TestEncodeJSON(t *testing.T) {
  11. tests := map[string]string{
  12. "a b\nc\td\a": `a b\nc\td\u0007`,
  13. "•": `\u2022`,
  14. `a"b\c`: `a\"b\\c`,
  15. "\U0001f123": `\ud83c\udd23`,
  16. }
  17. var s escaped_string
  18. for x, expected := range tests {
  19. s = escaped_string(x)
  20. expected = `"` + expected + `"`
  21. actualb, _ := s.MarshalJSON()
  22. actual := string(actualb)
  23. if expected != actual {
  24. t.Fatalf("Failed for %#v\n%#v != %#v", x, expected, actual)
  25. }
  26. }
  27. }
  28. func TestCommandToJSON(t *testing.T) {
  29. pv := fmt.Sprint(ProtocolVersion[0], ",", ProtocolVersion[1], ",", ProtocolVersion[2])
  30. rc, err := create_rc_ls([]string{})
  31. if err != nil {
  32. t.Fatal(err)
  33. }
  34. marshal := func(rc *utils.RemoteControlCmd) string {
  35. q, err := json.Marshal(rc)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. return string(q)
  40. }
  41. test := func(rc *utils.RemoteControlCmd, rest string) {
  42. q := marshal(rc)
  43. expected := `{"cmd":"` + rc.Cmd + `","version":[` + pv + `]`
  44. expected += rest + "}"
  45. if q != expected {
  46. t.Fatalf("expected != actual: %#v != %#v", expected, q)
  47. }
  48. }
  49. test(rc, "")
  50. }
  51. func TestRCSerialization(t *testing.T) {
  52. io_data := rc_io_data{}
  53. err := create_serializer(password{"", false}, "", &io_data)
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. var ver = [3]int{1, 2, 3}
  58. rc := utils.RemoteControlCmd{
  59. Cmd: "test", Version: ver,
  60. }
  61. simple := func(expected string) {
  62. actual, err := io_data.serializer(&rc)
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. as := string(actual)
  67. if as != expected {
  68. t.Fatalf("Incorrect serialization: %s != %s", expected, as)
  69. }
  70. }
  71. simple(string(`{"cmd":"test","version":[1,2,3]}`))
  72. pubkey_b, _, err := crypto.KeyPair("1")
  73. if err != nil {
  74. t.Fatal(err)
  75. }
  76. pubkey, err := crypto.EncodePublicKey(pubkey_b, "1")
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. err = create_serializer(password{"tpw", true}, pubkey, &io_data)
  81. if err != nil {
  82. t.Fatal(err)
  83. }
  84. raw, err := io_data.serializer(&rc)
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. var ec utils.EncryptedRemoteControlCmd
  89. err = json.Unmarshal([]byte(raw), &ec)
  90. if err != nil {
  91. t.Fatal(err)
  92. }
  93. if ec.Version != ver {
  94. t.Fatal("Incorrect version in encrypted command: ", ec.Version)
  95. }
  96. }