openGraph_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
  2. // See LICENSE.txt for license information.
  3. package api4
  4. import (
  5. "fmt"
  6. "net/http"
  7. "net/http/httptest"
  8. "testing"
  9. "github.com/stretchr/testify/require"
  10. "github.com/mattermost/mattermost-server/v5/model"
  11. )
  12. func TestGetOpenGraphMetadata(t *testing.T) {
  13. th := Setup(t).InitBasic()
  14. defer th.TearDown()
  15. Client := th.Client
  16. enableLinkPreviews := *th.App.Config().ServiceSettings.EnableLinkPreviews
  17. allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections
  18. defer func() {
  19. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews })
  20. th.App.UpdateConfig(func(cfg *model.Config) {
  21. cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections
  22. })
  23. }()
  24. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = true })
  25. th.App.UpdateConfig(func(cfg *model.Config) {
  26. *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost,127.0.0.1"
  27. })
  28. ogDataCacheMissCount := 0
  29. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  30. ogDataCacheMissCount++
  31. if r.URL.Path == "/og-data/" {
  32. fmt.Fprintln(w, `
  33. <html><head><meta property="og:type" content="article" />
  34. <meta property="og:title" content="Test Title" />
  35. <meta property="og:url" content="http://example.com/" />
  36. </head><body></body></html>
  37. `)
  38. } else if r.URL.Path == "/no-og-data/" {
  39. fmt.Fprintln(w, `<html><head></head><body></body></html>`)
  40. }
  41. }))
  42. for _, data := range [](map[string]interface{}){
  43. {"path": "/og-data/", "title": "Test Title", "cacheMissCount": 1},
  44. {"path": "/no-og-data/", "title": "", "cacheMissCount": 2},
  45. // Data should be cached for following
  46. {"path": "/og-data/", "title": "Test Title", "cacheMissCount": 2},
  47. {"path": "/no-og-data/", "title": "", "cacheMissCount": 2},
  48. } {
  49. openGraph, resp := Client.OpenGraph(ts.URL + data["path"].(string))
  50. CheckNoError(t, resp)
  51. require.Equalf(t, openGraph["title"], data["title"].(string),
  52. "OG data title mismatch for path \"%s\".")
  53. require.Equal(t, ogDataCacheMissCount, data["cacheMissCount"].(int),
  54. "Cache miss count didn't match.")
  55. }
  56. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = false })
  57. _, resp := Client.OpenGraph(ts.URL + "/og-data/")
  58. CheckNotImplementedStatus(t, resp)
  59. }