"""Independent tests for async image metadata, transformations and access.""" import io from pathlib import Path import sys import unittest import uuid from urllib.parse import quote sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'tests')] from client import Client from images import bomb class Images(unittest.TestCase): def setUp(self): self.c=Client(); self.alice,self.bob,self.eve,self.chat=self.c.bootstrap() self.path='/api/v1/chats/'+self.chat['id'] self.raw=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes() def test_async_variants_and_replay(self): queued,_=self.c.attachment(self.alice,self.chat) self.assertEqual(queued['status'],'queued') key=uuid.uuid4().hex one=self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json'] self.assertEqual(self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json'],one) ready=self.c.wait_ready(self.alice,queued) self.assertEqual({v['name'] for v in ready['variants']},{'thumbnail','crop','optimized'}) dimensions={v['name']:(v['width'],v['height']) for v in ready['variants']} self.assertEqual(dimensions,{'thumbnail':(256,160),'crop':(128,128),'optimized':(320,200)}) for v in ready['variants']: import hashlib r=self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant='+v['name'],actor=self.bob) self.assertEqual(hashlib.sha256(r['bytes']).hexdigest(),v['sha256']) self.assertEqual(len(r['bytes']),v['size_bytes']) self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant=absent',404,actor=self.bob) def test_mime_bytes_pixels_and_filename(self): path=self.path+'/attachments?filename=test.png' for raw,mime,status in [(b'not image','image/png',415),(self.raw[:20],'image/png',415),(self.raw,'image/jpeg',415),(bomb(),'image/png',413),(b'x'*(10485760+1),'image/png',413)]: self.c.call('POST',path,status,actor=self.alice,raw=raw,headers={'Content-Type':mime}) for name in ('../x.png','a\\x.png','a\0.png','a\n.png','a'*256,''): self.c.call('POST',self.path+'/attachments?filename='+quote(name,safe=''),400,actor=self.alice,raw=self.raw,headers={'Content-Type':'image/png'}) def test_private_and_cross_chat(self): att,_=self.c.attachment(self.alice,self.chat) for suffix in ('','/content'): self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=self.eve) self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,401) other=self.c.call('POST','/api/v1/chats',201,actor=self.alice,body={'title':'other','member_ids':[self.alice['id']]},schema='Chat')['json'] self.c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=self.alice,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex}) if __name__=='__main__': unittest.main(verbosity=2)