youtube_test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package processor // import "miniflux.app/v2/internal/reader/processor"
  4. import (
  5. "bytes"
  6. "log/slog"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "testing"
  11. "time"
  12. "miniflux.app/v2/internal/config"
  13. )
  14. func TestGetYouTubeVideoIDFromURL(t *testing.T) {
  15. scenarios := []struct {
  16. url string
  17. expected string
  18. }{
  19. {"https://www.youtube.com/watch?v=HLrqNhgdiC0", "HLrqNhgdiC0"},
  20. {"https://www.youtube.com/watch?v=HLrqNhgdiC0&feature=youtu.be", "HLrqNhgdiC0"},
  21. {"https://example.org/test", ""},
  22. }
  23. for _, tc := range scenarios {
  24. result := getVideoIDFromYouTubeURL(tc.url)
  25. if tc.expected != result {
  26. t.Errorf(`Unexpected result, got %q for url %q`, result, tc.url)
  27. }
  28. }
  29. }
  30. func TestIsYouTubeVideoURL(t *testing.T) {
  31. scenarios := []struct {
  32. url string
  33. expected bool
  34. }{
  35. {"https://www.youtube.com/watch?v=HLrqNhgdiC0", true},
  36. {"https://www.youtube.com/watch?v=HLrqNhgdiC0&feature=youtu.be", true},
  37. {"https://example.org/test", false},
  38. }
  39. for _, tc := range scenarios {
  40. result := isYouTubeVideoURL(tc.url)
  41. if tc.expected != result {
  42. t.Errorf(`Unexpected result, got %v for url %q`, result, tc.url)
  43. }
  44. }
  45. }
  46. func configureYouTubeAPIOptions(t *testing.T, apiKey string) {
  47. t.Helper()
  48. t.Setenv("YOUTUBE_API_KEY", apiKey)
  49. t.Setenv("FETCHER_ALLOW_PRIVATE_NETWORKS", "1")
  50. parsedOptions, err := config.NewConfigParser().ParseEnvironmentVariables()
  51. if err != nil {
  52. t.Fatalf("Unable to configure test options: %v", err)
  53. }
  54. previousOptions := config.Opts
  55. config.Opts = parsedOptions
  56. t.Cleanup(func() {
  57. config.Opts = previousOptions
  58. })
  59. }
  60. func captureDebugLogs(t *testing.T) *bytes.Buffer {
  61. t.Helper()
  62. var logs bytes.Buffer
  63. previousLogger := slog.Default()
  64. slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})))
  65. t.Cleanup(func() { slog.SetDefault(previousLogger) })
  66. return &logs
  67. }
  68. func TestFetchYouTubeWatchTimeFromAPIInBulkSendsKeyInHeader(t *testing.T) {
  69. const apiKey = "AIzaSyTestKey"
  70. configureYouTubeAPIOptions(t, apiKey)
  71. logs := captureDebugLogs(t)
  72. server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
  73. if got := request.Header.Get("X-Goog-Api-Key"); got != apiKey {
  74. t.Errorf("Expected the X-Goog-Api-Key header to be %q, got %q", apiKey, got)
  75. }
  76. if request.URL.Query().Has("key") {
  77. t.Errorf("Expected no key query parameter, got %q", request.URL.RawQuery)
  78. }
  79. if got := request.URL.Query().Get("id"); got != "video1,video2" {
  80. t.Errorf("Expected the id query parameter to be %q, got %q", "video1,video2", got)
  81. }
  82. if got := request.URL.Query().Get("part"); got != "contentDetails" {
  83. t.Errorf("Expected the part query parameter to be %q, got %q", "contentDetails", got)
  84. }
  85. writer.Header().Set("Content-Type", "application/json")
  86. writer.Write([]byte(`{"items":[{"id":"video1","contentDetails":{"duration":"PT1M30S"}},{"id":"video2","contentDetails":{"duration":"PT1H"}}]}`))
  87. }))
  88. defer server.Close()
  89. watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(server.URL, []string{"video1", "video2"})
  90. if err != nil {
  91. t.Fatalf("Expected no error, got %v", err)
  92. }
  93. expectedWatchTimes := map[string]time.Duration{
  94. "video1": 90 * time.Second,
  95. "video2": time.Hour,
  96. }
  97. for videoID, expectedWatchTime := range expectedWatchTimes {
  98. if watchTimeMap[videoID] != expectedWatchTime {
  99. t.Errorf("Expected watch time %v for %q, got %v", expectedWatchTime, videoID, watchTimeMap[videoID])
  100. }
  101. }
  102. if strings.Contains(logs.String(), apiKey) {
  103. t.Errorf("Logs contain the API key:\n%s", logs.String())
  104. }
  105. }
  106. func TestFetchYouTubeWatchTimeFromAPIInBulkKeepsKeyOutOfErrors(t *testing.T) {
  107. const apiKey = "AIzaSyTestKey"
  108. configureYouTubeAPIOptions(t, apiKey)
  109. logs := captureDebugLogs(t)
  110. server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
  111. serverURL := server.URL
  112. server.Close()
  113. _, err := fetchYouTubeWatchTimeFromApiInBulk(serverURL, []string{"video1"})
  114. if err == nil {
  115. t.Fatal("Expected an error when the API is unreachable")
  116. }
  117. if strings.Contains(err.Error(), apiKey) {
  118. t.Errorf("Error contains the API key: %v", err)
  119. }
  120. if strings.Contains(logs.String(), apiKey) {
  121. t.Errorf("Logs contain the API key:\n%s", logs.String())
  122. }
  123. }
  124. func TestFetchYouTubeWatchTimeFromAPIInBulkDoesNotFollowRedirects(t *testing.T) {
  125. const apiKey = "AIzaSyTestKey"
  126. configureYouTubeAPIOptions(t, apiKey)
  127. redirectTarget := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
  128. t.Errorf("Expected the redirect not to be followed, got a request with X-Goog-Api-Key %q", request.Header.Get("X-Goog-Api-Key"))
  129. }))
  130. defer redirectTarget.Close()
  131. server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
  132. http.Redirect(writer, request, redirectTarget.URL, http.StatusFound)
  133. }))
  134. defer server.Close()
  135. if _, err := fetchYouTubeWatchTimeFromApiInBulk(server.URL, []string{"video1"}); err == nil {
  136. t.Fatal("Expected an error when the API responds with a redirect")
  137. }
  138. }