test_3_0_ldp.py 71 KB

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