fix(scrapers): add sanitized collection diagnostics
Report source, HTTP status, article counts, and outcome without logging response bodies; preserve the existing extraction and parsing flow. Refs #20 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -0,0 +1,99 @@
|
||||
package yahoofinance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type ticket20RoundTrip func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f ticket20RoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func ticket20CaptureStdout(t *testing.T, run func()) string {
|
||||
t.Helper()
|
||||
reader, writer, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := os.Stdout
|
||||
os.Stdout = writer
|
||||
defer func() { os.Stdout = previous }()
|
||||
run()
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := io.ReadAll(reader)
|
||||
_ = reader.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func TestTicket20Yahoo400DiagnosticConnectsSymbolsStatusAndCountWithoutResponseBody(t *testing.T) {
|
||||
const privateHTML = `<html><title>PRIVATE_YAHOO_RESPONSE_DO_NOT_LOG</title><article>PRIVATE_ARTICLE_BODY_DO_NOT_LOG</article></html>`
|
||||
var requested string
|
||||
yahoo := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
requested = r.URL.Query().Get("s")
|
||||
return &http.Response{StatusCode: http.StatusBadRequest, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(privateHTML)), Request: r}, nil
|
||||
})}}
|
||||
var articles int
|
||||
logs := ticket20CaptureStdout(t, func() {
|
||||
got, err := yahoo.Scrape(context.Background(), []string{"SSAAPL INDEX"})
|
||||
if err != nil {
|
||||
t.Fatalf("Scrape returned error: %v", err)
|
||||
}
|
||||
articles = len(got)
|
||||
})
|
||||
if requested != "SSAAPL INDEX" {
|
||||
t.Fatalf("fake Yahoo request symbol=%q, want SSAAPL INDEX reproduction", requested)
|
||||
}
|
||||
for _, diagnostic := range []string{"symbol=SSAAPL INDEX", "yahoo_symbol=SSAAPL INDEX", "status=400", "articles=0"} {
|
||||
if !strings.Contains(logs, diagnostic) {
|
||||
t.Errorf("Yahoo diagnostic lacks %q: %q", diagnostic, logs)
|
||||
}
|
||||
}
|
||||
if articles != 0 {
|
||||
t.Errorf("articles=%d, want 0", articles)
|
||||
}
|
||||
for _, secret := range []string{"PRIVATE_YAHOO_RESPONSE_DO_NOT_LOG", "PRIVATE_ARTICLE_BODY_DO_NOT_LOG", privateHTML} {
|
||||
if strings.Contains(logs, secret) {
|
||||
t.Errorf("Yahoo diagnostics leaked response/article content %q", secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket19YahooReceivesOnlySelectedFinanceDatabaseYahooSymbols(t *testing.T) {
|
||||
// Yahoo must receive the runtime-selected primary listings. The raw fixture
|
||||
// still contains BIDU and 1211.HK, but FinanceDatabase selects 9888.HK and
|
||||
// 002594.SZ for those companies at the pinned upstream snapshot.
|
||||
want := []string{"NVDA", "AAPL", "9888.HK", "002594.SZ", "0285.HK"}
|
||||
var requested []string
|
||||
yahoo := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
symbol := r.URL.Query().Get("s")
|
||||
requested = append(requested, symbol)
|
||||
body := fmt.Sprintf(`<rss><channel><item><title>Fixture %s</title><link>https://fixture.invalid/%s</link><description>synthetic only</description></item></channel></rss>`, symbol, symbol)
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
|
||||
})}}
|
||||
articles, err := yahoo.Scrape(context.Background(), want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(requested, want) {
|
||||
t.Fatalf("Yahoo symbols=%v, want selected Yahoo tickers %v", requested, want)
|
||||
}
|
||||
if len(articles) != len(want) {
|
||||
t.Fatalf("articles=%d, want one fixture article per symbol", len(articles))
|
||||
}
|
||||
for i, symbol := range want {
|
||||
if len(articles[i].Symbols) != 1 || articles[i].Symbols[0] != symbol {
|
||||
t.Errorf("article %d symbols=%v, want %q", i, articles[i].Symbols, symbol)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@ -49,16 +48,31 @@ func (y *YahooFinance) Scrape(ctx context.Context, symbols []string) ([]scraper.
|
||||
}
|
||||
items, err := y.fetchSymbol(ctx, symbol)
|
||||
if err != nil {
|
||||
fmt.Printf("yahoofinance %s: %v\n", symbol, err)
|
||||
continue
|
||||
}
|
||||
articles = append(articles, items...)
|
||||
fmt.Printf("yahoofinance %s: %d articles fetched\n", symbol, len(items))
|
||||
}
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) ([]scraper.Article, error) {
|
||||
func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) (articles []scraper.Article, resultErr error) {
|
||||
status := 0
|
||||
defer func() {
|
||||
outcome := "ok"
|
||||
if resultErr != nil {
|
||||
outcome = "failed"
|
||||
}
|
||||
safeSymbol := strings.Map(func(r rune) rune {
|
||||
if r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune(" .-^=", r) {
|
||||
return r
|
||||
}
|
||||
return '_'
|
||||
}, symbol)
|
||||
if len(safeSymbol) > 64 {
|
||||
safeSymbol = safeSymbol[:64]
|
||||
}
|
||||
fmt.Printf("yahoofinance symbol=%s yahoo_symbol=%s status=%d articles=%d outcome=%s\n", safeSymbol, safeSymbol, status, len(articles), outcome)
|
||||
}()
|
||||
url := fmt.Sprintf(
|
||||
"https://feeds.finance.yahoo.com/rss/2.0/headline?s=%s®ion=US&lang=en-US",
|
||||
symbol,
|
||||
@ -76,9 +90,9 @@ func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) ([]scrape
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
status = resp.StatusCode
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
||||
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var feed rssFeed
|
||||
@ -87,8 +101,6 @@ func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) ([]scrape
|
||||
}
|
||||
|
||||
const maxPerSymbol = 5
|
||||
|
||||
var articles []scraper.Article
|
||||
for _, item := range feed.Channel.Items {
|
||||
if len(articles) >= maxPerSymbol {
|
||||
break
|
||||
|
||||
Reference in New Issue
Block a user