BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
424 lines · 49.3 KB · download this file
#!/usr/bin/env python3
"""Pages built from blocks: the seed's pages, the page builder in the
admin, new pages and their addresses. Runs on a new site's
catalogue (never the site's own); never touches live data, credentials or media."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets
import html as H
script=str(pathlib.Path(sys.argv[1]).resolve())
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)
checks=[]
def check(v,msg):
assert v,msg
checks.append(msg);print('PASS',msg,flush=True)
with tempfile.TemporaryDirectory(prefix='blowfish-pages-test-') as tmp:
root=pathlib.Path(tmp);data=root/'var/db/blowfishcms';(data/'admin/tmp').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)
copied_uploads=start_catalog(data/'catalog.sqlite')
with signin.connect(data/'catalog.sqlite') as copy:
for table in ['pages','page_blocks','site_settings']:copy.execute('drop table if exists '+table)
ensure_samples(copy)
uploads_at_start=copy.execute('select count(*) from uploads').fetchone()[0]
env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_PAGES_SEED':str(pathlib.Path(__file__).resolve().parent/'fixtures/sample-pages-seed.json')}
def run(path,fields=None,cookie='',user='',fetch=False,page_route=False,files=None):
url=urllib.parse.urlsplit(path);body=urllib.parse.urlencode(fields or {},doseq=True).encode() if fields is not None else b'';ctype='application/x-www-form-urlencoded'
if files:
boundary='bftest'+secrets.token_hex(8);parts=[f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode() for k,v in (fields or {}).items()]
parts+=[f'--{boundary}\r\nContent-Disposition: form-data; name="{n}"; filename="{fn}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+blob+b'\r\n' for n,fn,blob in files]
body=b''.join(parts)+f'--{boundary}--\r\n'.encode();ctype='multipart/form-data; boundary='+boundary
e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST' if fields is not None else 'GET','SCRIPT_NAME':'/_page' if page_route else url.path,'DOCUMENT_URI':url.path,
'QUERY_STRING':url.query,'CONTENT_TYPE':ctype,'CONTENT_LENGTH':str(len(body)),'HTTP_COOKIE':cookie,'REMOTE_USER':user,
'HTTP_ORIGIN':'https://example.net','REMOTE_ADDR':'192.0.2.1'}
if fetch:e['HTTP_X_REQUESTED_WITH']='fetch'
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])
head,html=p.stdout.decode().split('\r\n\r\n',1);hdr={}
for line in head.split('\r\n'):k,v=line.split(': ',1);hdr[k]=v
return int(hdr['Status']),html,hdr
def main(html):return re.search(r'<main id="main"[^>]*>(.*)</main>',html,re.S).group(1)
def nav(html):return re.findall(r'<a href="([^"]+)"',re.search(r'id="main-menu">(.*?)</div>',html,re.S).group(1))
originals=['/','/projects/','/photography/','/music/','/blog/','/links/','/resume/','/contact/']
# ---- The seed's pages, made once by the migration -----------------------
# blowfishctl looks for these names before running the maintenance modes.
app=pathlib.Path(__file__).resolve().parent.parent
check(all("'%s'"%m in (app/'cgi-bin/site.pl').read_text() for m in ['--migrate','--comments-init']),'site.pl advertises its maintenance modes to the deploy script')
check(subprocess.run(['perl',str(app/'cgi-bin/site.pl'),'--bogus'],env=env,capture_output=True).returncode!=0,'unknown maintenance option refused')
out=subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.PIPE,text=True).stdout
check('Pages made from the seed' in out,'migration makes the seed\'s pages')
con=sqlite3.connect(data/'catalog.sqlite');con.row_factory=sqlite3.Row
check([r[0] for r in con.execute('select slug from pages order by created_at,slug')]!=[] and con.execute('select count(*) from pages').fetchone()[0]==8,'eight pages stored')
check(con.execute('select count(*) from page_blocks').fetchone()[0]==18,'eighteen blocks stored')
for p in originals:check(run(p)[0]==200 and '<!--EDIT' not in run(p)[1],'page renders: '+p)
out=subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.PIPE,text=True).stdout
check('Pages made' not in out and con.execute('select count(*) from page_blocks').fetchone()[0]==18,'migration runs once; later runs keep the pages')
check('Welcome' in run('/')[1],'the starter homepage heading is in the about block')
html=run('/resume/')[1]
check(html.count('<div class="grid-2">')==1 and 'class="window print-hide"' in html and '/css/looks/' not in html,'resume keeps its columns and sections; pages have no looks')
check(json.loads(con.execute("select style from pages where slug='home'").fetchone()[0]).get('width')=='narrow','the starter Home page has the narrow column')
check('<form action="/contact/send"' in run('/contact/')[1] and 'project-grid' not in run('/projects/')[1] and '/js/projects.js' not in run('/projects/')[1],'the contact form is a block; GitHub projects is an add-on now')
check('<dialog id="photo-viewer"' in run('/photography/')[1] and 'photo-viewer' not in run('/music/')[1],'photo viewer only where there is a gallery')
check(run('/index.html')[0]==200 and run('/resume/index.html')[0]==200 and run('/nope/')[0]==404 and run('/Resume/')[0]==404,'page addresses: index.html accepted, unknown 404')
# ---- Page builder -------------------------------------------------------
status,html,hdr=run('/admin/',user='admin');csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1);admin='bf_csrf='+csrf
def post(fields,fetch=False):return run('/admin/',{'csrf':csrf,**fields},cookie=admin,user='admin',fetch=fetch)
check(run('/links/')[0]==200,'the Links page is on, like the other pages a site starts with')
def blocks(slug):return [dict(r) for r in con.execute('select * from page_blocks where page=? order by sort_order',(slug,))]
def form(slug):
# Everything the editor's form would send for this page as it is stored now.
p=dict(con.execute('select * from pages where slug=?',(slug,)).fetchone())
f={'kind':'page','page':slug,'action':'page_save','title':p['title'],'description':p['description'],'nav_label':p['nav_label'],'slug':slug}
f.update({'style_'+k:v for k,v in {'width':'original','font':'theme','size':'normal','spacing':'normal','align':'original','layout':'original'}.items()})
html=run('/admin/?kind=page&page='+slug,user='admin',cookie=admin)[1]
for tag in re.findall(r'<input [^>]*>',html):
name=re.search(r'name="(b\.[^"]+)"',tag);value=re.search(r'value="([^"]*)"',tag)
if name and 'type="checkbox"' not in tag:f.setdefault(name.group(1),(value.group(1) if value else '').replace('<','<').replace('>','>').replace('"','"').replace(''',"'").replace('&','&'))
for name,body in re.findall(r'<textarea name="(b\.[^"]+)"[^>]*>(.*?)</textarea>',html,re.S):f[name]=body.replace('<','<').replace('>','>').replace('"','"').replace(''',"'").replace('&','&')
for name,opts in re.findall(r'<select name="(b\.[^"]+)"[^>]*>(.*?)</select>',html,re.S):
sel=re.search(r'<option value="([^"]*)" selected',opts) or re.search(r'<option value="([^"]*)"',opts);f[name]=sel.group(1)
for name in re.findall(r'<input type="checkbox"[^>]*? name="(b\.[^"]+)"[^>]*checked',html):f[name]='1'
return f
for slug in ['home','projects','photography','music','blog','links','resume','contact']:
status,html,_=run('/admin/?kind=page&page='+slug,user='admin',cookie=admin)
check(status==200 and '>save</button>' in html and html.count('data-pe-fields=')==len(blocks(slug)) and html.count('data-pe-select=')==len(blocks(slug)) and 'class="admin-crumbs"' in html,'page builder opens: '+slug)
f=form(slug);first=blocks(slug)[0]['id'];f['b.%s.title'%first]='Edited '+slug+' <script> é';f['style_width']='narrow'
status,body,_=post(f,fetch=True);check(status==200 and json.loads(body)['ok'],'page saves: '+slug)
path='/' if slug=='home' else '/'+slug+'/'
html=run(path)[1];check('Edited '+slug+' <script> é' in html and 'data-page-width="narrow"' in html,'edits render escaped: '+slug)
f['style_font']='url(evil)';check(post(f,fetch=True)[0]==400,'invalid page style rejected: '+slug)
# Hiding a page from search engines (page settings).
f=form('music');f['noindex']=['1','0'];check(post(f,fetch=True)[0]==200 and '<meta name="robots" content="noindex">' in run('/music/')[1] and '/music/</loc>' not in run('/sitemap.xml')[1],'a page can be hidden from search engines')
check('name="noindex" value="1" form="bulk-edit" checked' in run('/admin/?kind=page&page=music',user='admin',cookie=admin)[1],'the page builder shows the search setting')
f['noindex']=['0'];post(f,fetch=True);check('name="robots"' not in run('/music/')[1],'and shown again')
# Live preview: the page with unsaved values, rendered like the public page; nothing saved.
f=form('contact');first=blocks('contact')[0]['id'];f['b.%s.title'%first]='Previewed <title>';f['style_width']='wide';f['action']='page_preview'
status,body,_=post(f,fetch=True);html=json.loads(body)['html'] if status==200 else ''
check('Previewed <title>' in html and 'data-page-width="wide"' in html and '<base target="_blank">' in html and 'class="site-nav' in html,'page preview shows unsaved edits as visitors would see them')
check('Previewed' not in run('/contact/')[1] and 'Previewed' not in json.dumps(blocks('contact')),'previewing a page saves nothing')
check('data-pe-block' not in html and 'page-canvas.css' not in html,'the plain preview has no editing marks')
# The editor's canvas: the same page, with each block and its texts marked for editing in place.
cf=dict(f);cf['edit']='1';cf['b.%s.title'%first]='Panel <one>'
status,body,_=post(cf,fetch=True);canvas=json.loads(body)['html'] if status==200 else ''
check(status==200 and '/css/page-canvas.css' in canvas and canvas.count('data-pe-block=')>=1 and f'data-pe-block="{first}"' in canvas,'the editing canvas marks each block')
check(f'data-pe-field="b.{first}.title"' in canvas and '>Panel <one></span>' in canvas and 'zpe' not in canvas,'and its texts, escaped, with no markers left over')
check('Previewed' not in run('/contact/')[1],'the canvas saves nothing either')
f['style_font']='url(evil)';check(post(f,fetch=True)[0]==400,'preview checks the values like saving does')
f=form('home');about=blocks('home')[0]['id'];f['b.%s.heading'%about]='New <heading> é';f['b.%s.body'%about]='A **shared** biography.\n\n[Link](https://example.com)'
post(f,fetch=True);html=run('/')[1]
check('<h1 class="block-heading">New <heading> é</h1>' in html and '<strong>shared</strong>' in html,'about block: escaped heading and Markdown')
cf=form('home');cf['action']='page_preview';cf['edit']='1'
canvas=json.loads(post(cf,fetch=True)[1])['html']
check(f'data-pe-field="b.{about}.body" data-pe-md' in canvas and '<strong>shared</strong>' in canvas.split(f'data-pe-field="b.{about}.body"')[1] and f'data-pe-field="b.{about}.heading"' in canvas,'in the canvas a Markdown text is marked as Markdown, shown rendered')
check('href="https://example.com"' in canvas and 'data-pe-field="b.%s.link'%about not in canvas,'links stay links, not marked')
# Every window body has one class at most, set by the block; no empty heading is left behind.
f=form('photography');intro=blocks('photography')[0]['id'];f['b.%s.heading'%intro]='';f['b.%s.body'%intro]='Photographs, mostly of places.';post(f,fetch=True)
html=run('/photography/')[1];first=re.search(r'<div class="window__body media-intro">(.{0,30})',html).group(1)
check(first.startswith('<div class="page-copy">'),'text panel without a heading starts with its contents')
for p in originals:
classes=re.findall(r'<div class="window__body([^"]*)"',run(p)[1])
check(all(len(c.split())<=1 for c in classes),'one class per window body: '+p)
css=(pathlib.Path(__file__).resolve().parent.parent/'public/css/site.css').read_text()
check('.window__body>:first-child,.page-copy>:first-child{margin-top:0}' in css,'window edges trimmed in one place')
f=form('resume');b=blocks('resume')[1]
f['b.%s.body'%b['id']]='### Edited role\n\nDid things.';post(f,fetch=True)
html=run('/resume/')[1];check('<h3>Edited role</h3>' in html and '<div class="page-copy">' in html,'a panel’s text is Markdown')
# Old editor addresses lead to the builder.
check(run('/admin/?kind=resume',user='admin')[2].get('Location')=='/admin/' and run('/admin/?kind=appearance',user='admin')[2].get('Location')=='/admin/','addresses of screens that no longer exist go to the overview')
check('edit the Photography page' in run('/admin/?kind=photography',user='admin')[1],'library links to its page')
# Blocks: add, once-only types, move, widths, remove.
status,_,hdr=post({'kind':'page','page':'links','action':'block_add','type':'gallery','width':'left'});check(status==303 and '#block-' in hdr['Location'],'block added')
post({'kind':'page','page':'links','action':'block_add','type':'text','width':'right'})
check([b['type'] for b in blocks('links')]==['text','links','gallery','text'],'new blocks go at the end')
html=run('/links/')[1];check(html.count('<div class="grid-2">')==1 and 'photo-grid' in html and html.count('<dialog id="photo-viewer"')==1,'half-width blocks share a row; gallery works on any page')
html=post({'kind':'page','page':'contact','action':'block_add','type':'contact_form','width':'full'})[1]
check('one Contact form block' in html and len(blocks('contact'))==3,'one-per-page blocks refused twice')
check('Already on this page' in run('/admin/?kind=page&page=contact',user='admin',cookie=admin)[1],'add menu marks blocks already used')
check(post({'kind':'page','page':'links','action':'block_add','type':'bogus','width':'full'})[0]==200 and len(blocks('links'))==4,'unknown block type refused')
g=blocks('links')[2]['id'];post({'kind':'page','page':'links','action':'move','id':g,'direction':'up'})
check([b['type'] for b in blocks('links')]==['text','gallery','links','text'],'block moved up')
ed=run('/admin/?kind=page&page=links',user='admin',cookie=admin)[1]
check('role="switch" name="noindex" value="1" form="bulk-edit"' in ed and 'role="switch" name="menu" value="1" form="bulk-edit"' in ed and 'class="checkline"' not in ed and 'class="checkbox-label"' not in ed,'the page editor’s on/off settings are switches, with no tick boxes left')
ids=[b['id'] for b in blocks('links')]
check(post({'kind':'page','page':'links','action':'order','order':[ids[1],ids[0]]},fetch=True)[0]==200 and [b['id'] for b in blocks('links')]==[ids[1],ids[0]]+ids[2:],'blocks dragged into a new order')
post({'kind':'page','page':'links','action':'order','order':ids},fetch=True)
ed=run('/admin/?kind=page&page=links',user='admin',cookie=admin)[1]
check('data-reorder="page" data-reorder-fields="page=links"' in ed and ed.count('class="move-form"')==len(ids),'the page editor’s blocks can be dragged, or moved with ↑ and ↓')
post({'kind':'page','page':'links','action':'block_delete','id':g});check([b['type'] for b in blocks('links')]==['text','links','text'],'block removed')
f=form('links');t=blocks('links')[2]['id'];f['b.%s.width'%t]='sideways';check(post(f,fetch=True)[0]==400,'invalid width refused')
# Every block type renders on one new page.
status,_,hdr=post({'kind':'pages','action':'page_create','label':'Gear Room','slug':''})
check(status==303 and 'page=gear-room' in hdr['Location'],'new page created with an address from its name')
check('/gear-room/' not in nav(run('/')[1]) and run('/gear-room/',page_route=True)[0]==404,'new pages start off: out of the navigation, address not found')
check('/gear-room/' not in run('/sitemap.xml')[1],'a page that is off stays out of the sitemap')
check('view ↗' not in re.search(r'<h2>[^<]*(?:<span class="state-badge">Off</span>)?</h2><p class="media-label">/gear-room/.*?</article>',run('/admin/?kind=pages',user='admin')[1],re.S).group(0),'no view link while a page is off')
post({'kind':'pages','action':'nav_toggle','page':'gear-room'})
for t in ['about','picture_text','contact_form','gallery','music','posts','text']:post({'kind':'page','page':'gear-room','action':'block_add','type':t,'width':'full'})
f=form('gear-room');types={b['type']:b['id'] for b in blocks('gear-room')}
f['b.%s.limit'%types['posts']]='1';f['b.%s.feed_link'%blocks('gear-room')[0]['id']]='1'
status,body,_=post(f,fetch=True);check(status==200 and json.loads(body)['ok'],'page with every block type saves')
status,html,_=run('/gear-room/',page_route=True)
check(status==200 and all(s in html for s in ['action="/contact/send"','photo-grid','music-list','blog-list','href="/blog/feed.xml">RSS feed']),'every block type renders on a new page')
check(len(re.findall(r'<article><time',html))<=1,'posts block respects its limit')
check(run('/gear-room/')[0]==200,'new page served by the page route')
f['b.%s.limit'%types['posts']]='999';check('whole number' in json.loads(post(f,fetch=True)[1])['message'],'out-of-range number refused')
# Addresses
f=form('gear-room');f['slug']='admin';check(post(f,fetch=True)[0]==400,'reserved address refused')
f['slug']='css';check(post(f,fetch=True)[0]==400,'address of a public folder refused')
f['slug']='resume';check(post(f,fetch=True)[0]==400,'address in use refused')
f['slug']='kit';status,body,_=post(f,fetch=True);check(status==200 and json.loads(body)['address']=='/kit/','page address changed')
check(run('/kit/',page_route=True)[0]==200 and run('/gear-room/',page_route=True)[0]==301 and run('/gear-room/',page_route=True)[2]['Location']=='https://example.net/kit/' and len(blocks('kit'))==8,'blocks follow the new address; the old address redirects')
check(post({'kind':'pages','action':'page_create','label':'Kit'})[0]==200,'duplicate page name refused')
check(run('/admin/',page_route=True)[0]==404 and run('/x/../',page_route=True)[0]==404,'page route only serves plain page addresses')
# Navigation and sitemap include made pages once shown.
check('/kit/' in nav(run('/')[1]) and 'https://example.net/kit/' in run('/sitemap.xml')[1],'a page that is on is in the navigation and sitemap')
post({'kind':'pages','action':'nav_toggle','page':'kit'});check(run('/kit/',page_route=True)[0]==404 and '/kit/' not in nav(run('/')[1]),'turning a page off makes its address not found')
check(post({'kind':'page','page':'kit','action':'page_preview',**{k:v for k,v in form('kit').items() if k!='action'}},fetch=True)[0]==200,'a page that is off can still be previewed')
post({'kind':'pages','action':'nav_toggle','page':'kit'});check(run('/kit/',page_route=True)[0]==200,'turning it back on restores it')
# 0.39.2: on, but not in the navigation menu.
post({'kind':'pages','action':'nav_menu','page':'kit'})
check(run('/kit/',page_route=True)[0]==200 and '/kit/' not in nav(run('/')[1]) and 'https://example.net/kit/' in run('/sitemap.xml')[1],'out of the menu, a page that is on still opens at its address and stays in the sitemap')
lst=run('/admin/?kind=pages',user='admin',cookie=admin)[1]
check('<span class="state-badge">Not in menu</span>' in lst and re.search(r'aria-pressed="false" aria-label="In the navigation menu: no\. Change it for the [^"]+ page"',lst),'the Pages list marks it, and its menu switch is off')
post({'kind':'pages','action':'nav_menu','page':'kit'});check('/kit/' in nav(run('/')[1]),'the menu switch puts it back in the navigation')
f=form('kit');f['menu']='0';post(f,fetch=True)
check('/kit/' not in nav(run('/')[1]) and run('/kit/',page_route=True)[0]==200,'the page editor’s “In the navigation menu” takes it out too')
f=form('kit');post(f,fetch=True);check('/kit/' not in nav(run('/')[1]),'a save without the menu field leaves it as it was')
f['menu']='1';post(f,fetch=True);check('/kit/' in nav(run('/')[1]),'and ticking it puts it back')
# 0.43: menu groups, a label in the bar that drops down to show its pages.
def bar(html):
"""The menu as [address, …] with a group as (label, [addresses])."""
menu=html.split('id="main-menu">',1)[1];out=[]
while m:=re.match(r'<details class="nav-group[^"]*"><summary>([^<]*)<.*?</details>|<a href="([^"]+)"[^>]*>[^<]*</a>',menu,re.S):
out.append((m.group(1),re.findall(r'<a href="([^"]+)"',m.group(0))) if m.group(1) is not None else m.group(2));menu=menu[m.end():]
return out
def groups():return json.loads((con.execute("select value from site_settings where key='nav_groups'").fetchone() or ['[]'])[0])
check(post({'kind':'pages','action':'nav_group_add','label':''})[0]==200 and groups()==[],'a menu group needs a name')
check(post({'kind':'pages','action':'nav_group_add','label':'Media'})[0]==303 and [g['label'] for g in groups()]==['Media'],'a menu group is made')
check(post({'kind':'pages','action':'nav_group_add','label':'media'})[0]==200 and len(groups())==1,'two groups can’t share a name')
gid=groups()[0]['id'];check(re.fullmatch(r'[0-9a-f]{8}',gid) is not None,'its id is short and plain')
before=nav(run('/')[1])
check(all(not isinstance(x,tuple) for x in bar(run('/')[1])),'an empty group isn’t in the menu')
lst=run('/admin/?kind=pages',user='admin',cookie=admin)[1]
check('data-nav-tree' in lst and f'data-nav-group="{gid}"' in lst and 'class="row-menu__group" data-auto-submit' in lst,'the Pages list shows the group, and each page’s “…” menu can choose one')
post({'kind':'pages','action':'nav_group_set','page':'music','group':gid});post({'kind':'pages','action':'nav_group_set','page':'photography','group':gid})
b=bar(run('/')[1]);grp=[x for x in b if isinstance(x,tuple)]
check(grp==[('Media',['/music/','/photography/'])],'its pages drop down from it, in the order they were added')
check(b.index(grp[0])==[x for x in before if x!='/photography/'].index('/music/'),'the group stands where its first page was')
check('/music/' not in [x for x in b if not isinstance(x,tuple)],'a page in a group isn’t also on its own')
html=run('/music/')[1]
check('<details class="nav-group is-current"><summary>Media<span class="nav-group__caret" aria-hidden="true"></span></summary><div class="nav-group__menu" data-label="Media">' in html and 'href="/music/" aria-current="page"' in html,'on one of its pages the group is marked current, and the page within it')
check('<details class="nav-group">' in run('/blog/')[1],'elsewhere it isn’t')
post({'kind':'pages','action':'nav_menu','page':'music'})
check(('Media',['/photography/']) in bar(run('/')[1]),'a page taken out of the menu leaves its group too')
post({'kind':'pages','action':'nav_menu','page':'music'})
# Dragging posts the whole menu: each page with its group.
order=[i['page'] for i in json.loads(con.execute("select value from site_settings where key='nav'").fetchone()[0])]
order.remove('blog');order.insert(0,'blog')
fields={'kind':'pages','action':'nav_tree','order':order,'in':[gid if p in ('music','blog') else '' for p in order]}
status,body,_=post(fields,fetch=True)
check(status==200 and json.loads(body)['ok'],'the dragged menu saves')
b=bar(run('/')[1])
check(b[0]==('Media',['/blog/','/music/']) and '/photography/' in b,'dragging moves pages into and out of a group, and the group to where its first page is')
check(post({'kind':'pages','action':'nav_tree','order':['home'],'in':['','']},fetch=True)[0]==400,'a dragged menu that doesn’t add up is refused')
post({'kind':'pages','action':'nav_tree','order':['music','blog'],'in':[gid,'nogroup']},fetch=True)
b=bar(run('/')[1]);check(('Media',['/music/']) in b and '/blog/' in b and b.index('/blog/')<b.index('/'),'pages left out of a drag keep their place after it; an unknown group means on its own')
post({'kind':'pages','action':'nav_group_rename','group':gid,'label':'Listen & look'})
check(('Listen & look',['/music/']) in bar(run('/')[1]) and groups()[0]['id']==gid,'renaming keeps the group and its pages')
check(post({'kind':'pages','action':'nav_group_set','page':'photography','group':'deadbeef'})[0]==200,'an unknown group is refused')
post({'kind':'pages','action':'nav_group_set','page':'photography','group':gid});post({'kind':'pages','action':'nav_group_set','page':'music','group':''})
b=bar(run('/')[1]);check(('Listen & look',['/photography/']) in b and '/music/' in b,'a page can be put back on its own')
post({'kind':'pages','action':'nav_group_delete','group':gid})
check(groups()==[] and all(not isinstance(x,tuple) for x in bar(run('/')[1])) and '/photography/' in nav(run('/')[1]),'deleting a group puts its pages back on their own')
check(all('group' not in i for i in json.loads(con.execute("select value from site_settings where key='nav'").fetchone()[0])),'and forgets it on every page')
# Text and picture: a picture from the library, positions, caption and link.
had=[b['id'] for b in blocks('kit') if b['type']=='picture_text']
post({'kind':'page','page':'kit','action':'block_add','type':'picture_text','width':'full'})
post({'kind':'page','page':'kit','action':'block_add','type':'picture_text','width':'full'})
pts=[b for b in blocks('kit') if b['type']=='picture_text' and b['id'] not in had]
check(len(pts)==2,'a page can have several Text and picture blocks')
png=subprocess.run(['perl','-MGD','-e','my $i=GD::Image->new(300,200,1);$i->filledRectangle(0,0,299,199,$i->colorAllocate(200,30,30));binmode STDOUT;print $i->png'],capture_output=True,check=True).stdout
status,body,_=run('/admin/',{'csrf':csrf,'kind':'photography','action':'picture_upload','folder':''},cookie=admin,user='admin',files=[('picture','red square.png',png)],fetch=True)
picture=json.loads(body)['picture']
check(status==200 and picture['url'].startswith('/media/pictures/') and (root/'media/blowfishcms'/picture['url'][len('/media/'):]).exists(),'the chooser uploads a picture into the library')
pid=pts[0]['id']
f=form('kit');f['b.%s.picture'%pid]=picture['id'];f['b.%s.position'%pid]='left';f['b.%s.picture_size'%pid]='small';f['b.%s.alt'%pid]='A <red> square';f['b.%s.body'%pid]='Beside the picture.'
f['b.%s.caption'%pid]='Red, square';f['b.%s.link'%pid]='/contact/'
check(post(f,fetch=True)[0]==200,'picture, position, caption and link save with the page')
builder=run('/admin/?kind=page&page=kit',user='admin',cookie=admin)[1]
check('data-picture-field' in builder and picture['thumb'] in builder and 'value="block_picture"' not in builder,'the builder shows the chosen picture and a chooser, not an upload of its own')
html=run('/kit/',page_route=True)[1]
check(f'<div class="picture-text picture-text--left picture-text--small"><figure class="picture-text__picture"><a href="/contact/"><img src="{picture["url"]}" alt="A <red> square" width="300" height="200" loading="lazy" decoding="async"></a><figcaption>Red, square</figcaption></figure><div class="picture-text__text">' in html,'the picture sits left of the text, linked, captioned and described')
for pos,first in [('right','picture'),('above','picture'),('below','text')]:
f=form('kit');f['b.%s.position'%pid]=pos;post(f,fetch=True)
h=run('/kit/',page_route=True)[1];m=re.search(r'<div class="picture-text picture-text--'+pos+r' [^"]*">(<figure|<div)',h)
check(m and m.group(1)==('<figure' if first=='picture' else '<div'),'picture position: '+pos)
f=form('kit');f['b.%s.link'%pid]='javascript:alert(1)';post(f,fetch=True)
check('javascript:' not in run('/kit/',page_route=True)[1],'a link that is not an address is left off')
f=form('kit');f['b.%s.position'%pid]='nowhere';check(post(f,fetch=True)[0]==400,'an unknown position is refused')
f=form('kit');f['b.%s.picture'%pid]='0'*32;check(post(f,fetch=True)[0]==400,'a picture that is not in the library is refused')
check(run('/kit/',page_route=True)[1].count('picture-text--none')>=1,'a block without a picture shows just its text')
post({'kind':'page','page':'kit','action':'block_delete','id':pid})
check((root/'media/blowfishcms'/picture['url'][len('/media/'):]).exists(),'removing the block leaves its picture in the library')
# About me: a picture from the library, as a portrait card or placed beside the text, or none.
ab=[b for b in blocks('kit') if b['type']=='about'][0]['id']
check('about-card' not in run('/kit/',page_route=True)[1] and 'data-theme-profile' not in run('/kit/',page_route=True)[1],'a new About me block has no picture')
f=form('kit');check('b.%s.picture'%ab in f and 'b.%s.show_portrait'%ab not in f,'About me chooses a picture from the library (there\'s no portrait switch)')
f['b.%s.picture'%ab]=picture['id'];post(f,fetch=True);html=run('/kit/',page_route=True)[1]
check(re.search(r'<div class="about-card__photo"><img src="'+re.escape(picture['url'])+'"',html),'the chosen picture shows as a portrait card')
f=form('kit');f['b.%s.position'%ab]='left';post(f,fetch=True)
check(re.search(r'picture-text--left [^"]*"><figure class="picture-text__picture picture-text__picture--portrait"><img src="'+re.escape(picture['url'])+'"',run('/kit/',page_route=True)[1]),'or beside the text')
f=form('kit');f['b.%s.picture'%ab]='0'*32;check(post(f,fetch=True)[0]==400,'a picture that isn\'t in the library is refused')
f=form('kit');f['b.%s.picture'%ab]='';post(f,fetch=True)
check('picture-text__picture--portrait' not in run('/kit/',page_route=True)[1] and 'about-card__photo' not in run('/kit/',page_route=True)[1],'and the picture can be left out')
# Galleries: a folder (with or without subfolders), or chosen pictures in order.
run('/admin/',{'csrf':csrf,'kind':'photography','action':'folder_create','folder':'','name':'Trips'},cookie=admin,user='admin')
run('/admin/',{'csrf':csrf,'kind':'photography','action':'folder_create','folder':'trips','name':'Coast'},cookie=admin,user='admin')
up=lambda folder,name:json.loads(run('/admin/',{'csrf':csrf,'kind':'photography','action':'picture_upload','folder':folder},cookie=admin,user='admin',files=[('picture',name+'.png',png)],fetch=True)[1])['picture']
a1=up('trips','Alpha');c1=up('trips/coast','Cove')
post({'kind':'page','page':'kit','action':'block_add','type':'gallery','width':'full'})
g=[b for b in blocks('kit') if b['type']=='gallery'][-1]['id']
gallery=lambda:re.findall(r'<div class="photo-grid[^"]*">.*?</div>',run('/kit/',page_route=True)[1],re.S)[-1]
f=form('kit');f['b.%s.source'%g]='folder';f['b.%s.folder'%g]='trips';f['b.%s.subfolders'%g]='0';check(post(f,fetch=True)[0]==200,'a gallery can show a folder')
check('Alpha' in gallery() and 'Cove' not in gallery(),'a folder without its subfolders')
f=form('kit');f['b.%s.subfolders'%g]='1';post(f,fetch=True)
check('Alpha' in gallery() and 'Cove' in gallery(),'a folder with its subfolders')
f=form('kit');f['b.%s.source'%g]='picked';f['b.%s.pictures'%g]=c1['id']+','+a1['id'];f['b.%s.layout'%g]='rows';f['b.%s.captions'%g]='1';post(f,fetch=True)
html=gallery()
check(html.index('Cove')<html.index('Alpha') and 'photo-grid--rows' in html and re.search(r'<figcaption><h2><a href="/picture/[a-f0-9]{32}/">Cove</a></h2>',html),'chosen pictures in the chosen order, laid out in rows with titles')
f=form('kit');f['b.%s.captions'%g]='0';f['b.%s.layout'%g]='large';post(f,fetch=True)
check('photo-grid--large photo-grid--bare' in gallery() and '<figcaption>' not in gallery() and a1['url'] in gallery(),'large layout shows full-size pictures, without titles')
f=form('kit');f['b.%s.folder'%g]='nowhere';check(post(f,fetch=True)[0]==400,'a gallery cannot show a missing folder')
f=form('kit');f['b.%s.source'%g]='folder';f['b.%s.folder'%g]='trips/coast';post(f,fetch=True)
check('A gallery on' in run('/admin/',{'csrf':csrf,'kind':'photography','action':'folder_delete','folder':'trips/coast'},cookie=admin,user='admin')[1] or 'first' in run('/admin/',{'csrf':csrf,'kind':'photography','action':'folder_delete','folder':'trips/coast'},cookie=admin,user='admin')[1],'a folder a gallery shows is not deleted')
run('/admin/',{'csrf':csrf,'kind':'photography','action':'folder_rename','folder':'trips/coast','name':'Seaside'},cookie=admin,user='admin')
check(json.loads(con.execute('select data from page_blocks where id=?',(g,)).fetchone()[0])['folder']=='trips/seaside' and 'Cove' in gallery(),'a gallery follows its folder when it is renamed')
# Removing pages
check('can't be deleted' in post({'kind':'page','page':'home','action':'page_delete'})[1] and 'delete this page' not in run('/admin/?kind=page&page=home',user='admin',cookie=admin)[1],'home cannot be deleted')
check('won’t be public until a page at /blog/ exists again' in run('/admin/?kind=page&page=blog',user='admin',cookie=admin)[1],'deleting the blog page warns about the articles')
listing=run('/admin/?kind=pages',user='admin',cookie=admin)[1]
check('id="new-page"><h3>New page</h3>' in listing and '</span>new page</div>' not in listing and '</span>pages</div>' in listing,'new pages are made at the foot of the page list')
check('action" value="page_delete"' in listing and 'aria-label="Delete the Home' not in listing and 'data-confirm="Delete the' in listing,'the pages list offers delete, except for Home')
status,_,hdr=post({'kind':'page','page':'kit','action':'page_delete'})
check(status==303 and run('/kit/',page_route=True)[0]==404 and not blocks('kit') and '/kit/' not in nav(run('/')[1]),'page removed with its blocks and navigation entry')
post({'kind':'pages','action':'page_create','label':'Spare'})
status,_,hdr=post({'kind':'pages','action':'page_delete','page':'spare'})
check(status==303 and run('/spare/',page_route=True)[0]==404 and not blocks('spare') and 'deleted%20the%20spare%20page' in hdr.get('Location','').lower(),'a page can be deleted from the pages list')
check(con.execute("select count(*) from uploads where title not in ('red square','Alpha','Cove')").fetchone()[0]==uploads_at_start,'libraries untouched by page changes (besides the pictures this test uploaded)')
check(run('/admin/?kind=page&page=nope',user='admin',cookie=admin)[0]==404,'unknown page in the builder')
# ---- 0.19: new blocks, list fields, section styles, layouts, the editor's tabs ----------
status,_,hdr=post({'kind':'pages','action':'page_create','label':'Showcase','slug':'showcase'})
check(status==303 and 'page=showcase' in hdr['Location'],'a page to try the new blocks on')
pid=con.execute("select id from uploads where kind='photography' order by created_at limit 1").fetchone()
if not pid:
png=subprocess.run(['perl','-MGD','-e','my $i=GD::Image->new(600,400,1);$i->filledRectangle(0,0,599,399,$i->colorAllocate(40,90,160));binmode STDOUT;print $i->png'],capture_output=True,check=True).stdout
run('/admin/',{'csrf':csrf,'kind':'photography','action':'upload','folder':''},cookie=admin,user='admin',files=[('media','harbour.png',png)])
pid=con.execute("select id from uploads where kind='photography' order by created_at limit 1").fetchone()
pid=pid[0]
types=['hero','picture','slideshow','columns','divider','button','quote','faq','timeline','table','cards']
for t in types:
status,_,_=post({'kind':'page','page':'showcase','action':'block_add','type':t,'width':'side' if t=='quote' else 'full'})
check(status==303,f'a {t} block can be added')
html=run('/admin/?kind=page&page=showcase',user='admin',cookie=admin)[1]
check('data-page-editor' in html and 'data-pe-preview' in html and 'class="pe-list"' in html and html.count('data-tab-panel=')==3 and all(f'id="tab-{t}"' in html for t in ['layout','search','address']),'the editor is the page itself with a bar of blocks, and the page settings folded in the bar')
check(all(g in html for g in ['<legend>Text</legend>','<legend>Pictures, music and video</legend>','<legend>Layout</legend>','<legend>Content</legend>']),'adding a block offers them in groups')
check('class="block-style block-wide"' in html and 'data-items-field' in html and '<template data-items-template>' in html,'blocks fold their section style away; list fields can add entries')
f=form('showcase');ids={b['type']:b['id'] for b in blocks('showcase')}
check(json.loads([b for b in blocks('showcase') if b['type']=='button'][0]['data']).get('style')=='theme','a new button follows the theme’s own button')
# A list field's entries arrive numbered; their order is the numbers' order, and empty ones are dropped.
for k in [k for k in f if '.items.' in k]:del f[k]
F=lambda t,name:f'b.{ids[t]}.{name}'
f.update({F('hero','heading'):'Harbour Notes',F('hero','body'):'Notes from the [harbour](/blog/).',F('hero','picture'):pid,F('hero','button'):'Say hello',F('hero','button_link'):'/contact/',F('hero','height'):'tall',F('hero','button_style'):'dark',F('hero','button2'):'Our work',F('hero','button2_link'):'/photography/',F('hero','button2_link_newtab'):'1',F('hero','align'):'right',F('hero','picture_focus'):'top',
F('picture','picture'):pid,F('picture','caption'):'The harbour at dawn',F('picture','size'):'medium',F('picture','link'):'javascript:alert(1)',F('picture','zoom'):'1',F('picture','picture_shape'):'round',
F('slideshow','source'):'picked',F('slideshow','pictures'):pid,F('slideshow','interval'):'5',F('slideshow','height'):'video',F('slideshow','controls'):'dots',F('slideshow','picture_focus'):'bottom',
F('columns','count'):'3',F('columns','widths'):'wide',F('columns','valign'):'center',F('columns','col1'):'One',F('columns','col2'):'Two',F('columns','col3'):'Three',
F('divider','style'):'dots',F('divider','colour'):'accent',F('button','label'):'Write to us',F('button','link'):'/contact/',F('button','style'):'outline',F('button','size'):'large',F('button','fill'):'full',F('button','link_newtab'):'1',
F('quote','text'):'Small and fast.',F('quote','align'):'center',F('quote','picture'):pid,F('quote','who'):'A visitor',F('quote','where'):'[a review](https://example.org/)',
F('faq','items')+'.7.q':'Second?',F('faq','items')+'.7.a':'Yes, **second**.',F('faq','items')+'.2.q':'First?',F('faq','items')+'.2.a':'Indeed.',F('faq','items')+'.9.q':'',F('faq','items')+'.9.a':'',F('faq','open'):'1',F('faq','one'):'1',
F('timeline','items')+'.0.when':'2024',F('timeline','items')+'.0.what':'Started',F('timeline','items')+'.0.text':'The beginning.',F('timeline','items')+'.1.when':'March 2025',F('timeline','items')+'.1.what':'Grew',F('timeline','items')+'.2.when':'someday',F('timeline','items')+'.2.what':'Later',F('timeline','items')+'.3.when':'2024-01',F('timeline','items')+'.3.what':'Planned',F('timeline','order'):'newest',
F('table','rows'):'Plan | Price\nBasic | [10](/contact/)\n| Full | 20 |',F('table','header'):'1',F('table','striped'):'1',F('table','cell_align'):'numbers',
F('cards','count'):'2',F('cards','tone'):'dark',F('cards','text_align'):'center',F('cards','link_as'):'button',F('cards','picture_shape'):'square',F('cards','items')+'.0.link_newtab':'1',F('cards','items')+'.0.picture':pid,F('cards','items')+'.0.heading':'Boats',F('cards','items')+'.0.text':'Small ones.',F('cards','items')+'.0.link':'/photography/',F('cards','items')+'.0.link_label':'See them',
F('cards','items')+'.1.heading':'Gulls',F('cards','items')+'.1.link':'javascript:x',
F('columns','section_bg'):'soft',F('columns','section_pad'):'roomy',F('columns','section_picture'):pid,F('timeline','section_bar'):'1',F('table','section_bg'):'none',
'style_width':'full','style_sidebar':'left','visible':'1'})
status,body,_=post(f,fetch=True);check(status==200 and json.loads(body)['ok'],'the page saves with every new block')
d={b['type']:json.loads(b['data']) for b in blocks('showcase')}
check([i['q'] for i in d['faq']['items']]==['First?','Second?'] and [i['heading'] for i in d['cards']['items']]==['Boats','Gulls'],'list entries keep the order of their numbers; empty ones are dropped')
status,html,_=run('/showcase/')
check(status==200 and '/showcase/' in nav(html),'“on” under Address & menu puts the page in the navigation')
m=main(html)
check('class="hero hero--tall hero--dark hero--right hero--picture focus-top"' in m and '<h1>Harbour Notes</h1>' in m and '<a href="/blog/">harbour</a>' in m and '<a class="cta cta--dark" href="/contact/">Say hello</a>' in m and 'class="hero__bg"' in m,'hero header: heading, Markdown text, button and background picture')
check('class="block-picture block-picture--medium block-picture--center shape-round"' in m and '<figcaption>The harbour at dawn</figcaption>' in m and 'javascript:' not in m,'picture block, with a caption; an unsafe link is dropped')
check('data-slideshow data-interval="5"' in m and m.count('class="slideshow__slide"')==1,'slideshow of chosen pictures')
check('block-columns block-columns--3' in m and m.count('block-columns__col')==3,'three columns')
check('block-divider block-divider--dots' in m and '<a class="cta cta--outline cta--large cta--full" href="/contact/" target="_blank" rel="noopener">Write to us</a>' in m,'divider and button (colour, size, full width, a new tab)')
check('class="hero__buttons"><a class="cta cta--dark" href="/contact/">Say hello</a> <a class="cta cta--outline" href="/photography/" target="_blank" rel="noopener">Our work</a>' in m and 'hero--right hero--picture focus-top"' in m,'hero header: a second button (new tab), on the right, the picture’s top kept')
check('block-picture--center shape-round"' in m and 'javascript:' not in m and 'class="photo-open"' in m and 'id="photo-viewer"' in html,'picture: round, and opens larger (with the viewer on the page) when it links nowhere')
check('class="slideshow slideshow--video focus-bottom" data-slideshow data-interval="5" data-controls="dots"' in m,'slideshow: a fixed 16:9 height, its focus, dots')
check('class="block-columns block-columns--3 block-columns--wide block-columns--v-center"' in m,'columns: the first wider, lined up in the middle')
check('block-divider--dots block-divider--medium block-divider--accent' in m,'divider in the accent colour')
check('block-quote--large block-quote--center"><img class="block-quote__face"' in m,'quote: centred, with a picture of who said it')
check(re.search(r'<details class="faq__item" name="faq-[^"]+" open><summary>First\?',m),'questions and answers: only one open at a time')
tl=re.findall(r'<li class="timeline__entry">.*?<h3>([^<]+)</h3>',m)
check(tl==['Grew','Planned','Started','Later'],'timeline: newest first by the dates in “When” (a bare year counts as its start), undated entries last')
check('class="block-table block-table--striped block-table--numbers"' in m,'table: striped, numbers on the right')
check('<blockquote><p>Small and fast.</p>' in m and '<strong>A visitor</strong>, <a href="https://example.org/">a review</a>' in m,'quote with who and where')
check(m.index('<summary>First?</summary>')<m.index('<summary>Second?</summary>') and re.search(r'<details class="faq__item"[^>]* open><summary>First\?',m) and '<strong>second</strong>' in m,'questions and answers fold out, the first open')
check('<p class="timeline__when">2024</p><h3>Started</h3>' in m,'timeline entries')
check('<thead><tr><th>Plan</th><th>Price</th></tr></thead>' in m and '<td><a href="/contact/">10</a></td>' in m and '<td>Full</td><td>20</td>' in m,'table: a header row, Markdown links in cells, outer bars ignored')
check('class="cards cards--2 cards--tone-dark cards--center shape-square"' in m and 'class="cta cta--theme form-submit cta--small" href="/photography/" target="_blank" rel="noopener">See them</a>' in m and '<a href="/photography/" target="_blank" rel="noopener">Boats</a>' in m and '<h3>Gulls</h3>' in m,'cards: colour, centred text, a square picture, the link as a button opening a new tab (an unsafe link leaves a plain title)')
check(re.search(r'class="window section--bg-soft section--pad-roomy[^"]*section--backdrop"',m) and 'class="section__backdrop"' in m and 'section--no-bar' in m and 'section--bg-none' in m,'section styles: background, spacing, picture behind, no title bar, no panel')
check('class="with-sidebar with-sidebar--left"' in m and re.search(r'<aside class="with-sidebar__side">.*?block-quote',m,re.S),'a Sidebar block goes in a sidebar, on the side chosen')
check('data-page-width="full"' in html,'full width')
f=form('showcase');f['visible']='0';post(f,fetch=True)
check(run('/showcase/')[0]==404,'unticking “on” turns the page off')
lst=run('/admin/?kind=pages',user='admin',cookie=admin)[1]
check('view ↗' not in lst and 'aria-label="On: no. Change it for the Showcase page"' in lst and not re.search(r'row-menu__items">(?:(?!</details>).)*?value="nav_toggle"',lst,re.S),'the Pages list has no view button; the on switch is in view, not in the “…” menu')
# 0.26.1: the rest of the blocks' options.
for t in ['about','picture_text','gallery','music','posts','contact_form']:
check(post({'kind':'page','page':'showcase','action':'block_add','type':t,'width':'full'})[0]==303,f'a {t} block can be added (0.26.1 options)')
ed=run('/admin/?kind=page&page=showcase',user='admin',cookie=admin)[1]
check(re.search(r'data-show-when="b\.[^".]+\.button"',ed) and re.search(r'data-show-when="b\.[^".]+\.picture"',ed) and not re.search(r'name="b\.[^".]+\.button"[^>]*data-show-when',ed),'settings that only apply with another (a button’s link and style, a picture’s shape) name it, for admin.js to hide them until then')
f=form('showcase');ids={b['type']:b['id'] for b in blocks('showcase')};F=lambda t,name:f'b.{ids[t]}.{name}'
shown=con.execute("select count(*) from uploads where kind='photography' and gallery_hidden=0").fetchone()[0]
f.update({F('about','picture'):pid,F('about','picture_shape'):'round',F('about','button'):'Hire me',F('about','button_link'):'/contact/',F('about','button_style'):'soft',
F('picture_text','picture'):pid,F('picture_text','link'):'https://example.org/',F('picture_text','link_newtab'):'1',F('picture_text','picture_shape'):'video',F('picture_text','button'):'Read more',F('picture_text','button_link'):'/blog/',
F('gallery','source'):'folder',F('gallery','folder'):'',F('gallery','subfolders'):'1',F('gallery','columns'):'4',F('gallery','order'):'newest',F('gallery','limit'):'1',F('gallery','more_link'):'/photography/',
F('music','limit'):'1',F('music','more_link'):'/music/',
F('posts','layout'):'cards',F('posts','show_excerpt'):'1',F('posts','show_date'):'0',
F('contact_form','button_style'):'dark',F('contact_form','sent_message'):'Got it, thanks!',F('contact_form','subject'):'0','visible':'1'})
status,body,_=post(f,fetch=True);check(status==200 and json.loads(body)['ok'],'the page saves with the 0.26.1 options')
m=main(run('/showcase/')[1])
check('about-card__photo shape-round"' in m and '<p class="block-buttons"><a class="cta cta--soft" href="/contact/">Hire me</a></p>' in m,'about me: a round picture and a button under the text')
check('picture-text__picture shape-video"><a href="https://example.org/" target="_blank" rel="noopener">' in m and '<a class="cta cta--theme form-submit" href="/blog/">Read more</a>' in m,'text and picture: a 16:9 picture linking to a new tab, and a button')
check('photo-grid--grid photo-grid--cols-4' in m and (shown<2 or '<p class="block-more"><a href="/photography/">See all →</a></p>' in m),'gallery: four columns, limited, with “see all”')
cf=re.search(r'<form action="/contact/send".*?</form>',m,re.S).group(0)
check('name="subject"' not in cf and 'data-sent="Got it, thanks!"' in cf and '<button type="submit" class="cta cta--dark">' in cf,'contact form: no subject, its own sent message, the button’s colour')
check('class="cards cards--3 shape-wide post-cards"' in m and 'class="post-excerpt"' in m and '<time class="media-label"' not in re.search(r'post-cards">.*?</div></div>',m,re.S).group(0),'article list as cards with opening lines and no dates')
# Anchors: any block, a plain one too, can be jumped to at /page/#NAME.
f=form('showcase');F=lambda t,name:f'b.{ids[t]}.{name}'
f.update({F('table','section_anchor'):'#Our Prices',F('divider','section_anchor'):'more',F('button','link'):'#our-prices'})
status,body,_=post(f,fetch=True);check(status==200 and json.loads(body)['ok'],'anchors save; one typed as “#Our Prices” is kept as our-prices')
m=main(run('/showcase/')[1])
check(m.count('id="our-prices"')==1 and re.search(r'<section id="our-prices" class="window',m) and re.search(r'<div id="more" class="block-divider',m),'an anchor is its block’s id, on panels and plain blocks alike')
check('href="#our-prices"' in m,'a button can link to an anchor on its page')
check(f'name="b.{ids["table"]}.section_anchor" value="our-prices"' in run('/admin/?kind=page&page=showcase',user='admin',cookie=admin)[1],'the editor shows the anchor with the section style')
for bad in ['main','contact-name','9lives','bad!name']:
f[F('divider','section_anchor')]=bad;check(post(f,fetch=True)[0]==400,'an unusable anchor is refused: '+bad)
f[F('divider','section_anchor')]='our-prices';status,body,_=post(f,fetch=True)
check(status==400 and 'two blocks' in json.loads(body)['message'],'the same anchor on two blocks is refused')
f[F('divider','section_anchor')]='';check(post(f,fetch=True)[0]==200 and 'id="more"' not in main(run('/showcase/')[1]),'clearing an anchor takes the id away')
f=form('showcase');f['visible']='0';post(f,fetch=True)
# Moving between pages in the editor: a switcher of every page (those that
# are off marked), and the pages' addresses for the preview's links.
ed=run('/admin/?kind=page&page=home',user='admin',cookie=admin)[1]
sw=re.search(r'<form method="get" action="/admin/" class="admin-form pe-switch" data-pe-switch>(.*?)</form>',ed,re.S)
slugs={r[0] for r in con.execute('select slug from pages')}
opts=re.findall(r'<option value="([^"]+)"( selected)?>([^<]*)</option>',sw.group(1)) if sw else []
check(sw and {o[0] for o in opts}==slugs and [o[0] for o in opts if o[1]]==['home'] and 'name="kind" value="page"' in sw.group(1),'the editor offers every page to switch to, the one open selected (and works without the script)')
check(any(o[0]=='showcase' and o[2].endswith('(off)') for o in opts),'pages that are off are marked in the switcher')
m=re.search(r'data-pe-pages="([^"]*)"',ed);paths=json.loads(H.unescape(m.group(1))) if m else {}
check(paths.get('/')=='home' and set(paths.values())==slugs and all(k.startswith('/') for k in paths),'the editor knows every page\'s address, for the preview\'s links')
print(json.dumps({'checks':len(checks)}))