test_resource_api.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. import pdb
  2. import pytest
  3. from io import BytesIO
  4. from uuid import uuid4
  5. from rdflib import Graph, Literal, URIRef
  6. from lakesuperior import env
  7. from lakesuperior.api import resource as rsrc_api
  8. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  9. from lakesuperior.exceptions import (
  10. IncompatibleLdpTypeError, InvalidResourceError, ResourceNotExistsError,
  11. TombstoneError)
  12. from lakesuperior.globals import RES_CREATED, RES_UPDATED
  13. from lakesuperior.model.ldp.ldpr import Ldpr
  14. from lakesuperior.model.graph.graph import SimpleGraph, Imr
  15. @pytest.fixture(scope='module')
  16. def random_uuid():
  17. return str(uuid.uuid4())
  18. @pytest.fixture
  19. def dc_rdf():
  20. return b'''
  21. PREFIX dcterms: <http://purl.org/dc/terms/>
  22. PREFIX ldp: <http://www.w3.org/ns/ldp#>
  23. <> dcterms:title "Direct Container" ;
  24. ldp:membershipResource <info:fcres/member> ;
  25. ldp:hasMemberRelation dcterms:relation .
  26. '''
  27. @pytest.fixture
  28. def ic_rdf():
  29. return b'''
  30. PREFIX dcterms: <http://purl.org/dc/terms/>
  31. PREFIX ldp: <http://www.w3.org/ns/ldp#>
  32. PREFIX ore: <http://www.openarchives.org/ore/terms/>
  33. <> dcterms:title "Indirect Container" ;
  34. ldp:membershipResource <info:fcres/top_container> ;
  35. ldp:hasMemberRelation dcterms:relation ;
  36. ldp:insertedContentRelation ore:proxyFor .
  37. '''
  38. @pytest.mark.usefixtures('db')
  39. class TestResourceCRUD:
  40. '''
  41. Test interaction with the Resource API.
  42. '''
  43. def test_nodes_exist(self):
  44. """
  45. Verify whether nodes exist or not.
  46. """
  47. assert rsrc_api.exists('/') is True
  48. assert rsrc_api.exists('/{}'.format(uuid4())) is False
  49. def test_get_root_node_metadata(self):
  50. """
  51. Get the root node metadata.
  52. The ``dcterms:title`` property should NOT be included.
  53. """
  54. gr = rsrc_api.get_metadata('/')
  55. assert isinstance(gr, SimpleGraph)
  56. assert len(gr) == 9
  57. assert gr[gr.uri : nsc['rdf'].type : nsc['ldp'].Resource ]
  58. assert not gr[
  59. gr.uri : nsc['dcterms'].title : Literal("Repository Root")
  60. ]
  61. def test_get_root_node(self):
  62. """
  63. Get the root node.
  64. The ``dcterms:title`` property should be included.
  65. """
  66. rsrc = rsrc_api.get('/')
  67. assert isinstance(rsrc, Ldpr)
  68. gr = rsrc.imr
  69. assert len(gr) == 10
  70. assert gr[gr.uri : nsc['rdf'].type : nsc['ldp'].Resource ]
  71. assert gr[
  72. gr.uri : nsc['dcterms'].title : Literal('Repository Root')]
  73. def test_get_nonexisting_node(self):
  74. """
  75. Get a non-existing node.
  76. """
  77. with pytest.raises(ResourceNotExistsError):
  78. gr = rsrc_api.get('/{}'.format(uuid4()))
  79. def test_create_ldp_rs(self):
  80. """
  81. Create an RDF resource (LDP-RS) from a provided graph.
  82. """
  83. uid = '/rsrc_from_graph'
  84. uri = nsc['fcres'][uid]
  85. gr = Graph().parse(
  86. data='<> a <http://ex.org/type#A> .', format='turtle',
  87. publicID=uri)
  88. evt, _ = rsrc_api.create_or_replace(uid, graph=gr)
  89. rsrc = rsrc_api.get(uid)
  90. assert rsrc.imr[
  91. rsrc.uri : nsc['rdf'].type : URIRef('http://ex.org/type#A')]
  92. assert rsrc.imr[
  93. rsrc.uri : nsc['rdf'].type : nsc['ldp'].RDFSource]
  94. def test_create_ldp_nr(self):
  95. """
  96. Create a non-RDF resource (LDP-NR).
  97. """
  98. uid = '/{}'.format(uuid4())
  99. data = b'Hello. This is some dummy content.'
  100. rsrc_api.create_or_replace(
  101. uid, stream=BytesIO(data), mimetype='text/plain')
  102. rsrc = rsrc_api.get(uid)
  103. assert rsrc.content.read() == data
  104. def test_replace_rsrc(self):
  105. uid = '/test_replace'
  106. uri = nsc['fcres'][uid]
  107. gr1 = Graph().parse(
  108. data='<> a <http://ex.org/type#A> .', format='turtle',
  109. publicID=uri)
  110. evt, _ = rsrc_api.create_or_replace(uid, graph=gr1)
  111. assert evt == RES_CREATED
  112. rsrc = rsrc_api.get(uid)
  113. assert rsrc.imr[
  114. rsrc.uri : nsc['rdf'].type : URIRef('http://ex.org/type#A')]
  115. assert rsrc.imr[
  116. rsrc.uri : nsc['rdf'].type : nsc['ldp'].RDFSource]
  117. gr2 = Graph().parse(
  118. data='<> a <http://ex.org/type#B> .', format='turtle',
  119. publicID=uri)
  120. #pdb.set_trace()
  121. evt, _ = rsrc_api.create_or_replace(uid, graph=gr2)
  122. assert evt == RES_UPDATED
  123. rsrc = rsrc_api.get(uid)
  124. assert not rsrc.imr[
  125. rsrc.uri : nsc['rdf'].type : URIRef('http://ex.org/type#A')]
  126. assert rsrc.imr[
  127. rsrc.uri : nsc['rdf'].type : URIRef('http://ex.org/type#B')]
  128. assert rsrc.imr[
  129. rsrc.uri : nsc['rdf'].type : nsc['ldp'].RDFSource]
  130. def test_replace_incompatible_type(self):
  131. """
  132. Verify replacing resources with incompatible type.
  133. Replacing a LDP-NR with a LDP-RS, or vice versa, should fail.
  134. """
  135. uid_rs = '/test_incomp_rs'
  136. uid_nr = '/test_incomp_nr'
  137. data = b'mock binary content'
  138. gr = Graph().parse(
  139. data='<> a <http://ex.org/type#A> .', format='turtle',
  140. publicID=nsc['fcres'][uid_rs])
  141. rsrc_api.create_or_replace(uid_rs, graph=gr)
  142. rsrc_api.create_or_replace(
  143. uid_nr, stream=BytesIO(data), mimetype='text/plain')
  144. with pytest.raises(IncompatibleLdpTypeError):
  145. rsrc_api.create_or_replace(uid_nr, graph=gr)
  146. with pytest.raises(IncompatibleLdpTypeError):
  147. rsrc_api.create_or_replace(
  148. uid_rs, stream=BytesIO(data), mimetype='text/plain')
  149. with pytest.raises(IncompatibleLdpTypeError):
  150. rsrc_api.create_or_replace(uid_nr)
  151. def test_delta_update(self):
  152. """
  153. Update a resource with two sets of add and remove triples.
  154. """
  155. uid = '/test_delta_patch'
  156. uri = nsc['fcres'][uid]
  157. init_trp = {
  158. (URIRef(uri), nsc['rdf'].type, nsc['foaf'].Person),
  159. (URIRef(uri), nsc['foaf'].name, Literal('Joe Bob')),
  160. }
  161. remove_trp = {
  162. (URIRef(uri), nsc['rdf'].type, nsc['foaf'].Person),
  163. }
  164. add_trp = {
  165. (URIRef(uri), nsc['rdf'].type, nsc['foaf'].Organization),
  166. }
  167. gr = Graph()
  168. gr += init_trp
  169. rsrc_api.create_or_replace(uid, graph=gr)
  170. rsrc_api.update_delta(uid, remove_trp, add_trp)
  171. rsrc = rsrc_api.get(uid)
  172. assert rsrc.imr[
  173. rsrc.uri : nsc['rdf'].type : nsc['foaf'].Organization]
  174. assert rsrc.imr[rsrc.uri : nsc['foaf'].name : Literal('Joe Bob')]
  175. assert not rsrc.imr[
  176. rsrc.uri : nsc['rdf'].type : nsc['foaf'].Person]
  177. def test_delta_update_wildcard(self):
  178. """
  179. Update a resource using wildcard modifiers.
  180. """
  181. uid = '/test_delta_patch_wc'
  182. uri = nsc['fcres'][uid]
  183. init_trp = {
  184. (URIRef(uri), nsc['rdf'].type, nsc['foaf'].Person),
  185. (URIRef(uri), nsc['foaf'].name, Literal('Joe Bob')),
  186. (URIRef(uri), nsc['foaf'].name, Literal('Joe Average Bob')),
  187. (URIRef(uri), nsc['foaf'].name, Literal('Joe 12oz Bob')),
  188. }
  189. remove_trp = {
  190. (URIRef(uri), nsc['foaf'].name, None),
  191. }
  192. add_trp = {
  193. (URIRef(uri), nsc['foaf'].name, Literal('Joan Knob')),
  194. }
  195. gr = Graph()
  196. gr += init_trp
  197. rsrc_api.create_or_replace(uid, graph=gr)
  198. rsrc_api.update_delta(uid, remove_trp, add_trp)
  199. rsrc = rsrc_api.get(uid)
  200. assert rsrc.imr[
  201. rsrc.uri : nsc['rdf'].type : nsc['foaf'].Person]
  202. assert rsrc.imr[rsrc.uri : nsc['foaf'].name : Literal('Joan Knob')]
  203. assert not rsrc.imr[rsrc.uri : nsc['foaf'].name : Literal('Joe Bob')]
  204. assert not rsrc.imr[
  205. rsrc.uri : nsc['foaf'].name : Literal('Joe Average Bob')]
  206. assert not rsrc.imr[
  207. rsrc.uri : nsc['foaf'].name : Literal('Joe 12oz Bob')]
  208. def test_sparql_update(self):
  209. """
  210. Update a resource using a SPARQL Update string.
  211. Use a mix of relative and absolute URIs.
  212. """
  213. uid = '/test_sparql'
  214. rdf_data = b'<> <http://purl.org/dc/terms/title> "Original title." .'
  215. update_str = '''DELETE {
  216. <> <http://purl.org/dc/terms/title> "Original title." .
  217. } INSERT {
  218. <> <http://purl.org/dc/terms/title> "Title #2." .
  219. <info:fcres/test_sparql>
  220. <http://purl.org/dc/terms/title> "Title #3." .
  221. <#h1> <http://purl.org/dc/terms/title> "This is a hash." .
  222. } WHERE {
  223. }'''
  224. rsrc_api.create_or_replace(uid, rdf_data=rdf_data, rdf_fmt='turtle')
  225. ver_uid = rsrc_api.create_version(uid, 'v1').split('fcr:versions/')[-1]
  226. rsrc = rsrc_api.update(uid, update_str)
  227. assert (
  228. (rsrc.uri, nsc['dcterms'].title, Literal('Original title.'))
  229. not in set(rsrc.imr))
  230. assert (
  231. (rsrc.uri, nsc['dcterms'].title, Literal('Title #2.'))
  232. in set(rsrc.imr))
  233. assert (
  234. (rsrc.uri, nsc['dcterms'].title, Literal('Title #3.'))
  235. in set(rsrc.imr))
  236. assert ((
  237. URIRef(str(rsrc.uri) + '#h1'),
  238. nsc['dcterms'].title, Literal('This is a hash.'))
  239. in set(rsrc.imr))
  240. def test_create_ldp_dc_post(self, dc_rdf):
  241. """
  242. Create an LDP Direct Container via POST.
  243. """
  244. rsrc_api.create_or_replace('/member')
  245. dc_rsrc = rsrc_api.create(
  246. '/', 'test_dc_post', rdf_data=dc_rdf, rdf_fmt='turtle')
  247. member_rsrc = rsrc_api.get('/member')
  248. assert nsc['ldp'].Container in dc_rsrc.ldp_types
  249. assert nsc['ldp'].DirectContainer in dc_rsrc.ldp_types
  250. def test_create_ldp_dc_put(self, dc_rdf):
  251. """
  252. Create an LDP Direct Container via PUT.
  253. """
  254. dc_uid = '/test_dc_put01'
  255. _, dc_rsrc = rsrc_api.create_or_replace(
  256. dc_uid, rdf_data=dc_rdf, rdf_fmt='turtle')
  257. member_rsrc = rsrc_api.get('/member')
  258. assert nsc['ldp'].Container in dc_rsrc.ldp_types
  259. assert nsc['ldp'].DirectContainer in dc_rsrc.ldp_types
  260. def test_add_dc_member(self, dc_rdf):
  261. """
  262. Add members to a direct container and verify special properties.
  263. """
  264. dc_uid = '/test_dc_put02'
  265. _, dc_rsrc = rsrc_api.create_or_replace(
  266. dc_uid, rdf_data=dc_rdf, rdf_fmt='turtle')
  267. child_uid = rsrc_api.create(dc_uid, None).uid
  268. member_rsrc = rsrc_api.get('/member')
  269. assert member_rsrc.imr[
  270. member_rsrc.uri: nsc['dcterms'].relation: nsc['fcres'][child_uid]]
  271. def test_indirect_container(self, ic_rdf):
  272. """
  273. Create an indirect container verify special properties.
  274. """
  275. cont_uid = '/top_container'
  276. ic_uid = '{}/test_ic'.format(cont_uid)
  277. member_uid = '{}/ic_member'.format(ic_uid)
  278. target_uid = '/ic_target'
  279. ic_member_rdf = b'''
  280. PREFIX ore: <http://www.openarchives.org/ore/terms/>
  281. <> ore:proxyFor <info:fcres/ic_target> .'''
  282. rsrc_api.create_or_replace(cont_uid)
  283. rsrc_api.create_or_replace(target_uid)
  284. rsrc_api.create_or_replace(ic_uid, rdf_data=ic_rdf, rdf_fmt='turtle')
  285. rsrc_api.create_or_replace(
  286. member_uid, rdf_data=ic_member_rdf, rdf_fmt='turtle')
  287. ic_rsrc = rsrc_api.get(ic_uid)
  288. assert nsc['ldp'].Container in ic_rsrc.ldp_types
  289. assert nsc['ldp'].IndirectContainer in ic_rsrc.ldp_types
  290. assert nsc['ldp'].DirectContainer not in ic_rsrc.ldp_types
  291. member_rsrc = rsrc_api.get(member_uid)
  292. top_cont_rsrc = rsrc_api.get(cont_uid)
  293. assert top_cont_rsrc.imr[
  294. top_cont_rsrc.uri: nsc['dcterms'].relation:
  295. nsc['fcres'][target_uid]]
  296. @pytest.mark.usefixtures('db')
  297. class TestAdvancedDelete:
  298. '''
  299. Test resource version lifecycle.
  300. '''
  301. def test_soft_delete(self):
  302. """
  303. Soft-delete (bury) a resource.
  304. """
  305. uid = '/test_soft_delete01'
  306. rsrc_api.create_or_replace(uid)
  307. rsrc_api.delete(uid)
  308. with pytest.raises(TombstoneError):
  309. rsrc_api.get(uid)
  310. def test_resurrect(self):
  311. """
  312. Restore (resurrect) a soft-deleted resource.
  313. """
  314. uid = '/test_soft_delete02'
  315. rsrc_api.create_or_replace(uid)
  316. rsrc_api.delete(uid)
  317. rsrc_api.resurrect(uid)
  318. rsrc = rsrc_api.get(uid)
  319. assert nsc['ldp'].Resource in rsrc.ldp_types
  320. def test_hard_delete(self):
  321. """
  322. Hard-delete (forget) a resource.
  323. """
  324. uid = '/test_hard_delete01'
  325. rsrc_api.create_or_replace(uid)
  326. rsrc_api.delete(uid, False)
  327. with pytest.raises(ResourceNotExistsError):
  328. rsrc_api.get(uid)
  329. with pytest.raises(ResourceNotExistsError):
  330. rsrc_api.resurrect(uid)
  331. def test_delete_children(self):
  332. """
  333. Soft-delete a resource with children.
  334. """
  335. uid = '/test_soft_delete_children01'
  336. rsrc_api.create_or_replace(uid)
  337. for i in range(3):
  338. rsrc_api.create_or_replace('{}/child{}'.format(uid, i))
  339. rsrc_api.delete(uid)
  340. with pytest.raises(TombstoneError):
  341. rsrc_api.get(uid)
  342. for i in range(3):
  343. with pytest.raises(TombstoneError):
  344. rsrc_api.get('{}/child{}'.format(uid, i))
  345. # Cannot resurrect children of a tombstone.
  346. with pytest.raises(TombstoneError):
  347. rsrc_api.resurrect('{}/child{}'.format(uid, i))
  348. def test_resurrect_children(self):
  349. """
  350. Resurrect a resource with its children.
  351. This uses fixtures from the previous test.
  352. """
  353. uid = '/test_soft_delete_children01'
  354. rsrc_api.resurrect(uid)
  355. parent_rsrc = rsrc_api.get(uid)
  356. assert nsc['ldp'].Resource in parent_rsrc.ldp_types
  357. for i in range(3):
  358. child_rsrc = rsrc_api.get('{}/child{}'.format(uid, i))
  359. assert nsc['ldp'].Resource in child_rsrc.ldp_types
  360. def test_hard_delete_children(self):
  361. """
  362. Hard-delete (forget) a resource with its children.
  363. This uses fixtures from the previous test.
  364. """
  365. uid = '/test_hard_delete_children01'
  366. rsrc_api.create_or_replace(uid)
  367. for i in range(3):
  368. rsrc_api.create_or_replace('{}/child{}'.format(uid, i))
  369. rsrc_api.delete(uid, False)
  370. with pytest.raises(ResourceNotExistsError):
  371. rsrc_api.get(uid)
  372. with pytest.raises(ResourceNotExistsError):
  373. rsrc_api.resurrect(uid)
  374. for i in range(3):
  375. with pytest.raises(ResourceNotExistsError):
  376. rsrc_api.get('{}/child{}'.format(uid, i))
  377. with pytest.raises(ResourceNotExistsError):
  378. rsrc_api.resurrect('{}/child{}'.format(uid, i))
  379. def test_hard_delete_descendants(self):
  380. """
  381. Forget a resource with all its descendants.
  382. """
  383. uid = '/test_hard_delete_descendants01'
  384. rsrc_api.create_or_replace(uid)
  385. for i in range(1, 4):
  386. rsrc_api.create_or_replace('{}/child{}'.format(uid, i))
  387. for j in range(i):
  388. rsrc_api.create_or_replace('{}/child{}/grandchild{}'.format(
  389. uid, i, j))
  390. rsrc_api.delete(uid, False)
  391. with pytest.raises(ResourceNotExistsError):
  392. rsrc_api.get(uid)
  393. with pytest.raises(ResourceNotExistsError):
  394. rsrc_api.resurrect(uid)
  395. for i in range(1, 4):
  396. with pytest.raises(ResourceNotExistsError):
  397. rsrc_api.get('{}/child{}'.format(uid, i))
  398. with pytest.raises(ResourceNotExistsError):
  399. rsrc_api.resurrect('{}/child{}'.format(uid, i))
  400. for j in range(i):
  401. with pytest.raises(ResourceNotExistsError):
  402. rsrc_api.get('{}/child{}/grandchild{}'.format(
  403. uid, i, j))
  404. with pytest.raises(ResourceNotExistsError):
  405. rsrc_api.resurrect('{}/child{}/grandchild{}'.format(
  406. uid, i, j))
  407. @pytest.mark.usefixtures('db')
  408. class TestResourceVersioning:
  409. '''
  410. Test resource version lifecycle.
  411. '''
  412. def test_create_version(self):
  413. """
  414. Create a version snapshot.
  415. """
  416. uid = '/test_version1'
  417. rdf_data = b'<> <http://purl.org/dc/terms/title> "Original title." .'
  418. update_str = '''DELETE {
  419. <> <http://purl.org/dc/terms/title> "Original title." .
  420. } INSERT {
  421. <> <http://purl.org/dc/terms/title> "Title #2." .
  422. } WHERE {
  423. }'''
  424. rsrc_api.create_or_replace(uid, rdf_data=rdf_data, rdf_fmt='turtle')
  425. ver_uid = rsrc_api.create_version(uid, 'v1').split('fcr:versions/')[-1]
  426. #FIXME Without this, the test fails.
  427. set(rsrc_api.get_version(uid, ver_uid))
  428. rsrc_api.update(uid, update_str)
  429. current = rsrc_api.get(uid)
  430. assert (
  431. (current.uri, nsc['dcterms'].title, Literal('Title #2.'))
  432. in current.imr)
  433. assert (
  434. (current.uri, nsc['dcterms'].title, Literal('Original title.'))
  435. not in current.imr)
  436. v1 = rsrc_api.get_version(uid, ver_uid)
  437. assert (
  438. (v1.uri, nsc['dcterms'].title, Literal('Original title.'))
  439. in set(v1))
  440. assert (
  441. (v1.uri, nsc['dcterms'].title, Literal('Title #2.'))
  442. not in set(v1))
  443. def test_revert_to_version(self):
  444. """
  445. Test reverting to a previous version.
  446. Uses assets from previous test.
  447. """
  448. uid = '/test_version1'
  449. ver_uid = 'v1'
  450. rsrc_api.revert_to_version(uid, ver_uid)
  451. rev = rsrc_api.get(uid)
  452. assert (
  453. (rev.uri, nsc['dcterms'].title, Literal('Original title.'))
  454. in rev.imr)
  455. def test_versioning_children(self):
  456. """
  457. Test that children are not affected by version restoring.
  458. 1. create parent resource
  459. 2. Create child 1
  460. 3. Version parent
  461. 4. Create child 2
  462. 5. Restore parent to previous version
  463. 6. Verify that restored version still has 2 children
  464. """
  465. uid = '/test_version_children'
  466. ver_uid = 'v1'
  467. ch1_uid = '{}/kid_a'.format(uid)
  468. ch2_uid = '{}/kid_b'.format(uid)
  469. rsrc_api.create_or_replace(uid)
  470. rsrc_api.create_or_replace(ch1_uid)
  471. ver_uid = rsrc_api.create_version(uid, ver_uid).split('fcr:versions/')[-1]
  472. rsrc = rsrc_api.get(uid)
  473. assert nsc['fcres'][ch1_uid] in rsrc.imr[
  474. rsrc.uri : nsc['ldp'].contains]
  475. rsrc_api.create_or_replace(ch2_uid)
  476. rsrc = rsrc_api.get(uid)
  477. assert nsc['fcres'][ch2_uid] in rsrc.imr[
  478. rsrc.uri : nsc['ldp'].contains]
  479. rsrc_api.revert_to_version(uid, ver_uid)
  480. rsrc = rsrc_api.get(uid)
  481. assert nsc['fcres'][ch1_uid] in rsrc.imr[
  482. rsrc.uri : nsc['ldp'].contains]
  483. assert nsc['fcres'][ch2_uid] in rsrc.imr[
  484. rsrc.uri : nsc['ldp'].contains]