Files
hnsau/test_ownthedot.py
nathanwoodburn 8fc9bcdef7
Build Docker / Build Image (push) Successful in 56s
feat: Update OG data
2026-10-27 14:36:06 +11:00

611 lines
29 KiB
Python

import io
import os
import sys
import unittest
import zipfile
from unittest.mock import patch, MagicMock
from server import app
import nextcloud
def make_mock_nextcloud_zip() -> bytes:
"""Creates an in-memory zip archive mimicking Nextcloud public share export."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr(
"OwnTheDot/site.json",
'{"title": "Own The Dot", "hashtag": "#OwnTheDot", "nav_links": [{"label": "Home", "url": "/"}, {"label": "About", "url": "/about"}, {"label": "Articles", "url": "/articles"}, {"label": "Contact", "url": "/contact"}], "social_links": {"x": "https://x.com", "discord": "https://discord.gg/test"}, "footer": {"attribution": "OWN THE DOT by ERWIN GROEN is marked CC0 1.0 Universal.", "ecosystem_links": [{"label": "Handshake AU", "url": "https://hns.au"}]}}',
)
zf.writestr(
"OwnTheDot/home.md",
"---\nhero_title: Own the Dot\nfeatures:\n - title: Decentralized\n icon: shield\n---\nWelcome to Own The Dot.",
)
zf.writestr(
"OwnTheDot/about.md",
"---\ntitle: About Own The Dot\nbadge: Our Mission\nauthor: Handshake Australia\nshow_cc0_card: true\n---\nHandshake Australia is building the future of domain ownership with CC0 1.0 Universal dedication.",
)
zf.writestr(
"OwnTheDot/articles.md",
"---\nbadge: Knowledge Base\ntitle: Articles & Insights\n---\nIntroductory guide to articles.",
)
zf.writestr(
"OwnTheDot/articles/why-own-the-dot.md",
"---\ntitle: Why Own The Dot\nauthor: Handshake Australia\ndate: 2026-08-20\ntags: [Domain Ownership, Decentralization, Web3]\n---\nWhy own the dot content.",
)
zf.writestr(
"OwnTheDot/articles/the-handshake-protocol.md",
"---\ntitle: The Handshake Protocol\nauthor: Erwin Groen\ndate: 2026-08-21\n---\n# The Handshake Protocol\ndigital handshake details.",
)
zf.writestr(
"OwnTheDot/pages/faq.md",
"---\ntitle: Frequently Asked Questions\n---\nFrequently Asked Questions",
)
zf.writestr(
"OwnTheDot/pages/contact.md",
"---\ntitle: Contact & Community\nbadge: Get In Touch\n---\nReach out to the team.",
)
return buf.getvalue()
class TestOwnTheDot(unittest.TestCase):
@classmethod
def setUpClass(cls):
app.config['TESTING'] = True
os.environ['NEXTCLOUD_SHARE_TOKEN'] = 'DMqkYbZJMwnGyWy'
os.environ.pop('OWNTHEDOT_CONTENT_DIR', None)
os.environ.pop('NEXTCLOUD_ENABLED', None)
os.environ.pop('OWNTHEDOT_LOCAL_ONLY', None)
cls.mock_zip = make_mock_nextcloud_zip()
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
os.environ['NEXTCLOUD_SHARE_TOKEN'] = 'DMqkYbZJMwnGyWy'
os.environ.pop('OWNTHEDOT_CONTENT_DIR', None)
os.environ.pop('NEXTCLOUD_ENABLED', None)
os.environ.pop('OWNTHEDOT_LOCAL_ONLY', None)
# Patch Nextcloud provider session get to return valid mock zip by default
self.patcher = patch.object(nextcloud.nextcloud_provider._session, "get")
self.mock_get = self.patcher.start()
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.content = make_mock_nextcloud_zip()
self.mock_get.return_value = mock_resp
nextcloud.nextcloud_provider.clear_cache()
nextcloud.nextcloud_provider.warm_cache(force=True)
def tearDown(self):
self.patcher.stop()
nextcloud.nextcloud_provider._seed_initial_disk_cache()
nextcloud.nextcloud_provider._load_from_disk_cache()
def test_nextcloud_articles_loading(self):
"""Test that articles load and are parsed properly."""
articles = nextcloud.nextcloud_provider.get_articles(force_refresh=True)
self.assertGreater(len(articles), 0, "Should load at least one article")
first = articles[0]
self.assertIn('title', first)
self.assertIn('slug', first)
self.assertIn('html_content', first)
self.assertIn('display_date', first)
self.assertIn('read_time', first)
def test_article_tags_parsing(self):
"""Test that tags are parsed as clean lists of strings, not broken character arrays."""
article = nextcloud.nextcloud_provider.get_article('why-own-the-dot')
self.assertIsNotNone(article)
self.assertIsInstance(article['tags'], list)
self.assertIn("Domain Ownership", article['tags'])
self.assertIn("Decentralization", article['tags'])
self.assertIn("Web3", article['tags'])
# Test articles page rendering contains tag badge
res = self.client.get('/articles', headers={'Host': 'ownthedot.com'})
self.assertEqual(res.status_code, 200)
html = res.data.decode('utf-8')
self.assertIn('<span class="tag-badge"', html)
self.assertIn('Domain Ownership', html)
def test_nextcloud_single_article(self):
"""Test fetching a single article by slug."""
article = nextcloud.nextcloud_provider.get_article('the-handshake-protocol')
self.assertIsNotNone(article)
self.assertIn("The Handshake Protocol", article['title'])
self.assertIn("digital handshake", article['html_content'])
def test_nextcloud_about_content(self):
"""Test fetching about page markdown."""
about = nextcloud.nextcloud_provider.get_about_content(force_refresh=True)
self.assertIsNotNone(about)
self.assertIn("html_content", about)
self.assertIn("Handshake Australia", about['html_content'])
def test_ownthedot_home_route_with_host(self):
"""Test home page when host is ownthedot.com."""
response = self.client.get('/', headers={'Host': 'ownthedot.com'})
self.assertEqual(response.status_code, 200)
content = response.data.decode('utf-8')
self.assertIn("Own the Dot", content)
self.assertIn("#OwnTheDot", content)
self.assertIn("Latest Articles", content)
self.assertIn("Home", content)
self.assertIn("About", content)
self.assertIn("Articles", content)
def test_ownthedot_about_route_with_host(self):
"""Test /about when host is ownthedot.com."""
response = self.client.get('/about', headers={'Host': 'ownthedot.com'})
self.assertEqual(response.status_code, 200)
content = response.data.decode('utf-8')
self.assertIn("About Own The Dot", content)
self.assertIn("CC0 1.0 Universal", content)
def test_ownthedot_articles_list_route(self):
"""Test /articles list page."""
response = self.client.get('/articles', headers={'Host': 'ownthedot.com'})
self.assertEqual(response.status_code, 200)
content = response.data.decode('utf-8')
self.assertIn("Insights", content)
self.assertIn("The Handshake Protocol", content)
def test_ownthedot_single_article_route(self):
"""Test /articles/<slug> page."""
response = self.client.get('/articles/the-handshake-protocol', headers={'Host': 'ownthedot.com'})
self.assertEqual(response.status_code, 200)
content = response.data.decode('utf-8')
self.assertIn("The Handshake Protocol", content)
self.assertIn("Erwin Groen", content)
def test_article_open_graph_compliance(self):
"""Test that article pages render complete, valid, platform-compliant Open Graph and Twitter metadata."""
import json, re
# Test both direct ownthedot.com host and /ownthedot subpath
for host, path in [('ownthedot.com', '/articles/the-handshake-protocol'), ('hns.au', '/ownthedot/articles/the-handshake-protocol')]:
response = self.client.get(path, headers={'Host': host})
self.assertEqual(response.status_code, 200)
html = response.data.decode('utf-8')
# 1. Canonical and OG URLs must always resolve to official ownthedot.com URL
self.assertIn('<link rel="canonical" href="https://ownthedot.com/articles/the-handshake-protocol">', html)
self.assertIn('<meta property="og:url" content="https://ownthedot.com/articles/the-handshake-protocol">', html)
# 2. Open Graph Type and Site Name
self.assertIn('<meta property="og:type" content="article">', html)
self.assertIn('<meta property="og:site_name" content="Own The Dot">', html)
self.assertIn('<meta property="og:locale" content="en_AU">', html)
# 3. Titles and Descriptions
self.assertIn('<meta property="og:title" content="The Handshake Protocol | Own The Dot">', html)
self.assertIn('<meta name="twitter:title" content="The Handshake Protocol | Own The Dot">', html)
self.assertIn('<meta property="og:description"', html)
self.assertIn('<meta name="twitter:description"', html)
# 4. Images must be absolute HTTPS URLs
m_og_img = re.search(r'<meta property="og:image" content="(https://[^"]+)"', html)
self.assertIsNotNone(m_og_img, "og:image must be an absolute https:// URL")
m_tw_img = re.search(r'<meta name="twitter:image" content="(https://[^"]+)"', html)
self.assertIsNotNone(m_tw_img, "twitter:image must be an absolute https:// URL")
self.assertIn('<meta property="og:image:width" content="1200">', html)
self.assertIn('<meta property="og:image:height" content="630">', html)
# 5. Twitter Card properties
self.assertIn('<meta name="twitter:card" content="summary_large_image">', html)
self.assertIn('<meta name="twitter:site" content="@ownthedot">', html)
# 6. Article Specific Metadata
self.assertIn('<meta property="article:published_time"', html)
self.assertIn('<meta property="article:author" content="Erwin Groen">', html)
# 7. Schema.org JSON-LD Structured Data
m_json = re.search(r'<script type="application/ld\+json">(.*?)</script>', html, re.DOTALL)
self.assertIsNotNone(m_json, "Schema.org JSON-LD script must be present")
schema_data = json.loads(m_json.group(1).strip())
self.assertEqual(schema_data["@context"], "https://schema.org")
self.assertEqual(schema_data["@type"], "Article")
self.assertEqual(schema_data["headline"], "The Handshake Protocol")
self.assertEqual(schema_data["author"]["name"], "Erwin Groen")
self.assertEqual(schema_data["publisher"]["name"], "Own The Dot")
self.assertTrue(schema_data["image"][0].startswith("https://"))
def test_ownthedot_raw_markdown_download(self):
"""Test /articles/<slug>.md raw file download."""
response = self.client.get('/articles/the-handshake-protocol.md', headers={'Host': 'ownthedot.com'})
self.assertEqual(response.status_code, 200)
self.assertIn("text/plain", response.content_type)
content = response.data.decode('utf-8')
self.assertIn("# The Handshake Protocol", content)
def test_ownthedot_subpath_routes(self):
"""Test /ownthedot subpath on hns.au."""
res_home = self.client.get('/ownthedot', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_home.status_code, 200)
self.assertIn("Own the Dot", res_home.data.decode('utf-8'))
res_home_slash = self.client.get('/ownthedot/', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_home_slash.status_code, 200)
self.assertIn("Own the Dot", res_home_slash.data.decode('utf-8'))
res_about = self.client.get('/ownthedot/about', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_about.status_code, 200)
self.assertIn("About Own The Dot", res_about.data.decode('utf-8'))
res_about_slash = self.client.get('/ownthedot/about/', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_about_slash.status_code, 200)
self.assertIn("About Own The Dot", res_about_slash.data.decode('utf-8'))
res_articles = self.client.get('/ownthedot/articles', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_articles.status_code, 200)
self.assertIn("Insights", res_articles.data.decode('utf-8'))
res_articles_slash = self.client.get('/ownthedot/articles/', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_articles_slash.status_code, 200)
self.assertIn("Insights", res_articles_slash.data.decode('utf-8'))
def test_rss_feed(self):
"""Test RSS feed generation and W3C validity."""
response = self.client.get('/feed.xml', headers={'Host': 'ownthedot.com'})
self.assertEqual(response.status_code, 200)
self.assertIn("application/rss+xml", response.content_type)
content = response.data.decode('utf-8')
self.assertIn("<rss version=\"2.0\"", content)
self.assertIn('xmlns:dc="http://purl.org/dc/elements/1.1/"', content)
self.assertIn("<title>Own The Dot</title>", content)
self.assertIn("<item>", content)
self.assertIn("<dc:creator>", content)
# Raw <author> without email fails W3C RSS 2.0 validation; dc:creator is compliant
self.assertNotIn("<author>", content)
def test_site_config_loading(self):
"""Test that global site config is loaded from Nextcloud site.json."""
config = nextcloud.nextcloud_provider.get_site_config(force_refresh=True)
self.assertIn("title", config)
self.assertIn("social_links", config)
self.assertIn("x", config["social_links"])
def test_home_data_loading(self):
"""Test that home page data is loaded from Nextcloud home.md."""
home_data = nextcloud.nextcloud_provider.get_home_data(force_refresh=True)
self.assertIn("hero_title", home_data)
self.assertIn("features", home_data)
self.assertGreater(len(home_data["features"]), 0)
def test_custom_page_routing(self):
"""Test that custom pages in Nextcloud (e.g. pages/faq.md) render properly."""
# Top-level route on ownthedot.com
res = self.client.get('/faq', headers={'Host': 'ownthedot.com'}, follow_redirects=True)
self.assertEqual(res.status_code, 200)
self.assertIn("Frequently Asked Questions", res.data.decode('utf-8'))
# Subpath route on hns.au
res_sub = self.client.get('/ownthedot/faq', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_sub.status_code, 200)
self.assertIn("Frequently Asked Questions", res_sub.data.decode('utf-8'))
def test_api_refresh(self):
"""Test cache refresh API endpoint."""
response = self.client.get('/api/otd/refresh')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertEqual(data['status'], 'ok')
self.assertGreater(data['article_count'], 0)
self.assertIn('source', data)
self.assertIn('source_type', data['source'])
self.assertIn('location', data['source'])
def test_api_source(self):
"""Test data source inspection API endpoint."""
response = self.client.get('/api/otd/source')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertEqual(data['status'], 'ok')
self.assertIn('source', data)
self.assertIn('source_type', data['source'])
self.assertIn('location', data['source'])
self.assertIn('site_title', data)
def test_api_health_success(self):
"""Test that /api/health pre-warms cache and returns 200 with healthy status."""
nextcloud.nextcloud_provider.clear_cache()
response = self.client.get('/api/health')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertTrue(data.get('healthy'))
self.assertEqual(data.get('status'), 'ok')
self.assertGreater(data.get('article_count', 0), 0)
self.assertIn('cached_entries', data)
self.assertIn('articles_list', data['cached_entries'])
self.assertIn('site_config', data['cached_entries'])
def test_api_health_failure(self):
"""Test that /api/health returns 503 unhealthy when Nextcloud cannot be reached."""
mock_fail = MagicMock()
mock_fail.status_code = 500
self.mock_get.return_value = mock_fail
nextcloud.nextcloud_provider.clear_cache(clear_disk=True)
response = self.client.get('/api/health')
self.assertEqual(response.status_code, 503)
data = response.get_json()
self.assertFalse(data.get('healthy'))
self.assertEqual(data.get('status'), 'unhealthy')
self.assertIn('Failed to connect to Nextcloud', data.get('error', ''))
def test_nextcloud_error_handling(self):
"""Test that Nextcloud failures return a 503 status with an error page / JSON."""
mock_fail = MagicMock()
mock_fail.status_code = 500
self.mock_get.return_value = mock_fail
nextcloud.nextcloud_provider.clear_cache(clear_disk=True)
# Page route should return 503 error page
res_page = self.client.get('/', headers={'Host': 'ownthedot.com'})
self.assertEqual(res_page.status_code, 503)
self.assertIn("Unable to Load", res_page.data.decode('utf-8'))
# API route should return 503 JSON with error
res_api = self.client.get('/api/otd/refresh')
self.assertEqual(res_api.status_code, 503)
api_data = res_api.get_json()
self.assertEqual(api_data['status'], 'error')
self.assertIn('Failed to connect to Nextcloud', api_data['error'])
def test_contact_page(self):
"""Test that contact page renders from pages/contact.md on both domains."""
# Test on ownthedot.com
res = self.client.get('/contact', headers={'Host': 'ownthedot.com'}, follow_redirects=True)
self.assertEqual(res.status_code, 200)
html = res.data.decode('utf-8')
self.assertIn("Contact", html)
self.assertIn("Get In Touch", html)
# Test on hns.au
res_sub = self.client.get('/ownthedot/contact', headers={'Host': 'hns.au'}, follow_redirects=True)
self.assertEqual(res_sub.status_code, 200)
html_sub = res_sub.data.decode('utf-8')
self.assertIn("Contact", html_sub)
self.assertIn("Get In Touch", html_sub)
def test_about_data_customization(self):
"""Test that about page receives about_data and renders dynamic badges and cards."""
res = self.client.get('/about', headers={'Host': 'ownthedot.com'})
self.assertEqual(res.status_code, 200)
html = res.data.decode('utf-8')
self.assertIn("Our Mission", html)
self.assertIn("Handshake Australia", html)
def test_frontmatter_scalar_parsing(self):
"""Test that frontmatter parser correctly handles booleans, ints, floats, and strings."""
sample_md = """---
title: Test Frontmatter
show_flag: true
hide_flag: false
item_count: 42
rating: 4.85
tags: [alpha, beta]
---
Content here"""
data = nextcloud.nextcloud_provider._parse_markdown_file(sample_md, "test-frontmatter")
self.assertEqual(data["title"], "Test Frontmatter")
self.assertIs(data["show_flag"], True)
self.assertIs(data["hide_flag"], False)
self.assertEqual(data["item_count"], 42)
self.assertEqual(data["rating"], 4.85)
self.assertEqual(data["tags"], ["alpha", "beta"])
def test_legacy_owndot_redirects(self):
"""Test that legacy /own-the-dot routes redirect with 301 to /ownthedot."""
res_root = self.client.get('/own-the-dot', follow_redirects=False)
self.assertEqual(res_root.status_code, 301)
self.assertTrue(res_root.location.endswith('/ownthedot'))
def test_ownthedot_favicons(self):
"""Test that ownthedot has valid favicons like hns.au."""
res_otd = self.client.get('/', headers={'Host': 'ownthedot.com'})
self.assertEqual(res_otd.status_code, 200)
html_otd = res_otd.data.decode('utf-8')
res_hns = self.client.get('/', headers={'Host': 'hns.au'})
self.assertEqual(res_hns.status_code, 200)
html_hns = res_hns.data.decode('utf-8')
# Check favicon link tags count and content
self.assertEqual(html_otd.count('<link rel="icon"'), html_hns.count('<link rel="icon"'))
self.assertIn('<link rel="icon" type="image/png" sizes="600x627" href="/assets/img/favicon.png">', html_otd)
self.assertIn('<link rel="icon" type="image/png" sizes="600x627" href="/assets/img/favicon-light.png" media="(prefers-color-scheme: dark)">', html_otd)
# Check subpath /ownthedot on hns.au
res_sub = self.client.get('/ownthedot', headers={'Host': 'hns.au'})
self.assertEqual(res_sub.status_code, 200)
html_sub = res_sub.data.decode('utf-8')
self.assertEqual(html_sub.count('<link rel="icon"'), 7)
self.assertIn('/assets/img/favicon.png', html_sub)
self.assertIn('/assets/img/favicon-light.png', html_sub)
# Check static endpoints for favicons
res_png_otd = self.client.get('/favicon.png', headers={'Host': 'ownthedot.com'})
self.assertEqual(res_png_otd.status_code, 200)
self.assertIn('image/png', res_png_otd.content_type)
res_png_otd.close()
res_ico_otd = self.client.get('/favicon.ico', headers={'Host': 'ownthedot.com'})
self.assertEqual(res_ico_otd.status_code, 200)
res_ico_otd.close()
res_ico_hns = self.client.get('/favicon.ico', headers={'Host': 'hns.au'})
self.assertEqual(res_ico_hns.status_code, 200)
res_ico_hns.close()
def test_ownthedot_sitemap(self):
"""Test auto-generated sitemap.xml on ownthedot.com."""
import xml.etree.ElementTree as ET
res = self.client.get('/sitemap.xml', headers={'Host': 'ownthedot.com'})
self.assertEqual(res.status_code, 200)
self.assertIn('application/xml', res.content_type)
xml_content = res.data.decode('utf-8')
# Must be accurate for ownthedot.com, not hns.au
self.assertIn('https://ownthedot.com/', xml_content)
self.assertNotIn('https://hns.au', xml_content)
# Must parse as valid XML
root = ET.fromstring(xml_content)
urls = [url.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text for url in root]
# Verify core pages
self.assertIn('https://ownthedot.com/', urls)
self.assertIn('https://ownthedot.com/about', urls)
self.assertIn('https://ownthedot.com/articles', urls)
# Verify all articles are included
self.assertIn('https://ownthedot.com/articles/why-own-the-dot', urls)
self.assertIn('https://ownthedot.com/articles/the-handshake-protocol', urls)
# Verify custom pages from Nextcloud
self.assertIn('https://ownthedot.com/faq', urls)
self.assertIn('https://ownthedot.com/contact', urls)
# Check lastmod and priority attributes
article_nodes = [
url for url in root
if url.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text == 'https://ownthedot.com/articles/why-own-the-dot'
]
self.assertEqual(len(article_nodes), 1)
lastmod = article_nodes[0].find('{http://www.sitemaps.org/schemas/sitemap/0.9}lastmod')
self.assertIsNotNone(lastmod)
self.assertEqual(lastmod.text, '2026-08-20')
def test_ownthedot_sitemap_subpath(self):
"""Test /ownthedot/sitemap.xml on hns.au returns ownthedot.com sitemap."""
res = self.client.get('/ownthedot/sitemap.xml', headers={'Host': 'hns.au'})
self.assertEqual(res.status_code, 200)
self.assertIn('application/xml', res.content_type)
xml_content = res.data.decode('utf-8')
self.assertIn('https://ownthedot.com/articles/why-own-the-dot', xml_content)
self.assertNotIn('https://hns.au/blog', xml_content)
def test_hnsau_sitemap_preserved(self):
"""Test that /sitemap.xml on hns.au still serves hns.au sitemap."""
res = self.client.get('/sitemap.xml', headers={'Host': 'hns.au'})
self.assertEqual(res.status_code, 200)
self.assertIn('application/xml', res.content_type)
xml_content = res.data.decode('utf-8')
self.assertIn('https://hns.au/', xml_content)
self.assertNotIn('https://ownthedot.com', xml_content)
def test_dynamic_article_in_sitemap(self):
"""Test that adding a new article immediately appears in auto-generated sitemap."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr(
"OwnTheDot/site.json",
'{"title": "Own The Dot", "nav_links": [{"label": "Home", "url": "/"}]}',
)
zf.writestr(
"OwnTheDot/articles/fresh-new-post.md",
"---\ntitle: Fresh New Post\ndate: 2026-09-01\n---\nFresh new content.",
)
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.content = buf.getvalue()
self.mock_get.return_value = mock_resp
nextcloud.nextcloud_provider.clear_cache()
sitemap_xml = nextcloud.nextcloud_provider.generate_sitemap()
self.assertIn('https://ownthedot.com/articles/fresh-new-post', sitemap_xml)
self.assertIn('<lastmod>2026-09-01</lastmod>', sitemap_xml)
def test_media_retrieval_and_routes(self):
"""Test that media files are served with proper content-type and 200 status."""
# 1. Direct provider retrieval
res = nextcloud.nextcloud_provider.get_media("what-does-it-mean-to-own-the-dot.png")
self.assertIsNotNone(res)
data, mimetype = res
self.assertEqual(mimetype, "image/png")
self.assertGreater(len(data), 1000)
# 2. Flask routes
r1 = self.client.get("/media/what-does-it-mean-to-own-the-dot.png")
self.assertEqual(r1.status_code, 200)
self.assertEqual(r1.content_type, "image/png")
r2 = self.client.get("/ownthedot/media/what-does-it-mean-to-own-the-dot.png")
self.assertEqual(r2.status_code, 200)
self.assertEqual(r2.content_type, "image/png")
r3 = self.client.get("/articles/media/what-does-it-mean-to-own-the-dot.png")
self.assertEqual(r3.status_code, 200)
self.assertEqual(r3.content_type, "image/png")
# 3. Missing image returns 404
mock_404 = MagicMock()
mock_404.status_code = 404
self.mock_get.return_value = mock_404
r4 = self.client.get("/media/this-image-definitely-does-not-exist.png")
self.assertEqual(r4.status_code, 404)
def test_local_mirror_mode(self):
"""Test that OWNTHEDOT_CONTENT_DIR operates fully offline with zero remote network calls."""
import tempfile, shutil
temp_dir = tempfile.mkdtemp()
try:
# Setup mock local mirror directory
with open(os.path.join(temp_dir, "site.json"), "w") as f:
f.write('{"title": "Local Mirror Site", "nav_links": []}')
with open(os.path.join(temp_dir, "home.md"), "w") as f:
f.write('---\nhero_title: Local Home\n---\nLocal home body')
with open(os.path.join(temp_dir, "about.md"), "w") as f:
f.write('---\ntitle: Local About\n---\nLocal about body')
with open(os.path.join(temp_dir, "articles.md"), "w") as f:
f.write('---\ntitle: Local Articles\n---\nLocal articles intro')
os.makedirs(os.path.join(temp_dir, "articles"), exist_ok=True)
with open(os.path.join(temp_dir, "articles", "local-test-article.md"), "w") as f:
f.write('---\ntitle: Local Test Article\ndate: 2026-10-27\n---\nLocal article content')
os.makedirs(os.path.join(temp_dir, "media"), exist_ok=True)
with open(os.path.join(temp_dir, "media", "local-img.png"), "wb") as f:
f.write(b"\x89PNG\r\n\x1a\nlocalmockbytes")
with patch.dict(os.environ, {"OWNTHEDOT_CONTENT_DIR": temp_dir}):
nextcloud.nextcloud_provider.clear_cache()
nextcloud.nextcloud_provider.warm_cache(force=True)
# Check source info
info = nextcloud.nextcloud_provider.get_source_info()
self.assertEqual(info["source_type"], "local_mirror")
self.assertFalse(info["is_remote"])
self.assertEqual(info["location"], temp_dir)
# Check articles loaded from local mirror
articles = nextcloud.nextcloud_provider.get_articles()
self.assertEqual(len(articles), 1)
self.assertEqual(articles[0]["slug"], "local-test-article")
self.assertEqual(articles[0]["title"], "Local Test Article")
# Check media loaded from local mirror
res = nextcloud.nextcloud_provider.get_media("local-img.png")
self.assertIsNotNone(res)
data, mime = res
self.assertEqual(mime, "image/png")
self.assertIn(b"localmockbytes", data)
# Check /api/otd/refresh endpoint
r = self.client.get("/api/otd/refresh")
self.assertEqual(r.status_code, 200)
data = r.get_json()
self.assertEqual(data["source"]["source_type"], "local_mirror")
self.assertEqual(data["article_count"], 1)
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
nextcloud.nextcloud_provider.clear_cache()
if __name__ == '__main__':
unittest.main()