You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
3.5 KiB

  1. package imgur
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "testing"
  10. "github.com/matrix-org/go-neb/database"
  11. "github.com/matrix-org/go-neb/testutils"
  12. "github.com/matrix-org/go-neb/types"
  13. "maunium.net/go/mautrix"
  14. )
  15. func TestCommand(t *testing.T) {
  16. database.SetServiceDB(&database.NopStorage{})
  17. clientID := "My ID"
  18. imgurImageURL := "http://i.imgur.com/cat.jpg"
  19. testSearchString := "Czechoslovakian bananna"
  20. // Mock the response from imgur
  21. imgurTrans := testutils.NewRoundTripper(func(req *http.Request) (*http.Response, error) {
  22. imgurURL := "https://api.imgur.com/3/gallery/search"
  23. query := req.URL.Query()
  24. // Check the base API URL
  25. if !strings.HasPrefix(req.URL.String(), imgurURL) {
  26. t.Fatalf("Bad URL: got %s want prefix %s", req.URL.String(), imgurURL)
  27. }
  28. // Check the request method
  29. if req.Method != "GET" {
  30. t.Fatalf("Bad method: got %s want GET", req.Method)
  31. }
  32. // Check the Client ID
  33. authHeader := req.Header.Get("Authorization")
  34. if authHeader != "Client-ID "+clientID {
  35. t.Fatalf("Bad client ID - Expected: %s, got %s", "Client-ID "+clientID, authHeader)
  36. }
  37. // Check the search query
  38. var searchString = query.Get("q")
  39. if searchString != testSearchString {
  40. t.Fatalf("Bad search string - got: \"%s\", expected: \"%s\"", testSearchString, searchString)
  41. }
  42. img := imgurGalleryImage{
  43. Title: "A Cat",
  44. Link: imgurImageURL,
  45. Type: "image/jpeg",
  46. IsAlbum: func() *bool { b := false; return &b }(),
  47. }
  48. imgJSON, err := json.Marshal(img)
  49. if err != nil {
  50. t.Fatalf("Failed to Marshal test image data - %s", err)
  51. }
  52. rawImageJSON := json.RawMessage(imgJSON)
  53. res := imgurSearchResponse{
  54. Data: []json.RawMessage{
  55. rawImageJSON,
  56. },
  57. Success: func() *bool { b := true; return &b }(),
  58. Status: 200,
  59. }
  60. b, err := json.Marshal(res)
  61. if err != nil {
  62. t.Fatalf("Failed to marshal imgur response - %s", err)
  63. }
  64. return &http.Response{
  65. StatusCode: 200,
  66. Body: ioutil.NopCloser(bytes.NewBuffer(b)),
  67. }, nil
  68. })
  69. // clobber the imgur service http client instance
  70. httpClient = &http.Client{Transport: imgurTrans}
  71. // Create the imgur service
  72. srv, err := types.CreateService("id", ServiceType, "@imgurbot:hyrule", []byte(
  73. fmt.Sprintf(`{
  74. "client_id":"%s"
  75. }`, clientID),
  76. ))
  77. if err != nil {
  78. t.Fatal("Failed to create imgur service: ", err)
  79. }
  80. imgur := srv.(*Service)
  81. // Mock the response from Matrix
  82. matrixTrans := struct{ testutils.MockTransport }{}
  83. matrixTrans.RT = func(req *http.Request) (*http.Response, error) {
  84. if req.URL.String() == imgurImageURL { // getting the imgur image
  85. return &http.Response{
  86. StatusCode: 200,
  87. Body: ioutil.NopCloser(bytes.NewBufferString("some image data")),
  88. }, nil
  89. } else if strings.Contains(req.URL.String(), "_matrix/media/r0/upload") { // uploading the image to matrix
  90. return &http.Response{
  91. StatusCode: 200,
  92. Body: ioutil.NopCloser(bytes.NewBufferString(`{"content_uri":"mxc://foo/bar"}`)),
  93. }, nil
  94. }
  95. return nil, fmt.Errorf("Unknown URL: %s", req.URL.String())
  96. }
  97. matrixCli, _ := mautrix.NewClient("https://hyrule", "@imgurbot:hyrule", "its_a_secret")
  98. matrixCli.Client = &http.Client{Transport: matrixTrans}
  99. // Execute the matrix !command
  100. cmds := imgur.Commands(matrixCli)
  101. if len(cmds) != 2 {
  102. t.Fatalf("Unexpected number of commands: %d", len(cmds))
  103. }
  104. cmd := cmds[1]
  105. _, err = cmd.Command("!someroom:hyrule", "@navi:hyrule", []string{testSearchString})
  106. if err != nil {
  107. t.Fatalf("Failed to process command: %s", err.Error())
  108. }
  109. }