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.

117 lines
3.5 KiB

  1. package google
  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. "github.com/matrix-org/gomatrix"
  14. )
  15. // TODO: It would be nice to tabularise this test so we can try failing different combinations of responses to make
  16. // sure all cases are handled, rather than just the general case as is here.
  17. func TestCommand(t *testing.T) {
  18. database.SetServiceDB(&database.NopStorage{})
  19. apiKey := "secret"
  20. googleImageURL := "http://cat.com/cat.jpg"
  21. // Mock the response from Google
  22. googleTrans := testutils.NewRoundTripper(func(req *http.Request) (*http.Response, error) {
  23. googleURL := "https://www.googleapis.com/customsearch/v1"
  24. query := req.URL.Query()
  25. // Check the base API URL
  26. if !strings.HasPrefix(req.URL.String(), googleURL) {
  27. t.Fatalf("Bad URL: got %s want prefix %s", req.URL.String(), googleURL)
  28. }
  29. // Check the request method
  30. if req.Method != "GET" {
  31. t.Fatalf("Bad method: got %s want GET", req.Method)
  32. }
  33. // Check the API key
  34. if query.Get("key") != apiKey {
  35. t.Fatalf("Bad apiKey: got %s want %s", query.Get("key"), apiKey)
  36. }
  37. // Check the search query
  38. var searchString = query.Get("q")
  39. var searchStringLength = len(searchString)
  40. if searchStringLength > 0 && !strings.HasPrefix(searchString, "image") {
  41. t.Fatalf("Bad search string: got \"%s\" (%d characters) ", searchString, searchStringLength)
  42. }
  43. resImage := googleImage{
  44. Width: 64,
  45. Height: 64,
  46. }
  47. image := googleSearchResult{
  48. Title: "A Cat",
  49. Link: googleImageURL,
  50. Mime: "image/jpeg",
  51. Image: resImage,
  52. }
  53. res := googleSearchResults{
  54. Items: []googleSearchResult{
  55. image,
  56. },
  57. }
  58. b, err := json.Marshal(res)
  59. if err != nil {
  60. t.Fatalf("Failed to marshal Google response - %s", err)
  61. }
  62. return &http.Response{
  63. StatusCode: 200,
  64. Body: ioutil.NopCloser(bytes.NewBuffer(b)),
  65. }, nil
  66. })
  67. // clobber the Google service http client instance
  68. httpClient = &http.Client{Transport: googleTrans}
  69. // Create the Google service
  70. srv, err := types.CreateService("id", ServiceType, "@googlebot:hyrule", []byte(
  71. `{"api_key":"`+apiKey+`"}`,
  72. ))
  73. if err != nil {
  74. t.Fatal("Failed to create Google service: ", err)
  75. }
  76. google := srv.(*Service)
  77. // Mock the response from Matrix
  78. matrixTrans := struct{ testutils.MockTransport }{}
  79. matrixTrans.RT = func(req *http.Request) (*http.Response, error) {
  80. if req.URL.String() == googleImageURL { // getting the Google image
  81. return &http.Response{
  82. StatusCode: 200,
  83. Body: ioutil.NopCloser(bytes.NewBufferString("some image data")),
  84. }, nil
  85. } else if strings.Contains(req.URL.String(), "_matrix/media/r0/upload") { // uploading the image to matrix
  86. return &http.Response{
  87. StatusCode: 200,
  88. Body: ioutil.NopCloser(bytes.NewBufferString(`{"content_uri":"mxc://foo/bar"}`)),
  89. }, nil
  90. }
  91. return nil, fmt.Errorf("Unknown URL: %s", req.URL.String())
  92. }
  93. matrixCli, _ := gomatrix.NewClient("https://hyrule", "@googlebot:hyrule", "its_a_secret")
  94. matrixCli.Client = &http.Client{Transport: matrixTrans}
  95. // Execute the matrix !command
  96. cmds := google.Commands(matrixCli)
  97. if len(cmds) != 3 {
  98. t.Fatalf("Unexpected number of commands: %d", len(cmds))
  99. }
  100. cmd := cmds[0]
  101. _, err = cmd.Command("!someroom:hyrule", "@navi:hyrule", []string{"image", "Czechoslovakian bananna"})
  102. if err != nil {
  103. t.Fatalf("Failed to process command: %s", err.Error())
  104. }
  105. }