#!/usr/bin/env python3 """Rendered HTTP compatibility and crawl validation against a running website.""" import argparse,concurrent.futures,json,sys,urllib.request,urllib.parse,xml.etree.ElementTree as ET from html.parser import HTMLParser from pathlib import Path class Page(HTMLParser): def __init__(self):super().__init__();self.links=[];self.assets=[];self.canonical=[];self.description=[];self.title='';self.in_title=False;self.ld=[];self.in_ld=False def handle_starttag(self,tag,attrs): a=dict(attrs) if tag=='a' and a.get('href'):self.links.append(a['href']) if tag=='img' and a.get('src'):self.assets.append(a['src']) if tag=='script' and a.get('src'):self.assets.append(a['src']) if tag=='link' and a.get('rel')=='stylesheet':self.assets.append(a['href']) if tag=='link' and a.get('rel')=='canonical':self.canonical.append(a.get('href')) if tag=='meta' and a.get('name')=='description':self.description.append(a.get('content')) if tag=='title':self.in_title=True if tag=='script' and a.get('type')=='application/ld+json':self.in_ld=True;self.ld.append('') def handle_endtag(self,tag): if tag=='title':self.in_title=False if tag=='script':self.in_ld=False def handle_data(self,data): if self.in_title:self.title+=data if self.in_ld:self.ld[-1]+=data def run(origin,production=False): root=Path(__file__).resolve().parents[1];public=json.loads((root/'Tests/public-urls.json').read_text())['urls'] graph=json.loads((root/'PlotDirector.Website/Content/solver.json').read_text());editorial=json.loads((root/'PlotDirector.Website/Content/WritingSolver/Editorial/pages-v1.json').read_text()) urls={urllib.parse.urlsplit(u).path for u in public} urls|={'/problem-solver','/problem-solver/browse'}|{'/problem-solver/browse/'+a['id'] for a in editorial['areas']} urls|={'/problem-solver/'+s['slug'] for s in graph['solutions'] if s['active']} urls|={'/features/'+s['slug'] for s in graph['features'] if s['active']} errors=[];pages={};assets=set();links=set() def fetch(path): with urllib.request.urlopen(origin+path,timeout=30) as r:return r.status,r.read(),dict(r.headers) def check(path): try: status,data,headers=fetch(path);p=Page();p.feed(data.decode());return path,p,headers,None except Exception as e:return path,None,{},str(e) with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool: for path,p,headers,error in pool.map(check,sorted(urls)): if error:errors.append(path+': '+error);continue pages[path]=p if len(p.canonical)!=1 or p.canonical[0]!='https://plotdirector.com'+path:errors.append(path+': wrong canonical') if not p.title.strip() or not p.description or not p.description[0]:errors.append(path+': missing metadata') if not p.ld:errors.append(path+': missing JSON-LD') for ld in p.ld: try:json.loads(ld) except ValueError:errors.append(path+': invalid JSON-LD') robots=headers.get('X-Robots-Tag','') if not production and 'noindex' not in robots:errors.append(path+': Development indexing exposure') if production and path in {urllib.parse.urlsplit(u).path for u in public} and 'noindex' in robots:errors.append(path+': Production public page noindex') for link in p.links: if link.startswith('/') and not link.startswith('//') and not link.startswith('/Pricing/Checkout'): parsed=urllib.parse.urlsplit(link);links.add(parsed.path) assets.update(urllib.parse.urlsplit(a).path for a in p.assets if a.startswith('/')) if 'service-worker' in ' '.join(p.assets) or any('site.webmanifest' in a for a in p.assets):errors.append(path+': application PWA asset') for path in sorted((assets|links)-set(pages)): try:fetch(path) except Exception as e:errors.append(path+': broken internal link/asset '+str(e)) _,sitemap,_=fetch('/sitemap.xml');sitemap_urls={u.text for u in ET.fromstring(sitemap).findall('.//{*}loc')} if sitemap_urls!=set(public):errors.append('Sitemap differs from approved Production URL inventory') for path in ['/missing-page-acceptance','/help/missing/missing','/site.webmanifest','/service-worker.js','/hubs/word-companion-follow']: try:fetch(path);errors.append(path+': expected 404') except urllib.error.HTTPError as e: if e.code!=404:errors.append(path+': expected 404 got '+str(e.code)) report={'origin':origin,'productionPolicy':production,'baselineUrls':len(public),'renderedPages':len(pages),'internalPaths':len(links),'assets':len(assets),'errors':errors,'passed':not errors} print(json.dumps(report,indent=2));return bool(errors) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--origin',required=True);p.add_argument('--production',action='store_true');a=p.parse_args();sys.exit(run(a.origin.rstrip('/'),a.production))