repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

253 lines · 25.2 KB · download this file

#!/usr/bin/env python3
"""Exercise Perl CGI with a temporary catalogue; never change live credentials or media."""
# How every suite in tests/ works (this one is the broadest):
#   - It builds a throwaway site in a temporary folder (BLOWFISH_ROOT): its
#     folders, keys and a catalogue made by this release's own --migrate.
#   - request() (run() in other suites) plays the part of httpd: it puts a
#     request's details in the environment as httpd would (REQUEST_METHOD,
#     SCRIPT_NAME, QUERY_STRING, cookies, the body on standard input), runs the
#     script named on the command line (cgi-bin/site.pl, or tests/fcgi-cgi.pl
#     to go through a real FastCGI worker), and splits the answer into
#     status, headers and HTML.
#   - signin.sign() turns REMOTE_USER into a real session cookie, so admin
#     requests are signed in as that user.
#   - check(condition, what) stops the suite at the first failure, saying
#     what was being checked; each check that passes prints PASS and its text.
#   - The temporary folder is deleted at the end; nothing real is touched.
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,io,wave,struct,zlib,secrets,shutil
import html as H
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from sample_content import ensure_samples, start_catalog
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent));import signin  # signs requests in (REMOTE_USER → session cookie)
script=str(pathlib.Path(sys.argv[1]).resolve())
def image_size(path):
 """Width and height of a PNG, JPEG or WebP file, without extra libraries."""
 b=pathlib.Path(path).read_bytes()
 if b[:8]==b'\x89PNG\r\n\x1a\n':return struct.unpack('>II',b[16:24])
 if b[:4]==b'RIFF' and b[8:12]==b'WEBP':
  c=b[12:16]
  if c==b'VP8X':return (1+int.from_bytes(b[24:27],'little'),1+int.from_bytes(b[27:30],'little'))
  if c==b'VP8L':v=int.from_bytes(b[21:25],'little');return (1+(v&0x3fff),1+((v>>14)&0x3fff))
  if c==b'VP8 ':w,h=struct.unpack('<HH',b[26:30]);return (w&0x3fff,h&0x3fff)
 if b[:2]==b'\xff\xd8':
  i=2
  while i<len(b):
   while b[i]!=0xff:i+=1
   while b[i]==0xff:i+=1
   m=b[i];i+=1
   if 0xc0<=m<=0xcf and m not in (0xc4,0xc8,0xcc):h,w=struct.unpack('>HH',b[i+3:i+7]);return (w,h)
   i+=struct.unpack('>H',b[i:i+2])[0]
 raise ValueError('unknown image')
with tempfile.TemporaryDirectory(prefix='blowfish-perl-test-') as tmp:
 root=pathlib.Path(tmp); data=root/'var/db/blowfishcms';data.mkdir(parents=True)
 for folder in ['admin/tmp','admin/sessions']: (data/folder).mkdir(parents=True)
 (data/'admin/csrf.key').write_text(secrets.token_hex(32))
 for kind in ['photography','music','artwork','blog']:(root/'media/blowfishcms'/kind).mkdir(parents=True)
 start_catalog(data/'catalog.sqlite')
 with signin.connect(data/'catalog.sqlite') as copy:ensure_samples(copy)
 # The pages are rebuilt from the sample site's seed by the migration below.
 with signin.connect(data/'catalog.sqlite') as copy:
  for table in ['pages','page_blocks']:copy.execute('drop table if exists '+table)
 con=sqlite3.connect(data/'catalog.sqlite');con.row_factory=sqlite3.Row
 before=[dict(r) for r in con.execute('select * from uploads')]
 env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_PAGES_SEED':str(pathlib.Path(__file__).resolve().parent/'fixtures/sample-pages-seed.json')}
 subprocess.run(['perl',script,'--migrate'],env=env,check=True)
 subprocess.run(['perl',script,'--migrate'],env=env,check=True)
 # This suite checks how pages render, so every page is switched on (pages that are off answer not found).
 con.execute("insert or replace into site_settings(key,value) values ('nav',?)",(json.dumps([{'page':r[0],'visible':1} for r in con.execute('select slug from pages order by created_at,slug')]),));con.commit()
 assert con.execute('select count(*) from uploads').fetchone()[0]==len(before)
 cookie='';csrf='';checks=[]
 def check(v,msg):
  assert v,msg
  checks.append(msg);print('PASS',msg,flush=True)
 def request(path='/admin/',fields=None,files=(),auth=True,headers=None):
  global cookie,csrf
  url=urllib.parse.urlsplit(path);body=b'';ctype='application/x-www-form-urlencoded'
  if fields is not None:
   if files:
    boundary='---'+secrets.token_hex(12);parts=[]
    for k,v in fields.items():
     for value in v if isinstance(v,list) else [v]:parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{value}\r\n'.encode())
    for key,name,mime,content in files:parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"; filename="{name}"\r\nContent-Type: {mime}\r\n\r\n'.encode()+content+b'\r\n')
    body=b''.join(parts)+f'--{boundary}--\r\n'.encode();ctype='multipart/form-data; boundary='+boundary
   else:body=urllib.parse.urlencode(fields,doseq=True).encode()
  e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST' if fields is not None else 'GET','SCRIPT_NAME':url.path,'QUERY_STRING':url.query,'CONTENT_TYPE':ctype,'CONTENT_LENGTH':str(len(body)),'REMOTE_USER':'admin' if auth else '', 'HTTP_COOKIE':cookie,'HTTP_ORIGIN':'https://example.net','REMOTE_ADDR':'192.0.2.1',**(headers or {})}
  p=subprocess.run(['perl',script],input=body,env=signin.sign(e),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  assert p.returncode==0,(p.stderr.decode(),p.stdout[:300])
  raw=p.stdout.decode();head,html=raw.split('\r\n\r\n',1);hdr=dict(line.split(': ',1) for line in head.split('\r\n'))
  if 'Set-Cookie' in hdr:cookie=hdr['Set-Cookie'].split(';')[0];csrf=cookie.split('=',1)[1]
  if hdr['Status']=='303' and hdr.get('Location','').startswith('/admin/?kind=') and 'kind=blog' not in hdr['Location']:return request(hdr['Location'])
  return int(hdr['Status']),html,hdr
 def submit(action,kind='photography',**values):return request(fields={'csrf':csrf,'action':action,'kind':kind,**values})
 def png(width=48,height=32):
  def chunk(k,d):return struct.pack('>I',len(d))+k+d+struct.pack('>I',zlib.crc32(k+d)&0xffffffff)
  return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,2,0,0,0))+chunk(b'IDAT',zlib.compress((b'\0'+bytes([30,100,140])*width)*height))+chunk(b'IEND',b'')+b'<?php strip me ?>'
 status,html,_=request(auth=False);check(status==403,'admin requires trusted authenticated user')
 first_folder=(con.execute("select folder from uploads where kind='photography' limit 1").fetchone() or [''])[0]
 status,html,_=request('/admin/?kind=photography&folder='+urllib.parse.quote(first_folder));check(status==200 and 'class="lib-items"' in html and html.count('<li class="lib-item"')==html.count('<aside class="lib-panel"')>0 and 'data-bulk="folder"' in html,'admin renders the library with an edit panel per photo and bulk controls')
 status,_,_=request(fields={'action':'delete','kind':'music','csrf':'bad'});check(status==403,'CSRF rejected')
 request(fields={'csrf':csrf,'kind':'photography','action':'folder_create','folder':'','name':'QA'})
 status,html,_=request(fields={'csrf':csrf,'kind':'photography','action':'upload','folder':'qa'},files=[('media','first.png','image/png',png()),('media','second.png','image/png',png())]);check('2 uploads published' in html,'batch photo upload')
 photos=[dict(r) for r in con.execute("select * from uploads where folder='qa'")];check(len(photos)==2,'photo records stored')
 for photo in photos:
  check(b'<?php' not in (root/'media/blowfishcms/pictures/qa'/photo['filename']).read_bytes(),'image re-encoded')
  check((root/'media/blowfishcms/pictures/qa'/photo['thumbnail']).exists(),'thumbnail created')
 ids=[p['id'] for p in photos]
 fetch={'HTTP_X_REQUESTED_WITH':'fetch'}
 for i,id in enumerate(ids):
  status,body,_=request(fields={'csrf':csrf,'kind':'photography','action':'item_save','id':id,'title':f'Photo {i} <script>','folder':'qa','description':'Caption é'},headers=fetch)
  check(status==200 and json.loads(body)['item']['title']==f'Photo {i} <script>','panel saves a photo (autosave request)')
 check(all(r['description']=='Caption é' for r in con.execute("select * from uploads where folder='qa'")),'Unicode edits preserved')
 status,body,_=request(fields={'csrf':csrf,'kind':'photography','action':'item_save','id':ids[0],'title':'','folder':'qa','description':''},headers=fetch)
 check(status==400 and con.execute('select title from uploads where id=?',(ids[0],)).fetchone()[0]=='Photo 0 <script>','an empty title is refused and nothing changes')
 status,body,_=request(fields={'csrf':csrf,'kind':'music','action':'item_save','id':ids[0],'title':'x'},headers=fetch)
 check(status==400,'an item can only be saved in its own library')
 status,_,hdr=request(fields={'csrf':csrf,'kind':'photography','action':'item_save','id':ids[1],'title':'Photo 1 <script>','folder':'qa','description':'Caption é'})
 check(status==200,'panel saves without JavaScript too')
 order=lambda:[r[0] for r in con.execute("select id from uploads where kind='photography' and folder='qa' order by sort_order,created_at desc,id desc")]
 everything=order();shuffled=everything[::-1]
 status,body,_=request(fields={'csrf':csrf,'kind':'photography','action':'reorder','ids':shuffled},headers=fetch)
 check(status==200 and order()==shuffled,'dragged order saved in one request')
 status,body,_=request(fields={'csrf':csrf,'kind':'photography','action':'reorder','ids':shuffled[1:]},headers=fetch)
 check(status==400 and order()==shuffled,'an incomplete order is refused')
 other=con.execute("select id from uploads where kind='photography' and folder<>'qa'").fetchone()
 if other: check(request(fields={'csrf':csrf,'kind':'photography','action':'reorder','ids':[shuffled[0],other[0]]},headers=fetch)[0]==400,'pictures from different folders are not arranged together')
 request(fields={'csrf':csrf,'kind':'photography','action':'folder_create','folder':'qa','name':'Bulk QA'})
 status,body,_=request(fields={'csrf':csrf,'kind':'photography','action':'bulk','op':'folder','folder':'qa/bulk-qa','ids':ids},headers=fetch)
 check(status==200 and 'Moved 2 pictures' in json.loads(body)['message'] and all(r[0]=='qa/bulk-qa' for r in con.execute('select folder from uploads where id in (?,?)',ids)),'selected pictures moved to a folder together')
 check(all((root/'media/blowfishcms/pictures/qa/bulk-qa'/r[0]).exists() and not (root/'media/blowfishcms/pictures/qa'/r[0]).exists() for r in con.execute('select filename from uploads where id in (?,?)',ids)),'moved pictures moved on disk too')
 request(fields={'csrf':csrf,'kind':'photography','action':'bulk','op':'folder','folder':'qa','ids':ids},headers=fetch)
 submit('move',id=ids[0],direction='position',position='1')
 check(con.execute("select id from uploads where kind='photography' and folder='qa' order by sort_order,created_at desc,id desc").fetchone()[0]==ids[0],'move to position persists')
 submit('move',id=ids[0],direction='down')
 check(con.execute("select id from uploads where kind='photography' and folder='qa' order by sort_order,created_at desc,id desc").fetchall()[1][0]==ids[0],'move down persists')
 status,html,_=request('/photography/');check('&lt;script&gt;' in html and '<script>Photo' not in html,'gallery escapes titles')
 wav=io.BytesIO()
 with wave.open(wav,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(8000);w.writeframes(b'\0\0'*1600)
 status,html,_=request(fields={'csrf':csrf,'kind':'music','action':'upload','collection':'QA'},files=[('media','test.wav','audio/wav',wav.getvalue()),('artwork','cover.png','image/png',png())]);check('1 upload published' in html,'music with album artwork uploads')
 song=dict(con.execute("select * from uploads where collection='QA' and kind='music'").fetchone());old=song['artwork']
 check(bool(old) and (root/'media/blowfishcms/artwork'/old).exists(),'artwork stored')
 status,html,_=request('/music/');check(old in html and '<audio controls' in html,'public track displays art and player')
 status,html,_=request(fields={'csrf':csrf,'kind':'music','action':'artwork','id':song['id']},files=[('artwork','new.png','image/png',png())]);check('Artwork updated' in html and not (root/'media/blowfishcms/artwork'/old).exists(),'replace art removes previous image')
 submit('artwork','music',id=song['id'],remove_artwork='1');check(con.execute('select artwork from uploads where id=?',(song['id'],)).fetchone()[0]=='','artwork removal')
 # WebP decoder compatibility using libwebp CLI, without adding an application dependency.
 (root/'test.png').write_bytes(png());subprocess.run(['cwebp','-quiet',str(root/'test.png'),'-o',str(root/'test.webp')],check=True)
 status,html,_=request(fields={'csrf':csrf,'kind':'photography','action':'upload','folder':'qa'},files=[('media','test.webp','image/webp',(root/'test.webp').read_bytes())]);check('1 upload published' in html,'WebP accepted and re-encoded')
 jpeg=subprocess.run(['perl','-MGD','-e','my $im=GD::Image->newFromPng($ARGV[0],1);binmode STDOUT;print $im->jpeg(90);',str(root/'test.png')],stdout=subprocess.PIPE,check=True).stdout
 exif=b'Exif\0\0'+b'II'+struct.pack('<HIH',42,8,1)+struct.pack('<HHI',0x112,3,1)+struct.pack('<H',6)+b'\0\0'+b'\0'*4
 jpeg=jpeg[:2]+b'\xff\xe1'+struct.pack('>H',len(exif)+2)+exif+jpeg[2:]
 status,html,_=request(fields={'csrf':csrf,'kind':'photography','action':'upload','folder':'qa'},files=[('media','rotated.jpg','image/jpeg',jpeg)])
 check('1 upload published' in html,'JPEG uploads supported')
 rotated=con.execute("select width,height from uploads where title='rotated' and folder='qa'").fetchone()
 check(tuple(rotated)==(32,48),'JPEG EXIF orientation applied before metadata removal')
 status,html,_=request('/admin/?kind=blog');check('id="articles"' in html and 'class="theme-row lib-item"' in html and 'kind=blog&amp;new=1' in html and 'value="delete_post"' in re.search(r'row-menu__items">(.*?)</details>',html,re.S).group(1),'articles open on the list of articles, a row each, delete in its “…” menu')
 status,html,_=request('/admin/?kind=blog&new=1');check('id="article-editor"' in html and 'name="body"' in html and 'data-preview' in html,'new article opens the writing screen')
 md='## Hello\n\n**Bold** and *italic*\n\n<script>alert(1)</script>\n\n[good](https://example.com)\n\n[bad](javascript:alert(1))\n\n![remote](https://example.com/x.png)'
 status,_,hdr=submit('save_draft','blog',title='QA Blog',body=md)
 check(status==303,'draft saved');postid=urllib.parse.parse_qs(urllib.parse.urlsplit(hdr['Location']).query)['id'][0]
 check(request('/blog/?post='+postid)[0]==404,'draft inaccessible publicly')
 status,html,_=submit('preview','blog',id=postid,title='QA Blog',body=md)
 check('href="https://example.com"' in html,'Markdown keeps ordinary links')
 check('<h2>Hello</h2>' in html and '<strong>Bold</strong>' in html,'Markdown preview renders headings and emphasis')
 check('<script>alert' not in html and 'href="javascript:' not in html and 'src="https://example.com' not in html,'Markdown blocks HTML scripts unsafe links and remote images')
 status,_,_=request(fields={'csrf':csrf,'kind':'blog','action':'blog_image','id':postid,'title':'QA Blog','body':md,'image_alt':'A photo'},files=[('image','inline.png','image/png',png())]);check(status==303,'inline image insertion saves post')
 body=con.execute('select body from posts where id=?',(postid,)).fetchone()[0];check('![A photo](/media/pictures/articles/' in body,'inline image Markdown inserted')
 submit('publish','blog',id=postid,title='QA Blog',body=body)
 status,html,_=request('/blog/?post='+postid);check(status==200 and re.search(r'<img[^>]+src="/media/pictures/articles/',html),'published post renders inline image')
 shown=re.search(r'\]\((/media/pictures/articles/[^)\s]+)\)',body).group(1)
 check(f'<meta property="og:image" content="https://example.net{shown}">' in html,'an article shares with its first library picture')
 submit('save_draft','blog',id=postid,title='QA Blog',body=body);check(request('/blog/?post='+postid)[0]==404,'unpublish hides post')
 # The writing screen's background requests.
 fetch={'HTTP_X_REQUESTED_WITH':'fetch'}
 status,body_,_=request(fields={'csrf':csrf,'kind':'blog','action':'autosave','id':'','title':'Autosaved','body':'First *words*'},headers=fetch)
 auto=json.loads(body_)['id'];row=con.execute('select title,body,published_at from posts where id=?',(auto,)).fetchone()
 check(status==200 and tuple(row)==('Autosaved','First *words*',None),'autosave creates a draft and returns its id')
 request(fields={'csrf':csrf,'kind':'blog','action':'autosave','id':auto,'title':'Autosaved','body':'More words'},headers=fetch)
 check(con.execute('select body from posts where id=?',(auto,)).fetchone()[0]=='More words' and con.execute("select count(*) from posts where title='Autosaved'").fetchone()[0]==1,'autosave updates the same draft')
 status,body_,_=request(fields={'csrf':csrf,'kind':'blog','action':'autosave','id':'','title':'','body':'x'},headers=fetch);check(status==400,'autosave needs a title')
 status,body_,_=request(fields={'csrf':csrf,'kind':'blog','action':'preview_html','id':auto,'title':'Preview <b>','body':'## Sub\n\n<script>x</script> **bold**'},headers=fetch)
 html=json.loads(body_)['html']
 check(status==200 and '<base target="_blank">' in html and 'Preview &lt;b&gt;' in html and '<h2>Sub</h2>' in html and '<strong>bold</strong>' in html and '<script>x' not in html and 'class="site-nav' in html and 'comment-form' not in html,'article preview: the public page with the unsaved text, no comments')
 check(con.execute('select title from posts where id=?',(auto,)).fetchone()[0]=='Autosaved','previewing saves nothing')
 status,body_,_=request(fields={'csrf':csrf,'kind':'blog','action':'image_upload'},files=[('image','Harbour_view.png','image/png',png())],headers=fetch)
 md_=json.loads(body_)['markdown']
 check(status==200 and re.fullmatch(r'!\[Harbour view\]\(/media/pictures/articles/[a-f0-9]{32}\.\w+\)',md_) and (root/'media/blowfishcms/pictures/articles'/md_.split('/')[-1][:-1]).exists(),'dropped image uploaded; Markdown returned for the cursor position')
 status,body_,_=request(fields={'csrf':csrf,'kind':'blog','action':'publish','id':auto,'title':'Autosaved','body':'Live'},headers=fetch)
 check(status==200 and json.loads(body_)['message']=='Published.','publish answers the editor in JSON')
 status,body_,_=request(fields={'csrf':csrf,'kind':'blog','action':'autosave','id':auto,'title':'Autosaved','body':'Sneaky'},headers=fetch)
 check(status==400 and con.execute('select body from posts where id=?',(auto,)).fetchone()[0]=='Live','a published article never changes by autosave')
 submit('delete_post','blog',id=auto)
 # The page builder's preview.
 status,html,_=request('/admin/?kind=page&page=home')
 check('data-page-editor' in html and 'data-pe-preview' in html and 'is-page-editor' in html,'the page editor shows the page itself, to edit in place')
 submit('delete_post','blog',id=postid);check(con.execute('select count(*) from posts where id=?',(postid,)).fetchone()[0]==0,'post deletion')
 # Uploads in pieces (what admin.js uses for every library).
 def piecewise(kind,name,content,**finish):
  fetch={'HTTP_X_REQUESTED_WITH':'fetch'}
  status,body,_=request(fields={'csrf':csrf,'kind':kind,'action':'upload_start','name':name,'size':str(len(content)),'collection':'QA','folder':'qa','description':'pieces'},headers=fetch)
  r=json.loads(body);assert status==200,r
  half=len(content)//2
  for off,piece in [(0,content[:half]),(half,content[half:])]:
   status,body,_=request(fields={'csrf':csrf,'kind':kind,'action':'upload_chunk','upload':r['upload'],'offset':str(off)},files=[('chunk','piece','application/octet-stream',piece)],headers=fetch);assert status==200,body
  files=[(k,'art.png','image/png',v) for k,v in finish.items() if isinstance(v,bytes)]
  fields={'csrf':csrf,'kind':kind,'action':'upload_finish','upload':r['upload'],**{k:v for k,v in finish.items() if not isinstance(v,bytes)}}
  status,body,_=request(fields=fields,files=files,headers=fetch) if files else request(fields=fields,headers=fetch)
  return status,json.loads(body)
 status,r=piecewise('photography','Sunset_over-sea.png',png(64,40))
 shot=con.execute("select * from uploads where title='Sunset over sea'").fetchone()
 check(status==200 and r['message']=='“Sunset over sea” published.' and shot and shot['folder']=='qa' and shot['width']==64,'photo uploaded in pieces goes through the image pipeline')
 check(request(fields={'csrf':csrf,'kind':'photography','action':'upload_start','name':'notes.txt','size':'10'},headers={'HTTP_X_REQUESTED_WITH':'fetch'})[0]==400,'only image files start a photo upload')
 status,body,_=request(fields={'csrf':csrf,'kind':'photography','action':'upload_start','name':'huge.jpg','size':str(31*1048576)},headers={'HTTP_X_REQUESTED_WITH':'fetch'})
 check(status==400 and '30 MB or smaller' in json.loads(body)['message'],'photos over 30 MB refused before uploading')
 status,r=piecewise('photography','broken.png',b'\x89PNG not really an image')
 check(status==400 and not list((data/'admin/tmp').glob('upload-*')),'a refused photo leaves no temporary files')
 status,first=piecewise('music','Track one.wav',wav.getvalue(),artwork=png())
 status,second=piecewise('music','Track two.wav',wav.getvalue(),artwork_name=first.get('artwork',''))
 arts={r[0] for r in con.execute("select artwork from uploads where kind='music' and title like 'Track %'")}
 check(first.get('artwork') and arts=={first['artwork']},'a batch of tracks shares one stored album artwork')
 music=[dict(r) for r in con.execute("select * from uploads where collection='QA' and kind='music'")]
 for item in music:submit('delete','music',id=item['id'])
 shots=[dict(r) for r in con.execute("select * from uploads where folder='qa' and kind='photography'")]
 status,body,_=request(fields={'csrf':csrf,'kind':'photography','action':'bulk','op':'delete','ids':[p['id'] for p in shots]},headers={'HTTP_X_REQUESTED_WITH':'fetch'})
 check(status==200 and f'Deleted {len(shots)} pictures' in json.loads(body)['message'],'selected photos deleted together')
 check(not any((root/'media/blowfishcms/pictures'/p['folder']/p[k]).exists() for p in shots for k in ('filename','thumbnail')),'bulk delete removes the image files')
 check(con.execute("select count(*) from uploads where collection='QA' or folder='qa'").fetchone()[0]==0,'test uploads delete cleanly')
 now={r[0]:r[1] for r in con.execute('select id,folder from uploads')}
 check({b['id'] for b in before}<=set(now) and all(now[i]=='articles' for i in set(now)-{b['id'] for b in before}),'all preexisting media preserved (the test\'s article pictures stay in the Articles folder)')
 status,html,_=request('/admin/?kind=page&page=home')
 label=con.execute("select nav_label from pages where slug='home'").fetchone()[0]
 home_blocks=[tuple(r) for r in con.execute("select type,data from page_blocks where page='home' order by sort_order")]
 seen=f"status {status}; heading {re.findall(r'<h1>(.*?)</h1>',html)[:1]}; home blocks {[(t,sorted(json.loads(d))) for t,d in home_blocks]}; cards {re.findall(r'<strong>([^<]+)</strong>',html)[:12]}"
 check(status==200 and f'<h1>{H.escape(label[:1].upper()+label[1:])}</h1>' in html and '>save</button>' in html,'the home editor is the page builder ('+seen+')')
 check('Main picture' not in html,'the home editor has no portrait upload of its own ('+seen+')')
 if any(t=='about' for t,_ in home_blocks):check('data-picture-field' in html,'an About me block on the home page chooses its picture from the library ('+seen+')')
 home=request('/admin/?kind=themes')[1]
 check('id="portrait"' not in home and 'Main picture' not in home and 'profile_upload' not in home,'Themes has no portrait settings any more')
 # About me: a picture from the library, as a portrait card or beside the text, or none.
 pic=con.execute("select id,filename,folder,description,title from uploads where kind='photography' order by created_at limit 1").fetchone()
 about=con.execute("select id,data from page_blocks where page='home' and type='about'").fetchone()
 if not about:
  con.execute("insert into page_blocks(id,page,type,width,sort_order,data) values ('a1b2c3d4e5f60718','home','about','full',99,'{}')");con.commit()
  about=('a1b2c3d4e5f60718','{}')
 def set_about(**v):
  d={**json.loads(about[1]),'title':'about','heading':'Hello there','body':'Some words.',**v}
  con.execute('update page_blocks set data=? where id=?',(json.dumps(d),about[0]));con.commit()
 url='/media/pictures/'+(pic[2]+'/' if pic[2] else '')+pic[1]
 set_about(picture=pic[0],position='')
 page=request('/')[1]
 check(re.search(r'<div class="about-card__photo"><img src="'+re.escape(url)+'"',page) and 'Some words.' in page,'About me shows its library picture as a portrait card')
 set_about(picture=pic[0],position='left',picture_size='small')
 check(re.search(r'picture-text--left.*?<img src="'+re.escape(url)+'"',request('/')[1],re.S),'or beside the text')
 set_about(picture='')
 page=request('/')[1]
 check('about-card__photo' not in page and 'Some words.' in page and 'data-theme-profile' not in page,'with no picture chosen, About me is just the text')
 set_about(picture='0'*32)
 check('Some words.' in request('/')[1],'a picture that has gone from the library leaves just the text')
 con.execute('update page_blocks set data=? where id=?',(about[1],about[0]));con.commit()
 import html as htmllib
 # Page text and layout editing is covered by tests/pages.py.
 check('<form action="/contact/send"' in request('/contact/')[1],'contact editor preserves working form')
 check(request('/contact/send')[0]==405,'contact rejects GET')
 check(request('/contact/send',fields={'name':'test','email':'bad','message':'x'})[2]['Location']=='/contact/?sent=0','contact rejects invalid email without sending')
 check(request('/contact/send',fields={'company':'bot'})[2]['Location']=='/contact/?sent=1','contact honeypot does not send')
 print(json.dumps({'checks':len(checks),'existingUploadsPreserved':len(before)}))