71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package reddit
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestGetLatestImage(t *testing.T) {
|
|
// Mock Reddit API response
|
|
mockResponse := `{
|
|
"kind": "Listing",
|
|
"data": {
|
|
"after": null,
|
|
"dist": 1,
|
|
"modhash": "",
|
|
"geo_filter": "",
|
|
"children": [
|
|
{
|
|
"kind": "t3",
|
|
"data": {
|
|
"url_overridden_by_dest": "https://example.com/gallery",
|
|
"media_metadata": {},
|
|
"preview": {}
|
|
}
|
|
},
|
|
{
|
|
"kind": "t3",
|
|
"data": {
|
|
"url_overridden_by_dest": "https://example.com/image.jpg",
|
|
"media_metadata": {},
|
|
"preview": {}
|
|
}
|
|
}
|
|
]
|
|
}
|
|
}`
|
|
|
|
// Create a test server
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if strings.Contains(r.URL.Path, "/r/wallpaper/.json") {
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(mockResponse))
|
|
} else {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
|
|
// Custom httpGet function for testing
|
|
httpGet := func(url string) (*http.Response, error) {
|
|
if strings.Contains(url, "/r/wallpaper/.json") {
|
|
return http.Get(server.URL + "/r/wallpaper/.json")
|
|
}
|
|
return nil, fmt.Errorf("unexpected URL: %s", url)
|
|
}
|
|
|
|
// Test the function
|
|
imageURL, err := GetLatestImage(httpGet)
|
|
if err != nil {
|
|
t.Fatalf("expected no error, got %v", err)
|
|
}
|
|
|
|
expectedURL := "https://example.com/image.jpg"
|
|
if imageURL != expectedURL {
|
|
t.Errorf("expected %s, got %s", expectedURL, imageURL)
|
|
}
|
|
}
|