test_ldp.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. import pdb
  2. import pytest
  3. import uuid
  4. from base64 import b64encode
  5. from hashlib import sha1
  6. from flask import g
  7. from rdflib import Graph
  8. from rdflib.compare import isomorphic
  9. from rdflib.namespace import RDF
  10. from rdflib.term import Literal, URIRef
  11. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  12. from lakesuperior.model.ldpr import Ldpr
  13. @pytest.fixture(scope='module')
  14. def random_uuid():
  15. return str(uuid.uuid4())
  16. @pytest.mark.usefixtures('client_class')
  17. @pytest.mark.usefixtures('db')
  18. class TestLdp:
  19. """
  20. Test HTTP interaction with LDP endpoint.
  21. """
  22. def test_get_root_node(self):
  23. """
  24. Get the root node from two different endpoints.
  25. The test triplestore must be initialized, hence the `db` fixture.
  26. """
  27. ldp_resp = self.client.get('/ldp')
  28. rest_resp = self.client.get('/rest')
  29. assert ldp_resp.status_code == 200
  30. assert rest_resp.status_code == 200
  31. def test_put_empty_resource(self, random_uuid):
  32. """
  33. Check response headers for a PUT operation with empty payload.
  34. """
  35. resp = self.client.put('/ldp/new_resource')
  36. assert resp.status_code == 201
  37. assert resp.data == bytes(
  38. '{}/new_resource'.format(g.webroot), 'utf-8')
  39. def test_put_existing_resource(self, random_uuid):
  40. """
  41. Trying to PUT an existing resource should return a 204 if the payload
  42. is empty.
  43. """
  44. path = '/ldp/nonidempotent01'
  45. put1_resp = self.client.put(path)
  46. assert put1_resp.status_code == 201
  47. assert self.client.get(path).status_code == 200
  48. put2_resp = self.client.put(path)
  49. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  50. put2_resp = self.client.put(
  51. path, data=f, content_type='text/turtle')
  52. assert put2_resp.status_code == 204
  53. put2_resp = self.client.put(path)
  54. assert put2_resp.status_code == 204
  55. def test_put_tree(self, client):
  56. """
  57. PUT a resource with several path segments.
  58. The test should create intermediate path segments that are LDPCs,
  59. accessible to PUT or POST.
  60. """
  61. path = '/ldp/test_tree/a/b/c/d/e/f/g'
  62. self.client.put(path)
  63. assert self.client.get(path).status_code == 200
  64. assert self.client.get('/ldp/test_tree/a/b/c').status_code == 200
  65. assert self.client.post('/ldp/test_tree/a/b').status_code == 201
  66. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  67. put_int_resp = self.client.put(
  68. 'ldp/test_tree/a', data=f, content_type='text/turtle')
  69. assert put_int_resp.status_code == 204
  70. # @TODO More thorough testing of contents
  71. def test_put_nested_tree(self, client):
  72. """
  73. Verify that containment is set correctly in nested hierarchies.
  74. First put a new hierarchy and verify that the root node is its
  75. container; then put another hierarchy under it and verify that the
  76. first hierarchy is the container of the second one.
  77. """
  78. uuid1 = 'test_nested_tree/a/b/c/d'
  79. uuid2 = uuid1 + '/e/f/g'
  80. path1 = '/ldp/' + uuid1
  81. path2 = '/ldp/' + uuid2
  82. self.client.put(path1)
  83. cont1_data = self.client.get('/ldp').data
  84. gr1 = Graph().parse(data=cont1_data, format='turtle')
  85. assert gr1[ URIRef(g.webroot + '/') : nsc['ldp'].contains : \
  86. URIRef(g.webroot + '/test_nested_tree') ]
  87. self.client.put(path2)
  88. cont2_data = self.client.get(path1).data
  89. gr2 = Graph().parse(data=cont2_data, format='turtle')
  90. assert gr2[ URIRef(g.webroot + '/' + uuid1) : \
  91. nsc['ldp'].contains : \
  92. URIRef(g.webroot + '/' + uuid1 + '/e') ]
  93. def test_put_ldp_rs(self, client):
  94. """
  95. PUT a resource with RDF payload and verify.
  96. """
  97. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  98. self.client.put('/ldp/ldprs01', data=f, content_type='text/turtle')
  99. resp = self.client.get('/ldp/ldprs01',
  100. headers={'accept' : 'text/turtle'})
  101. assert resp.status_code == 200
  102. gr = Graph().parse(data=resp.data, format='text/turtle')
  103. assert URIRef('http://vocab.getty.edu/ontology#Subject') in \
  104. gr.objects(None, RDF.type)
  105. def test_put_ldp_nr(self, rnd_img):
  106. """
  107. PUT a resource with binary payload and verify checksums.
  108. """
  109. rnd_img['content'].seek(0)
  110. resp = self.client.put('/ldp/ldpnr01', data=rnd_img['content'],
  111. headers={
  112. 'Content-Type': 'image/png',
  113. 'Content-Disposition' : 'attachment; filename={}'.format(
  114. rnd_img['filename'])})
  115. assert resp.status_code == 201
  116. resp = self.client.get(
  117. '/ldp/ldpnr01', headers={'accept' : 'image/png'})
  118. assert resp.status_code == 200
  119. assert sha1(resp.data).hexdigest() == rnd_img['hash']
  120. def test_put_ldp_nr_multipart(self, rnd_img):
  121. """
  122. PUT a resource with a multipart/form-data payload.
  123. """
  124. rnd_img['content'].seek(0)
  125. resp = self.client.put(
  126. '/ldp/ldpnr02',
  127. data={
  128. 'file': (
  129. rnd_img['content'], rnd_img['filename'],
  130. 'image/png',
  131. )
  132. }
  133. )
  134. assert resp.status_code == 201
  135. resp = self.client.get(
  136. '/ldp/ldpnr02', headers={'accept' : 'image/png'})
  137. assert resp.status_code == 200
  138. assert sha1(resp.data).hexdigest() == rnd_img['hash']
  139. def test_put_mismatched_ldp_rs(self, rnd_img):
  140. """
  141. Verify MIME type / LDP mismatch.
  142. PUT a LDP-RS, then PUT a LDP-NR on the same location and verify it
  143. fails.
  144. """
  145. path = '/ldp/' + str(uuid.uuid4())
  146. rnd_img['content'].seek(0)
  147. ldp_nr_resp = self.client.put(path, data=rnd_img['content'],
  148. headers={
  149. 'Content-Disposition' : 'attachment; filename={}'.format(
  150. rnd_img['filename'])})
  151. assert ldp_nr_resp.status_code == 201
  152. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  153. ldp_rs_resp = self.client.put(path, data=f,
  154. content_type='text/turtle')
  155. assert ldp_rs_resp.status_code == 415
  156. def test_put_mismatched_ldp_nr(self, rnd_img):
  157. """
  158. Verify MIME type / LDP mismatch.
  159. PUT a LDP-NR, then PUT a LDP-RS on the same location and verify it
  160. fails.
  161. """
  162. path = '/ldp/' + str(uuid.uuid4())
  163. with open('tests/data/marcel_duchamp_single_subject.ttl', 'rb') as f:
  164. ldp_rs_resp = self.client.put(path, data=f,
  165. content_type='text/turtle')
  166. assert ldp_rs_resp.status_code == 201
  167. rnd_img['content'].seek(0)
  168. ldp_nr_resp = self.client.put(path, data=rnd_img['content'],
  169. headers={
  170. 'Content-Disposition' : 'attachment; filename={}'.format(
  171. rnd_img['filename'])})
  172. assert ldp_nr_resp.status_code == 415
  173. def test_missing_reference(self, client):
  174. """
  175. PUT a resource with RDF payload referencing a non-existing in-repo
  176. resource.
  177. """
  178. self.client.get('/ldp')
  179. data = '''
  180. PREFIX ns: <http://example.org#>
  181. PREFIX res: <http://example-source.org/res/>
  182. <> ns:p1 res:bogus ;
  183. ns:p2 <{0}> ;
  184. ns:p3 <{0}/> ;
  185. ns:p4 <{0}/nonexistent> .
  186. '''.format(g.webroot)
  187. put_rsp = self.client.put('/ldp/test_missing_ref', data=data, headers={
  188. 'content-type': 'text/turtle'})
  189. assert put_rsp.status_code == 201
  190. resp = self.client.get('/ldp/test_missing_ref',
  191. headers={'accept' : 'text/turtle'})
  192. assert resp.status_code == 200
  193. gr = Graph().parse(data=resp.data, format='text/turtle')
  194. assert URIRef('http://example-source.org/res/bogus') in \
  195. gr.objects(None, URIRef('http://example.org#p1'))
  196. assert URIRef(g.webroot + '/') in (
  197. gr.objects(None, URIRef('http://example.org#p2')))
  198. assert URIRef(g.webroot + '/') in (
  199. gr.objects(None, URIRef('http://example.org#p3')))
  200. assert URIRef(g.webroot + '/nonexistent') not in (
  201. gr.objects(None, URIRef('http://example.org#p4')))
  202. def test_post_resource(self, client):
  203. """
  204. Check response headers for a POST operation with empty payload.
  205. """
  206. res = self.client.post('/ldp/')
  207. assert res.status_code == 201
  208. assert 'Location' in res.headers
  209. def test_post_ldp_nr(self, rnd_img):
  210. """
  211. POST a resource with binary payload and verify checksums.
  212. """
  213. rnd_img['content'].seek(0)
  214. resp = self.client.post('/ldp/', data=rnd_img['content'],
  215. headers={
  216. 'slug': 'ldpnr03',
  217. 'Content-Type': 'image/png',
  218. 'Content-Disposition' : 'attachment; filename={}'.format(
  219. rnd_img['filename'])})
  220. assert resp.status_code == 201
  221. resp = self.client.get(
  222. '/ldp/ldpnr03', headers={'accept' : 'image/png'})
  223. assert resp.status_code == 200
  224. assert sha1(resp.data).hexdigest() == rnd_img['hash']
  225. def test_post_slug(self):
  226. """
  227. Verify that a POST with slug results in the expected URI only if the
  228. resource does not exist already.
  229. """
  230. slug01_resp = self.client.post('/ldp', headers={'slug' : 'slug01'})
  231. assert slug01_resp.status_code == 201
  232. assert slug01_resp.headers['location'] == \
  233. g.webroot + '/slug01'
  234. slug02_resp = self.client.post('/ldp', headers={'slug' : 'slug01'})
  235. assert slug02_resp.status_code == 201
  236. assert slug02_resp.headers['location'] != \
  237. g.webroot + '/slug01'
  238. def test_post_404(self):
  239. """
  240. Verify that a POST to a non-existing parent results in a 404.
  241. """
  242. assert self.client.post('/ldp/{}'.format(uuid.uuid4()))\
  243. .status_code == 404
  244. def test_post_409(self, rnd_img):
  245. """
  246. Verify that you cannot POST to a binary resource.
  247. """
  248. rnd_img['content'].seek(0)
  249. self.client.put('/ldp/post_409', data=rnd_img['content'], headers={
  250. 'Content-Disposition' : 'attachment; filename={}'.format(
  251. rnd_img['filename'])})
  252. assert self.client.post('/ldp/post_409').status_code == 409
  253. def test_patch_root(self):
  254. """
  255. Test patching root node.
  256. """
  257. path = '/ldp/'
  258. self.client.get(path)
  259. uri = g.webroot + '/'
  260. with open('tests/data/sparql_update/simple_insert.sparql') as data:
  261. resp = self.client.patch(path,
  262. data=data,
  263. headers={'content-type' : 'application/sparql-update'})
  264. assert resp.status_code == 204
  265. resp = self.client.get(path)
  266. gr = Graph().parse(data=resp.data, format='text/turtle')
  267. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Hello') ]
  268. def test_patch(self):
  269. """
  270. Test patching a resource.
  271. """
  272. path = '/ldp/test_patch01'
  273. self.client.put(path)
  274. uri = g.webroot + '/test_patch01'
  275. with open('tests/data/sparql_update/simple_insert.sparql') as data:
  276. resp = self.client.patch(path,
  277. data=data,
  278. headers={'content-type' : 'application/sparql-update'})
  279. assert resp.status_code == 204
  280. resp = self.client.get(path)
  281. gr = Graph().parse(data=resp.data, format='text/turtle')
  282. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Hello') ]
  283. self.client.patch(path,
  284. data=open('tests/data/sparql_update/delete+insert+where.sparql'),
  285. headers={'content-type' : 'application/sparql-update'})
  286. resp = self.client.get(path)
  287. gr = Graph().parse(data=resp.data, format='text/turtle')
  288. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Ciao') ]
  289. def test_patch_ssr(self):
  290. """
  291. Test patching a resource violating the single-subject rule.
  292. """
  293. path = '/ldp/test_patch_ssr'
  294. self.client.put(path)
  295. uri = g.webroot + '/test_patch_ssr'
  296. nossr_qry = 'INSERT { <http://bogus.org> a <urn:ns:A> . } WHERE {}'
  297. abs_qry = 'INSERT {{ <{}> a <urn:ns:A> . }} WHERE {{}}'.format(uri)
  298. frag_qry = 'INSERT {{ <{}#frag> a <urn:ns:A> . }} WHERE {{}}'\
  299. .format(uri)
  300. # @TODO Leave commented until a decision is made about SSR.
  301. assert self.client.patch(
  302. path, data=nossr_qry,
  303. headers={'content-type': 'application/sparql-update'}
  304. ).status_code == 204
  305. assert self.client.patch(
  306. path, data=abs_qry,
  307. headers={'content-type': 'application/sparql-update'}
  308. ).status_code == 204
  309. assert self.client.patch(
  310. path, data=frag_qry,
  311. headers={'content-type': 'application/sparql-update'}
  312. ).status_code == 204
  313. def test_patch_ldp_nr_metadata(self):
  314. """
  315. Test patching a LDP-NR metadata resource from the fcr:metadata URI.
  316. """
  317. path = '/ldp/ldpnr01'
  318. with open('tests/data/sparql_update/simple_insert.sparql') as data:
  319. self.client.patch(path + '/fcr:metadata',
  320. data=data,
  321. headers={'content-type' : 'application/sparql-update'})
  322. resp = self.client.get(path + '/fcr:metadata')
  323. assert resp.status_code == 200
  324. uri = g.webroot + '/ldpnr01'
  325. gr = Graph().parse(data=resp.data, format='text/turtle')
  326. assert gr[URIRef(uri) : nsc['dc'].title : Literal('Hello')]
  327. with open(
  328. 'tests/data/sparql_update/delete+insert+where.sparql') as data:
  329. patch_resp = self.client.patch(path + '/fcr:metadata',
  330. data=data,
  331. headers={'content-type' : 'application/sparql-update'})
  332. assert patch_resp.status_code == 204
  333. resp = self.client.get(path + '/fcr:metadata')
  334. assert resp.status_code == 200
  335. gr = Graph().parse(data=resp.data, format='text/turtle')
  336. assert gr[ URIRef(uri) : nsc['dc'].title : Literal('Ciao') ]
  337. def test_patch_ldpnr(self):
  338. """
  339. Verify that a direct PATCH to a LDP-NR results in a 415.
  340. """
  341. with open(
  342. 'tests/data/sparql_update/delete+insert+where.sparql') as data:
  343. patch_resp = self.client.patch('/ldp/ldpnr01',
  344. data=data,
  345. headers={'content-type': 'application/sparql-update'})
  346. assert patch_resp.status_code == 415
  347. def test_patch_invalid_mimetype(self, rnd_img):
  348. """
  349. Verify that a PATCH using anything other than an
  350. `application/sparql-update` MIME type results in an error.
  351. """
  352. self.client.put('/ldp/test_patch_invalid_mimetype')
  353. rnd_img['content'].seek(0)
  354. ldpnr_resp = self.client.patch('/ldp/ldpnr01/fcr:metadata',
  355. data=rnd_img,
  356. headers={'content-type' : 'image/jpeg'})
  357. ldprs_resp = self.client.patch('/ldp/test_patch_invalid_mimetype',
  358. data=b'Hello, I\'m not a SPARQL update.',
  359. headers={'content-type' : 'text/plain'})
  360. assert ldprs_resp.status_code == ldpnr_resp.status_code == 415
  361. def test_delete(self):
  362. """
  363. Test delete response codes.
  364. """
  365. self.client.put('/ldp/test_delete01')
  366. delete_resp = self.client.delete('/ldp/test_delete01')
  367. assert delete_resp.status_code == 204
  368. bogus_delete_resp = self.client.delete('/ldp/test_delete101')
  369. assert bogus_delete_resp.status_code == 404
  370. def test_tombstone(self):
  371. """
  372. Test tombstone behaviors.
  373. For POST on a tombstone, check `test_resurrection`.
  374. """
  375. tstone_resp = self.client.get('/ldp/test_delete01')
  376. assert tstone_resp.status_code == 410
  377. assert tstone_resp.headers['Link'] == \
  378. '<{}/test_delete01/fcr:tombstone>; rel="hasTombstone"'\
  379. .format(g.webroot)
  380. tstone_path = '/ldp/test_delete01/fcr:tombstone'
  381. assert self.client.get(tstone_path).status_code == 405
  382. assert self.client.put(tstone_path).status_code == 405
  383. assert self.client.delete(tstone_path).status_code == 204
  384. assert self.client.get('/ldp/test_delete01').status_code == 404
  385. def test_delete_recursive(self):
  386. """
  387. Test response codes for resources deleted recursively and their
  388. tombstones.
  389. """
  390. child_suffixes = ('a', 'a/b', 'a/b/c', 'a1', 'a1/b1')
  391. self.client.put('/ldp/test_delete_recursive01')
  392. for cs in child_suffixes:
  393. self.client.put('/ldp/test_delete_recursive01/{}'.format(cs))
  394. assert self.client.delete(
  395. '/ldp/test_delete_recursive01').status_code == 204
  396. tstone_resp = self.client.get('/ldp/test_delete_recursive01')
  397. assert tstone_resp.status_code == 410
  398. assert tstone_resp.headers['Link'] == \
  399. '<{}/test_delete_recursive01/fcr:tombstone>; rel="hasTombstone"'\
  400. .format(g.webroot)
  401. for cs in child_suffixes:
  402. child_tstone_resp = self.client.get(
  403. '/ldp/test_delete_recursive01/{}'.format(cs))
  404. assert child_tstone_resp.status_code == tstone_resp.status_code
  405. assert 'Link' not in child_tstone_resp.headers.keys()
  406. def test_put_fragments(self):
  407. """
  408. Test the correct handling of fragment URIs on PUT and GET.
  409. """
  410. with open('tests/data/fragments.ttl', 'rb') as f:
  411. self.client.put(
  412. '/ldp/test_fragment01',
  413. headers={
  414. 'Content-Type' : 'text/turtle',
  415. },
  416. data=f
  417. )
  418. rsp = self.client.get('/ldp/test_fragment01')
  419. gr = Graph().parse(data=rsp.data, format='text/turtle')
  420. assert gr[
  421. URIRef(g.webroot + '/test_fragment01#hash1')
  422. : URIRef('http://ex.org/p2') : URIRef('http://ex.org/o2')]
  423. def test_patch_fragments(self):
  424. """
  425. Test the correct handling of fragment URIs on PATCH.
  426. """
  427. self.client.put('/ldp/test_fragment_patch')
  428. with open('tests/data/fragments_insert.sparql', 'rb') as f:
  429. self.client.patch(
  430. '/ldp/test_fragment_patch',
  431. headers={
  432. 'Content-Type' : 'application/sparql-update',
  433. },
  434. data=f
  435. )
  436. ins_rsp = self.client.get('/ldp/test_fragment_patch')
  437. ins_gr = Graph().parse(data=ins_rsp.data, format='text/turtle')
  438. assert ins_gr[
  439. URIRef(g.webroot + '/test_fragment_patch#hash1234')
  440. : URIRef('http://ex.org/p3') : URIRef('http://ex.org/o3')]
  441. with open('tests/data/fragments_delete.sparql', 'rb') as f:
  442. self.client.patch(
  443. '/ldp/test_fragment_patch',
  444. headers={
  445. 'Content-Type' : 'application/sparql-update',
  446. },
  447. data=f
  448. )
  449. del_rsp = self.client.get('/ldp/test_fragment_patch')
  450. del_gr = Graph().parse(data=del_rsp.data, format='text/turtle')
  451. assert not del_gr[
  452. URIRef(g.webroot + '/test_fragment_patch#hash1234')
  453. : URIRef('http://ex.org/p3') : URIRef('http://ex.org/o3')]
  454. @pytest.mark.usefixtures('client_class')
  455. @pytest.mark.usefixtures('db')
  456. class TestMimeType:
  457. """
  458. Test ``Accept`` headers and input & output formats.
  459. """
  460. def test_accept(self):
  461. """
  462. Verify the default serialization method.
  463. """
  464. accept_list = {
  465. ('', 'text/turtle'),
  466. ('text/turtle', 'text/turtle'),
  467. ('application/rdf+xml', 'application/rdf+xml'),
  468. ('application/n-triples', 'application/n-triples'),
  469. ('application/bogus', 'text/turtle'),
  470. (
  471. 'application/rdf+xml;q=0.5,application/n-triples;q=0.7',
  472. 'application/n-triples'),
  473. (
  474. 'application/rdf+xml;q=0.5,application/bogus;q=0.7',
  475. 'application/rdf+xml'),
  476. ('application/rdf+xml;q=0.5,text/n3;q=0.7', 'text/n3'),
  477. (
  478. 'application/rdf+xml;q=0.5,application/ld+json;q=0.7',
  479. 'application/ld+json'),
  480. }
  481. for mimetype, fmt in accept_list:
  482. rsp = self.client.get('/ldp', headers={'Accept': mimetype})
  483. assert rsp.mimetype == fmt
  484. gr = Graph(identifier=g.webroot + '/').parse(
  485. data=rsp.data, format=fmt)
  486. assert nsc['fcrepo'].RepositoryRoot in set(gr.objects())
  487. def test_provided_rdf(self):
  488. """
  489. Test several input RDF serialiation formats.
  490. """
  491. self.client.get('/ldp')
  492. gr = Graph()
  493. gr.add((
  494. URIRef(g.webroot + '/test_mimetype'),
  495. nsc['dcterms'].title, Literal('Test MIME type.')))
  496. test_list = {
  497. 'application/n-triples',
  498. 'application/rdf+xml',
  499. 'text/n3',
  500. 'text/turtle',
  501. 'application/ld+json',
  502. }
  503. for mimetype in test_list:
  504. rdf_data = gr.serialize(format=mimetype)
  505. self.client.put('/ldp/test_mimetype', data=rdf_data, headers={
  506. 'content-type': mimetype})
  507. rsp = self.client.get('/ldp/test_mimetype')
  508. rsp_gr = Graph(identifier=g.webroot + '/test_mimetype').parse(
  509. data=rsp.data, format='text/turtle')
  510. assert (
  511. URIRef(g.webroot + '/test_mimetype'),
  512. nsc['dcterms'].title, Literal('Test MIME type.')) in rsp_gr
  513. @pytest.mark.usefixtures('client_class')
  514. @pytest.mark.usefixtures('db')
  515. class TestPrefHeader:
  516. """
  517. Test various combinations of `Prefer` header.
  518. """
  519. @pytest.fixture(scope='class')
  520. def cont_structure(self):
  521. """
  522. Create a container structure to be used for subsequent requests.
  523. """
  524. parent_path = '/ldp/test_parent'
  525. self.client.put(parent_path)
  526. self.client.put(parent_path + '/child1')
  527. self.client.put(parent_path + '/child2')
  528. self.client.put(parent_path + '/child3')
  529. return {
  530. 'path' : parent_path,
  531. 'response' : self.client.get(parent_path),
  532. 'subject' : URIRef(g.webroot + '/test_parent')
  533. }
  534. def test_put_prefer_handling(self, random_uuid):
  535. """
  536. Trying to PUT an existing resource should:
  537. - Return a 204 if the payload is empty
  538. - Return a 204 if the payload is RDF, server-managed triples are
  539. included and the 'Prefer' header is set to 'handling=lenient'
  540. - Return a 412 (ServerManagedTermError) if the payload is RDF,
  541. server-managed triples are included and handling is set to 'strict',
  542. or not set.
  543. """
  544. path = '/ldp/put_pref_header01'
  545. assert self.client.put(path).status_code == 201
  546. assert self.client.get(path).status_code == 200
  547. assert self.client.put(path).status_code == 204
  548. # Default handling is strict.
  549. with open('tests/data/rdf_payload_w_srv_mgd_trp.ttl', 'rb') as f:
  550. rsp_default = self.client.put(
  551. path,
  552. headers={
  553. 'Content-Type' : 'text/turtle',
  554. },
  555. data=f
  556. )
  557. assert rsp_default.status_code == 412
  558. with open('tests/data/rdf_payload_w_srv_mgd_trp.ttl', 'rb') as f:
  559. rsp_len = self.client.put(
  560. path,
  561. headers={
  562. 'Prefer' : 'handling=lenient',
  563. 'Content-Type' : 'text/turtle',
  564. },
  565. data=f
  566. )
  567. assert rsp_len.status_code == 204
  568. with open('tests/data/rdf_payload_w_srv_mgd_trp.ttl', 'rb') as f:
  569. rsp_strict = self.client.put(
  570. path,
  571. headers={
  572. 'Prefer' : 'handling=strict',
  573. 'Content-Type' : 'text/turtle',
  574. },
  575. data=f
  576. )
  577. assert rsp_strict.status_code == 412
  578. # @HOLD Embed children is debated.
  579. def _disabled_test_embed_children(self, cont_structure):
  580. """
  581. verify the "embed children" prefer header.
  582. """
  583. parent_path = cont_structure['path']
  584. cont_resp = cont_structure['response']
  585. cont_subject = cont_structure['subject']
  586. #minimal_resp = self.client.get(parent_path, headers={
  587. # 'Prefer' : 'return=minimal',
  588. #})
  589. incl_embed_children_resp = self.client.get(parent_path, headers={
  590. 'Prefer' : 'return=representation; include={}'\
  591. .format(Ldpr.EMBED_CHILD_RES_URI),
  592. })
  593. omit_embed_children_resp = self.client.get(parent_path, headers={
  594. 'Prefer' : 'return=representation; omit={}'\
  595. .format(Ldpr.EMBED_CHILD_RES_URI),
  596. })
  597. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  598. incl_gr = Graph().parse(
  599. data=incl_embed_children_resp.data, format='turtle')
  600. omit_gr = Graph().parse(
  601. data=omit_embed_children_resp.data, format='turtle')
  602. assert isomorphic(omit_gr, default_gr)
  603. children = set(incl_gr[cont_subject : nsc['ldp'].contains])
  604. assert len(children) == 3
  605. children = set(incl_gr[cont_subject : nsc['ldp'].contains])
  606. for child_uri in children:
  607. assert set(incl_gr[ child_uri : : ])
  608. assert not set(omit_gr[ child_uri : : ])
  609. def test_return_children(self, cont_structure):
  610. """
  611. verify the "return children" prefer header.
  612. """
  613. parent_path = cont_structure['path']
  614. cont_resp = cont_structure['response']
  615. cont_subject = cont_structure['subject']
  616. incl_children_resp = self.client.get(parent_path, headers={
  617. 'Prefer' : 'return=representation; include={}'\
  618. .format(Ldpr.RETURN_CHILD_RES_URI),
  619. })
  620. omit_children_resp = self.client.get(parent_path, headers={
  621. 'Prefer' : 'return=representation; omit={}'\
  622. .format(Ldpr.RETURN_CHILD_RES_URI),
  623. })
  624. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  625. incl_gr = Graph().parse(data=incl_children_resp.data, format='turtle')
  626. omit_gr = Graph().parse(data=omit_children_resp.data, format='turtle')
  627. assert isomorphic(incl_gr, default_gr)
  628. children = incl_gr[cont_subject : nsc['ldp'].contains]
  629. for child_uri in children:
  630. assert not omit_gr[cont_subject : nsc['ldp'].contains : child_uri]
  631. def test_inbound_rel(self, cont_structure):
  632. """
  633. verify the "inbound relationships" prefer header.
  634. """
  635. self.client.put('/ldp/test_target')
  636. data = '<> <http://ex.org/ns#shoots> <{}> .'.format(
  637. g.webroot + '/test_target')
  638. self.client.put('/ldp/test_shooter', data=data,
  639. headers={'Content-Type': 'text/turtle'})
  640. cont_resp = self.client.get('/ldp/test_target')
  641. incl_inbound_resp = self.client.get('/ldp/test_target', headers={
  642. 'Prefer' : 'return=representation; include="{}"'\
  643. .format(Ldpr.RETURN_INBOUND_REF_URI),
  644. })
  645. omit_inbound_resp = self.client.get('/ldp/test_target', headers={
  646. 'Prefer' : 'return=representation; omit="{}"'\
  647. .format(Ldpr.RETURN_INBOUND_REF_URI),
  648. })
  649. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  650. incl_gr = Graph().parse(data=incl_inbound_resp.data, format='turtle')
  651. omit_gr = Graph().parse(data=omit_inbound_resp.data, format='turtle')
  652. subject = URIRef(g.webroot + '/test_target')
  653. inbd_subject = URIRef(g.webroot + '/test_shooter')
  654. assert isomorphic(omit_gr, default_gr)
  655. assert len(set(incl_gr[inbd_subject : : ])) == 1
  656. assert incl_gr[
  657. inbd_subject : URIRef('http://ex.org/ns#shoots') : subject]
  658. assert not len(set(omit_gr[inbd_subject : :]))
  659. def test_srv_mgd_triples(self, cont_structure):
  660. """
  661. verify the "server managed triples" prefer header.
  662. """
  663. parent_path = cont_structure['path']
  664. cont_resp = cont_structure['response']
  665. cont_subject = cont_structure['subject']
  666. incl_srv_mgd_resp = self.client.get(parent_path, headers={
  667. 'Prefer' : 'return=representation; include={}'\
  668. .format(Ldpr.RETURN_SRV_MGD_RES_URI),
  669. })
  670. omit_srv_mgd_resp = self.client.get(parent_path, headers={
  671. 'Prefer' : 'return=representation; omit={}'\
  672. .format(Ldpr.RETURN_SRV_MGD_RES_URI),
  673. })
  674. default_gr = Graph().parse(data=cont_resp.data, format='turtle')
  675. incl_gr = Graph().parse(data=incl_srv_mgd_resp.data, format='turtle')
  676. omit_gr = Graph().parse(data=omit_srv_mgd_resp.data, format='turtle')
  677. assert isomorphic(incl_gr, default_gr)
  678. for pred in {
  679. nsc['fcrepo'].created,
  680. nsc['fcrepo'].createdBy,
  681. nsc['fcrepo'].lastModified,
  682. nsc['fcrepo'].lastModifiedBy,
  683. nsc['ldp'].contains,
  684. }:
  685. assert set(incl_gr[ cont_subject : pred : ])
  686. assert not set(omit_gr[ cont_subject : pred : ])
  687. for type in {
  688. nsc['fcrepo'].Resource,
  689. nsc['ldp'].Container,
  690. nsc['ldp'].Resource,
  691. }:
  692. assert incl_gr[ cont_subject : RDF.type : type ]
  693. assert not omit_gr[ cont_subject : RDF.type : type ]
  694. def test_delete_no_tstone(self):
  695. """
  696. Test the `no-tombstone` Prefer option.
  697. """
  698. self.client.put('/ldp/test_delete_no_tstone01')
  699. self.client.put('/ldp/test_delete_no_tstone01/a')
  700. self.client.delete('/ldp/test_delete_no_tstone01', headers={
  701. 'prefer' : 'no-tombstone'})
  702. resp = self.client.get('/ldp/test_delete_no_tstone01')
  703. assert resp.status_code == 404
  704. child_resp = self.client.get('/ldp/test_delete_no_tstone01/a')
  705. assert child_resp.status_code == 404
  706. @pytest.mark.usefixtures('client_class')
  707. @pytest.mark.usefixtures('db')
  708. class TestDigest:
  709. """
  710. Test digest and ETag handling.
  711. """
  712. def test_digest_post(self):
  713. """
  714. Test ``Digest`` and ``ETag`` headers on resource POST.
  715. """
  716. resp = self.client.post('/ldp/')
  717. assert 'Digest' in resp.headers
  718. assert 'ETag' in resp.headers
  719. assert (
  720. b64encode(bytes.fromhex(
  721. resp.headers['ETag'].replace('W/', '')
  722. )).decode('ascii') ==
  723. resp.headers['Digest'].replace('SHA256=', ''))
  724. def test_digest_put(self):
  725. """
  726. Test ``Digest`` and ``ETag`` headers on resource PUT.
  727. """
  728. resp_put = self.client.put('/ldp/test_digest_put')
  729. assert 'Digest' in resp_put.headers
  730. assert 'ETag' in resp_put.headers
  731. assert (
  732. b64encode(bytes.fromhex(
  733. resp_put.headers['ETag'].replace('W/', '')
  734. )).decode('ascii') ==
  735. resp_put.headers['Digest'].replace('SHA256=', ''))
  736. resp_get = self.client.get('/ldp/test_digest_put')
  737. assert 'Digest' in resp_get.headers
  738. assert 'ETag' in resp_get.headers
  739. assert (
  740. b64encode(bytes.fromhex(
  741. resp_get.headers['ETag'].replace('W/', '')
  742. )).decode('ascii') ==
  743. resp_get.headers['Digest'].replace('SHA256=', ''))
  744. def test_digest_patch(self):
  745. """
  746. Verify that the digest and ETag change on resource change.
  747. """
  748. path = '/ldp/test_digest_patch'
  749. self.client.put(path)
  750. rsp1 = self.client.get(path)
  751. self.client.patch(
  752. path, data=b'DELETE {} INSERT {<> a <http://ex.org/Test> .} '
  753. b'WHERE {}',
  754. headers={'Content-Type': 'application/sparql-update'})
  755. rsp2 = self.client.get(path)
  756. assert rsp1.headers['ETag'] != rsp2.headers['ETag']
  757. assert rsp1.headers['Digest'] != rsp2.headers['Digest']
  758. @pytest.mark.usefixtures('client_class')
  759. @pytest.mark.usefixtures('db')
  760. class TestVersion:
  761. """
  762. Test version creation, retrieval and deletion.
  763. """
  764. def test_create_versions(self):
  765. """
  766. Test that POSTing multiple times to fcr:versions creates the
  767. 'hasVersions' triple and yields multiple version snapshots.
  768. """
  769. self.client.put('/ldp/test_version')
  770. create_rsp = self.client.post('/ldp/test_version/fcr:versions')
  771. assert create_rsp.status_code == 201
  772. rsrc_rsp = self.client.get('/ldp/test_version')
  773. rsrc_gr = Graph().parse(data=rsrc_rsp.data, format='turtle')
  774. assert len(set(rsrc_gr[: nsc['fcrepo'].hasVersions :])) == 1
  775. info_rsp = self.client.get('/ldp/test_version/fcr:versions')
  776. assert info_rsp.status_code == 200
  777. info_gr = Graph().parse(data=info_rsp.data, format='turtle')
  778. assert len(set(info_gr[: nsc['fcrepo'].hasVersion :])) == 1
  779. self.client.post('/ldp/test_version/fcr:versions')
  780. info2_rsp = self.client.get('/ldp/test_version/fcr:versions')
  781. info2_gr = Graph().parse(data=info2_rsp.data, format='turtle')
  782. assert len(set(info2_gr[: nsc['fcrepo'].hasVersion :])) == 2
  783. def test_version_with_slug(self):
  784. """
  785. Test a version with a slug.
  786. """
  787. self.client.put('/ldp/test_version_slug')
  788. create_rsp = self.client.post('/ldp/test_version_slug/fcr:versions',
  789. headers={'slug' : 'v1'})
  790. new_ver_uri = create_rsp.headers['Location']
  791. assert new_ver_uri == g.webroot + '/test_version_slug/fcr:versions/v1'
  792. info_rsp = self.client.get('/ldp/test_version_slug/fcr:versions')
  793. info_gr = Graph().parse(data=info_rsp.data, format='turtle')
  794. assert info_gr[
  795. URIRef(new_ver_uri) :
  796. nsc['fcrepo'].hasVersionLabel :
  797. Literal('v1')]
  798. def test_dupl_version(self):
  799. """
  800. Make sure that two POSTs with the same slug result in two different
  801. versions.
  802. """
  803. path = '/ldp/test_duplicate_slug'
  804. self.client.put(path)
  805. v1_rsp = self.client.post(path + '/fcr:versions',
  806. headers={'slug' : 'v1'})
  807. v1_uri = v1_rsp.headers['Location']
  808. dup_rsp = self.client.post(path + '/fcr:versions',
  809. headers={'slug' : 'v1'})
  810. dup_uri = dup_rsp.headers['Location']
  811. assert v1_uri != dup_uri
  812. # @TODO Reverting from version and resurrecting is not fully functional.
  813. def _disabled_test_revert_version(self):
  814. """
  815. Take a version snapshot, update a resource, and then revert to the
  816. previous vresion.
  817. """
  818. rsrc_path = '/ldp/test_revert_version'
  819. payload1 = '<> <urn:demo:p1> <urn:demo:o1> .'
  820. payload2 = '<> <urn:demo:p1> <urn:demo:o2> .'
  821. self.client.put(rsrc_path, headers={
  822. 'content-type': 'text/turtle'}, data=payload1)
  823. self.client.post(
  824. rsrc_path + '/fcr:versions', headers={'slug': 'v1'})
  825. v1_rsp = self.client.get(rsrc_path)
  826. v1_gr = Graph().parse(data=v1_rsp.data, format='turtle')
  827. assert v1_gr[
  828. URIRef(g.webroot + '/test_revert_version')
  829. : URIRef('urn:demo:p1')
  830. : URIRef('urn:demo:o1')
  831. ]
  832. self.client.put(rsrc_path, headers={
  833. 'content-type': 'text/turtle'}, data=payload2)
  834. v2_rsp = self.client.get(rsrc_path)
  835. v2_gr = Graph().parse(data=v2_rsp.data, format='turtle')
  836. assert v2_gr[
  837. URIRef(g.webroot + '/test_revert_version')
  838. : URIRef('urn:demo:p1')
  839. : URIRef('urn:demo:o2')
  840. ]
  841. self.client.patch(rsrc_path + '/fcr:versions/v1')
  842. revert_rsp = self.client.get(rsrc_path)
  843. revert_gr = Graph().parse(data=revert_rsp.data, format='turtle')
  844. assert revert_gr[
  845. URIRef(g.webroot + '/test_revert_version')
  846. : URIRef('urn:demo:p1')
  847. : URIRef('urn:demo:o1')
  848. ]
  849. def test_resurrection(self):
  850. """
  851. Delete and then resurrect a resource.
  852. Make sure that the resource is resurrected to the latest version.
  853. """
  854. path = '/ldp/test_lazarus'
  855. self.client.put(path)
  856. self.client.post(path + '/fcr:versions', headers={'slug': 'v1'})
  857. self.client.put(
  858. path, headers={'content-type': 'text/turtle'},
  859. data=b'<> <urn:demo:p1> <urn:demo:o1> .')
  860. self.client.post(path + '/fcr:versions', headers={'slug': 'v2'})
  861. self.client.put(
  862. path, headers={'content-type': 'text/turtle'},
  863. data=b'<> <urn:demo:p1> <urn:demo:o2> .')
  864. self.client.delete(path)
  865. assert self.client.get(path).status_code == 410
  866. self.client.post(path + '/fcr:tombstone')
  867. laz_data = self.client.get(path).data
  868. laz_gr = Graph().parse(data=laz_data, format='turtle')
  869. assert laz_gr[
  870. URIRef(g.webroot + '/test_lazarus')
  871. : URIRef('urn:demo:p1')
  872. : URIRef('urn:demo:o2')
  873. ]