repository

BlowfishCMS

A small content management system for OpenBSD

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

276 lines · 29.6 KB · download this file

#!/usr/bin/env python3
"""Add-ons: finding them, switching them on and off, and each place they plug
in (blocks, addresses, admin screens, sitemap, robots.txt, page assets), using
the sample add-ons in tests/fixtures/addons. Uses a fresh catalogue; never
touches live data."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets
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())
checks=[]
version=re.search(r"VERSION='([^']+)'",(pathlib.Path(__file__).resolve().parent.parent/'lib/BlowfishCMS.pm').read_text()).group(1)
def check(v,msg):
 assert v,msg
 checks.append(msg);print('PASS',msg,flush=True)
with tempfile.TemporaryDirectory(prefix='blowfish-addons-test-') as tmp:
 root=pathlib.Path(tmp)
 conf=root/'etc/blowfishcms.conf';conf.parent.mkdir(parents=True)
 conf.write_text('domain = example.org\nadmin_user = alice\ndata = /var/db/bf\nmedia = /media/bf\ncomments = /var/db/bf-comments\ncontact = /var/db/bf-contact\nsecrets = /etc/bf\n')
 data=root/'var/db/bf';(data/'admin/tmp').mkdir(parents=True)
 (data/'admin/csrf.key').write_text(secrets.token_hex(32))
 media=root/'media/bf'
 for kind in ['photography','music','artwork','blog','video']:(media/kind).mkdir(parents=True)
 # A copy of the sample add-ons, so one can be put in place while the site runs.
 addons_dir=root/'opt-addons';__import__('shutil').copytree(pathlib.Path(__file__).resolve().parent/'fixtures/addons',addons_dir)
 env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_ADDONS_PATH':str(addons_dir)}
 env.pop('BLOWFISH_PAGES_SEED',None)
 subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
 db=data/'catalog.sqlite'
 def sql(q,args=()):
  with signin.connect(db) as c:return c.execute(q,args).fetchall()
 def run(path,fields=None,user='',cookie='',fetch=False,files=None,page_route=False):
  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=[]
   for k,v in (fields or {}).items():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
   for name,filename,blob in files:parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()+blob+b'\r\n')
   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)),'REMOTE_USER':user,'HTTP_ORIGIN':'https://example.org','HTTP_COOKIE':cookie,'REMOTE_ADDR':'192.0.2.9',**({'HTTP_X_REQUESTED_WITH':'fetch'} if fetch else {})}
  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
 status,_,hdr=run('/admin/',user='alice');csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1);cookie='bf_csrf='+csrf
 adm=lambda fields,**o:run('/admin/',{'csrf':csrf,**fields},user='alice',cookie=cookie,**o)
 page=lambda path:run(path,page_route=True)

 # ---- Finding add-ons --------------------------------------------------------------
 status,html,_=run('/admin/?kind=addons',user='alice',cookie=cookie)
 check(status==200 and 'href="/admin/?kind=addons" aria-current="page"' in html,'add-ons screen opens from the sidebar')
 check('<h2>Hello <span class="media-label">1.0.0</span></h2>' in html and 'no outside connections' in html and 'by BlowfishCMS tests' in html and 'aria-label="On: no. Change it for Hello"' in html,'a usable add-on is listed, off, with its switch')
 check(re.search(r'aria-label="More for Hello">…</summary><div class="row-menu__items">(?:(?!</details>).)*remove',html,re.S),'removing an add-on that’s off is in its row’s “…” menu')
 check('Can’t be used: the folder must be named other' in html and f'needs BlowfishCMS 9.0.0 or newer (this is {version})' in html,'unusable add-ons are listed with the reason')
 out=subprocess.run(['perl',script,'--addons'],env=env,capture_output=True,text=True).stdout
 # The request runner installs as root while the admin's worker keeps running: it sees the new one at once.
 late=addons_dir/'late';__import__('shutil').copytree(addons_dir/'hello',late)
 (late/'addon.json').write_text((late/'addon.json').read_text().replace('"name": "hello"','"name": "late"').replace('"label": "Hello"','"label": "Late"').replace('"slug": "greetings"','"slug": "late"'))
 check('<h2>Late <span class="media-label">1.0.0</span></h2>' in run('/admin/?kind=addons',user='alice',cookie=cookie)[1],'an add-on installed while the site runs is listed at once (FastCGI workers read the folder again when it changes)')
 __import__('shutil').rmtree(late)
 check('<h2>Late ' not in run('/admin/?kind=addons',user='alice',cookie=cookie)[1],'and one removed is gone at once')
 check('hello\toff\t-\tok\t-' in out and 'future\toff' in out,'the command line lists add-ons (the last column says whether one has served files)')
 # Served files (0.37): only for an add-on with its own service; request_max in MB, 1 to 64.
 probe=subprocess.run(['perl','-I',str(pathlib.Path(script).resolve().parents[1]/'lib'),'-MBlowfishCMS','-MJSON::PP','-e',
  'my $d=shift;my $m=decode_json(do{local(@ARGV,$/)="$d/addon.json";<>});print join("|",map {BlowfishCMS::addon_manifest_problem({%$m,%$_},$d)||"ok"} {files=>1},{service=>1,files=>1,request_max=>99},{service=>1,files=>1,request_max=>32}),"\n"',
  str(pathlib.Path(__file__).resolve().parent/'fixtures/addons/hello')],env=env,capture_output=True,text=True).stdout.strip()
 check(probe=='files needs "service": true (the folder belongs to its account)|request_max must be a number of MB from 1 to 64|ok','files needs a service, and request_max is a size in MB')
 # Off: nothing of it anywhere.
 check(page('/x/hello/ping')[0]==404 or run('/_addon',page_route=False)[0]==404,'an add-on that is off has no addresses')
 e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_NAME':'/_addon','DOCUMENT_URI':'/x/hello/ping','QUERY_STRING':''}
 def addon_get(path,user=''):
  p=subprocess.run(['perl',script],env=signin.sign({**e,'DOCUMENT_URI':path,'REMOTE_USER':user}),capture_output=True)
  head,_,body=p.stdout.decode().partition('\r\n\r\n');return int(re.search(r'Status: (\d+)',head).group(1)),body
 check(addon_get('/x/hello/ping')[0]==404,'an add-on that is off answers nothing')
 check('/addons/hello/' not in run('/')[1] and 'hello_greeting' not in run('/admin/?kind=page&page=home',user='alice',cookie=cookie)[1],'an add-on that is off adds no assets or blocks')
 check('kind=x-hello' not in run('/admin/',user='alice',cookie=cookie)[1],'and no admin screen')

 # ---- Switching on ----------------------------------------------------------------------
 check('There’s no usable add-on' in adm({'kind':'addons','action':'addon_enable','name':'broken'})[1],'an unusable add-on can\'t be switched on')
 status,_,hdr=adm({'kind':'addons','action':'addon_enable','name':'hello'})
 check(status==303 and sql("select count(*) from sqlite_master where name='hello_greetings'")[0][0]==1 and json.loads(sql("select value from site_settings where key='addons'")[0][0])==['hello'],'switching on runs its migration and records it')
 html=run('/admin/',user='alice',cookie=cookie)[1]
 check('kind=x-hello' not in html.split('<main')[0] and '<p class="admin-nav__group">Add-ons</p>' not in html,'its admin screen isn’t in the sidebar')
 tabs=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('<nav class="admin-tabs" aria-label="Add-ons"><a href="/admin/?kind=addons" aria-current="page">Add-ons</a></nav>' in tabs and 'href="/admin/?kind=x-hello">open</a>' in tabs,'the Add-ons screen’s tab row is short; an add-on’s row opens its screen')
 status,html,_=run('/admin/?kind=x-hello',user='alice',cookie=cookie)
 check(status==200 and 'class="hello-admin"' in html and '<nav class="admin-tabs" aria-label="Add-ons"><a href="/admin/?kind=addons">Add-ons</a><a href="/admin/?kind=x-hello" aria-current="page">Hello</a></nav>' in html,'its admin screen opens, as a tab beside Add-ons')
 pc=None
 # Its own page: made when it's switched on, off until you turn it on.
 check(sql("select addon,nav_label from pages where slug='greetings'")==[('hello','greetings')] and [b for (b,) in sql("select type from page_blocks where page='greetings'")]==['hello_greeting'],'switching it on makes its page, with its block')
 check(run('/greetings/')[0]==404 and 'Its page: Greetings at /greetings/, off. Its layout and blocks are edited under <a href="/admin/?kind=x-hello-page">Page</a>.' in html,'the page starts off, and the add-on’s tab links to its Page tab')
 # The page is edited on the add-on's Page tab (0.29): the page editor, with the add-on's tabs.
 sub=re.search(r'<nav class="admin-tabs admin-tabs--sub" aria-label="Hello">(.*?)</nav>',html,re.S)
 check(sub and re.findall(r'href="([^"]+)"',sub.group(1))==['/admin/?kind=x-hello','/admin/?kind=x-hello-page'],'an add-on with a page has a Page tab after its own screens')
 status,html,_=run('/admin/?kind=page&page=greetings',user='alice',cookie=cookie)
 check(status==200 and 'data-page-editor' in html and 'what it shows is managed on <a href="/admin/?kind=x-hello">its Hello screen</a>' in html and re.search(r'<a href="/admin/\?kind=pages"[^>]*aria-current="page"',html) and 'aria-label="Add-ons"' not in html,'its page opens in the page editor under Pages (0.39.2), with a link to the add-on’s screen')
 status,html,_=run('/admin/?kind=x-hello-page',user='alice',cookie=cookie)
 check(status==200 and 'data-page-editor' in html and 'href="/admin/?kind=x-hello-page" aria-current="page"' in html and 'id="tab-layout"' in html and 'admin-crumbs' not in html,'the Page tab is the page editor, layout and all, under the add-on’s tabs')
 lst=run('/admin/?kind=pages',user='alice',cookie=cookie)[1]
 check('href="/admin/?kind=page&amp;page=greetings">edit</a>' in lst,'Pages’ edit opens the page editor, an add-on’s page too')
 tabbed=run('/admin/?kind=x-hello-page',user='alice',cookie=cookie)[1]
 check('name="tab" value="x-hello-page"' in tabbed and 'what it shows is managed on' not in tabbed,'the Page tab’s forms come back to the tab')
 st,_,_=adm({'kind':'page','page':'greetings','action':'page_save','title':'Greetings','description':'Hello there','nav_label':'greetings','slug':'greetings','visible':'0',**{f'b.{i}.width':'full' for (i,) in sql("select id from page_blocks where page='greetings'")}})
 check(st==303 and sql("select description from pages where slug='greetings'")[0][0]=='Hello there','the editor on the Page tab saves as the page editor does')
 sql("delete from page_blocks where page='greetings'")
 html=run('/admin/?kind=x-hello-page',user='alice',cookie=cookie)[1]
 check('This page has none of Hello’s blocks yet.' in html and 'value="addon_blocks_add"' in html,'a page with none of its add-on’s blocks is offered them')
 st,_,_=adm({'kind':'page','page':'greetings','action':'addon_blocks_add'})
 check(st==303 and [b for (b,) in sql("select type from page_blocks where page='greetings'")]==['hello_greeting'] and 'none of Hello' not in run('/admin/?kind=x-hello-page',user='alice',cookie=cookie)[1],'and gets them back with one click')
 lst=run('/admin/?kind=pages',user='alice',cookie=cookie)[1]
 check('/greetings/ · visitors get “not found” · from Hello' in lst and 'manage on the Hello tab</a>' in lst,'the Pages list says which add-on a page belongs to, with a way to its tab')
 adm({'kind':'pages','action':'nav_toggle','page':'greetings'})
 status,html,_=run('/greetings/')
 check(status==200 and '<p class="hello">Hello, visitors!</p>' in html and '/greetings/' in html.split('id="main-menu"')[1].split('</div>')[0],'turned on, it shows its block and is in the navigation')
 pc=sql("select count(*) from pages")[0][0];sql("update pages set addon='',slug='elsewhere',path='/elsewhere/' where slug='greetings'");sql("update page_blocks set page='elsewhere' where page='greetings'")
 subprocess.run(['perl',script,'--migrate'],env=env,capture_output=True)
 check(sql("select addon from pages where slug='elsewhere'")==[('',)] and sql("select count(*) from pages")[0][0]==pc,'once an add-on has had a page, the update neither takes one elsewhere nor makes another')
 sql("update pages set slug='greetings',path='/greetings/' where slug='elsewhere'");sql("update page_blocks set page='greetings' where page='elsewhere'")
 subprocess.run(['perl',script,'--migrate'],env=env,capture_output=True)
 check(sql("select addon from pages where slug='greetings'")==[('hello',)] and sql("select count(*) from pages")[0][0]==pc,'but a page at its own address becomes its page again')
 sql("update pages set addon='hello' where slug='greetings'")
 status,body=addon_get('/x/hello/ping')
 check(status==200 and json.loads(body)=={'pong':1,'greetings':0},'its address answers, with the catalogue to read')
 check(addon_get('/x/hello/nothing')[0]==404 and addon_get('/x/hello/../etc')[0]==404 and addon_get('/x/hello/.hidden')[0]==404,'unknown or unsafe add-on addresses are 404')
 check(addon_get('/admin/x/hello/')[0] in (303,401,403),'add-on admin addresses need the admin account')
 css='<link rel="stylesheet" href="/addons/hello/hello.css?v=1.0.0">'
 check(css in run('/greetings/')[1] and css not in run('/')[1],'its CSS is on its own page, not on pages without its blocks')
 check('<loc>https://example.org/x/hello/ping</loc><lastmod>2026-11-01</lastmod>' in run('/sitemap.xml')[1] and 'Disallow: /x/hello/private/' in run('/robots.txt')[1],'its sitemap and robots.txt entries are added')
 # Its block on a page.
 builder=run('/admin/?kind=page&page=home',user='alice',cookie=cookie)[1]
 check(re.search(r'value="hello_greeting"[^>]*><span class="block-choice__name">Greeting</span>',builder),'its block type is offered in the page builder')
 status,_,_=adm({'kind':'page','page':'home','action':'block_add','type':'hello_greeting','width':'full'})
 html=run('/')[1]
 check(status==303 and '<p class="hello">Hello, world!</p>' in html and css in html,'its block renders on the page, with its CSS')
 check('Who to greet' in run('/admin/?kind=page&page=home',user='alice',cookie=cookie)[1],'its block\'s fields are editable')

 # ---- Switching off ------------------------------------------------------------------
 status,_,_=adm({'kind':'addons','action':'addon_disable','name':'hello'})
 html=run('/')[1]
 check(status==303 and 'class="hello"' not in html and '/addons/hello/' not in html and addon_get('/x/hello/ping')[0]==404,'switched off: its block, assets and addresses are gone')
 check(run('/greetings/')[0]==404 and '/greetings/' not in html.split('id="main-menu"')[1].split('</div>')[0] and sql("select count(*) from pages where slug='greetings'")[0][0]==1,'its page is hidden while it’s off, and kept')
 check('Block from an add-on that’s off' in run('/admin/?kind=page&page=home',user='alice',cookie=cookie)[1] and sql("select count(*) from page_blocks where type='hello_greeting'")[0][0]==2,'its blocks are kept, marked in the builder')
 check(sql("select count(*) from sqlite_master where name='hello_greetings'")[0][0]==1,'its data is kept')
 check(run('/admin/?kind=x-hello',user='alice',cookie=cookie)[0]==303,'its admin screen is gone (back to the overview)')
 # The command line (what blowfishctl uses) switches add-ons too.
 r=subprocess.run(['perl',script,'--addon-enable','hello'],env=env,capture_output=True,text=True)
 check(r.returncode==0 and 'hello: on' in r.stdout and '<p class="hello">Hello, world!</p>' in run('/')[1],'the command line switches an add-on on')
 check(run('/greetings/')[0]==200 and sql("select count(*) from pages where addon='hello'")[0][0]==1,'switched on again, its page is back (not a second one)')
 sql("delete from page_blocks where page='greetings'");sql("delete from pages where slug='greetings'")
 subprocess.run(['perl',script,'--migrate'],env=env,capture_output=True)
 check(sql("select count(*) from pages where addon='hello' or slug='greetings'")[0][0]==0 and sql("select addon from pages where slug='home'")==[('',)],'a deleted add-on page isn’t made again by the update, and Home is never adopted')
 r=subprocess.run(['perl',script,'--addon-enable','future'],env=env,capture_output=True,text=True)
 check(r.returncode==1 and 'No usable add-on called future' in r.stderr,'the command line refuses an unusable add-on')
 r=subprocess.run(['perl',script,'--hourly'],env=env,capture_output=True,text=True)
 check(r.returncode==0 and 'hello: said hello' in r.stdout,'the hourly run calls the hourly hook of add-ons that are on')
 # Hand-overs (0.45.0): what root's runner moved into addons-in/ goes to the add-on's from_service.
 inbox=data/'addons-in';inbox.mkdir(mode=0o700)
 (inbox/'hello-20261201T000000-a.json').write_text(json.dumps({'text':'from its service ☺'}),encoding='utf-8')
 (inbox/'hello-20261201T000001-b.json').write_text(json.dumps({'text':''}))
 (inbox/'future-20261201T000002-c.json').write_text(json.dumps({'text':'nobody'}))
 r=subprocess.run(['perl',script,'--addons-in'],env=env,capture_output=True,text=True)
 check(r.returncode==1 and 'kept from its service ☺' in r.stdout and sql("select text from hello_greetings")==[('from its service ☺',)],'a hand-over reaches its add-on’s from_service hook, as the admin')
 check(sorted(p.name for p in inbox.iterdir())==['failed'] and sorted(p.name for p in (inbox/'failed').iterdir())==['future-20261201T000002-c.json','future-20261201T000002-c.json.why','hello-20261201T000001-b.json','hello-20261201T000001-b.json.why']
       and 'No text to keep' in (inbox/'failed/hello-20261201T000001-b.json.why').read_text() and 'isn’t on' in (inbox/'failed/future-20261201T000002-c.json.why').read_text(),'one it refuses, or for an add-on that isn’t on, is kept aside with why')

 # ---- The list: uploads, the server's address, install, update, remove ----------------
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('doas blowfishctl addon add FILE.tar.gz' in html and 'addons_upload' not in html,'without the request runner, the screen gives the command')
 system=data/'system'
 for d in ['requests','results','downloads','releases']:(system/d).mkdir(parents=True)
 (system/'results/state.json').write_text(json.dumps({'checked':int(__import__('time').time()),'kept':[]}))
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('action="/admin/?kind=addons&amp;upload=addons" enctype="multipart/form-data"' in html and 'No add-ons uploaded yet.' in html,'with the runner: an upload form, and nothing in the list yet')
 check('addons_refresh' not in html and 'github.com' not in html,'without an address there’s nothing to check, and nothing points at GitHub')
 up=lambda blob,name='archive':run('/admin/?kind=addons&upload=addons',{'csrf':csrf,'kind':'addons','action':'addons_upload'},user='alice',cookie=cookie,files=[(name,'hello.tar.gz',blob)])
 check('.tar.gz archive' in up(b'PK\x03\x04zip')[1] and not list((system/'requests').glob('*.json')) and not list((system/'releases').iterdir()),'only gzip archives are taken')
 check('Choose the add-ons' in up(__import__('gzip').compress(b'x'),name='other')[1],'an upload needs its file')
 status,_,hdr=up(__import__('gzip').compress(b'an add-on archive',mtime=0))
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and len(req)==1 and req[0]['action']=='addons_add' and req[0]['by']=='alice','an upload files a request to add it to the list')
 rid=next((system/'requests').glob('*.json')).stem
 check((system/'releases'/f'{rid}.tar.gz').read_bytes()==__import__('gzip').compress(b'an add-on archive',mtime=0),'and the archive waits beside it for the server')
 check('still busy' in up(__import__('gzip').compress(b'more'))[1] and len(list((system/'releases').iterdir()))==1,'one request at a time, and a refused upload isn’t kept')
 for f in [*(system/'requests').glob('*.json'),*(system/'releases').iterdir()]:f.unlink()
 (system/'results/addons.json').write_text(json.dumps({'source':'https://example.org/x/repos/addons/archive/latest.tar.gz','addons':[]}))
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('takes add-ons from <code>https://example.org/x/repos/addons/archive/latest.tar.gz</code>' in html and 'Not checked yet.' in html and 'check now' in html,'a server with an address says so, with “check now”')
 status,_,hdr=adm({'kind':'addons','action':'addons_refresh'})
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and len(req)==1 and req[0]['action']=='addons_refresh' and req[0]['by']=='alice','checking files a request for the server')
 check('still busy' in adm({'kind':'addons','action':'addons_refresh'})[1],'one request at a time')
 for f in (system/'requests').glob('*.json'):f.unlink()
 (system/'results/addons.json').write_text(json.dumps({'fetched':int(__import__('time').time())-600,'source':'https://example.org/addons.tar.gz','addons':[
  {'name':'hello','label':'Hello','version':'1.2.0','blowfishcms':'0.9.0','description':'Newer hello.'},
  {'name':'extra','label':'Extra <b>','version':'2.0.0','blowfishcms':'0.9.0','description':'Something more.','author':'Someone','network':['api.example.net']},
  {'name':'later','label':'Later','version':'1.0.0','blowfishcms':'9.0.0','description':'Needs a newer site.'}]}))
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('Checked 10 minutes ago.' in html and 'update to 1.2.0' in html,'an installed add-on with a newer version offers an update')
 check('<h2>Extra &lt;b&gt; <span class="media-label">2.0.0</span></h2>' in html and 'connects to api.example.net' in html and re.search(r'value="addon_install".*?name="name" value="extra"',html,re.S),'add-ons not installed are offered, escaped')
 check('needs BlowfishCMS 9.0.0' in html and not re.search(r'value="addon_install"[^<]*(?:<[^>]*>){0,6}[^<]*value="later"',html),'one that needs a newer BlowfishCMS can’t be installed')
 status,_,hdr=adm({'kind':'addons','action':'addon_install','name':'extra'})
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and req and req[0]['action']=='addon_install' and req[0]['arg']=='extra','installing files a request')
 for f in (system/'requests').glob('*.json'):f.unlink()
 check('needs BlowfishCMS 9.0.0' in adm({'kind':'addons','action':'addon_install','name':'later'})[1] and 'no add-on called that' in adm({'kind':'addons','action':'addon_install','name':'nothere'})[1],'installs are checked against the list')
 check('already installed' in adm({'kind':'addons','action':'addon_install','name':'hello'})[1],'an installed add-on isn’t installed twice')
 status,_,_=adm({'kind':'addons','action':'addon_update','name':'hello'})
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and req and req[0]['action']=='addon_update' and req[0]['arg']=='hello','an update is only made when the owner asks')
 for f in (system/'requests').glob('*.json'):f.unlink()

 # ---- Update all: one request for every add-on with an update, at the versions shown ----------
 check('update all add-ons' not in html,'with one update there’s no “update all”, only its own button')
 now=int(__import__('time').time())
 def offer(hello,future,future_needs='0.9.0'):
  (system/'results/addons.json').write_text(json.dumps({'fetched':now-600,'source':'https://example.org/addons.tar.gz','addons':[
   {'name':'hello','label':'Hello','version':hello,'blowfishcms':'0.9.0'},{'name':'future','label':'Future','version':future,'blowfishcms':future_needs},
   {'name':'extra','label':'Extra','version':'2.0.0','blowfishcms':'0.9.0'}]}))
 offer('1.3.0','1.1.0')
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('update all add-ons (2)' in html and 'Future 1.1.0, Hello 1.3.0' in html,'two or more updates: “update all”, naming each and its version')
 toast=html.split('class="toasts"')[1] if 'class="toasts"' in html else ''
 check('2 updates for add-ons and themes' in toast and 'value="updates_all"' in toast,'arriving together, they’re one pop-up with “update all”')
 r=subprocess.run(['perl',script,'--updates','addon'],env=env,capture_output=True,text=True)
 check(r.returncode==0 and r.stdout.splitlines()==['future\t1.1.0\t','hello\t1.3.0\t'],'site.pl --updates lists them for the server’s runner')
 status,_,hdr=adm({'kind':'addons','action':'addons_update_all'})
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and len(req)==1 and req[0]['action']=='addons_update_all' and req[0]['pins']==['addon:future:1.1.0','addon:hello:1.3.0'],'update all files one request, pinned to the versions shown')
 check('still busy' in adm({'kind':'addons','action':'addons_update_all'})[1],'and waits its turn like any request')
 for f in (system/'requests').glob('*.json'):f.unlink()
 offer('1.3.0','1.1.0','9.0.0')
 r=subprocess.run(['perl',script,'--updates','addon'],env=env,capture_output=True,text=True)
 check('future\t1.1.0\t9.0.0' in r.stdout,'one that needs a newer BlowfishCMS is listed with the release it needs')
 check('update all add-ons' not in run('/admin/?kind=addons',user='alice',cookie=cookie)[1],'and isn’t counted, so one left is updated on its own')
 offer('1.3.0','1.1.0')
 html=run('/admin/?kind=notices',user='alice',cookie=cookie)[1]
 check('update all add-ons and themes (2)' in html,'Notifications has “update all add-ons and themes”')
 status,_,_=adm({'kind':'notices','action':'updates_all'})
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and req and req[0]['action']=='updates_all' and req[0]['pins']==['addon:future:1.1.0','addon:hello:1.3.0'],'which files one request for both')
 for f in (system/'requests').glob('*.json'):f.unlink()
 rid='b'*32
 (system/f'results/{rid}.json').write_text(json.dumps({'id':rid,'status':'running','action':'addons_update_all','arg':'','by':'alice','at':now}))
 (system/f'results/{rid}.log').write_text('blowfishctl: updating 1 of 2: future to 1.1.0\nblowfishctl: updating 2 of 2: hello to 1.3.0\n')
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('Updating 2 of 2: hello to 1.3.0' in html and 'disabled>update all' in html.replace('" disabled','disabled'),'while it runs, the screen says which one it’s on')
 (system/f'results/{rid}.json').write_text(json.dumps({'id':rid,'status':'failed','action':'addons_update_all','arg':'','by':'alice','at':now}))
 (system/f'results/{rid}.log').write_text('blowfishctl: updating 1 of 2: future to 1.1.0\nblowfishctl: future wasn\'t updated; it keeps the version it had\nblowfishctl: summary: updated hello 1.3.0; failed future\n')
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('The last update all: updated hello 1.3.0; failed future' in html and 'admin-notice--error' in html and 'The last request (' not in html,'then what it did, once, with its log')
 (system/f'results/{rid}.log').write_text('blowfishctl: error: the add-ons archive contains symlinks\n')
 check('The last update all: nothing was updated (the add-ons archive contains symlinks)' in run('/admin/?kind=addons',user='alice',cookie=cookie)[1],'one that stopped before updating anything says why')
 (system/f'results/{rid}.json').unlink();(system/f'results/{rid}.log').unlink()
 offer('1.2.0','1.0.0')

 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check(re.search(r'aria-label="More for Hello">…</summary><div class="row-menu__items">(?:(?!</details>).)*Switch Hello off and remove it\?',html,re.S),'an add-on that’s on can be removed too, from its “…” menu, which says it’s switched off first')
 status,body,_=adm({'kind':'addons','action':'addon_remove','name':'hello'})
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and req and req[0]['action']=='addon_remove' and req[0]['arg']=='hello','removing one that’s on files a request (the server switches it off first)')
 for f in (system/'requests').glob('*.json'):f.unlink()
 adm({'kind':'addons','action':'addon_disable','name':'hello'})
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check(re.search(r'value="addon_remove".*?value="hello"',html,re.S),'one that’s off can be removed')
 status,_,_=adm({'kind':'addons','action':'addon_remove','name':'hello'})
 req=[json.loads(f.read_text()) for f in (system/'requests').glob('*.json')]
 check(status==303 and req and req[0]['action']=='addon_remove','removing files a request')
 for f in (system/'requests').glob('*.json'):f.unlink()
 (system/'results/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json').write_text(json.dumps({'id':'a'*32,'status':'failed','action':'addon_install','arg':'extra','by':'alice','at':int(__import__('time').time())}))
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('The last request (addon_install extra) failed just now' in html and 'kind=system&amp;log='+'a'*32 in html,'a failed request is shown, with its log')
 check('data-dismiss="'+'a'*32+'"' in html and 'class="notice-dismiss"' in html,'a failed request can be hidden (remembered by its id)')
 (system/'results/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json').write_text(json.dumps({'id':'a'*32,'status':'failed','action':'addon_install','arg':'extra','by':'alice','at':int(__import__('time').time())-90000}))
 html=run('/admin/?kind=addons',user='alice',cookie=cookie)[1]
 check('The last request' not in html,'a failure more than a day old is no longer shown')
 (system/'results/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json').unlink()
print(json.dumps({'checks':len(checks)}))