import urllib.request, urllib.error, json, pathlib, subprocess
root=pathlib.Path(__file__).parent
host='http://gitea.127.0.0.1.nip.io:3917'
token=(root/'token').read_text().strip()
def api(path, body=None, method=None):
    req=urllib.request.Request(host+'/api/v1/'+path, data=json.dumps(body).encode() if body is not None else None, headers={'Authorization':'token '+token,'Content-Type':'application/json'}, method=method)
    return json.load(urllib.request.urlopen(req))
api('user/repos',{'name':'secret','private':True,'auto_init':True,'default_branch':'main'})
api('repos/tester/secret/branches',{'new_branch_name':'feature','old_branch_name':'main'})
import base64
api('repos/tester/secret/contents/feature.txt',{'branch':'feature','content':base64.b64encode(b'Feature with a private screenshot\n').decode(),'message':'Add feature'})
api('repos/tester/secret/pulls',{'head':'feature','base':'main','title':'Feature with screenshot','body':'Screenshot below'})
raw=subprocess.check_output(['curl','-fsS','-H','Authorization: token '+token,'-F','attachment=@'+str(root/'shot.png'),host+'/api/v1/repos/tester/secret/issues/1/assets'])
asset=json.loads(raw)
url=host+'/attachments/'+asset['uuid']
api('repos/tester/secret/issues/1',{'body':'Screenshot below\n\n![shot]('+url+')'},'PATCH')
for auth in [False, True]:
    req=urllib.request.Request(url, headers={'Authorization':'token '+token} if auth else {})
    try:
        res=urllib.request.urlopen(req)
        print('authenticated' if auth else 'anonymous',res.status,res.headers.get('Content-Type'))
    except urllib.error.HTTPError as e:
        print('authenticated' if auth else 'anonymous',e.code)
(root/'fixture.json').write_text(json.dumps({'remote':host+'/tester/secret.git','attachment':url}))
