Files
RSS/tests/test_merge.py
Yuzhen e19f4bf49c
Update RSS / update (push) Successful in 5m14s
Update secrets
2026-08-29 15:11:13 +08:00

73 lines
2.8 KiB
Python

from datetime import datetime, timezone
from pathlib import Path
import sys
import unittest
import xml.etree.ElementTree as ET
from urllib.parse import parse_qs, urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from merge import FeedItem, add_rsshub_access_key, build_rss, redact_secret, sort_and_limit
def item(title, link, hour, description=""):
return FeedItem(
title=title,
link=link,
guid=link,
published=datetime(2026, 1, 1, hour, tzinfo=timezone.utc),
description=description,
source_title="Test Feed",
source_url="https://example.com/feed.xml",
)
class MergeTests(unittest.TestCase):
def test_adds_rsshub_key_and_preserves_existing_query(self):
result = add_rsshub_access_key(
"https://rsshub.yuzhen.pub/github/trending/daily?language=python&key=old",
"new key&value",
)
query = parse_qs(urlsplit(result).query)
self.assertEqual(query, {"language": ["python"], "key": ["new key&value"]})
upgraded = add_rsshub_access_key("http://rsshub.yuzhen.pub/feed", "secret")
self.assertEqual(urlsplit(upgraded).scheme, "https")
def test_does_not_add_key_to_other_hosts(self):
url = "https://example.com/feed.xml?category=tech"
self.assertEqual(add_rsshub_access_key(url, "secret"), url)
def test_redacts_raw_and_encoded_key(self):
message = "raw=a b&encoded=a+b&percent=a%20b"
self.assertNotIn("a b", redact_secret(message, "a b"))
self.assertNotIn("a+b", redact_secret(message, "a b"))
self.assertNotIn("a%20b", redact_secret(message, "a b"))
def test_sorts_keeps_duplicates_and_limits(self):
values = [
item("Older", "https://example.com/old", 1),
item("Newest", "https://example.com/new", 3),
item("Duplicate title", "https://example.com/new#comments", 2),
]
merged = sort_and_limit(values, 2)
self.assertEqual([value.title for value in merged], ["Newest", "Duplicate title"])
def test_builds_valid_rss(self):
group = {
"title": "Merged",
"sources": ["https://example.com/feed.xml"],
"self_url": "https://example.com/all.xml",
}
document = build_rss("all", group, [item("Hello", "https://example.com/hello", 1, "<p>Body</p>")])
root = ET.fromstring(document)
self.assertEqual(root.tag, "rss")
self.assertEqual(root.findtext("channel/title"), "Merged")
self.assertEqual(root.findtext("channel/item/title"), "Hello")
self.assertEqual(root.findtext("channel/item/description"), "<p>Body</p>")
self.assertEqual(root.find("channel/item/source").get("url"), "https://example.com/feed.xml")
if __name__ == "__main__":
unittest.main()