test_3_0_ldp.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  1. import hashlib
  2. import pdb
  3. import pytest
  4. from base64 import b64encode
  5. from datetime import timedelta
  6. from hashlib import sha1, sha256, blake2b
  7. from uuid import uuid4
  8. from werkzeug.http import http_date
  9. import arrow
  10. import requests
  11. from flask import g
  12. from rdflib import Graph
  13. from rdflib.compare import isomorphic
  14. from rdflib.namespace import RDF
  15. from rdflib.term import Literal, URIRef
  16. from lakesuperior import env
  17. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  18. from lakesuperior.model.ldp.ldpr import Ldpr
  19. digest_algo = env.app_globals.config['application']['uuid']['algo']
  20. @pytest.fixture(scope='module')
  21. def random_uuid():
  22. return str(uuid4())
  23. @pytest.mark.usefixtures('client_class')
  24. @pytest.mark.usefixtures('db')
  25. class TestLdp:
  26. """
  27. Test HTTP interaction with LDP endpoint.
  28. """
  29. def test_get_root_node(self):
  30. """
  31. Get the root node from two different endpoints.
  32. The test triplestore must be initialized, hence the `db` fixture.
  33. """
  34. ldp_resp = self.client.get('/ldp')
  35. rest_resp = self.client.get('/rest')
  36. assert ldp_resp.status_code == 200
  37. assert rest_resp.status_code == 200
  38. def test_put_empty_ldpr(self):
  39. """
  40. Check response headers for a PUT operation with empty payload.
  41. """
  42. url = f'/ldp/empty-{uuid4()}'
  43. rsp = self.client.put(url)
  44. assert rsp.status_code == 201
  45. assert rsp.data == bytes(url.replace('/ldp', g.webroot), 'utf-8')
  46. def test_put_empty_ldpnr(self):
  47. """
  48. Check response headers for a PUT operation with empty payload.
  49. Without specifying a MIME type, an LDP-NR should be created.
  50. """
  51. url = f'/ldp/empty-{uuid4()}'
  52. rsp = self.client.put(url)
  53. get_rsp = self.client.get(url)
  54. assert 'application/octet-stream' in get_rsp.content_type
  55. assert (
  56. '<http://www.w3.org/ns/ldp#NonRDFSource>;rel="type"'
  57. in get_rsp.headers.get_all('link'))
  58. def test_put_empty_ldprs(self):
  59. """
  60. Check response headers for a PUT operation with empty payload.
  61. Specify MIME type to force LDPC creation.
  62. """
  63. url = f'/ldp/empty-{uuid4()}'
  64. rsp = self.client.put(url, content_type='text/turtle')
  65. get_rsp = self.client.get(url)
  66. assert 'text/turtle' in get_rsp.content_type
  67. assert (
  68. '<http://www.w3.org/ns/ldp#RDFSource>;rel="type"'
  69. in get_rsp.headers.get_all('link'))
  70. def test_put_existing_ldpnr_empty(self):
  71. """
  72. Trying to PUT an existing LDP-NR should return a 204 if the LDP
  73. interaction type is the same.
  74. """
  75. url = f'/ldp/overwrite-{uuid4()}'
  76. self.client.put(url)
  77. put2_resp = self.client.put(url)
  78. assert put2_resp.status_code == 204
  79. def test_put_existing_ldprs_empty(self):
  80. """
  81. Trying to PUT an existing LDP-RS should return a 204 if the LDP
  82. interaction type is the same.
  83. """
  84. url = f'/ldp/overwrite-{uuid4()}'
  85. self.client.put(url, content_type='text/turtle')
  86. put2_resp = self.client.put(url, content_type='text/turtle')
  87. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  88. put2_resp = self.client.put(
  89. url, data=f, content_type='text/turtle')
  90. assert put2_resp.status_code == 204
  91. def test_put_existing_ldpnr_conflict(self):
  92. """
  93. Trying to PUT an existing LDP-RS should return a 415 if the LDP
  94. interaction type is different.
  95. """
  96. url = f'/ldp/overwrite-{uuid4()}'
  97. put1_resp = self.client.put(url)
  98. assert put1_resp.status_code == 201
  99. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  100. put2_resp = self.client.put(
  101. url, data=f, content_type='text/turtle')
  102. assert put2_resp.status_code == 415
  103. def test_put_existing_ldpnr_conflict(self):
  104. """
  105. Trying to PUT an existing LDP-RS should return a 415 if the LDP
  106. interaction type is different.
  107. """
  108. url = f'/ldp/overwrite-{uuid4()}'
  109. put1_resp = self.client.put(url, content_type='text/turtle')
  110. put2_resp = self.client.put(url, data=b'hello')
  111. assert put2_resp.status_code == 415
  112. def test_put_force_ldpnr(self):
  113. """
  114. Test forcing LDP-NR creation even with an RDF content type.
  115. """
  116. url = f'/ldp/force_ldpnr-{uuid4()}'
  117. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  118. rsp = self.client.put(
  119. url, data=f, content_type='text/turtle',
  120. headers={
  121. 'link': '<http://www.w3.org/ns/ldp#NonRDFSource>;rel="type"'
  122. })
  123. f.seek(0)
  124. data = f.read()
  125. get_rsp = self.client.get(url)
  126. assert 'text/turtle' in get_rsp.content_type
  127. assert (
  128. '<http://www.w3.org/ns/ldp#NonRDFSource>;rel="type"'
  129. in get_rsp.headers.get_all('link'))
  130. assert get_rsp.data == data
  131. def test_put_tree(self, client):
  132. """
  133. PUT a resource with several path segments.
  134. The test should create intermediate path segments that are LDPCs,
  135. accessible to PUT or POST.
  136. """
  137. path = '/ldp/test_tree/a/b/c/d/e/f/g'
  138. self.client.put(path)
  139. assert self.client.get(path).status_code == 200
  140. assert self.client.get('/ldp/test_tree/a/b/c').status_code == 200
  141. assert self.client.post(
  142. '/ldp/test_tree/a/b',
  143. content_type='text/turtle').status_code == 201
  144. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  145. put_int_resp = self.client.put(
  146. 'ldp/test_tree/a', data=f, content_type='text/turtle')
  147. assert put_int_resp.status_code == 204
  148. # @TODO More thorough testing of contents
  149. def test_put_nested_tree(self, client):
  150. """
  151. Verify that containment is set correctly in nested hierarchies.
  152. First put a new hierarchy and verify that the root node is its
  153. container; then put another hierarchy under it and verify that the
  154. first hierarchy is the container of the second one.
  155. """
  156. uuid1 = 'test_nested_tree/a/b/c/d'
  157. uuid2 = uuid1 + '/e/f/g'
  158. path1 = '/ldp/' + uuid1
  159. path2 = '/ldp/' + uuid2
  160. self.client.put(path1, content_type='text/turtle')
  161. cont1_data = self.client.get('/ldp').data
  162. gr1 = Graph().parse(data=cont1_data, format='turtle')
  163. assert gr1[ URIRef(g.webroot + '/') : nsc['ldp'].contains : \
  164. URIRef(g.webroot + '/test_nested_tree') ]
  165. self.client.put(path2, content_type='text/turtle')
  166. cont2_data = self.client.get(path1).data
  167. gr2 = Graph().parse(data=cont2_data, format='turtle')
  168. assert gr2[ URIRef(g.webroot + '/' + uuid1) : \
  169. nsc['ldp'].contains : \
  170. URIRef(g.webroot + '/' + uuid1 + '/e') ]
  171. def test_put_ldp_rs(self, client):
  172. """
  173. PUT a resource with RDF payload and verify.
  174. """
  175. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  176. self.client.put('/ldp/ldprs01', data=f, content_type='text/turtle')
  177. resp = self.client.get('/ldp/ldprs01',
  178. headers={'accept' : 'text/turtle'})
  179. assert resp.status_code == 200
  180. gr = Graph().parse(data=resp.data, format='text/turtle')
  181. assert URIRef('http://vocab.getty.edu/ontology#Subject') in \
  182. gr.objects(None, RDF.type)
  183. def test_put_ldp_nr(self, rnd_img):
  184. """
  185. PUT a resource with binary payload and verify checksums.
  186. """
  187. rnd_img['content'].seek(0)
  188. resp = self.client.put('/ldp/ldpnr01', data=rnd_img['content'],
  189. headers={
  190. 'Content-Type': 'image/png',
  191. 'Content-Disposition' : 'attachment; filename={}'.format(
  192. rnd_img['filename'])})
  193. assert resp.status_code == 201
  194. resp = self.client.get(
  195. '/ldp/ldpnr01', headers={'accept' : 'image/png'})
  196. assert resp.status_code == 200
  197. assert sha1(resp.data).hexdigest() == rnd_img['hash']
  198. def test_put_ldp_nr_multipart(self, rnd_img):
  199. """
  200. PUT a resource with a multipart/form-data payload.
  201. """
  202. rnd_img['content'].seek(0)
  203. resp = self.client.put(
  204. '/ldp/ldpnr02',
  205. data={
  206. 'file': (
  207. rnd_img['content'], rnd_img['filename'],
  208. 'image/png',
  209. )
  210. }
  211. )
  212. assert resp.status_code == 201
  213. resp = self.client.get(
  214. '/ldp/ldpnr02', headers={'accept' : 'image/png'})
  215. assert resp.status_code == 200
  216. assert sha1(resp.data).hexdigest() == rnd_img['hash']
  217. def test_get_ldp_nr(self, rnd_img):
  218. """
  219. PUT a resource with binary payload and test various retieval methods.
  220. """
  221. uid = '/ldpnr03'
  222. path = '/ldp' + uid
  223. content = b'This is some exciting content.'
  224. resp = self.client.put(path, data=content,
  225. headers={
  226. 'Content-Type': 'text/plain',
  227. 'Content-Disposition' : 'attachment; filename=exciting.txt'})
  228. assert resp.status_code == 201
  229. uri = g.webroot + uid
  230. # Content retrieval methods.
  231. resp_bin1 = self.client.get(path)
  232. assert resp_bin1.status_code == 200
  233. assert resp_bin1.data == content
  234. resp_bin2 = self.client.get(path, headers={'accept' : 'text/plain'})
  235. assert resp_bin2.status_code == 200
  236. assert resp_bin2.data == content
  237. resp_bin3 = self.client.get(path + '/fcr:content')
  238. assert resp_bin3.status_code == 200
  239. assert resp_bin3.data == content
  240. # Metadata retrieval methods.
  241. resp_md1 = self.client.get(path, headers={'accept' : 'text/turtle'})
  242. assert resp_md1.status_code == 200
  243. gr1 = Graph().parse(data=resp_md1.data, format='text/turtle')
  244. assert gr1[ URIRef(uri) : nsc['rdf'].type : nsc['ldp'].Resource]
  245. resp_md2 = self.client.get(path + '/fcr:metadata')
  246. assert resp_md2.status_code == 200
  247. gr2 = Graph().parse(data=resp_md2.data, format='text/turtle')
  248. assert isomorphic(gr1, gr2)
  249. def test_metadata_describe_header(self):
  250. """
  251. Verify that a "describe" Link header is presented for LDP-NR metadata.
  252. """
  253. uid = f'/{uuid4()}'
  254. self.client.put(f'/ldp{uid}', data=b'ciao')
  255. md_rsp = self.client.get(f'/ldp{uid}/fcr:metadata')
  256. assert (
  257. f'<{g.tbox.uid_to_uri(uid)}>; rel=describes'
  258. in md_rsp.headers.get_all('Link'))
  259. def test_put_mismatched_ldp_rs(self, rnd_img):
  260. """
  261. Verify MIME type / LDP mismatch.
  262. PUT a LDP-RS, then PUT a LDP-NR on the same location and verify it
  263. fails.
  264. """
  265. path = '/ldp/' + str(uuid4())
  266. rnd_img['content'].seek(0)
  267. ldp_nr_resp = self.client.put(path, data=rnd_img['content'],
  268. headers={
  269. 'Content-Disposition' : 'attachment; filename={}'.format(
  270. rnd_img['filename'])})
  271. assert ldp_nr_resp.status_code == 201
  272. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  273. ldp_rs_resp = self.client.put(path, data=f,
  274. content_type='text/turtle')
  275. assert ldp_rs_resp.status_code == 415
  276. def test_put_mismatched_ldp_nr(self, rnd_img):
  277. """
  278. Verify MIME type / LDP mismatch.
  279. PUT a LDP-NR, then PUT a LDP-RS on the same location and verify it
  280. fails.
  281. """
  282. path = '/ldp/' + str(uuid4())
  283. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  284. ldp_rs_resp = self.client.put(path, data=f,
  285. content_type='text/turtle')
  286. assert ldp_rs_resp.status_code == 201
  287. rnd_img['content'].seek(0)
  288. ldp_nr_resp = self.client.put(path, data=rnd_img['content'],
  289. headers={
  290. 'Content-Disposition' : 'attachment; filename={}'.format(
  291. rnd_img['filename'])})
  292. assert ldp_nr_resp.status_code == 415
  293. def test_missing_reference(self, client):
  294. """
  295. PUT a resource with RDF payload referencing a non-existing in-repo
  296. resource.
  297. """
  298. self.client.get('/ldp')
  299. data = '''
  300. PREFIX ns: <http://example.org#>
  301. PREFIX res: <http://example-source.org/res/>
  302. <> ns:p1 res:bogus ;
  303. ns:p2 <{0}> ;
  304. ns:p3 <{0}/> ;
  305. ns:p4 <{0}/nonexistent> .
  306. '''.format(g.webroot)
  307. put_rsp = self.client.put('/ldp/test_missing_ref', data=data, headers={
  308. 'content-type': 'text/turtle'})
  309. assert put_rsp.status_code == 201
  310. resp = self.client.get('/ldp/test_missing_ref',
  311. headers={'accept' : 'text/turtle'})
  312. assert resp.status_code == 200
  313. gr = Graph().parse(data=resp.data, format='text/turtle')
  314. assert URIRef('http://example-source.org/res/bogus') in \
  315. gr.objects(None, URIRef('http://example.org#p1'))
  316. assert URIRef(g.webroot + '/') in (
  317. gr.objects(None, URIRef('http://example.org#p2')))
  318. assert URIRef(g.webroot + '/') in (
  319. gr.objects(None, URIRef('http://example.org#p3')))
  320. assert URIRef(g.webroot + '/nonexistent') not in (
  321. gr.objects(None, URIRef('http://example.org#p4')))
  322. def test_post_resource(self, client):
  323. """
  324. Check response headers for a POST operation with empty payload.
  325. """
  326. res = self.client.post('/ldp/')
  327. assert res.status_code == 201
  328. assert 'Location' in res.headers
  329. def test_post_ldp_nr(self, rnd_img):
  330. """
  331. POST a resource with binary payload and verify checksums.
  332. """
  333. rnd_img['content'].seek(0)
  334. resp = self.client.post('/ldp/', data=rnd_img['content'],
  335. headers={
  336. 'slug': 'ldpnr04',
  337. 'Content-Type': 'image/png',
  338. 'Content-Disposition' : 'attachment; filename={}'.format(
  339. rnd_img['filename'])})
  340. assert resp.status_code == 201
  341. resp = self.client.get(
  342. '/ldp/ldpnr04', headers={'accept' : 'image/png'})
  343. assert resp.status_code == 200
  344. assert sha1(resp.data).hexdigest() == rnd_img['hash']
  345. def test_post_slug(self):
  346. """
  347. Verify that a POST with slug results in the expected URI only if the
  348. resource does not exist already.
  349. """
  350. slug01_resp = self.client.post('/ldp', headers={'slug' : 'slug01'})
  351. assert slug01_resp.status_code == 201
  352. assert slug01_resp.headers['location'] == \
  353. g.webroot + '/slug01'
  354. slug02_resp = self.client.post('/ldp', headers={'slug' : 'slug01'})
  355. assert slug02_resp.status_code == 201
  356. assert slug02_resp.headers['location'] != \
  357. g.webroot + '/slug01'
  358. def test_post_404(self):
  359. """
  360. Verify that a POST to a non-existing parent results in a 404.
  361. """
  362. assert self.client.post('/ldp/{}'.format(uuid4()))\
  363. .status_code == 404
  364. def test_post_409(self, rnd_img):
  365. """
  366. Verify that you cannot POST to a binary resource.
  367. """
  368. rnd_img['content'].seek(0)
  369. self.client.put('/ldp/post_409', data=rnd_img['content'], headers={
  370. 'Content-Disposition' : 'attachment; filename={}'.format(
  371. rnd_img['filename'])})
  372. assert self.client.post('/ldp/post_409').status_code == 409
  373. def test_patch_root(self):
  374. """
  375. Test patching root node.
  376. """
  377. path = '/ldp/'
  378. self.client.get(path)
  379. uri = g.webroot + '/'
  380. with open('tests/data/sparql_update/simple_insert.sparql') as data:
  381. resp = self.client.patch(path,
  382. data=data,
  383. headers={'content-type' : 'application/sparql-update'})
  384. assert resp.status_code == 204
  385. resp = self.client.get(path)
  386. gr = Graph().parse(data=resp.data, format='text/turtle')
  387. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Hello') ]
  388. def test_patch(self):
  389. """
  390. Test patching a resource.
  391. """
  392. path = '/ldp/test_patch01'
  393. self.client.put(path, content_type='text/turtle')
  394. uri = g.webroot + '/test_patch01'
  395. with open('tests/data/sparql_update/simple_insert.sparql') as data:
  396. resp = self.client.patch(path,
  397. data=data,
  398. headers={'content-type' : 'application/sparql-update'})
  399. assert resp.status_code == 204
  400. resp = self.client.get(path)
  401. gr = Graph().parse(data=resp.data, format='text/turtle')
  402. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Hello') ]
  403. self.client.patch(path,
  404. data=open('tests/data/sparql_update/delete+insert+where.sparql'),
  405. headers={'content-type' : 'application/sparql-update'})
  406. resp = self.client.get(path)
  407. gr = Graph().parse(data=resp.data, format='text/turtle')
  408. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Ciao') ]
  409. def test_patch_no_single_subject(self):
  410. """
  411. Test patching a resource violating the single-subject rule.
  412. """
  413. path = '/ldp/test_patch_ssr'
  414. self.client.put(path, content_type='text/turtle')
  415. uri = g.webroot + '/test_patch_ssr'
  416. nossr_qry = 'INSERT { <http://bogus.org> a <urn:ns:A> . } WHERE {}'
  417. abs_qry = 'INSERT {{ <{}> a <urn:ns:A> . }} WHERE {{}}'.format(uri)
  418. frag_qry = 'INSERT {{ <{}#frag> a <urn:ns:A> . }} WHERE {{}}'\
  419. .format(uri)
  420. # @TODO Leave commented until a decision is made about SSR.
  421. assert self.client.patch(
  422. path, data=nossr_qry,
  423. headers={'content-type': 'application/sparql-update'}
  424. ).status_code == 204
  425. assert self.client.patch(
  426. path, data=abs_qry,
  427. headers={'content-type': 'application/sparql-update'}
  428. ).status_code == 204
  429. assert self.client.patch(
  430. path, data=frag_qry,
  431. headers={'content-type': 'application/sparql-update'}
  432. ).status_code == 204
  433. def test_patch_ldp_nr_metadata(self):
  434. """
  435. Test patching a LDP-NR metadata resource from the fcr:metadata URI.
  436. """
  437. path = '/ldp/ldpnr01'
  438. with open('tests/data/sparql_update/simple_insert.sparql') as data:
  439. self.client.patch(path + '/fcr:metadata',
  440. data=data,
  441. headers={'content-type' : 'application/sparql-update'})
  442. resp = self.client.get(path + '/fcr:metadata')
  443. assert resp.status_code == 200
  444. uri = g.webroot + '/ldpnr01'
  445. gr = Graph().parse(data=resp.data, format='text/turtle')
  446. assert gr[URIRef(uri) : nsc['dc'].title : Literal('Hello')]
  447. with open(
  448. 'tests/data/sparql_update/delete+insert+where.sparql') as data:
  449. patch_resp = self.client.patch(path + '/fcr:metadata',
  450. data=data,
  451. headers={'content-type' : 'application/sparql-update'})
  452. assert patch_resp.status_code == 204
  453. resp = self.client.get(path + '/fcr:metadata')
  454. assert resp.status_code == 200
  455. gr = Graph().parse(data=resp.data, format='text/turtle')
  456. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Ciao') ]
  457. def test_patch_ldpnr(self):
  458. """
  459. Verify that a direct PATCH to a LDP-NR results in a 415.
  460. """
  461. with open(
  462. 'tests/data/sparql_update/delete+insert+where.sparql') as data:
  463. patch_resp = self.client.patch('/ldp/ldpnr01',
  464. data=data,
  465. headers={'content-type': 'application/sparql-update'})
  466. assert patch_resp.status_code == 415
  467. def test_patch_invalid_mimetype(self, rnd_img):
  468. """
  469. Verify that a PATCH using anything other than an
  470. `application/sparql-update` MIME type results in an error.
  471. """
  472. self.client.put(
  473. '/ldp/test_patch_invalid_mimetype', content_type='text/turtle')
  474. rnd_img['content'].seek(0)
  475. ldpnr_resp = self.client.patch('/ldp/ldpnr01/fcr:metadata',
  476. data=rnd_img,
  477. headers={'content-type' : 'image/jpeg'})
  478. ldprs_resp = self.client.patch('/ldp/test_patch_invalid_mimetype',
  479. data=b'Hello, I\'m not a SPARQL update.',
  480. headers={'content-type' : 'text/plain'})
  481. assert ldprs_resp.status_code == ldpnr_resp.status_code == 415
  482. def test_patch_srv_mgd_pred(self, rnd_img):
  483. """
  484. Verify that adding or removing a server-managed predicate fails.
  485. """
  486. uid = '/test_patch_sm_pred'
  487. path = f'/ldp{uid}'
  488. self.client.put(path, content_type='text/turtle')
  489. self.client.put(path + '/child1', content_type='text/turtle')
  490. uri = g.webroot + uid
  491. ins_qry1 = f'INSERT {{ <> <{nsc["ldp"].contains}> <http://bogus.com/ext1> . }} WHERE {{}}'
  492. ins_qry2 = (
  493. f'INSERT {{ <> <{nsc["fcrepo"].created}>'
  494. f'"2019-04-01T05:57:36.899033+00:00"^^<{nsc["xsd"].dateTime}> . }}'
  495. 'WHERE {}'
  496. )
  497. # The following won't change the graph so it does not raise an error.
  498. ins_qry3 = f'INSERT {{ <> a <{nsc["ldp"].Container}> . }} WHERE {{}}'
  499. del_qry1 = (
  500. f'DELETE {{ <> <{nsc["ldp"].contains}> ?o . }} '
  501. f'WHERE {{ <> <{nsc["ldp"].contains}> ?o . }}'
  502. )
  503. del_qry2 = f'DELETE {{ <> a <{nsc["ldp"].Container}> . }} WHERE {{}}'
  504. # No-op as ins_qry3
  505. del_qry3 = (
  506. f'DELETE {{ <> a <{nsc["ldp"].DirectContainer}> .}} '
  507. 'WHERE {}'
  508. )
  509. assert self.client.patch(
  510. path, data=ins_qry1,
  511. headers={'content-type': 'application/sparql-update'}
  512. ).status_code == 412
  513. assert self.client.patch(
  514. path, data=ins_qry1,
  515. headers={
  516. 'content-type': 'application/sparql-update',
  517. 'prefer': 'handling=lenient',
  518. }
  519. ).status_code == 204
  520. assert self.client.patch(
  521. path, data=ins_qry2,
  522. headers={'content-type': 'application/sparql-update'}
  523. ).status_code == 412
  524. assert self.client.patch(
  525. path, data=ins_qry2,
  526. headers={
  527. 'content-type': 'application/sparql-update',
  528. 'prefer': 'handling=lenient',
  529. }
  530. ).status_code == 204
  531. assert self.client.patch(
  532. path, data=ins_qry3,
  533. headers={'content-type': 'application/sparql-update'}
  534. ).status_code == 204
  535. assert self.client.patch(
  536. path, data=del_qry1,
  537. headers={'content-type': 'application/sparql-update'}
  538. ).status_code == 412
  539. assert self.client.patch(
  540. path, data=del_qry1,
  541. headers={
  542. 'content-type': 'application/sparql-update',
  543. 'prefer': 'handling=lenient',
  544. }
  545. ).status_code == 204
  546. assert self.client.patch(
  547. path, data=del_qry2,
  548. headers={'content-type': 'application/sparql-update'}
  549. ).status_code == 412
  550. assert self.client.patch(
  551. path, data=ins_qry2,
  552. headers={
  553. 'content-type': 'application/sparql-update',
  554. 'prefer': 'handling=lenient',
  555. }
  556. ).status_code == 204
  557. assert self.client.patch(
  558. path, data=del_qry3,
  559. headers={'content-type': 'application/sparql-update'}
  560. ).status_code == 204
  561. def test_delete(self):
  562. """
  563. Test delete response codes.
  564. """
  565. self.client.put('/ldp/test_delete01')
  566. delete_resp = self.client.delete('/ldp/test_delete01')
  567. assert delete_resp.status_code == 204
  568. bogus_delete_resp = self.client.delete('/ldp/test_delete101')
  569. assert bogus_delete_resp.status_code == 404
  570. def test_tombstone(self):
  571. """
  572. Test tombstone behaviors.
  573. For POST on a tombstone, check `test_resurrection`.
  574. """
  575. tstone_resp = self.client.get('/ldp/test_delete01')
  576. assert tstone_resp.status_code == 410
  577. assert tstone_resp.headers['Link'] == \
  578. '<{}/test_delete01/fcr:tombstone>; rel="hasTombstone"'\
  579. .format(g.webroot)
  580. tstone_path = '/ldp/test_delete01/fcr:tombstone'
  581. assert self.client.get(tstone_path).status_code == 405
  582. assert self.client.put(tstone_path).status_code == 405
  583. assert self.client.delete(tstone_path).status_code == 204
  584. assert self.client.get('/ldp/test_delete01').status_code == 404
  585. def test_delete_recursive(self):
  586. """
  587. Test response codes for resources deleted recursively and their
  588. tombstones.
  589. """
  590. child_suffixes = ('a', 'a/b', 'a/b/c', 'a1', 'a1/b1')
  591. self.client.put('/ldp/test_delete_recursive01')
  592. for cs in child_suffixes:
  593. self.client.put('/ldp/test_delete_recursive01/{}'.format(cs))
  594. assert self.client.delete(
  595. '/ldp/test_delete_recursive01').status_code == 204
  596. tstone_resp = self.client.get('/ldp/test_delete_recursive01')
  597. assert tstone_resp.status_code == 410
  598. assert tstone_resp.headers['Link'] == \
  599. '<{}/test_delete_recursive01/fcr:tombstone>; rel="hasTombstone"'\
  600. .format(g.webroot)
  601. for cs in child_suffixes:
  602. child_tstone_resp = self.client.get(
  603. '/ldp/test_delete_recursive01/{}'.format(cs))
  604. assert child_tstone_resp.status_code == tstone_resp.status_code
  605. assert 'Link' not in child_tstone_resp.headers.keys()
  606. def test_put_fragments(self):
  607. """
  608. Test the correct handling of fragment URIs on PUT and GET.
  609. """
  610. with open('tests/data/fragments.ttl', 'rb') as f:
  611. self.client.put(
  612. '/ldp/test_fragment01', content_type='text/turtle', data=f)
  613. rsp = self.client.get('/ldp/test_fragment01')
  614. gr = Graph().parse(data=rsp.data, format='text/turtle')
  615. assert gr[
  616. URIRef(g.webroot + '/test_fragment01#hash1')
  617. : URIRef('http://ex.org/p2') : URIRef('http://ex.org/o2')]
  618. def test_patch_fragments(self):
  619. """
  620. Test the correct handling of fragment URIs on PATCH.
  621. """
  622. self.client.put('/ldp/test_fragment_patch', content_type='text/turtle')
  623. with open('tests/data/fragments_insert.sparql', 'rb') as f:
  624. self.client.patch(
  625. '/ldp/test_fragment_patch',
  626. content_type='application/sparql-update', data=f)
  627. ins_rsp = self.client.get('/ldp/test_fragment_patch')
  628. ins_gr = Graph().parse(data=ins_rsp.data, format='text/turtle')
  629. assert ins_gr[
  630. URIRef(g.webroot + '/test_fragment_patch#hash1234')
  631. : URIRef('http://ex.org/p3') : URIRef('http://ex.org/o3')]
  632. with open('tests/data/fragments_delete.sparql', 'rb') as f:
  633. self.client.patch(
  634. '/ldp/test_fragment_patch',
  635. headers={
  636. 'Content-Type' : 'application/sparql-update',
  637. },
  638. data=f
  639. )
  640. del_rsp = self.client.get('/ldp/test_fragment_patch')
  641. del_gr = Graph().parse(data=del_rsp.data, format='text/turtle')
  642. assert not del_gr[
  643. URIRef(g.webroot + '/test_fragment_patch#hash1234')
  644. : URIRef('http://ex.org/p3') : URIRef('http://ex.org/o3')]
  645. @pytest.mark.usefixtures('client_class')
  646. @pytest.mark.usefixtures('db')
  647. class TestMimeType:
  648. """
  649. Test ``Accept`` headers and input & output formats.
  650. """
  651. def test_accept(self):
  652. """
  653. Verify the default serialization method.
  654. """
  655. accept_list = {
  656. ('', 'text/turtle'),
  657. ('text/turtle', 'text/turtle'),
  658. ('application/rdf+xml', 'application/rdf+xml'),
  659. ('application/n-triples', 'application/n-triples'),
  660. ('application/bogus', 'text/turtle'),
  661. (
  662. 'application/rdf+xml;q=0.5,application/n-triples;q=0.7',
  663. 'application/n-triples'),
  664. (
  665. 'application/rdf+xml;q=0.5,application/bogus;q=0.7',
  666. 'application/rdf+xml'),
  667. ('application/rdf+xml;q=0.5,text/n3;q=0.7', 'text/n3'),
  668. (
  669. 'application/rdf+xml;q=0.5,application/ld+json;q=0.7',
  670. 'application/ld+json'),
  671. }
  672. for mimetype, fmt in accept_list:
  673. rsp = self.client.get('/ldp', headers={'Accept': mimetype})
  674. assert rsp.mimetype == fmt
  675. gr = Graph(identifier=g.webroot + '/').parse(
  676. data=rsp.data, format=fmt)
  677. assert nsc['fcrepo'].RepositoryRoot in set(gr.objects())
  678. def test_provided_rdf(self):
  679. """
  680. Test several input RDF serialiation formats.
  681. """
  682. self.client.get('/ldp')
  683. gr = Graph()
  684. gr.add((
  685. URIRef(g.webroot + '/test_mimetype'),
  686. nsc['dcterms'].title, Literal('Test MIME type.')))
  687. test_list = {
  688. 'application/n-triples',
  689. 'application/rdf+xml',
  690. 'text/n3',
  691. 'text/turtle',
  692. 'application/ld+json',
  693. }
  694. for mimetype in test_list:
  695. rdf_data = gr.serialize(format=mimetype)
  696. self.client.put(
  697. '/ldp/test_mimetype', data=rdf_data, content_type=mimetype)
  698. rsp = self.client.get('/ldp/test_mimetype')
  699. rsp_gr = Graph(identifier=g.webroot + '/test_mimetype').parse(
  700. data=rsp.data, format='text/turtle')
  701. assert (
  702. URIRef(g.webroot + '/test_mimetype'),
  703. nsc['dcterms'].title, Literal('Test MIME type.')) in rsp_gr
  704. @pytest.mark.usefixtures('client_class')
  705. class TestDigestHeaders:
  706. """
  707. Test Digest and ETag headers.
  708. """
  709. def test_etag_digest(self):
  710. """
  711. Verify ETag and Digest headers on creation.
  712. The headers must correspond to the checksum of the binary content.
  713. """
  714. uid = '/test_etag1'
  715. path = '/ldp' + uid
  716. content = uuid4().bytes
  717. content_cksum = hashlib.new(digest_algo, content)
  718. put_rsp = self.client.put(
  719. path, data=content, content_type='text/plain')
  720. assert content_cksum.hexdigest() in \
  721. put_rsp.headers.get('etag').split(',')
  722. assert put_rsp.headers.get('digest') == \
  723. f'{digest_algo.upper()}=' + b64encode(content_cksum.digest()).decode()
  724. get_rsp = self.client.get(path)
  725. assert content_cksum.hexdigest() in \
  726. put_rsp.headers.get('etag').split(',')
  727. assert get_rsp.headers.get('digest') == \
  728. f'{digest_algo.upper()}=' + b64encode(content_cksum.digest()).decode()
  729. def test_etag_ident(self):
  730. """
  731. Verify that two resources with the same content yield identical ETags.
  732. """
  733. path1 = f'/ldp/{uuid4()}'
  734. path2 = f'/ldp/{uuid4()}'
  735. content = uuid4().bytes
  736. content_cksum = hashlib.new(digest_algo, content)
  737. self.client.put(path1, data=content, content_type='text/plain')
  738. self.client.put(path2, data=content, content_type='text/plain')
  739. get_rsp1 = self.client.get(path1)
  740. get_rsp2 = self.client.get(path2)
  741. assert get_rsp1.headers.get('etag') == get_rsp2.headers.get('etag')
  742. assert get_rsp1.headers.get('digest') == get_rsp2.headers.get('digest')
  743. def test_etag_diff(self):
  744. """
  745. Verify that two resources with different content yield different ETags.
  746. """
  747. path1 = f'/ldp/{uuid4()}'
  748. path2 = f'/ldp/{uuid4()}'
  749. content1 = b'some interesting content.'
  750. content_cksum1 = hashlib.new(digest_algo, content1)
  751. content2 = b'Some great content.'
  752. content_cksum2 = hashlib.new(digest_algo, content2)
  753. self.client.put(path1, data=content1, content_type='text/plain')
  754. self.client.put(path2, data=content2, content_type='text/plain')
  755. get_rsp1 = self.client.get(path1)
  756. get_rsp2 = self.client.get(path2)
  757. assert get_rsp1.headers.get('etag') != get_rsp2.headers.get('etag')
  758. assert get_rsp1.headers.get('digest') != get_rsp2.headers.get('digest')
  759. def test_etag_update(self):
  760. """
  761. Verify that ETag and digest change when the resource is updated.
  762. The headers should NOT change if the same binary content is
  763. re-submitted.
  764. """
  765. path = f'/ldp/{uuid4()}'
  766. content1 = uuid4().bytes
  767. content_cksum1 = hashlib.new(digest_algo, content1)
  768. content2 = uuid4().bytes
  769. content_cksum2 = hashlib.new(digest_algo, content2)
  770. self.client.put(path, data=content1, content_type='text/plain')
  771. get_rsp = self.client.get(path)
  772. assert content_cksum1.hexdigest() == \
  773. get_rsp.headers.get('etag').strip('"')
  774. assert get_rsp.headers.get('digest') == \
  775. f'{digest_algo.upper()}=' + b64encode(content_cksum1.digest()).decode()
  776. put_rsp = self.client.put(
  777. path, data=content2, content_type='text/plain')
  778. assert content_cksum2.hexdigest() == \
  779. put_rsp.headers.get('etag').strip('"')
  780. assert put_rsp.headers.get('digest') == \
  781. f'{digest_algo.upper()}=' + b64encode(content_cksum2.digest()).decode()
  782. get_rsp = self.client.get(path)
  783. assert content_cksum2.hexdigest() == \
  784. get_rsp.headers.get('etag').strip('"')
  785. assert get_rsp.headers.get('digest') == \
  786. f'{digest_algo.upper()}=' + b64encode(content_cksum2.digest()).decode()
  787. def test_etag_rdf(self):
  788. """
  789. Verify that LDP-RS resources don't get an ETag.
  790. TODO This is by design for now; when a reliable hashing method
  791. for a graph is devised, this test should change.
  792. """
  793. path = f'/ldp/{uuid4()}'
  794. put_rsp = self.client.put(path, content_type='text/turtle')
  795. assert not put_rsp.headers.get('etag')
  796. assert not put_rsp.headers.get('digest')
  797. get_rsp = self.client.get(path)
  798. assert not get_rsp.headers.get('etag')
  799. assert not get_rsp.headers.get('digest')
  800. def test_digest_put(self):
  801. """
  802. Test the ``Digest`` header with PUT to verify content integrity.
  803. """
  804. path1 = f'/ldp/{uuid4()}'
  805. path2 = f'/ldp/{uuid4()}'
  806. path3 = f'/ldp/{uuid4()}'
  807. content = uuid4().bytes
  808. content_sha1 = sha1(content).hexdigest()
  809. content_sha256 = sha256(content).hexdigest()
  810. content_blake2b = blake2b(content).hexdigest()
  811. assert self.client.put(path1, data=content, headers={
  812. 'digest': 'sha1=abcd'}).status_code == 409
  813. assert self.client.put(path1, data=content, headers={
  814. 'digest': f'sha1={content_sha1}'}).status_code == 201
  815. assert self.client.put(path2, data=content, headers={
  816. 'digest': f'SHA1={content_sha1}'}).status_code == 201
  817. assert self.client.put(path3, data=content, headers={
  818. 'digest': f'SHA256={content_sha256}'}).status_code == 201
  819. assert self.client.put(path3, data=content, headers={
  820. 'digest': f'blake2b={content_blake2b}'}).status_code == 204
  821. def test_digest_post(self):
  822. """
  823. Test the ``Digest`` header with POST to verify content integrity.
  824. """
  825. path = '/ldp'
  826. content = uuid4().bytes
  827. content_sha1 = sha1(content).hexdigest()
  828. content_sha256 = sha256(content).hexdigest()
  829. content_blake2b = blake2b(content).hexdigest()
  830. assert self.client.post(path, data=content, headers={
  831. 'digest': 'sha1=abcd'}).status_code == 409
  832. assert self.client.post(path, data=content, headers={
  833. 'digest': f'sha1={content_sha1}'}).status_code == 201
  834. assert self.client.post(path, data=content, headers={
  835. 'digest': f'SHA1={content_sha1}'}).status_code == 201
  836. assert self.client.post(path, data=content, headers={
  837. 'digest': f'SHA256={content_sha256}'}).status_code == 201
  838. assert self.client.post(path, data=content, headers={
  839. 'digest': f'blake2b={content_blake2b}'}).status_code == 201
  840. assert self.client.post(path, data=content, headers={
  841. 'digest': f'bogusmd={content_blake2b}'}).status_code == 400
  842. bencoded = b64encode(content_blake2b.encode())
  843. assert self.client.post(
  844. path, data=content,
  845. headers={'digest': f'blake2b={bencoded}'}
  846. ).status_code == 400
  847. @pytest.mark.usefixtures('client_class')
  848. class TestETagCondHeaders:
  849. """
  850. Test Digest and ETag headers.
  851. """
  852. def test_if_match_get(self):
  853. """
  854. Test the If-Match header on GET requests.
  855. Test providing single and multiple ETags.
  856. """
  857. path = '/ldp/test_if_match1'
  858. content = uuid4().bytes
  859. content_cksum = hashlib.new(digest_algo, content).hexdigest()
  860. bogus_cksum = uuid4().hex
  861. self.client.put(
  862. path, data=content, headers={'content-type': 'text/plain'})
  863. get_rsp = self.client.get(path, headers={
  864. 'if-match': f'"{content_cksum}"'})
  865. assert get_rsp.status_code == 200
  866. get_rsp = self.client.get(path, headers={
  867. 'if-match': f'"{bogus_cksum}"'})
  868. assert get_rsp.status_code == 412
  869. get_rsp = self.client.get(path, headers={
  870. 'if-match': f'"{content_cksum}", "{bogus_cksum}"'})
  871. assert get_rsp.status_code == 200
  872. def test_if_match_put(self):
  873. """
  874. Test the If-Match header on PUT requests.
  875. Test providing single and multiple ETags.
  876. """
  877. path = '/ldp/test_if_match1'
  878. content = uuid4().bytes
  879. content_cksum = hashlib.new(digest_algo, content).hexdigest()
  880. bogus_cksum = uuid4().hex
  881. get_rsp = self.client.get(path)
  882. old_cksum = get_rsp.headers.get('etag')
  883. put_rsp = self.client.put(path, data=content, headers={
  884. 'if-match': f'"{content_cksum}"'})
  885. assert put_rsp.status_code == 412
  886. put_rsp = self.client.put(path, data=content, headers={
  887. 'if-match': f'"{content_cksum}", "{bogus_cksum}"'})
  888. assert put_rsp.status_code == 412
  889. put_rsp = self.client.put(path, data=content, headers={
  890. 'if-match': f'"{old_cksum}", "{bogus_cksum}"'})
  891. assert put_rsp.status_code == 204
  892. # Now contents have changed.
  893. put_rsp = self.client.put(path, data=content, headers={
  894. 'if-match': f'"{old_cksum}"'})
  895. assert put_rsp.status_code == 412
  896. put_rsp = self.client.put(path, data=content, headers={
  897. 'if-match': f'"{content_cksum}"'})
  898. assert put_rsp.status_code == 204
  899. # Exactly the same content was uploaded, so the ETag should not have
  900. # changed.
  901. put_rsp = self.client.put(path, data=content, headers={
  902. 'if-match': f'"{content_cksum}"'})
  903. assert put_rsp.status_code == 204
  904. # Catch-all: Proceed if resource exists at the given location.
  905. put_rsp = self.client.put(path, data=content, headers={
  906. 'if-match': '*'})
  907. assert put_rsp.status_code == 204
  908. # This is wrong syntax. It will not update because the literal asterisk
  909. # won't match.
  910. put_rsp = self.client.put(path, data=content, headers={
  911. 'if-match': '"*"'})
  912. assert put_rsp.status_code == 412
  913. # Test delete.
  914. del_rsp = self.client.delete(path, headers={
  915. 'if-match': f'"{old_cksum}"', 'Prefer': 'no-tombstone'})
  916. assert del_rsp.status_code == 412
  917. del_rsp = self.client.delete(path, headers={
  918. 'if-match': f'"{content_cksum}"', 'Prefer': 'no-tombstone'})
  919. assert del_rsp.status_code == 204
  920. put_rsp = self.client.put(path, data=content, headers={
  921. 'if-match': '*'})
  922. assert put_rsp.status_code == 412
  923. def test_if_none_match_get(self):
  924. """
  925. Test the If-None-Match header on GET requests.
  926. Test providing single and multiple ETags.
  927. """
  928. path = '/ldp/test_if_none_match1'
  929. content = uuid4().bytes
  930. content_cksum = hashlib.new(digest_algo, content).hexdigest()
  931. bogus_cksum = uuid4().hex
  932. self.client.put(
  933. path, data=content, headers={'content-type': 'text/plain'})
  934. get_rsp1 = self.client.get(path, headers={
  935. 'if-none-match': f'"{content_cksum}"'})
  936. assert get_rsp1.status_code == 304
  937. get_rsp2 = self.client.get(path, headers={
  938. 'if-none-match': f'"{bogus_cksum}"'})
  939. assert get_rsp2.status_code == 200
  940. get_rsp3 = self.client.get(path, headers={
  941. 'if-none-match': f'"{content_cksum}", "{bogus_cksum}"'})
  942. assert get_rsp3.status_code == 304
  943. # 404 has precedence on ETag handling.
  944. get_rsp = self.client.get('/ldp/bogus', headers={
  945. 'if-none-match': f'"{bogus_cksum}"'})
  946. assert get_rsp.status_code == 404
  947. get_rsp = self.client.get('/ldp/bogus', headers={
  948. 'if-none-match': f'"{content_cksum}"'})
  949. assert get_rsp.status_code == 404
  950. def test_if_none_match_put(self):
  951. """
  952. Test the If-None-Match header on PUT requests.
  953. Test providing single and multiple ETags.
  954. Uses a previously created resource.
  955. """
  956. path = '/ldp/test_if_none_match1'
  957. content = uuid4().bytes
  958. content_cksum = hashlib.new(digest_algo, content).hexdigest()
  959. bogus_cksum = uuid4().hex
  960. get_rsp = self.client.get(path)
  961. old_cksum = get_rsp.headers.get('etag')
  962. put_rsp = self.client.put(path, data=content, headers={
  963. 'if-none-match': f'"{old_cksum}"'})
  964. assert put_rsp.status_code == 412
  965. put_rsp = self.client.put(path, data=content, headers={
  966. 'if-none-match': f'"{old_cksum}", "{bogus_cksum}"'})
  967. assert put_rsp.status_code == 412
  968. put_rsp = self.client.put(path, data=content, headers={
  969. 'if-none-match': f'"{bogus_cksum}"'})
  970. assert put_rsp.status_code == 204
  971. # Now contents have changed.
  972. put_rsp = self.client.put(path, data=content, headers={
  973. 'if-none-match': f'"{content_cksum}"'})
  974. assert put_rsp.status_code == 412
  975. put_rsp = self.client.put(path, data=content, headers={
  976. 'if-none-match': f'"{old_cksum}"'})
  977. assert put_rsp.status_code == 204
  978. # Catch-all: fail if any resource exists at the given location.
  979. put_rsp = self.client.put(path, data=content, headers={
  980. 'if-none-match': '*'})
  981. assert put_rsp.status_code == 412
  982. # Test delete.
  983. del_rsp = self.client.delete(path, headers={
  984. 'if-none-match': f'"{content_cksum}"', 'Prefer': 'no-tombstone'})
  985. assert del_rsp.status_code == 412
  986. del_rsp = self.client.delete(path, headers={
  987. 'if-none-match': f'"{bogus_cksum}"', 'Prefer': 'no-tombstone'})
  988. assert del_rsp.status_code == 204
  989. put_rsp = self.client.put(path, data=content, headers={
  990. 'if-none-match': '*'})
  991. assert put_rsp.status_code == 201
  992. # This is wrong syntax. It will update because the literal asterisk
  993. # won't match.
  994. put_rsp = self.client.put(path, data=content, headers={
  995. 'if-none-match': '"*"'})
  996. assert put_rsp.status_code == 204
  997. def test_etag_notfound(self):
  998. """
  999. Verify that 404 and 410 have precedence on ETag handling.
  1000. """
  1001. path = f'/ldp/{uuid4()}'
  1002. bogus_cksum = uuid4().hex
  1003. get_rsp = self.client.get(path, headers={
  1004. 'if-match': f'"{bogus_cksum}"'})
  1005. assert get_rsp.status_code == 404
  1006. get_rsp = self.client.get(path, headers={
  1007. 'if-match': '*'})
  1008. assert get_rsp.status_code == 404
  1009. get_rsp = self.client.get(path, headers={
  1010. 'if-none-match': f'"{bogus_cksum}"'})
  1011. assert get_rsp.status_code == 404
  1012. self.client.put(path)
  1013. self.client.delete(path)
  1014. get_rsp = self.client.get(path, headers={
  1015. 'if-match': f'"{bogus_cksum}"'})
  1016. assert get_rsp.status_code == 410
  1017. get_rsp = self.client.get(path, headers={
  1018. 'if-none-match': f'"{bogus_cksum}"'})
  1019. assert get_rsp.status_code == 410
  1020. get_rsp = self.client.get(path, headers={
  1021. 'if-match': '*'})
  1022. assert get_rsp.status_code == 410
  1023. @pytest.mark.usefixtures('client_class')
  1024. class TestModifyTimeCondHeaders:
  1025. """
  1026. Test time-related conditional headers.
  1027. """
  1028. @pytest.fixture(scope='class')
  1029. def timeframe(self):
  1030. """
  1031. Times used in these tests: UTC midnight of today, yesterday, tomorrow.
  1032. """
  1033. today = arrow.utcnow().floor('day')
  1034. yesterday = today.shift(days=-1)
  1035. tomorrow = today.shift(days=1)
  1036. path = f'/ldp/{uuid4()}'
  1037. self.client.put(path)
  1038. return path, today, yesterday, tomorrow
  1039. def test_nothing(self):
  1040. """
  1041. For some reason, without this the fixture won't initialize properly.
  1042. """
  1043. self.client.get('/')
  1044. def test_if_modified_since(self, timeframe):
  1045. """
  1046. Test various uses of the If-Modified-Since header.
  1047. """
  1048. path, today, yesterday, tomorrow = timeframe
  1049. assert self.client.head(
  1050. path, headers={'if-modified-since': http_date(today.timestamp)}
  1051. ).status_code == 200
  1052. assert self.client.get(
  1053. path, headers={'if-modified-since': http_date(today.timestamp)}
  1054. ).status_code == 200
  1055. assert self.client.head(
  1056. path, headers={'if-modified-since': http_date(yesterday.timestamp)}
  1057. ).status_code == 200
  1058. assert self.client.get(
  1059. path, headers={'if-modified-since': http_date(yesterday.timestamp)}
  1060. ).status_code == 200
  1061. assert self.client.head(
  1062. path, headers={'if-modified-since': http_date(tomorrow.timestamp)}
  1063. ).status_code == 304
  1064. assert self.client.get(
  1065. path, headers={'if-modified-since': http_date(tomorrow.timestamp)}
  1066. ).status_code == 304
  1067. def test_if_unmodified_since(self, timeframe):
  1068. """
  1069. Test various uses of the If-Unmodified-Since header.
  1070. """
  1071. path, today, yesterday, tomorrow = timeframe
  1072. assert self.client.head(
  1073. path, headers={'if-unmodified-since': http_date(today.timestamp)}
  1074. ).status_code == 304
  1075. assert self.client.get(
  1076. path, headers={'if-unmodified-since': http_date(today.timestamp)}
  1077. ).status_code == 304
  1078. assert self.client.head(
  1079. path, headers={'if-unmodified-since': http_date(yesterday.timestamp)}
  1080. ).status_code == 304
  1081. assert self.client.get(
  1082. path, headers={'if-unmodified-since': http_date(yesterday.timestamp)}
  1083. ).status_code == 304
  1084. assert self.client.head(
  1085. path, headers={'if-unmodified-since': http_date(tomorrow.timestamp)}
  1086. ).status_code == 200
  1087. assert self.client.get(
  1088. path, headers={'if-unmodified-since': http_date(tomorrow.timestamp)}
  1089. ).status_code == 200
  1090. def test_time_range(self, timeframe):
  1091. """
  1092. Test conditions inside and outside of a time range.
  1093. """
  1094. path, today, yesterday, tomorrow = timeframe
  1095. # Send me the resource if it has been modified between yesterday
  1096. # and tomorrow.
  1097. assert self.client.get(path, headers={
  1098. 'if-modified-since': http_date(yesterday.timestamp),
  1099. 'if-unmodified-since': http_date(tomorrow.timestamp),
  1100. }).status_code == 200
  1101. # Send me the resource if it has been modified between today
  1102. # and tomorrow.
  1103. assert self.client.get(path, headers={
  1104. 'if-modified-since': http_date(today.timestamp),
  1105. 'if-unmodified-since': http_date(tomorrow.timestamp),
  1106. }).status_code == 200
  1107. # Send me the resource if it has been modified between yesterday
  1108. # and today.
  1109. assert self.client.get(path, headers={
  1110. 'if-modified-since': http_date(yesterday.timestamp),
  1111. 'if-unmodified-since': http_date(today.timestamp),
  1112. }).status_code == 304
  1113. # Send me the resource if it has been modified between two days ago
  1114. # and yesterday.
  1115. assert self.client.get(path, headers={
  1116. 'if-modified-since': http_date(yesterday.shift(days=-1).timestamp),
  1117. 'if-unmodified-since': http_date(yesterday.timestamp),
  1118. }).status_code == 304
  1119. # Send me the resource if it has been modified between tomorrow
  1120. # and two days from today.
  1121. assert self.client.get(path, headers={
  1122. 'if-modified-since': http_date(tomorrow.timestamp),
  1123. 'if-unmodified-since': http_date(tomorrow.shift(days=1).timestamp),
  1124. }).status_code == 304
  1125. def test_time_etag_combo(self, timeframe):
  1126. """
  1127. Test evaluation priorities among ETag and time headers.
  1128. """
  1129. _, today, yesterday, tomorrow = timeframe
  1130. path = f'/ldp/{uuid4()}'
  1131. content = uuid4().bytes
  1132. content_cksum = hashlib.new(digest_algo, content).hexdigest()
  1133. bogus_cksum = uuid4().hex
  1134. self.client.put(
  1135. path, data=content, headers={'content-type': 'text/plain'})
  1136. # Negative ETag match wins.
  1137. assert self.client.get(path, headers={
  1138. 'if-match': f'"{bogus_cksum}"',
  1139. 'if-modified-since': http_date(yesterday.timestamp),
  1140. }).status_code == 412
  1141. assert self.client.get(path, headers={
  1142. 'if-match': f'"{bogus_cksum}"',
  1143. 'if-unmodified-since': http_date(tomorrow.timestamp),
  1144. }).status_code == 412
  1145. assert self.client.get(path, headers={
  1146. 'if-none-match': f'"{content_cksum}"',
  1147. 'if-modified-since': http_date(yesterday.timestamp),
  1148. }).status_code == 304
  1149. assert self.client.get(path, headers={
  1150. 'if-none-match': f'"{content_cksum}"',
  1151. 'if-unmodified-since': http_date(tomorrow.timestamp),
  1152. }).status_code == 304
  1153. # Positive ETag match wins.
  1154. assert self.client.get(path, headers={
  1155. 'if-match': f'"{content_cksum}"',
  1156. 'if-unmodified-since': http_date(yesterday.timestamp),
  1157. }).status_code == 200
  1158. assert self.client.get(path, headers={
  1159. 'if-match': f'"{content_cksum}"',
  1160. 'if-modified-since': http_date(tomorrow.timestamp),
  1161. }).status_code == 200
  1162. assert self.client.get(path, headers={
  1163. 'if-none-match': f'"{bogus_cksum}"',
  1164. 'if-unmodified-since': http_date(yesterday.timestamp),
  1165. }).status_code == 200
  1166. assert self.client.get(path, headers={
  1167. 'if-none-match': f'"{bogus_cksum}"',
  1168. 'if-modified-since': http_date(tomorrow.timestamp),
  1169. }).status_code == 200
  1170. @pytest.mark.usefixtures('client_class')
  1171. class TestRange:
  1172. """
  1173. Test byte range retrieval.
  1174. This should not need too deep testing since it's functionality implemented
  1175. in Werkzeug/Flask.
  1176. """
  1177. @pytest.fixture(scope='class')
  1178. def bytestream(self):
  1179. """
  1180. Create a sample bytestream with predictable (8x8 bytes) content.
  1181. """
  1182. return b''.join([bytes([n] * 8) for n in range(8)])
  1183. def test_get_range(self, bytestream):
  1184. """
  1185. Get different ranges of the bitstream.
  1186. """
  1187. path = '/ldp/test_range'
  1188. self.client.put(path, data=bytestream)
  1189. # First 8 bytes.
  1190. assert self.client.get(
  1191. path, headers={'range': 'bytes=0-7'}).data == b'\x00' * 8
  1192. # Last 4 bytes of first block, first 4 of second block.
  1193. assert self.client.get(
  1194. path, headers={'range': 'bytes=4-11'}
  1195. ).data == b'\x00' * 4 + b'\x01' * 4
  1196. # Last 8 bytes.
  1197. assert self.client.get(
  1198. path, headers={'range': 'bytes=56-'}).data == b'\x07' * 8
  1199. def test_fail_ranges(self, bytestream):
  1200. """
  1201. Test malformed or unsupported ranges.
  1202. """
  1203. path = '/ldp/test_range'
  1204. # TODO This shall be a 206 when multiple ranges are supported.
  1205. fail_rsp = self.client.get(path, headers={'range': 'bytes=0-1, 7-8'})
  1206. assert fail_rsp.status_code == 501
  1207. # Bad ranges will be ignored.
  1208. for rng in ((10, 4), ('', 3), (3600, 6400)):
  1209. bad_rsp = self.client.get(
  1210. path, headers={'range': 'bytes={rng[0]}-{rng[1]}'})
  1211. assert bad_rsp.status_code == 200
  1212. assert bad_rsp.data == bytestream
  1213. assert int(bad_rsp.headers['content-length']) == len(bytestream)
  1214. def test_range_rsp_headers(self, bytestream):
  1215. """
  1216. Test various headers for a ranged response.
  1217. """
  1218. path = '/ldp/test_range'
  1219. start_b = 0
  1220. end_b = 7
  1221. full_rsp = self.client.get(path)
  1222. part_rsp = self.client.get(path, headers={
  1223. 'range': f'bytes={start_b}-{end_b}'})
  1224. for hdr_name in ['etag', 'digest', 'content-type']:
  1225. assert part_rsp.headers[hdr_name] == full_rsp.headers[hdr_name]
  1226. for hdr in part_rsp.headers['link']:
  1227. assert hdr in full_rsp.headers['link']
  1228. assert int(part_rsp.headers['content-length']) == end_b - start_b + 1
  1229. assert part_rsp.headers['content-range'] == \
  1230. f'bytes {start_b}-{end_b} / {len(bytestream)}'
  1231. @pytest.mark.usefixtures('client_class')
  1232. class TestPrefHeader:
  1233. """
  1234. Test various combinations of `Prefer` header.
  1235. """
  1236. @pytest.fixture(scope='class')
  1237. def cont_structure(self):
  1238. """
  1239. Create a container structure to be used for subsequent requests.
  1240. """
  1241. parent_path = '/ldp/test_parent'
  1242. self.client.put(parent_path, content_type='text/turtle')
  1243. self.client.put(parent_path + '/child1', content_type='text/turtle')
  1244. self.client.put(parent_path + '/child2', content_type='text/turtle')
  1245. self.client.put(parent_path + '/child3', content_type='text/turtle')
  1246. return {
  1247. 'path' : parent_path,
  1248. 'response' : self.client.get(parent_path),
  1249. }
  1250. def test_put_prefer_handling(self, random_uuid):
  1251. """
  1252. Trying to PUT an existing resource should:
  1253. - Return a 204 if the payload is empty
  1254. - Return a 204 if the payload is RDF, server-managed triples are
  1255. included and the 'Prefer' header is set to 'handling=lenient'
  1256. - Return a 412 (ServerManagedTermError) if the payload is RDF,
  1257. server-managed triples are included and handling is set to 'strict',
  1258. or not set.
  1259. """
  1260. path = '/ldp/put_pref_header01'
  1261. assert self.client.put(path, content_type='text/turtle').status_code == 201
  1262. assert self.client.get(path).status_code == 200
  1263. assert self.client.put(path, content_type='text/turtle').status_code == 204
  1264. # Default handling is strict.
  1265. with open('tests/data/rdf_payload_w_srv_mgd_trp.ttl', 'rb') as f:
  1266. rsp_default = self.client.put(
  1267. path,
  1268. headers={
  1269. 'Content-Type' : 'text/turtle',
  1270. },
  1271. data=f
  1272. )
  1273. assert rsp_default.status_code == 412
  1274. with open('tests/data/rdf_payload_w_srv_mgd_trp.ttl', 'rb') as f:
  1275. rsp_len = self.client.put(
  1276. path,
  1277. headers={
  1278. 'Prefer' : 'handling=lenient',
  1279. 'Content-Type' : 'text/turtle',
  1280. },
  1281. data=f
  1282. )
  1283. assert rsp_len.status_code == 204
  1284. with open('tests/data/rdf_payload_w_srv_mgd_trp.ttl', 'rb') as f:
  1285. rsp_strict = self.client.put(
  1286. path,
  1287. headers={
  1288. 'Prefer' : 'handling=strict',
  1289. 'Content-Type' : 'text/turtle',
  1290. },
  1291. data=f
  1292. )
  1293. assert rsp_strict.status_code == 412
  1294. # @HOLD Embed children is debated.
  1295. def _disabled_test_embed_children(self, cont_structure):
  1296. """
  1297. verify the "embed children" prefer header.
  1298. """
  1299. self.client.get('/ldp')
  1300. parent_path = cont_structure['path']
  1301. cont_resp = cont_structure['response']
  1302. cont_subject = URIRef(g.webroot + '/test_parent')
  1303. #minimal_resp = self.client.get(parent_path, headers={
  1304. # 'Prefer' : 'return=minimal',
  1305. #})
  1306. incl_embed_children_resp = self.client.get(parent_path, headers={
  1307. 'Prefer' : 'return=representation; include={}'\
  1308. .format(Ldpr.EMBED_CHILD_RES_URI),
  1309. })
  1310. omit_embed_children_resp = self.client.get(parent_path, headers={
  1311. 'Prefer' : 'return=representation; omit={}'\
  1312. .format(Ldpr.EMBED_CHILD_RES_URI),
  1313. })
  1314. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  1315. incl_gr = Graph().parse(
  1316. data=incl_embed_children_resp.data, format='turtle')
  1317. omit_gr = Graph().parse(
  1318. data=omit_embed_children_resp.data, format='turtle')
  1319. assert isomorphic(omit_gr, default_gr)
  1320. children = set(incl_gr[cont_subject : nsc['ldp'].contains])
  1321. assert len(children) == 3
  1322. children = set(incl_gr[cont_subject : nsc['ldp'].contains])
  1323. for child_uri in children:
  1324. assert set(incl_gr[ child_uri : : ])
  1325. assert not set(omit_gr[ child_uri : : ])
  1326. def test_return_children(self, cont_structure):
  1327. """
  1328. verify the "return children" prefer header.
  1329. """
  1330. self.client.get('/ldp')
  1331. parent_path = cont_structure['path']
  1332. cont_resp = cont_structure['response']
  1333. cont_subject = URIRef(g.webroot + '/test_parent')
  1334. incl_children_resp = self.client.get(parent_path, headers={
  1335. 'Prefer' : 'return=representation; include={}'\
  1336. .format(Ldpr.RETURN_CHILD_RES_URI),
  1337. })
  1338. omit_children_resp = self.client.get(parent_path, headers={
  1339. 'Prefer' : 'return=representation; omit={}'\
  1340. .format(Ldpr.RETURN_CHILD_RES_URI),
  1341. })
  1342. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  1343. incl_gr = Graph().parse(data=incl_children_resp.data, format='turtle')
  1344. omit_gr = Graph().parse(data=omit_children_resp.data, format='turtle')
  1345. assert isomorphic(incl_gr, default_gr)
  1346. children = incl_gr[cont_subject : nsc['ldp'].contains]
  1347. for child_uri in children:
  1348. assert not omit_gr[cont_subject : nsc['ldp'].contains : child_uri]
  1349. def test_inbound_rel(self, cont_structure):
  1350. """
  1351. verify the "inbound relationships" prefer header.
  1352. """
  1353. self.client.put('/ldp/test_target', content_type='text/turtle')
  1354. data = '<> <http://ex.org/ns#shoots> <{}> .'.format(
  1355. g.webroot + '/test_target')
  1356. self.client.put('/ldp/test_shooter', data=data,
  1357. headers={'Content-Type': 'text/turtle'})
  1358. cont_resp = self.client.get('/ldp/test_target')
  1359. incl_inbound_resp = self.client.get('/ldp/test_target', headers={
  1360. 'Prefer' : 'return=representation; include="{}"'\
  1361. .format(Ldpr.RETURN_INBOUND_REF_URI),
  1362. })
  1363. omit_inbound_resp = self.client.get('/ldp/test_target', headers={
  1364. 'Prefer' : 'return=representation; omit="{}"'\
  1365. .format(Ldpr.RETURN_INBOUND_REF_URI),
  1366. })
  1367. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  1368. incl_gr = Graph().parse(data=incl_inbound_resp.data, format='turtle')
  1369. omit_gr = Graph().parse(data=omit_inbound_resp.data, format='turtle')
  1370. subject = URIRef(g.webroot + '/test_target')
  1371. inbd_subject = URIRef(g.webroot + '/test_shooter')
  1372. assert isomorphic(omit_gr, default_gr)
  1373. assert len(set(incl_gr[inbd_subject : : ])) == 1
  1374. assert incl_gr[
  1375. inbd_subject : URIRef('http://ex.org/ns#shoots') : subject]
  1376. assert not len(set(omit_gr[inbd_subject : :]))
  1377. def test_srv_mgd_triples(self, cont_structure):
  1378. """
  1379. verify the "server managed triples" prefer header.
  1380. """
  1381. self.client.get('/ldp')
  1382. parent_path = cont_structure['path']
  1383. cont_resp = cont_structure['response']
  1384. cont_subject = URIRef(g.webroot + '/test_parent')
  1385. incl_srv_mgd_resp = self.client.get(parent_path, headers={
  1386. 'Prefer' : 'return=representation; include={}'\
  1387. .format(Ldpr.RETURN_SRV_MGD_RES_URI),
  1388. })
  1389. omit_srv_mgd_resp = self.client.get(parent_path, headers={
  1390. 'Prefer' : 'return=representation; omit={}'\
  1391. .format(Ldpr.RETURN_SRV_MGD_RES_URI),
  1392. })
  1393. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  1394. incl_gr = Graph().parse(data=incl_srv_mgd_resp.data, format='turtle')
  1395. omit_gr = Graph().parse(data=omit_srv_mgd_resp.data, format='turtle')
  1396. assert isomorphic(incl_gr, default_gr)
  1397. for pred in {
  1398. nsc['fcrepo'].created,
  1399. nsc['fcrepo'].createdBy,
  1400. nsc['fcrepo'].lastModified,
  1401. nsc['fcrepo'].lastModifiedBy,
  1402. nsc['ldp'].contains,
  1403. }:
  1404. assert set(incl_gr[ cont_subject : pred : ])
  1405. assert not set(omit_gr[ cont_subject : pred : ])
  1406. for type in {
  1407. nsc['fcrepo'].Resource,
  1408. nsc['ldp'].Container,
  1409. nsc['ldp'].Resource,
  1410. }:
  1411. assert incl_gr[ cont_subject : RDF.type : type ]
  1412. assert not omit_gr[ cont_subject : RDF.type : type ]
  1413. def test_delete_no_tstone(self):
  1414. """
  1415. Test the `no-tombstone` Prefer option.
  1416. """
  1417. self.client.put('/ldp/test_delete_no_tstone01')
  1418. self.client.put('/ldp/test_delete_no_tstone01/a')
  1419. self.client.delete('/ldp/test_delete_no_tstone01', headers={
  1420. 'prefer' : 'no-tombstone'})
  1421. resp = self.client.get('/ldp/test_delete_no_tstone01')
  1422. assert resp.status_code == 404
  1423. child_resp = self.client.get('/ldp/test_delete_no_tstone01/a')
  1424. assert child_resp.status_code == 404
  1425. #@pytest.mark.usefixtures('client_class')
  1426. #@pytest.mark.usefixtures('db')
  1427. #class TestDigest:
  1428. # """
  1429. # Test digest and ETag handling.
  1430. # """
  1431. # @pytest.mark.skip(reason='TODO Need to implement async digest queue')
  1432. # def test_digest_post(self):
  1433. # """
  1434. # Test ``Digest`` and ``ETag`` headers on resource POST.
  1435. # """
  1436. # resp = self.client.post('/ldp/')
  1437. # assert 'Digest' in resp.headers
  1438. # assert 'ETag' in resp.headers
  1439. # assert (
  1440. # b64encode(bytes.fromhex(
  1441. # resp.headers['ETag'].replace('W/', '')
  1442. # )).decode('ascii') ==
  1443. # resp.headers['Digest'].replace('SHA256=', ''))
  1444. #
  1445. #
  1446. # @pytest.mark.skip(reason='TODO Need to implement async digest queue')
  1447. # def test_digest_put(self):
  1448. # """
  1449. # Test ``Digest`` and ``ETag`` headers on resource PUT.
  1450. # """
  1451. # resp_put = self.client.put('/ldp/test_digest_put')
  1452. # assert 'Digest' in resp_put.headers
  1453. # assert 'ETag' in resp_put.headers
  1454. # assert (
  1455. # b64encode(bytes.fromhex(
  1456. # resp_put.headers['ETag'].replace('W/', '')
  1457. # )).decode('ascii') ==
  1458. # resp_put.headers['Digest'].replace('SHA256=', ''))
  1459. #
  1460. # resp_get = self.client.get('/ldp/test_digest_put')
  1461. # assert 'Digest' in resp_get.headers
  1462. # assert 'ETag' in resp_get.headers
  1463. # assert (
  1464. # b64encode(bytes.fromhex(
  1465. # resp_get.headers['ETag'].replace('W/', '')
  1466. # )).decode('ascii') ==
  1467. # resp_get.headers['Digest'].replace('SHA256=', ''))
  1468. #
  1469. #
  1470. # @pytest.mark.skip(reason='TODO Need to implement async digest queue')
  1471. # def test_digest_patch(self):
  1472. # """
  1473. # Verify that the digest and ETag change on resource change.
  1474. # """
  1475. # path = '/ldp/test_digest_patch'
  1476. # self.client.put(path)
  1477. # rsp1 = self.client.get(path)
  1478. #
  1479. # self.client.patch(
  1480. # path, data=b'DELETE {} INSERT {<> a <http://ex.org/Test> .} '
  1481. # b'WHERE {}',
  1482. # headers={'Content-Type': 'application/sparql-update'})
  1483. # rsp2 = self.client.get(path)
  1484. #
  1485. # assert rsp1.headers['ETag'] != rsp2.headers['ETag']
  1486. # assert rsp1.headers['Digest'] != rsp2.headers['Digest']
  1487. @pytest.mark.usefixtures('client_class')
  1488. @pytest.mark.usefixtures('db')
  1489. class TestVersion:
  1490. """
  1491. Test version creation, retrieval and deletion.
  1492. """
  1493. def test_create_versions(self):
  1494. """
  1495. Test that POSTing multiple times to fcr:versions creates the
  1496. 'hasVersions' triple and yields multiple version snapshots.
  1497. """
  1498. self.client.put('/ldp/test_version', content_type='text/turtle')
  1499. create_rsp = self.client.post('/ldp/test_version/fcr:versions')
  1500. assert create_rsp.status_code == 201
  1501. rsrc_rsp = self.client.get('/ldp/test_version')
  1502. rsrc_gr = Graph().parse(data=rsrc_rsp.data, format='turtle')
  1503. assert len(set(rsrc_gr[: nsc['fcrepo'].hasVersions :])) == 1
  1504. info_rsp = self.client.get('/ldp/test_version/fcr:versions')
  1505. assert info_rsp.status_code == 200
  1506. info_gr = Graph().parse(data=info_rsp.data, format='turtle')
  1507. assert len(set(info_gr[: nsc['fcrepo'].hasVersion :])) == 1
  1508. self.client.post('/ldp/test_version/fcr:versions')
  1509. info2_rsp = self.client.get('/ldp/test_version/fcr:versions')
  1510. info2_gr = Graph().parse(data=info2_rsp.data, format='turtle')
  1511. assert len(set(info2_gr[: nsc['fcrepo'].hasVersion :])) == 2
  1512. def test_version_with_slug(self):
  1513. """
  1514. Test a version with a slug.
  1515. """
  1516. self.client.put('/ldp/test_version_slug', content_type='text/turtle')
  1517. create_rsp = self.client.post('/ldp/test_version_slug/fcr:versions',
  1518. headers={'slug' : 'v1'})
  1519. new_ver_uri = create_rsp.headers['Location']
  1520. assert new_ver_uri == g.webroot + '/test_version_slug/fcr:versions/v1'
  1521. info_rsp = self.client.get('/ldp/test_version_slug/fcr:versions')
  1522. info_gr = Graph().parse(data=info_rsp.data, format='turtle')
  1523. assert info_gr[
  1524. URIRef(new_ver_uri) :
  1525. nsc['fcrepo'].hasVersionLabel :
  1526. Literal('v1')]
  1527. def test_dupl_version(self):
  1528. """
  1529. Make sure that two POSTs with the same slug result in two different
  1530. versions.
  1531. """
  1532. path = '/ldp/test_duplicate_slug'
  1533. self.client.put(path, content_type='text/turtle')
  1534. v1_rsp = self.client.post(path + '/fcr:versions',
  1535. headers={'slug' : 'v1'})
  1536. v1_uri = v1_rsp.headers['Location']
  1537. dup_rsp = self.client.post(path + '/fcr:versions',
  1538. headers={'slug' : 'v1'})
  1539. dup_uri = dup_rsp.headers['Location']
  1540. assert v1_uri != dup_uri
  1541. def test_revert_version(self):
  1542. """
  1543. Take a version snapshot, update a resource, and then revert to the
  1544. previous vresion.
  1545. """
  1546. rsrc_path = '/ldp/test_revert_version'
  1547. payload1 = '<> <urn:demo:p1> <urn:demo:o1> .'
  1548. payload2 = '<> <urn:demo:p1> <urn:demo:o2> .'
  1549. self.client.put(rsrc_path, headers={
  1550. 'content-type': 'text/turtle'}, data=payload1)
  1551. self.client.post(
  1552. rsrc_path + '/fcr:versions', headers={'slug': 'v1'})
  1553. v1_rsp = self.client.get(rsrc_path)
  1554. v1_gr = Graph().parse(data=v1_rsp.data, format='turtle')
  1555. assert v1_gr[
  1556. URIRef(g.webroot + '/test_revert_version')
  1557. : URIRef('urn:demo:p1')
  1558. : URIRef('urn:demo:o1')
  1559. ]
  1560. self.client.put(rsrc_path, headers={
  1561. 'content-type': 'text/turtle'}, data=payload2)
  1562. v2_rsp = self.client.get(rsrc_path)
  1563. v2_gr = Graph().parse(data=v2_rsp.data, format='turtle')
  1564. assert v2_gr[
  1565. URIRef(g.webroot + '/test_revert_version')
  1566. : URIRef('urn:demo:p1')
  1567. : URIRef('urn:demo:o2')
  1568. ]
  1569. self.client.patch(rsrc_path + '/fcr:versions/v1')
  1570. revert_rsp = self.client.get(rsrc_path)
  1571. revert_gr = Graph().parse(data=revert_rsp.data, format='turtle')
  1572. assert revert_gr[
  1573. URIRef(g.webroot + '/test_revert_version')
  1574. : URIRef('urn:demo:p1')
  1575. : URIRef('urn:demo:o1')
  1576. ]
  1577. def test_resurrection(self):
  1578. """
  1579. Delete and then resurrect a resource.
  1580. Make sure that the resource is resurrected to the latest version.
  1581. """
  1582. path = '/ldp/test_lazarus'
  1583. self.client.put(path, content_type='text/turtle')
  1584. self.client.post(path + '/fcr:versions', headers={'slug': 'v1'})
  1585. self.client.put(
  1586. path, headers={'content-type': 'text/turtle'},
  1587. data=b'<> <urn:demo:p1> <urn:demo:o1> .')
  1588. self.client.post(path + '/fcr:versions', headers={'slug': 'v2'})
  1589. self.client.put(
  1590. path, headers={'content-type': 'text/turtle'},
  1591. data=b'<> <urn:demo:p1> <urn:demo:o2> .')
  1592. self.client.delete(path)
  1593. assert self.client.get(path).status_code == 410
  1594. self.client.post(path + '/fcr:tombstone')
  1595. laz_data = self.client.get(path).data
  1596. laz_gr = Graph().parse(data=laz_data, format='turtle')
  1597. assert laz_gr[
  1598. URIRef(g.webroot + '/test_lazarus')
  1599. : URIRef('urn:demo:p1')
  1600. : URIRef('urn:demo:o2')
  1601. ]