import unittest from datetime import datetime, timezone, timedelta from unittest.mock import patch import httpx from fastapi import HTTPException from app import app, make_example, recent_activity, recent_likes, repo_item, paper_item, blog_item def date(n): return (datetime(2026, 11, 18, tzinfo=timezone.utc) - timedelta(days=n)).isoformat() class ExampleHub: def __init__(self): self.calls, self.resolved = [], [] self.fail_activity = False async def get(self, path, params=None, **kwargs): self.calls.append((path, params, kwargs)) if path.endswith('/overview'): if 'unknown' in path:raise HTTPException(404, 'Not found') return {'name': 'alice'} if path.endswith('/likes'): return {'data': [{'createdAt': date(n), 'repo': {'type': 'model', 'name': f'alice/model-{n}'}} for n in range(16)], 'cursor': None} if path == '/api/recent-activity': if self.fail_activity:raise HTTPException(502, 'Unavailable') if params['activityType'] == 'upvote': return {'recentActivity': [ {'type': 'upvote', 'user': 'alice', 'targetType': 'collection', 'targetUrl': '/collections/alice/list', 'time': date(0)}, {'type': 'upvote', 'user': 'alice', 'targetType': 'paper', 'targetUrl': '/papers/1706.03762', 'time': date(0), 'target': {'publishedAt': '2017-06-12'}}, {'type': 'upvote', 'user': 'alice', 'targetType': 'article', 'targetUrl': '/blog/alice/post', 'time': date(1)}, {'type': 'upvote', 'user': 'alice', 'targetType': 'paper', 'targetUrl': '/papers/1706.03762', 'time': date(5)}]} return {'recentActivity': [ {'type': 'article', 'user': 'alice', 'time': date(0), 'blog': {'url': '/blog/alice/post', 'publishedAt': date(1), 'editedAt': date(0), 'authorsData': [{'name': 'alice'}]}}, {'type': 'article', 'user': 'alice', 'time': date(0), 'blog': {'url': '/blog/other/post', 'publishedAt': date(0), 'authorsData': [{'name': 'other'}]}}, {'type': 'article', 'user': 'alice', 'time': date(0), 'blog': {'url': '/blog/alice/draft', 'publishedAt': date(0), 'status': 'draft', 'authorsData': [{'name': 'alice'}]}}]} kind = path.removeprefix('/api/').removesuffix('s') return [{'id': f'alice/{kind}-{n}', 'author': 'alice', 'createdAt': date(n+2), 'lastModified': date(0), 'private': n == 0} for n in range(5)] async def resolve(self, kind, identifier): self.resolved.append((kind, identifier)) if identifier == 'alice/model-0':raise HTTPException(404, 'Deleted') if kind == 'paper':return paper_item({'id': identifier, 'title': 'Attention'}) if kind == 'blog':return blog_item({'url': '/blog/' + identifier, 'title': 'A post'}) return repo_item({'id': identifier, 'title': identifier}, kind) class ExampleTests(unittest.IsolatedAsyncioTestCase): async def test_favorites_merge_event_dates_dedupe_backfill_and_ten_limit(self): h = ExampleHub();result = await make_example(h, 'favorites', 'alice') self.assertEqual(len(result['items']), 10) self.assertEqual(len(set(i['key'] for i in result['items'])), 10) self.assertEqual(result['items'][0]['kind'], 'paper') self.assertEqual(result['items'][0]['activityAt'], date(0)) self.assertNotIn('alice/model-0', [i['id'] for i in result['items']]) self.assertTrue(any('unavailable' in w for w in result['warnings'])) self.assertLessEqual(len(h.resolved), 12) async def test_creations_use_creation_dates_and_confirm_blog_authors(self): result = await make_example(ExampleHub(), 'creations', 'alice') self.assertEqual(len(result['items']), 10) self.assertEqual(result['items'][0]['id'], 'alice/post') self.assertEqual(result['items'][0]['activityAt'], date(1)) self.assertFalse(any(i['id'].startswith('other/') or i['id'].endswith('/draft') or i['id'].endswith('-0') for i in result['items'])) self.assertTrue(all(i['kind'] != 'paper' for i in result['items'])) async def test_partial_upvotes_failure_keeps_available_likes_with_note(self): h=ExampleHub();h.fail_activity=True result=await make_example(h,'favorites','alice') self.assertEqual(len(result['items']),10) self.assertTrue(any('Upvotes' in w for w in result['warnings'])) async def test_likes_pagination_does_not_stop_on_an_empty_page(self): class Pages: async def get(self,path,params,**kwargs): if not params.get('cursor'):return {'data': [], 'cursor': 'next'} return {'data':[{'createdAt':date(1),'repo':{'name':'alice/a','type':'space'}}],'cursor':None} rows,_=await recent_likes(Pages(),'alice');self.assertEqual(rows[0]['id'],'alice/a') async def test_changed_activity_contract_is_explicit(self): class Changed: async def get(self,*args,**kwargs):return {'unknown':[]} with self.assertRaises(HTTPException):await recent_activity(Changed(),'alice','upvote') async def test_foreign_authors_unsafe_paths_and_private_upvotes_are_skipped(self): class Bad: async def get(self,*args,**kwargs):return {'recentActivity':[ {'type':'upvote','user':'bob','targetType':'paper','targetUrl':'/papers/1706.03762','time':date(0)}, {'type':'upvote','user':'alice','targetType':'article','targetUrl':'/blog/../../secret','time':date(0)}, {'type':'upvote','user':'alice','targetType':'paper','targetUrl':'/papers/1706.03762','time':date(0),'target':{'private':True}}]} self.assertEqual((await recent_activity(Bad(),'alice','upvote'))[0],[]) async def test_demo_needs_no_profile_and_keeps_editorial_order(self): result=await make_example(ExampleHub(),'demo') self.assertEqual(len(result['items']),5) self.assertEqual([i['kind'] for i in result['items']],['space','model','dataset','paper','blog']) async def test_all_sources_fail_without_empty_success(self): class Offline: async def get(self,*args,**kwargs):raise HTTPException(502,'Offline') with self.assertRaises(HTTPException) as e:await make_example(Offline(),'favorites','alice') self.assertEqual(e.exception.status_code,502) async def test_public_profile_and_authenticated_identity_are_separate(self): app.state.hub=ExampleHub() class Identity: def user(self,request):return {'username':'alice'} if request.headers.get('authorization')=='Bearer test-session' else None app.state.identity=Identity() async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='https://test') as c: self.assertEqual((await c.get('/api/examples?source=favorites')).status_code,401) self.assertEqual((await c.get('/api/examples?source=favorites&username=alice')).status_code,200) self.assertEqual((await c.get('/api/examples?source=favorites',headers={'Authorization':'Bearer test-session'})).status_code,200) self.assertEqual((await c.get('/api/examples?source=favorites&username=../bad')).status_code,422) self.assertEqual((await c.get('/api/examples?source=favorites&username=unknown')).status_code,404) self.assertEqual((await c.get('/api/examples?source=other')).status_code,422)