An open source, non-profit web search engine
Add a functional test of crawler (and some missing files)
Daoud Clarke821545ef00bd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1c49173..c3e4af3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -70,5 +70,6 @@ jobs:- name: Run testsenv:DATABASE_URL: postgres://postgres:postgres@localhost:5432/test_mwmbl+ DJANGO_SETTINGS_MODULE: mwmbl.settings_testrun: |poetry run pytestdiff --git a/mwmbl/crawl.py b/mwmbl/crawl.pyindex 72acdf0..facb8d4 100644--- a/mwmbl/crawl.py+++ b/mwmbl/crawl.py@@ -51,7 +51,7 @@ def check_redis():redis.ping()logger.debug("Redis ping successful")except ConnectionError as e:- raise SystemExit(f"Cannot reach Redis at {REDIS_URL}. Make sure your Redis server is running.")+ raise SystemExit(f"Cannot reach Redis at {settings.REDIS_URL}. Make sure your Redis server is running.")check_redis()url_queue = RedisURLQueue(redis, lambda: set())diff --git a/mwmbl/migrations/0015_alter_searchresultvote_vote_type.py b/mwmbl/migrations/0015_alter_searchresultvote_vote_type.pynew file mode 100644index 0000000..4d33dee--- /dev/null+++ b/mwmbl/migrations/0015_alter_searchresultvote_vote_type.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.23 on 2025-07-20 21:01++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('mwmbl', '0014_remove_searchresultvote_mwmbl_searchresultvote_user_url_query_unique_and_more'),+ ]++ operations = [+ migrations.AlterField(+ model_name='searchresultvote',+ name='vote_type',+ field=models.CharField(choices=[('upvote', 'User upvoted this result'), ('downvote', 'User downvoted this result')], max_length=10),+ ),+ ]diff --git a/mwmbl/settings_test.py b/mwmbl/settings_test.pynew file mode 100644index 0000000..de903f0--- /dev/null+++ b/mwmbl/settings_test.py@@ -0,0 +1,30 @@+from mwmbl.settings_dev import *++# Disable database setup for testing+SETUP_DATABASE = False++# Use in-memory SQLite for Django ORM tests+DATABASES = {+ 'default': {+ 'ENGINE': 'django.db.backends.sqlite3',+ 'NAME': ':memory:',+ }+}++# Test-specific settings+DATA_PATH = "/tmp/test_mwmbl_data"+INDEX_NAME = "test-index.tinysearch"+NUM_PAGES = 10++# Disable Redis URL requirement for testing+REDIS_URL = "redis://localhost:6379"++# Test bloom filter paths+URLS_BLOOM_FILTER_PATH = "/tmp/test_urls-{year}-{month}.bloom"+URLS_BLOOM_FILTER_FALLBACK_PATH = "/tmp/test_urls.bloom"+NUM_URLS_IN_BLOOM_FILTER = 1000++DOMAIN_LINKS_BLOOM_FILTER_PATH = "/tmp/test_links_{domain_group}.bloom"+NUM_DOMAINS_IN_BLOOM_FILTER = 1000++REQUEST_CACHE_PATH = "/tmp/test_request_cache"diff --git a/poetry.lock b/poetry.lockindex d8c4e78..9018a69 100644--- a/poetry.lock+++ b/poetry.lock@@ -610,6 +610,28 @@ files = [{file = "docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f"},]+[[package]]+name = "fakeredis"+version = "2.30.1"+description = "Python implementation of redis API, can be used for testing purposes."+optional = false+python-versions = ">=3.7"+files = [+ {file = "fakeredis-2.30.1-py3-none-any.whl", hash = "sha256:b594a9c20aef8b94c4d923f489210ef443e4001e62ad3cd73b9a01298dcef743"},+ {file = "fakeredis-2.30.1.tar.gz", hash = "sha256:6489f2926e39815c9bf0fce80751635e0898e333c43a767825adf101180dbc45"},+]++[package.dependencies]+redis = {version = ">=4.3", markers = "python_version > \"3.8\""}+sortedcontainers = ">=2,<3"++[package.extras]+bf = ["pyprobables (>=0.6)"]+cf = ["pyprobables (>=0.6)"]+json = ["jsonpath-ng (>=1.6,<2.0)"]+lua = ["lupa (>=2.1,<3.0)"]+probabilistic = ["pyprobables (>=0.6)"]+[[package]]name = "h11"version = "0.16.0"@@ -2160,6 +2182,17 @@ files = [{file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"},]+[[package]]+name = "sortedcontainers"+version = "2.4.0"+description = "Sorted Containers -- Sorted List, Sorted Dict, Sorted Set"+optional = false+python-versions = "*"+files = [+ {file = "sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0"},+ {file = "sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88"},+]+[[package]]name = "soupsieve"version = "2.7"@@ -2521,4 +2554,4 @@ indexer = ["Levenshtein", "beautifulsoup4", "idna", "langdetect", "pyarrow", "py[metadata]lock-version = "2.0"python-versions = ">=3.11,<3.12"-content-hash = "a7c1ab87d8f3f1cd694b1009f9e4b61369ff50d9edd1b0691b8f167a3714667f"+content-hash = "ce66d3d41bcf5895a0aaca110397c427e43916db8df4f1702ebcaa5ee77cc205"diff --git a/pyproject.toml b/pyproject.tomlindex 59915c3..9e80294 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -64,19 +64,8 @@ indexer = [][tool.poetry.dev-dependencies]-# botocore = "^1.23.20"-# boto3 = "^1.20.20"-# ujson = "^4.3.0"-# warcio = "^1.7.4"-# idna = "^3.3"-# beautifulsoup4 = "^4.10.0"-# lxml = "^4.6.4"-# jusText = "^3.0.0"-# pyspark = "^3.2.0"-# langdetect = "^1.0.9"-# spacy = "^3.2.1"-# Levenshtein = "^0.16.0"pytest = "^7.0.1"+fakeredis = "^2.30.1"[build-system]requires = ["poetry-core>=1.0.0"]diff --git a/test/test_crawl_functional.py b/test/test_crawl_functional.pynew file mode 100644index 0000000..9df06aa--- /dev/null+++ b/test/test_crawl_functional.py@@ -0,0 +1,400 @@+import json+import os+import tempfile+import time+from datetime import datetime, timedelta+from pathlib import Path+from unittest.mock import patch, MagicMock, mock_open++import fakeredis+import pytest+from django.test import override_settings++from mwmbl.crawler.batch import HashedBatch, Result+from mwmbl.crawler.urls import FoundURL, URLStatus+from mwmbl.redis_url_queue import RedisURLQueue+++def fake_redis():+ """Create a fake Redis instance for testing"""+ return fakeredis.FakeRedis(decode_responses=True, health_check_interval=30)+++def temp_data_path():+ """Create a temporary directory for test data"""+ with tempfile.TemporaryDirectory() as temp_dir:+ yield Path(temp_dir)+++def mock_settings(temp_data_path):+ """Mock Django settings for crawler"""+ with override_settings(+ DATA_PATH=str(temp_data_path),+ INDEX_NAME="test-index.tinysearch",+ REDIS_URL="redis://localhost:6379",+ SETUP_DATABASE=False, # Disable database setup for testing+ NUM_PAGES=10 # Small number for testing+ ):+ yield+++def mock_environment():+ """Mock environment variables"""+ env_vars = {+ 'MWMBL_API_KEY': 'test-api-key',+ 'MWMBL_CONTACT_INFO': '[email protected]',+ 'CRAWLER_WORKERS': '1',+ 'CRAWL_DELAY_SECONDS': '0.0'+ }+ with patch.dict(os.environ, env_vars):+ yield+++def mock_crawl_response():+ """Mock successful crawl response"""+ return {+ 'url': 'https://example.com',+ 'status': 200,+ 'timestamp': int(time.time() * 1000),+ 'content': {+ 'title': 'Example Page',+ 'extract': 'This is an example page with some content.',+ 'links': ['https://example.com/page1', 'https://example.com/page2'],+ 'extra_links': ['https://example.com/extra1']+ },+ 'error': None+ }+++def sample_found_urls():+ """Create sample FoundURL objects for testing"""+ return [+ FoundURL(+ url='https://example.com/page1',+ user_id_hash='test_user_hash',+ status=URLStatus.NEW,+ timestamp=datetime.utcnow(),+ last_crawled=datetime.utcnow() - timedelta(days=60)+ ),+ FoundURL(+ url='https://example.com/page2',+ user_id_hash='test_user_hash',+ status=URLStatus.NEW,+ timestamp=datetime.utcnow(),+ last_crawled=datetime.utcnow() - timedelta(days=90)+ ),+ FoundURL(+ url='https://test.com/article',+ user_id_hash='test_user_hash',+ status=URLStatus.NEW,+ timestamp=datetime.utcnow(),+ last_crawled=None+ )+ ]+++class TestCrawlFunctional:+ """Functional tests for the crawl.py module"""++ def test_redis_connection_and_health_check(self, fake_redis, mock_settings, mock_environment):+ """Test Redis connection and health check functionality"""+ with patch('mwmbl.crawl.redis', fake_redis):+ with patch('redis.Redis.from_url', return_value=fake_redis):+ # Import after patching to ensure mocks are in place+ from mwmbl.crawl import check_redis++ # Should not raise an exception+ check_redis()++ # Test with broken Redis+ broken_redis = MagicMock()+ broken_redis.ping.side_effect = ConnectionError("Redis unavailable")++ with patch('mwmbl.crawl.redis', broken_redis):+ with pytest.raises(SystemExit):+ check_redis()++ def test_url_queue_operations(self, fake_redis, sample_found_urls):+ """Test RedisURLQueue operations with fake Redis"""+ url_queue = RedisURLQueue(fake_redis, lambda: set())++ # Test queuing URLs+ url_queue.queue_urls(sample_found_urls)++ # Verify URLs were queued+ assert fake_redis.zcard("domain-scores") > 0++ # Test getting a batch+ batch = url_queue.get_batch("test_user")+ assert len(batch) > 0+ assert all(url.startswith('http') for url in batch)++ def test_process_batch_workflow(self, fake_redis, mock_settings, mock_environment, mock_crawl_response):+ """Test the complete batch processing workflow"""+ with patch('mwmbl.crawl.redis', fake_redis):+ with patch('redis.Redis.from_url', return_value=fake_redis):+ with patch('mwmbl.crawl.url_queue') as mock_url_queue:+ with patch('mwmbl.crawl.crawl_url', return_value=mock_crawl_response):+ with patch('mwmbl.crawl.record_urls_in_database'):+ # Setup URL queue mock+ mock_url_queue.get_batch.return_value = ['https://example.com']++ # Import and test process_batch+ from mwmbl.crawl import process_batch++ # Should complete without errors+ process_batch()++ # Verify batch was pushed to Redis+ batch_data = fake_redis.lpop("batch-queue")+ assert batch_data is not None++ # Verify batch structure+ batch = json.loads(batch_data)+ assert 'user_id_hash' in batch+ assert 'timestamp' in batch+ assert 'items' in batch+ assert len(batch['items']) == 1++ def test_indexing_workflow(self, fake_redis, mock_settings, mock_environment, temp_data_path):+ """Test the indexing workflow with fake Redis"""+ # Create a sample batch in Redis+ sample_batch = HashedBatch(+ user_id_hash="test_user",+ timestamp=int(time.time() * 1000),+ items=[+ Result(+ url="https://example.com",+ title="Example",+ extract="Test content",+ score=0.8,+ term="example",+ state=1+ )+ ]+ )+ fake_redis.rpush("batch-queue", sample_batch.json())++ with patch('mwmbl.crawl.redis', fake_redis):+ with patch('redis.Redis.from_url', return_value=fake_redis):+ # Mock Counter object for index_batches return value+ from collections import Counter+ mock_counter = Counter({'example': 1})+ with patch('mwmbl.crawl.index_batches', return_value=mock_counter):+ with patch('mwmbl.crawl.RemoteIndex') as mock_remote_index:+ with patch('mwmbl.crawl.TinyIndex') as mock_tiny_index:+ with patch('requests.post') as mock_post:+ # Setup mocks+ mock_remote_index_instance = MagicMock()+ mock_remote_index.return_value = mock_remote_index_instance+ mock_remote_index_instance.retrieve.return_value = []++ mock_tiny_index_instance = MagicMock()+ mock_tiny_index.return_value.__enter__.return_value = mock_tiny_index_instance+ mock_tiny_index_instance.retrieve.return_value = []+ mock_tiny_index_instance.get_key_page_index.return_value = 0+ mock_tiny_index_instance.get_page.return_value = "test page content"++ mock_post.return_value.status_code = 200+ mock_post.return_value.text = "OK"++ # Import and test run_indexing+ from mwmbl.crawl import run_indexing++ # Should complete without errors+ run_indexing()++ # Verify batch was consumed from Redis+ remaining_batches = fake_redis.llen("batch-queue")+ assert remaining_batches == 0++ def test_crawl_url_functionality(self, mock_environment):+ """Test individual URL crawling functionality"""+ mock_html_content = b"""+ <html>+ <head><title>Test Page</title></head>+ <body>+ <p>This is test content with a <a href="/link1">link</a>.</p>+ <p>More content here.</p>+ </body>+ </html>+ """++ with patch('mwmbl.crawler.retrieve.fetch') as mock_fetch:+ with patch('mwmbl.crawler.retrieve.robots_allowed', return_value=True):+ mock_fetch.return_value = (200, mock_html_content)++ from mwmbl.crawl import crawl_url++ result = crawl_url('https://example.com')++ assert result['url'] == 'https://example.com'+ assert result['status'] == 200+ assert result['content'] is not None+ assert result['content']['title'] == 'Test Page'+ assert 'test content' in result['content']['extract'].lower()+ assert result['error'] is None++ def test_crawl_url_error_handling(self, mock_environment):+ """Test URL crawling error handling"""+ with patch('mwmbl.crawler.retrieve.fetch') as mock_fetch:+ with patch('mwmbl.crawler.retrieve.robots_allowed', return_value=True):+ # Test connection error+ mock_fetch.side_effect = ConnectionError("Connection failed")++ from mwmbl.crawl import crawl_url++ result = crawl_url('https://example.com')++ assert result['url'] == 'https://example.com'+ assert result['status'] is None+ assert result['content'] is None+ assert result['error'] is not None+ assert result['error']['name'] == 'AbortError'++ def test_robots_denied_handling(self, mock_environment):+ """Test robots.txt denial handling"""+ with patch('mwmbl.crawler.retrieve.robots_allowed', return_value=False):+ from mwmbl.crawl import crawl_url++ result = crawl_url('https://example.com')++ assert result['url'] == 'https://example.com'+ assert result['status'] is None+ assert result['content'] is None+ assert result['error'] is not None+ assert result['error']['name'] == 'RobotsDenied'++ def test_batch_queue_operations(self, fake_redis):+ """Test batch queue operations in Redis"""+ # Test pushing and popping batches+ sample_batch = {+ 'user_id_hash': 'test_user',+ 'timestamp': int(time.time() * 1000),+ 'items': []+ }++ # Push batch+ fake_redis.rpush("batch-queue", json.dumps(sample_batch))++ # Pop batch+ batch_data = fake_redis.lpop("batch-queue")+ assert batch_data is not None++ retrieved_batch = json.loads(batch_data)+ assert retrieved_batch['user_id_hash'] == 'test_user'++ def test_domain_scoring_and_url_management(self, fake_redis, sample_found_urls):+ """Test domain scoring and URL management in Redis"""+ url_queue = RedisURLQueue(fake_redis, lambda: set())++ # Queue URLs+ url_queue.queue_urls(sample_found_urls)++ # Check domain scores were created+ domain_count = fake_redis.zcard("domain-scores")+ assert domain_count > 0++ # Check individual domain URL counts+ example_count = url_queue.get_domain_count("example.com")+ test_count = url_queue.get_domain_count("test.com")++ assert example_count >= 0+ assert test_count >= 0++ def test_user_url_assignment(self, fake_redis, sample_found_urls):+ """Test user URL assignment and tracking"""+ url_queue = RedisURLQueue(fake_redis, lambda: set())++ # Queue URLs and get batch+ url_queue.queue_urls(sample_found_urls)+ batch = url_queue.get_batch("test_user")++ # Check user assignment+ user_urls = fake_redis.get("user-urls-test_user")+ assert user_urls is not None++ assigned_urls = json.loads(user_urls)+ assert len(assigned_urls) == len(batch)++ # Test URL checking+ uncrawled = url_queue.check_user_crawled_urls("test_user", batch)+ assert len(uncrawled) == 0 # All URLs should be assigned to this user++ def test_integration_workflow(self, fake_redis, mock_settings, mock_environment,+ sample_found_urls, mock_crawl_response, temp_data_path):+ """Test the complete integration workflow"""+ with patch('mwmbl.crawl.redis', fake_redis):+ with patch('redis.Redis.from_url', return_value=fake_redis):+ # Setup URL queue+ url_queue = RedisURLQueue(fake_redis, lambda: set())+ url_queue.queue_urls(sample_found_urls)++ with patch('mwmbl.crawl.url_queue', url_queue):+ with patch('mwmbl.crawl.crawl_url', return_value=mock_crawl_response):+ with patch('mwmbl.crawl.record_urls_in_database'):+ # Mock Counter object for index_batches return value+ from collections import Counter+ mock_counter = Counter({'example': 1})+ with patch('mwmbl.crawl.index_batches', return_value=mock_counter):+ with patch('mwmbl.crawl.RemoteIndex') as mock_remote_index:+ with patch('mwmbl.crawl.TinyIndex') as mock_tiny_index:+ with patch('requests.post') as mock_post:+ # Setup mocks for indexing+ mock_remote_index_instance = MagicMock()+ mock_remote_index.return_value = mock_remote_index_instance+ mock_remote_index_instance.retrieve.return_value = []++ mock_tiny_index_instance = MagicMock()+ mock_tiny_index.return_value.__enter__.return_value = mock_tiny_index_instance+ mock_tiny_index_instance.retrieve.return_value = []+ mock_tiny_index_instance.get_key_page_index.return_value = 0+ mock_tiny_index_instance.get_page.return_value = "test content"++ mock_post.return_value.status_code = 200+ mock_post.return_value.text = "OK"++ # Import functions+ from mwmbl.crawl import process_batch, run_indexing++ # Run complete workflow+ process_batch() # Should create batch in Redis++ # Verify batch was created+ batch_count = fake_redis.llen("batch-queue")+ assert batch_count == 1++ # Run indexing+ run_indexing() # Should process the batch++ # Verify batch was consumed+ remaining_batches = fake_redis.llen("batch-queue")+ assert remaining_batches == 0++ def test_error_recovery_and_resilience(self, fake_redis, mock_settings, mock_environment):+ """Test error recovery and system resilience"""+ with patch('mwmbl.crawl.redis', fake_redis):+ with patch('redis.Redis.from_url', return_value=fake_redis):+ with patch('mwmbl.crawl.url_queue') as mock_url_queue:+ with patch('mwmbl.crawl.record_urls_in_database'):+ # Test with empty batch+ mock_url_queue.get_batch.return_value = []++ from mwmbl.crawl import process_batch++ # Should handle empty batch gracefully+ process_batch()++ # Test indexing with no batches - mock sleep to avoid waiting+ with patch('time.sleep'):+ from mwmbl.crawl import run_indexing++ # Should handle no batches gracefully (will sleep and return)+ run_indexing()diff --git a/test/test_openapi.py b/test/test_openapi.pynew file mode 100644index 0000000..7f104b7--- /dev/null+++ b/test/test_openapi.py@@ -0,0 +1,200 @@+import pytest+import json+from django.test import Client+from django.contrib.auth import get_user_model+from allauth.account.models import EmailAddress+from ninja_jwt.tokens import RefreshToken++User = get_user_model()+++def user():+ """Create a test user"""+ return User.objects.create_user(+ username='testuser',+ email='[email protected]',+ password='testpass123'+ )+++def verified_user(user):+ """Create a user with verified email"""+ EmailAddress.objects.create(+ user=user,+ email='[email protected]',+ verified=True,+ primary=True+ )+ return user+++def access_token(verified_user):+ """Generate JWT access token for verified user"""+ refresh = RefreshToken.for_user(verified_user)+ return str(refresh.access_token)+++def test_openapi_spec_generation():+ """Test that the OpenAPI spec can be generated without errors"""+ client = Client()++ # Test that the OpenAPI JSON endpoint works+ response = client.get('/api/v1/platform/openapi.json')+ assert response.status_code == 200++ # Parse the JSON to ensure it's valid+ openapi_spec = response.json()++ # Basic OpenAPI spec validation+ assert 'openapi' in openapi_spec+ assert 'info' in openapi_spec+ assert 'paths' in openapi_spec+ assert 'components' in openapi_spec++ # Check that our voting endpoints are present+ paths = openapi_spec['paths']+ assert '/api/v1/platform/search-results/vote' in paths+ assert '/api/v1/platform/search-results/votes' in paths+ assert '/api/v1/platform/search-results/my-votes' in paths++ # Check that POST endpoint for voting exists+ vote_endpoint = paths['/api/v1/platform/search-results/vote']+ assert 'post' in vote_endpoint+ assert 'delete' in vote_endpoint++ # Check that GET endpoint for vote counts exists+ votes_endpoint = paths['/api/v1/platform/search-results/votes']+ assert 'get' in votes_endpoint++ # Check that GET endpoint for user vote history exists+ my_votes_endpoint = paths['/api/v1/platform/search-results/my-votes']+ assert 'get' in my_votes_endpoint+++def test_openapi_docs_page():+ """Test that the OpenAPI docs page loads without errors"""+ client = Client()++ # Test that the docs page works+ response = client.get('/api/v1/platform/docs')+ assert response.status_code == 200+ assert 'text/html' in response['Content-Type']+++def test_voting_schemas_in_openapi():+ """Test that our voting schemas are properly defined in the OpenAPI spec"""+ client = Client()++ response = client.get('/api/v1/platform/openapi.json')+ assert response.status_code == 200++ openapi_spec = response.json()+ components = openapi_spec.get('components', {})+ schemas = components.get('schemas', {})++ # Check that our voting schemas are present+ assert 'VoteRequest' in schemas+ assert 'VoteStats' in schemas+ assert 'VoteResponse' in schemas+ assert 'UserVoteHistory' in schemas+ assert 'VoteRemoveRequest' in schemas++ # Check VoteRequest schema structure+ vote_request_schema = schemas['VoteRequest']+ assert 'properties' in vote_request_schema+ properties = vote_request_schema['properties']++ assert 'url' in properties+ assert 'query' in properties+ assert 'vote_type' in properties++ # Check that vote_type has the correct enum values+ vote_type_property = properties['vote_type']+ assert 'enum' in vote_type_property+ assert 'upvote' in vote_type_property['enum']+ assert 'downvote' in vote_type_property['enum']++ # Check that descriptions are present+ assert 'description' in vote_type_property+ assert 'description' in properties['url']+ assert 'description' in properties['query']+++def test_voting_endpoint_documentation():+ """Test that voting endpoints have proper documentation in OpenAPI spec"""+ client = Client()++ response = client.get('/api/v1/platform/openapi.json')+ assert response.status_code == 200++ openapi_spec = response.json()+ paths = openapi_spec['paths']++ # Check POST /search-results/vote endpoint documentation+ vote_post = paths['/api/v1/platform/search-results/vote']['post']+ assert 'summary' in vote_post+ assert 'description' in vote_post+ assert 'tags' in vote_post+ assert 'Search Result Voting' in vote_post['tags']++ # Check GET /search-results/votes endpoint documentation+ votes_get = paths['/api/v1/platform/search-results/votes']['get']+ assert 'summary' in votes_get+ assert 'description' in votes_get+ assert 'tags' in votes_get+ assert 'Search Result Voting' in votes_get['tags']++ # Check DELETE /search-results/vote endpoint documentation+ vote_delete = paths['/api/v1/platform/search-results/vote']['delete']+ assert 'summary' in vote_delete+ assert 'description' in vote_delete+ assert 'tags' in vote_delete+ assert 'Search Result Voting' in vote_delete['tags']++ # Check GET /search-results/my-votes endpoint documentation+ my_votes_get = paths['/api/v1/platform/search-results/my-votes']['get']+ assert 'summary' in my_votes_get+ assert 'description' in my_votes_get+ assert 'tags' in my_votes_get+ assert 'Search Result Voting' in my_votes_get['tags']+++def test_schema_examples_in_openapi():+ """Test that our schemas have proper examples in the OpenAPI spec"""+ client = Client()++ response = client.get('/api/v1/platform/openapi.json')+ assert response.status_code == 200++ openapi_spec = response.json()+ schemas = openapi_spec['components']['schemas']++ # Check VoteRequest schema has examples+ vote_request = schemas['VoteRequest']+ properties = vote_request['properties']++ # Check that examples are present+ assert 'example' in properties['url']+ assert 'example' in properties['query']+ assert 'example' in properties['vote_type']++ # Check example values are reasonable+ assert 'https://' in properties['url']['example']+ assert properties['vote_type']['example'] in ['upvote', 'downvote']++ # Check VoteStats schema has examples+ vote_stats = schemas['VoteStats']+ vote_stats_properties = vote_stats['properties']++ assert 'example' in vote_stats_properties['upvotes']+ assert 'example' in vote_stats_properties['downvotes']+ assert isinstance(vote_stats_properties['upvotes']['example'], int)+ assert isinstance(vote_stats_properties['downvotes']['example'], int)