BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
165 lines · 16.0 KB · download this file
#!/usr/bin/env python3
"""Library items as pages of their own: tags, likes, comments and sharing on
pictures, music, videos and articles, the switches that turn them off, and the
blocks' tag filters. Runs on a new, empty catalogue; never touches live data."""
import sys,pathlib;sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from sample_content import start_catalog
import os,tempfile,sqlite3,subprocess,json,re,urllib.parse,secrets
import signin # signs requests in (REMOTE_USER → session cookie)
script=str(pathlib.Path(sys.argv[1]).resolve())
checks=[]
def check(v,msg):
assert v,msg
checks.append(msg);print('PASS',msg,flush=True)
with tempfile.TemporaryDirectory(prefix='blowfish-items-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','video']:(root/'media/blowfishcms'/kind).mkdir(parents=True)
start_catalog(data/'catalog.sqlite')
env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_PAGES_SEED':str(pathlib.Path(__file__).resolve().parent/'fixtures/sample-pages-seed.json'),'BLOWFISH_THEMES_PATH':str(pathlib.Path(__file__).resolve().parent/'fixtures/themes')}
def run(path,fields=None,cookie='',user='',ip='192.0.2.1',fetch=False,page_route=False,item_route=False):
url=urllib.parse.urlsplit(path);body=urllib.parse.urlencode(fields or {},doseq=True).encode() if fields is not None else b''
e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST' if fields is not None else 'GET','SCRIPT_NAME':'/_item' if item_route else '/_page' if page_route else url.path,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
'CONTENT_TYPE':'application/x-www-form-urlencoded','CONTENT_LENGTH':str(len(body)),'HTTP_COOKIE':cookie,'REMOTE_USER':user,'HTTP_ORIGIN':'https://example.net','REMOTE_ADDR':ip}
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
subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.DEVNULL)
con=sqlite3.connect(data/'catalog.sqlite');con.row_factory=sqlite3.Row
check({'item_tags'}<={r[0] for r in con.execute("select name from sqlite_master")} and 'talk_off' in [r[1] for r in con.execute('pragma table_info(posts)')],'the catalogue has item tags and the per-item switch')
now='2026-01-01T00:00:00Z'
def upload(kind,title,**extra):
i=secrets.token_hex(16);f=secrets.token_hex(16)
row={'id':i,'kind':kind,'title':title,'description':extra.pop('description',''),'collection':'','filename':f+{'photography':'.jpg','music':'.mp3','video':'.mp4'}[kind],'mime':'application/octet-stream','bytes':10,'created_at':now,'folder':'','gallery_hidden':0,**extra}
con.execute('insert into uploads (%s) values (%s)'%(','.join(row),','.join('?'*len(row))),list(row.values()));con.commit();return i
pic=upload('photography','Harbour at dusk',description='Boats in the harbour',width=800,height=600)
logo=upload('photography','Logo',gallery_hidden=1)
song=upload('music','Night song');film=upload('video','Short film')
post=secrets.token_hex(16);con.execute('insert into posts (id,title,body,published_at,created_at,updated_at) values (?,?,?,?,?,?)',(post,'Hello article','Some words',now,now,now));con.commit()
# ---- Item pages -----------------------------------------------------------------
for path,title in [('/picture/%s/'%pic,'Harbour at dusk'),('/track/%s/'%song,'Night song'),('/video/%s/'%film,'Short film')]:
st,html,_=run(path)
check(st==200 and title in html and 'og:title' in html and 'data-copy-link' in html and 'https://example.net'+path in html,'%s has its own page, shareable'%path.split('/')[1])
check('action="/talk/like"' not in html,'%s: no likes until comments are set up'%path.split('/')[1])
check(run('/picture/%s/'%logo)[0]==404 and run('/picture/%s/'%song)[0]==404 and run('/picture/%s/'%('0'*32))[0]==404,'pictures kept out of galleries, wrong kinds and missing items have no page')
html=run('/track/%s/'%song)[1];check('/track/%s/"'%song not in html.split('<main')[1].split('class="post-actions"')[0],'an item’s own page doesn’t link the title to itself')
(root/'var/db/blowfishcms-comments').mkdir(parents=True)
for path in ['/picture/%s/'%pic,'/track/%s/'%song,'/video/%s/'%film,'/blog/?post='+post]:
html=run(path)[1];check('action="/talk/like"' in html and 'id="comment-form"' in html and '/js/talk.js' in html,'likes and comments on '+path.split('/')[1].split('?')[0])
# ---- Likes and comments on library items ---------------------------------------
ref='picture:'+pic
st,body,hdr=run('/talk/like',{'item':ref},fetch=True);check(st==200 and json.loads(body)['count']==1,'a picture can be liked')
st,_,hdr=run('/talk/comment',{'item':ref,'name':'Visitor One','body':'Lovely light'},ip='192.0.2.7')
check(st==303 and hdr['Location'].startswith('/picture/%s/?c=ok#comment-'%pic),'a picture can be commented on; the visitor returns to its page')
check('Lovely light' in run('/picture/%s/'%pic)[1],'the comment shows on the picture’s page')
check(run('/talk/like',{'item':'picture:'+logo})[0]==404 and run('/talk/like',{'item':'track:'+pic})[0]==404 and run('/talk/like',{'item':'nope:'+pic})[0]==404,'hidden items, wrong kinds and unknown kinds can’t be liked')
st,body,_=run('/talk/like',{'item':'video:'+film},fetch=True);check(json.loads(body)['count']==1,'a video can be liked')
st,body,_=run('/talk/like',{'item':post},fetch=True);check(json.loads(body)['count']==1,'articles keep their bare ids')
cdb=sqlite3.connect(root/'var/db/blowfishcms-comments/comments.sqlite')
check({r[0] for r in cdb.execute('select post_id from likes')}=={ref,'video:'+film,post},'likes are stored by item reference')
# ---- The admin: tags, the per-item switch, the library switch --------------------
st,html,hdr=run('/admin/?kind=photography',user='admin');csrf=re.match(r'bf_csrf=([^;]+)',hdr['Set-Cookie']).group(1);admin='bf_csrf='+csrf
check('name="tags"' in html and 'role="switch" name="talk_on"' in html and 'class="talk-switch"' in html and 'aria-label="Likes and comments on picture pages: yes. Change it"' in html,'the picture library edits tags and the likes-and-comments switches')
def admin_post(**f):return run('/admin/',{'csrf':csrf,**f},cookie=admin,user='admin')
overview=run('/admin/',cookie=admin,user='admin')[1]
check(f'<a href="/picture/{pic}/"' in overview and '(picture)' in overview and '/blog/?post=picture:' not in overview,'the Overview links a picture’s comment to the picture')
st,_,_=admin_post(kind='photography',action='item_save',id=pic,title='Harbour at dusk',description='Boats in the harbour',folder='',tags='#Sea, boats #sea #Long-Exposure! ',talk_off='0')
check(st==303 and [r[0] for r in con.execute('select tag from item_tags where item=? order by tag',(pic,))]==['boats','long-exposure','sea'],'tags are cleaned, lower-cased and kept once')
html=run('/picture/%s/'%pic)[1];check('href="/tags/sea/"' in html and 'href="/tags/boats/"' in html,'the picture’s page links its tags')
admin_post(kind='music',action='item_save',id=song,title='Night song',collection='',description='',tags='sea',talk_off='1')
html=run('/track/%s/'%song)[1];check('action="/talk/like"' not in html and 'data-copy-link' in html,'one item’s likes and comments can be turned off; it stays shareable')
check(run('/talk/like',{'item':'track:'+song})[0]==404,'and its likes are refused')
admin_post(kind='blog',action='talk_switch',on='0')
check('action="/talk/like"' not in run('/blog/?post='+post)[1] and 'action="/talk/like"' in run('/video/%s/'%film)[1],'a library’s switch turns off its likes and comments only')
admin_post(kind='blog',action='talk_switch',on='1')
st,_,_=admin_post(kind='blog',action='publish',id=post,title='Hello article',body='Some words',tags='#sea #news',talk_off='0')
check(st==303 and [r[0] for r in con.execute("select tag from item_tags where kind='blog' order by tag")]==['news','sea'],'the article editor saves tags')
st,_,_=admin_post(kind='video',action='bulk',op='tags',ids=[film],tags='#Sea #film');tagsof=lambda i:[r[0] for r in con.execute('select tag from item_tags where item=? order by tag',(i,))]
check(st==303 and tagsof(film)==['film','sea'],'tags can be added to several items at once')
admin_post(kind='video',action='bulk',op='tags',ids=[film],tags='#extra');check(tagsof(film)==['extra','film','sea'],'adding tags keeps the ones they had')
# ---- Markdown as GitHub writes it: fenced code, tables; code keeps its quotes --------------
con.execute('update posts set body=? where id=?',('Use `"q" & <b>` here.\n\n```json\n{"a": "<b>"}\n```\n\n| Name | Size |\n|---|---|\n| **x** | `1` |\n| <i> | 2 |\n',post));con.commit()
html=run('/blog/?post='+post)[1]
check('<code>"q" & <b></code>' in html and '<pre><code class="lang-json">{<span class="tok-a">"a"</span>: <span class="tok-s">"<b>"</span>}' in html,'code is shown as written, escaped once, and ``` fences make code blocks (coloured by their language since 0.40)')
check('<table><thead><tr><th>Name</th><th>Size</th></tr></thead><tbody><tr><td><strong>x</strong></td><td><code>1</code></td></tr><tr><td><i></td><td>2</td></tr></tbody></table>' in html,'pipe tables become tables, their cells escaped')
# ---- Tag pages ------------------------------------------------------------------
st,html,_=run('/tags/');check(st==200 and 'href="/tags/sea/"' in html and 'href="/tags/news/"' in html,'/tags/ lists every tag')
st,html,_=run('/tags/sea/');check(st==200 and 'Harbour at dusk' in html and 'Night song' in html and 'Hello article' in html,'a tag’s page lists everything with it, of every kind')
con.execute('update uploads set gallery_hidden=1 where id=?',(pic,));con.commit()
check('Harbour at dusk' not in run('/tags/sea/')[1],'items that aren’t public leave tag pages')
con.execute('update uploads set gallery_hidden=0 where id=?',(pic,));con.commit()
check(run('/tags/nothing-here/')[0]==404,'an unused tag is not found')
# ---- Through httpd: two-part addresses come in as /_item --------------------------
check(run('/picture/%s/'%pic,item_route=True)[0]==200 and run('/tags/sea/',item_route=True)[0]==200,'item and tag pages answer through httpd’s /_item address')
check(run('/admin/comments/',item_route=True)[0]==404 and run('/talk/like/',item_route=True)[0]==404 and run('/blog/x/',item_route=True)[0]==404,'and nothing else does')
# ---- Lists link to item pages; blocks filter by tag ------------------------------
gallery=upload('photography','Hills')
st,_,hdr=admin_post(kind='pages',action='page_create',label='Tagged',slug='')
check(st==303 and 'page=tagged' in hdr['Location'],'a page to hold the blocks')
admin_post(kind='pages',action='nav_toggle',page='tagged')
for t in ['gallery','music','posts','videos']:admin_post(kind='page',page='tagged',action='block_add',type=t,width='full')
blocks={r['type']:r['id'] for r in con.execute("select id,type from page_blocks where page='tagged'")}
check(set(blocks)>={'gallery','music','posts'},'gallery, music and posts blocks added')
page=lambda:run('/tagged/',page_route=True)[1]
html=page()
check('data-page="/picture/%s/"'%pic in html,'a gallery’s viewer links each picture to its page')
check('<a href="/track/%s/">Night song</a>'%song in html,'a music list links each track to its page')
check(re.search(r'<a href="/video/%s/">Short film</a></h2><span class="post-stats">♥ 1 · 0 comments</span>'%film,html),'lists link videos to their pages, with likes and comments counts')
check(re.search(r'<a href="/track/%s/">Night song</a></h2>(?!<span class="post-stats")'%song,html),'but not counts for an item with likes and comments off')
con.executemany("update page_blocks set data=json_set(data,'$.tag','sea') where id=?",[(blocks[t],) for t in ('gallery','music','posts')]);con.commit()
html=page()
check('Harbour at dusk' in html and 'Hills' not in html,'a gallery can show only pictures with a tag')
check('Night song' in html and 'Hello article' in html,'music and posts blocks filter by tag too')
# ---- Comments and sharing on any page (0.39): the block, keyed by its own id --------------
admin_post(kind='page',page='tagged',action='block_add',type='talk',width='full')
talk=con.execute("select id from page_blocks where page='tagged' and type='talk'").fetchone()[0]
html=page()
check('id="post-actions"' in html and 'data-copy-link' in html and 'action="/talk/like"' in html and 'id="comment-form"' in html and '/js/talk.js' in html,'a Comments and sharing block gives a page sharing, likes and comments')
check('<meta property="og:title"' in html,'and link previews for sharing')
st,body,_=run('/talk/like',{'item':'page:'+talk},fetch=True);check(st==200 and json.loads(body)['count']==1,'the page can be liked')
st,_,hdr=run('/talk/comment',{'item':'page:'+talk,'name':'Page Visitor','body':'Great stream'},ip='192.0.2.31')
check(st==303 and hdr['Location'].startswith('/tagged/?c=ok') and 'Great stream' in page(),'commented on, back on the page itself')
check('Great stream' in run('/admin/comments/?library=page',user='admin')[1],'the Comments screen lists them under pages')
check(run('/talk/like',{'item':'page:'+'0'*16})[0]==404,'only a page’s own block takes them')
admin_post(kind='pages',action='nav_toggle',page='tagged')
check(run('/talk/like',{'item':'page:'+talk})[0]==404,'nor one on a page that’s off')
admin_post(kind='pages',action='nav_toggle',page='tagged')
admin_post(kind='page',page='tagged',action='block_delete',id=talk)
check(con.execute("select count(*) from page_blocks where id=?",(talk,)).fetchone()[0]==0,'and the block can be removed like any other')
# ---- Tag buttons for visitors, on any list ---------------------------------------------
con.executemany("update page_blocks set data=json_set(json_set(data,'$.tag',''),'$.tag_buttons',1) where id=?",[(blocks[t],) for t in ('gallery','music','videos')]);con.commit()
html=page()
vid=html.split('class="video-list"')[0].rsplit('<div class="tag-filter"',1)[1]
check('data-tag="film"' in vid and 'data-tag="sea"' in vid and 'data-tag=""' in vid,'a list offers buttons for its items’ tags, and “all”')
check(re.search(r'<article class="video-card" data-collection="" data-tags="extra film sea">',html),'each item carries its tags for the page script')
check(html.count('class="tag-filter"')==3,'galleries and music lists can have them too')
con.execute("update page_blocks set data=json_set(data,'$.tag_buttons',0) where id=?",(blocks['videos'],));con.commit()
check(page().count('class="tag-filter"')==2,'and they’re off unless chosen')
# ---- A video's page tells search engines what it is ---------------------------------------
con.execute('update uploads set duration=754,width=1920,height=1080 where id=?',(film,));con.commit()
html=run('/video/%s/'%film)[1]
ld=[json.loads(x) for x in re.findall(r'<script type="application/ld\+json">(.*?)</script>',html)]
vo=[x for x in ld if x.get('@type')=='VideoObject']
check(len(vo)==1 and vo[0]['name']=='Short film' and vo[0]['duration']=='PT12M34S' and vo[0]['contentUrl'].startswith('https://example.net/media/') and vo[0]['url']=='https://example.net/video/%s/'%film and vo[0]['width']==1920,'a video’s page has its VideoObject: name, duration, address, size')
check(not any(x.get('@type')=='VideoObject' for p in ('/picture/%s/'%pic,'/track/%s/'%song) for x in [json.loads(y) for y in re.findall(r'<script type="application/ld\+json">(.*?)</script>',run(p)[1])]),'and only videos’ pages do')
# ---- Deleting an item removes its tags ------------------------------------------
admin_post(kind='photography',action='delete',id=pic)
check(con.execute('select count(*) from item_tags where item=?',(pic,)).fetchone()[0]==0,'deleting a picture removes its tags')
admin_post(kind='blog',action='delete_post',id=post)
check(con.execute("select count(*) from item_tags where kind='blog'").fetchone()[0]==0,'deleting an article removes its tags')
print(json.dumps({'checks':len(checks)}))