import contextlib import io import os import re from pathlib import Path import runpy import tempfile import unittest from unittest.mock import patch import urllib.request from tools.publish import SameOriginRedirect, main class DistributionTests(unittest.TestCase): def test_documentation_links_and_neomutt_example(self): root=Path(__file__).resolve().parent for document in [root/'README.md',root/'DISTRIBUTION.md',*sorted((root/'docs').glob('*.md'))]: for target in re.findall(r'\]\(([^)]+)\)',document.read_text()): if '://' in target or target.startswith('#'):continue self.assertTrue((document.parent/target.split('#',1)[0]).is_file(),(document.name,target)) example=(root/'examples/neomuttrc').read_text() self.assertIn('pages task from-mail',example) self.assertIn('pages contacts query --neomutt -- %s',example) self.assertNotIn('--include-body',example) def test_version_matches(self): module=runpy.run_path(str(Path(__file__).with_name('pages'))) self.assertEqual(module['VERSION'],Path('VERSION').read_text().strip()) output=io.StringIO() with contextlib.redirect_stdout(output),self.assertRaises(SystemExit) as exited:module['main'](['--version']) self.assertEqual(exited.exception.code,0) self.assertIn(module['VERSION'],output.getvalue()) def test_credential_redirect_is_same_origin_only(self): redirect=SameOriginRedirect() req=urllib.request.Request('https://git.anya.jp/asset',headers={'Authorization':'token synthetic'}) for url in ['https://other.invalid/asset','http://git.anya.jp/asset']: with self.assertRaises(RuntimeError):redirect.redirect_request(req,None,302,'',{},url) new=redirect.redirect_request(req,None,302,'',{},'https://git.anya.jp/attachment') self.assertEqual(new.get_header('Authorization'),'token synthetic') def test_publisher_rejects_wrong_tag_before_network(self): env={'GITEA_SERVER_URL':'https://git.anya.jp','GITEA_REPOSITORY':'anya/pages-cli','GITEA_TOKEN':'synthetic','GITEA_REF':'refs/tags/v9.9.9'} with patch.dict(os.environ,env),patch('urllib.request.build_opener') as network,self.assertRaises(SystemExit):main() network.assert_not_called() def test_publisher_rejects_tampered_artifacts(self): cwd=Path.cwd() with tempfile.TemporaryDirectory() as root: try: os.chdir(root);Path('VERSION').write_text('0.1.0');Path('release').mkdir() Path('release/asset').write_bytes(b'bad') Path('release/test-SHA256SUMS').write_text('0'*64+' asset\n') env={'GITEA_SERVER_URL':'https://git.anya.jp','GITEA_REPOSITORY':'anya/pages-cli','GITEA_TOKEN':'synthetic','GITEA_REF':'refs/tags/v0.1.0','GITEA_SHA':'a'*40} with patch.dict(os.environ,env),patch('subprocess.check_output',return_value='a'*40),patch('urllib.request.build_opener') as opener,self.assertRaises(SystemExit):main() opener.return_value.open.assert_not_called() finally:os.chdir(cwd) if __name__=='__main__':unittest.main()