package cnbcbusiness
import (
"bytes"
"context"
"errors"
"io"
"log"
"net/http"
"strings"
"testing"
)
type fakeTransport func(*http.Request) (*http.Response, error)
func (f fakeTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestCNBCBusinessRSSMapsMetadataWithoutArticleRequests(t *testing.T) {
calls := 0
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(r *http.Request) (*http.Response, error) {
calls++
if r.Method != "GET" || r.URL.String() != "https://www.cnbc.com/id/10001147/device/rss/rss.html" {
t.Fatalf("unexpected request %s %s", r.Method, r.URL)
}
body := `- Business & markets https://www.cnbc.com/fixture.htmlAvailable RSS evidence.
]]>Mon, 02 Jan 2006 15:04:05 -0700- Duplicatehttps://www.cnbc.com/fixture.html
- No descriptionhttps://www.cnbc.com/empty.htmlinvalid
- Unsafejavascript:alert(1)
- Missing link
`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
})}}
got, err := feed.Scrape(context.Background(), []string{"IGNORED"})
if err != nil || len(got) != 2 || calls != 1 {
t.Fatalf("articles=%+v calls=%d err=%v", got, calls, err)
}
if feed.Name() != "cnbc_business" || got[0].Title != "Business & markets" || got[0].Content != "Available RSS evidence." || got[0].PublishedAt == nil || got[0].PublishedAt.Year() != 2006 {
t.Fatalf("mapping=%+v", got[0])
}
if got[1].Content != "" || got[1].PublishedAt != nil {
t.Fatalf("invented missing data=%+v", got[1])
}
}
func TestCNBCBusinessFailsSafelyAndLogsOnlyDiagnostics(t *testing.T) {
for _, tc := range []struct {
name string
status int
body string
}{
{"http", 503, "PRIVATE_RESPONSE https://secret.invalid/?key=PRIVATE_SECRET"},
{"malformed", 200, "PRIVATE_TITLE