Files
TradarrV2/backend/internal/scraper/articlecontent/granular_fetch_metrics_ticket40_test.go

255 lines
9.8 KiB
Go

package articlecontent
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
const granularMetricCanary = "fixture_private_body_title_url_secret_canary"
func jsonLD(t *testing.T, value any) string {
t.Helper()
raw, err := json.Marshal(value)
if err != nil {
t.Fatal("could not build anonymous metrics fixture")
}
return `<script type="application/ld+json">` + string(raw) + `</script>`
}
func fetchMetricsForFixturePages(t *testing.T, source string, pages map[string]string) scraper.FetchMetrics {
t.Helper()
articles := make([]scraper.Article, 0, len(pages))
for target := range pages {
articles = append(articles, scraper.Article{URL: target, Title: granularMetricCanary})
}
ctx, meter := scraper.WithFetchMetrics(context.Background())
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
body, ok := pages[r.URL.String()]
if !ok {
return nil, fmt.Errorf("fixture route not found")
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
})}
got, err := Enrich(ctx, client, source, articles)
if err != nil || len(got) != len(articles) {
t.Fatal("fixture enrichment failed")
}
return meter.Finish()
}
func requireAnonymousAggregate(t *testing.T, metrics scraper.FetchMetrics, fixtureValues ...string) map[string]any {
t.Helper()
raw, err := json.Marshal(metrics)
if err != nil {
t.Fatal("aggregate metrics were not JSON serializable")
}
serialized := string(raw)
for _, value := range append([]string{"http://", "https://", "finance.yahoo.com", "www.cnbc.com", granularMetricCanary}, fixtureValues...) {
if strings.Contains(serialized, value) {
t.Error("aggregate JSON exposed fixture source data")
}
}
var data map[string]any
if err := json.Unmarshal(raw, &data); err != nil {
t.Fatal("aggregate metrics JSON could not be inspected")
}
return data
}
func requireAggregateCounter(t *testing.T, data map[string]any, path []string, want int) {
t.Helper()
var value any = data
for _, key := range path {
parent, ok := value.(map[string]any)
if !ok {
t.Errorf("aggregate cause counter is missing: %s", strings.Join(path, "."))
return
}
value, ok = parent[key]
if !ok {
t.Errorf("aggregate cause counter is missing: %s", strings.Join(path, "."))
return
}
}
got, ok := value.(float64)
if !ok || int(got) != want {
t.Errorf("aggregate cause counter mismatch: %s", strings.Join(path, "."))
}
}
func requireNoAggregateCounter(t *testing.T, data map[string]any, path []string) {
t.Helper()
var value any = data
for _, key := range path {
parent, ok := value.(map[string]any)
if !ok {
return
}
value, ok = parent[key]
if !ok {
return
}
}
t.Errorf("global page challenge was incorrectly exposed as root-scoped: %s", strings.Join(path, "."))
}
func TestYahooIdentityCauseMetricsSeparateMetadataKindsAndRelations(t *testing.T) {
const sameHostOther = "https://finance.yahoo.com/news/other-fixture.html"
const otherHost = "https://www.cnbc.com/2026/01/02/other-fixture.html"
const fixtureBody = "Editorial body canary " + granularMetricCanary
targets := make([]string, 10)
for i := range targets {
targets[i] = fmt.Sprintf("https://finance.yahoo.com/news/identity-fixture-%02d.html", i+1)
}
pages := map[string]string{}
for i, target := range targets {
metadata := ""
switch i {
case 0:
metadata = `<link rel="canonical" href="` + sameHostOther + `">`
case 1:
metadata = `<link rel="canonical" href="` + otherHost + `">`
case 2:
metadata = `<link rel="canonical" href="http://[invalid">`
case 3:
metadata = ""
case 4:
metadata = `<meta property="og:url" content="` + sameHostOther + `">`
case 5:
metadata = `<meta property="og:url" content="` + otherHost + `">`
case 6:
metadata = `<meta property="og:url" content="http://[invalid">`
case 7:
metadata = ""
case 8:
metadata = jsonLD(t, map[string]any{"@type": "NewsArticle", "url": sameHostOther})
case 9:
metadata = jsonLD(t, map[string]any{"@type": "NewsArticle", "url": target, "articleBody": fixtureBody})
}
if i < 8 {
pages[target] = metadata + `<article><div class="caas-body"></div></article>`
} else {
pages[target] = metadata + `<article><div class="caas-body"><p>` + fixtureBody + `</p></div></article>`
}
}
metrics := fetchMetricsForFixturePages(t, "yahoo_finance", pages)
data := requireAnonymousAggregate(t, metrics, sameHostOther, otherHost, granularMetricCanary)
if metrics.Attempted != 10 || metrics.HTTP.TwoXX != 10 || metrics.Root.Yes != 10 {
t.Fatal("Yahoo fixture aggregate did not retain bounded anonymous fetch counts")
}
// Each family appears on 3 of the 10 pages; the remaining 7 are absent,
// including pages with only the other family or only JSON-LD.
for _, tc := range []struct {
kind, cause string
want int
}{
{"canonical", "same_source_different_identity", 1},
{"canonical", "valid_other_host", 1},
{"canonical", "invalid", 1},
{"canonical", "absent", 7},
{"og", "same_source_different_identity", 1},
{"og", "valid_other_host", 1},
{"og", "invalid", 1},
{"og", "absent", 7},
{"jsonld", "mismatch", 1},
{"jsonld", "associated", 1},
} {
requireAggregateCounter(t, data, []string{"identity_evidence", tc.kind, tc.cause}, tc.want)
}
}
func TestCNBCChallengeMetricsAreGlobalPageSignalsNotRootScoped(t *testing.T) {
const body = "Synthetic editorial paragraph " + granularMetricCanary + ". "
text := strings.Repeat(body, 100)
pages := map[string]string{}
for i, marker := range []string{`<aside id="challengeGate">verification overlay</aside>`, `<div id="challengeGate">verification overlay</div>`} {
url := fmt.Sprintf("https://www.cnbc.com/2026/02/02/challenge-fixture-%d.html", i+1)
outside, inside := marker, ""
if i == 1 {
outside, inside = "", marker
}
pages[url] = `<link rel="canonical" href="` + url + `">` + outside + `<div data-module="ArticleBody"><p>` + text + `</p>` + inside + `</div>`
}
metrics := fetchMetricsForFixturePages(t, "cnbc_business", pages)
data := requireAnonymousAggregate(t, metrics, "www.cnbc.com/2026/02/02/", granularMetricCanary, "verification overlay")
if metrics.Attempted != 2 || metrics.HTTP.TwoXX != 2 || metrics.Root.Yes != 2 || metrics.Identity.Yes != 2 || metrics.Length.Large != 2 {
t.Fatal("CNBC challenge fixtures did not retain anonymous page/root/body counters")
}
// Challenges can cover the entire rendered page, including when the marker
// sits beside or inside the editorial root. Measure them as page-global;
// they are never a root-scoped paywall category.
requireAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "global_page"}, 2)
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "article_root"})
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "outside_root"})
}
func TestCNBCBlockingCauseMetricsSeparateCategoryAndEditorialScope(t *testing.T) {
const longFixtureBody = "Synthetic editorial paragraph " + granularMetricCanary + ". "
body := strings.Repeat(longFixtureBody, 100)
type scenario struct {
category string
inside string
outside string
}
scenarios := []scenario{
{"paywall", `<div class="paywall">restricted</div>`, `<aside class="paywall">subscription prompt</aside>`},
{"partial", `<div data-content-state="partial"></div>`, `<aside data-content-state="partial"></aside>`},
{"truncated", `<div data-content-truncated="true"></div>`, `<aside data-content-truncated="true"></aside>`},
{"placeholder", `<div class="article-placeholder"></div>`, `<aside class="article-placeholder"></aside>`},
}
pages := map[string]string{}
wants := make(map[string]int)
index := 0
for _, tc := range scenarios {
for _, scoped := range []struct {
name, marker string
}{{"article_root", tc.inside}, {"outside_root", tc.outside}} {
index++
url := fmt.Sprintf("https://www.cnbc.com/2026/02/01/fixture-%02d.html", index)
inside, outside := "", ""
if scoped.name == "article_root" {
inside = scoped.marker
} else {
outside = scoped.marker
}
pages[url] = `<link rel="canonical" href="` + url + `"><aside>` + outside + `</aside><div data-module="ArticleBody"><p>` + body + `</p>` + inside + `</div>`
wants[tc.category+"."+scoped.name] = 1
}
}
for _, scoped := range []string{"article_root", "outside_root"} {
for _, category := range []string{"accessibility", "body_conflict"} {
index++
url := fmt.Sprintf("https://www.cnbc.com/2026/02/01/fixture-%02d.html", index)
metadata := map[string]any{"@type": "NewsArticle", "url": url}
if category == "accessibility" {
metadata["isAccessibleForFree"] = false
} else {
metadata["articleBody"] = "metadata body does not match the extracted fixture body"
}
json := jsonLD(t, metadata)
if scoped == "article_root" {
pages[url] = `<link rel="canonical" href="` + url + `"><div data-module="ArticleBody">` + json + `<p>` + body + `</p></div>`
} else {
pages[url] = `<link rel="canonical" href="` + url + `">` + json + `<div data-module="ArticleBody"><p>` + body + `</p></div>`
}
wants[category+"."+scoped] = 1
}
}
metrics := fetchMetricsForFixturePages(t, "cnbc_business", pages)
data := requireAnonymousAggregate(t, metrics, "www.cnbc.com/2026/02/01/", granularMetricCanary, "metadata body does not match", "article-placeholder", "subscription prompt")
if metrics.Attempted != 12 || metrics.HTTP.TwoXX != 12 || metrics.Root.Yes != 12 || metrics.Identity.Yes != 12 || metrics.Length.Large != 12 {
t.Fatal("CNBC fixture aggregate did not retain root, identity and long-body counts")
}
for name, count := range wants {
parts := strings.SplitN(name, ".", 2)
requireAggregateCounter(t, data, []string{"blocking_evidence", parts[0], parts[1]}, count)
}
}