Ignoring the missing type RDF error for the page under testing's url.
[htsworkflow.git] / htsworkflow / frontend / samples / test_samples.py
1 import datetime
2 import unittest
3
4 try:
5     import json
6 except ImportError, e:
7     import simplejson as json
8
9 from django.test import TestCase
10
11 from htsworkflow.frontend.samples.models import \
12         Affiliation, \
13         ExperimentType, \
14         Species, \
15         Library
16
17 from htsworkflow.frontend.samples.views import \
18      library_dict, \
19      library_json
20
21 from htsworkflow.frontend.auth import apidata
22 from htsworkflow.util.conversion import unicode_or_none
23 from htsworkflow.util.ethelp import validate_xhtml
24
25 class LibraryTestCase(TestCase):
26     fixtures = ['test_samples.json']
27
28     def setUp(self):
29         create_db(self)
30
31     def testOrganism(self):
32         self.assertEquals(self.library_10001.organism(), 'human')
33
34     def testAffiliations(self):
35         self.library_10001.affiliations.add(self.affiliation_alice)
36         self.library_10002.affiliations.add(
37                 self.affiliation_alice,
38                 self.affiliation_bob
39         )
40         self.failUnless(len(self.library_10001.affiliations.all()), 1)
41         self.failUnless(self.library_10001.affiliation(), 'Alice')
42
43         self.failUnless(len(self.library_10002.affiliations.all()), 2)
44         self.failUnless(self.library_10001.affiliation(), 'Alice, Bob')
45
46
47 class SampleWebTestCase(TestCase):
48     """
49     Test returning data from our database in rest like ways.
50     (like returning json objects)
51     """
52     fixtures = ['test_samples.json']
53
54     def test_library_info(self):
55         for lib in Library.objects.all():
56             lib_dict = library_dict(lib.id)
57             url = '/samples/library/%s/json' % (lib.id,)
58             lib_response = self.client.get(url, apidata)
59             self.failUnlessEqual(lib_response.status_code, 200)
60             lib_json = json.loads(lib_response.content)
61
62             for d in [lib_dict, lib_json]:
63                 # amplified_from_sample is a link to the library table,
64                 # I want to use the "id" for the data lookups not
65                 # the embedded primary key.
66                 # It gets slightly confusing on how to implement sending the right id
67                 # since amplified_from_sample can be null
68                 #self.failUnlessEqual(d['amplified_from_sample'], lib.amplified_from_sample)
69                 self.failUnlessEqual(d['antibody_id'], lib.antibody_id)
70                 self.failUnlessEqual(d['cell_line_id'], lib.cell_line_id)
71                 self.failUnlessEqual(d['cell_line'], unicode_or_none(lib.cell_line))
72                 self.failUnlessEqual(d['experiment_type'], lib.experiment_type.name)
73                 self.failUnlessEqual(d['experiment_type_id'], lib.experiment_type_id)
74                 self.failUnlessEqual(d['gel_cut_size'], lib.gel_cut_size)
75                 self.failUnlessEqual(d['hidden'], lib.hidden)
76                 self.failUnlessEqual(d['id'], lib.id)
77                 self.failUnlessEqual(d['insert_size'], lib.insert_size)
78                 self.failUnlessEqual(d['library_name'], lib.library_name)
79                 self.failUnlessEqual(d['library_species'], lib.library_species.scientific_name)
80                 self.failUnlessEqual(d['library_species_id'], lib.library_species_id)
81                 self.failUnlessEqual(d['library_type_id'], lib.library_type_id)
82                 if lib.library_type_id is not None:
83                     self.failUnlessEqual(d['library_type'], lib.library_type.name)
84                 else:
85                     self.failUnlessEqual(d['library_type'], None)
86                     self.failUnlessEqual(d['made_for'], lib.made_for)
87                     self.failUnlessEqual(d['made_by'], lib.made_by)
88                     self.failUnlessEqual(d['notes'], lib.notes)
89                     self.failUnlessEqual(d['replicate'], lib.replicate)
90                     self.failUnlessEqual(d['stopping_point'], lib.stopping_point)
91                     self.failUnlessEqual(d['successful_pM'], lib.successful_pM)
92                     self.failUnlessEqual(d['undiluted_concentration'],
93                                          unicode(lib.undiluted_concentration))
94                 # some specific tests
95                 if lib.id == '10981':
96                     # test a case where there is no known status
97                     lane_set = {u'status': u'Unknown',
98                                 u'paired_end': True,
99                                 u'read_length': 75,
100                                 u'lane_number': 1,
101                                 u'lane_id': 1193,
102                                 u'flowcell': u'303TUAAXX',
103                                 u'status_code': None}
104                     self.failUnlessEqual(len(d['lane_set']), 1)
105                     self.failUnlessEqual(d['lane_set'][0], lane_set)
106                 elif lib.id == '11016':
107                     # test a case where there is a status
108                     lane_set = {u'status': 'Good',
109                                 u'paired_end': True,
110                                 u'read_length': 75,
111                                 u'lane_number': 5,
112                                 u'lane_id': 1197,
113                                 u'flowcell': u'303TUAAXX',
114                                 u'status_code': 2}
115                     self.failUnlessEqual(len(d['lane_set']), 1)
116                     self.failUnlessEqual(d['lane_set'][0], lane_set)
117
118
119     def test_invalid_library_json(self):
120         """
121         Make sure we get a 404 if we request an invalid library id
122         """
123         response = self.client.get('/samples/library/nottheone/json', apidata)
124         self.failUnlessEqual(response.status_code, 404)
125
126
127     def test_invalid_library(self):
128         response = self.client.get('/library/nottheone/')
129         self.failUnlessEqual(response.status_code, 404)
130
131
132     def test_library_no_key(self):
133         """
134         Make sure we get a 302 if we're not logged in
135         """
136         response = self.client.get('/samples/library/10981/json')
137         self.failUnlessEqual(response.status_code, 403)
138         response = self.client.get('/samples/library/10981/json', apidata)
139         self.failUnlessEqual(response.status_code, 200)
140
141     def test_library_rdf(self):
142         import RDF
143         from htsworkflow.util.rdfhelp import get_model, \
144              dump_model, \
145              fromTypedNode, \
146              load_string_into_model, \
147              rdfNS, \
148              libraryOntology
149         model = get_model()
150
151         response = self.client.get('/library/10981/')
152         self.assertEqual(response.status_code, 200)
153         content = response.content
154         load_string_into_model(model, 'rdfa', content)
155
156         body = """prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
157         prefix libns: <http://jumpgate.caltech.edu/wiki/LibraryOntology#>
158
159         select ?library ?name ?library_id ?gel_cut ?made_by
160         where {
161            ?library a libns:library ;
162                     libns:name ?name ;
163                     libns:library_id ?library_id ;
164                     libns:gel_cut ?gel_cut ;
165                     libns:made_by ?made_by
166         }"""
167         query = RDF.SPARQLQuery(body)
168         for r in query.execute(model):
169             self.assertEqual(fromTypedNode(r['library_id']), u'10981')
170             self.assertEqual(fromTypedNode(r['name']),
171                              u'Paired End Multiplexed Sp-BAC')
172             self.assertEqual(fromTypedNode(r['gel_cut']), 400)
173             self.assertEqual(fromTypedNode(r['made_by']), u'Igor')
174
175         state = validate_xhtml(content)
176         if state is not None:
177             self.assertTrue(state)
178
179         # validate a library page.
180         from htsworkflow.util.rdfhelp import add_default_schemas
181         from htsworkflow.util.rdfinfer import Infer
182         add_default_schemas(model)
183         inference = Infer(model)
184         errmsgs = list(inference.run_validation())
185         self.assertEqual(len(errmsgs), 0)
186
187     def test_library_index_rdfa(self):
188         from htsworkflow.util.rdfhelp import \
189              add_default_schemas, get_model, load_string_into_model, \
190              dump_model
191         from htsworkflow.util.rdfinfer import Infer
192
193         model = get_model()
194         add_default_schemas(model)
195         inference = Infer(model)
196
197         response = self.client.get('/library/')
198         self.assertEqual(response.status_code, 200)
199         load_string_into_model(model, 'rdfa', response.content)
200
201         errmsgs = list(inference.run_validation())
202         self.assertEqual(len(errmsgs), 0)
203
204         body =  """prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
205         prefix libns: <http://jumpgate.caltech.edu/wiki/LibraryOntology#>
206
207         select ?library ?library_id ?name ?species ?species_name
208         where {
209            ?library a libns:Library .
210            OPTIONAL { ?library libns:library_id ?library_id . }
211            OPTIONAL { ?library libns:species ?species .
212                       ?species libns:species_name ?species_name . }
213            OPTIONAL { ?library libns:name ?name . }
214         }"""
215         bindings = set(['library', 'library_id', 'name', 'species', 'species_name'])
216         query = RDF.SPARQLQuery(body)
217         count = 0
218         for r in query.execute(model):
219             count += 1
220             for name, value in r.items():
221                 self.assertTrue(name in bindings)
222                 self.assertTrue(value is not None)
223
224         self.assertEqual(count, len(Library.objects.filter(hidden=False)))
225
226         state = validate_xhtml(response.content)
227         if state is not None: self.assertTrue(state)
228
229
230 # The django test runner flushes the database between test suites not cases,
231 # so to be more compatible with running via nose we flush the database tables
232 # of interest before creating our sample data.
233 def create_db(obj):
234     obj.species_human = Species.objects.get(pk=8)
235     obj.experiment_rna_seq = ExperimentType.objects.get(pk=4)
236     obj.affiliation_alice = Affiliation.objects.get(pk=1)
237     obj.affiliation_bob = Affiliation.objects.get(pk=2)
238
239     Library.objects.all().delete()
240     obj.library_10001 = Library(
241         id = "10001",
242         library_name = 'C2C12 named poorly',
243         library_species = obj.species_human,
244         experiment_type = obj.experiment_rna_seq,
245         creation_date = datetime.datetime.now(),
246         made_for = 'scientist unit 2007',
247         made_by = 'microfludics system 7321',
248         stopping_point = '2A',
249         undiluted_concentration = '5.01',
250         hidden = False,
251     )
252     obj.library_10001.save()
253     obj.library_10002 = Library(
254         id = "10002",
255         library_name = 'Worm named poorly',
256         library_species = obj.species_human,
257         experiment_type = obj.experiment_rna_seq,
258         creation_date = datetime.datetime.now(),
259         made_for = 'scientist unit 2007',
260         made_by = 'microfludics system 7321',
261         stopping_point = '2A',
262         undiluted_concentration = '5.01',
263         hidden = False,
264     )
265     obj.library_10002.save()
266
267 try:
268     import RDF
269     HAVE_RDF = True
270
271     rdfNS = RDF.NS("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
272     xsdNS = RDF.NS("http://www.w3.org/2001/XMLSchema#")
273     libNS = RDF.NS("http://jumpgate.caltech.edu/wiki/LibraryOntology#")
274 except ImportError,e:
275     HAVE_RDF = False
276
277
278 class TestRDFaLibrary(TestCase):
279     fixtures = ['test_samples.json']
280
281     def test_parse_rdfa(self):
282         model = get_rdf_memory_model()
283         parser = RDF.Parser(name='rdfa')
284         url = '/library/10981/'
285         lib_response = self.client.get(url)
286         self.failIfEqual(len(lib_response.content), 0)
287
288         parser.parse_string_into_model(model,
289                                        lib_response.content,
290                                        'http://localhost'+url)
291         # http://jumpgate.caltech.edu/wiki/LibraryOntology#affiliation>
292         self.check_literal_object(model, ['Bob'], p=libNS['affiliation'])
293         self.check_literal_object(model, ['Multiplexed'], p=libNS['experiment_type'])
294         self.check_literal_object(model, ['400'], p=libNS['gel_cut'])
295         self.check_literal_object(model, ['Igor'], p=libNS['made_by'])
296         self.check_literal_object(model, ['Paired End Multiplexed Sp-BAC'], p=libNS['name'])
297         self.check_literal_object(model, ['Drosophila melanogaster'], p=libNS['species_name'])
298
299         self.check_uri_object(model,
300                               [u'http://localhost/lane/1193'],
301                               p=libNS['has_lane'])
302
303         fc_uri = RDF.Uri('http://localhost/flowcell/303TUAAXX/')
304         self.check_literal_object(model,
305                                   [u"303TUAAXX"],
306                                   s=fc_uri, p=libNS['flowcell_id'])
307
308     def check_literal_object(self, model, values, s=None, p=None, o=None):
309         statements = list(model.find_statements(
310             RDF.Statement(s,p,o)))
311         self.failUnlessEqual(len(statements), len(values),
312                         "Couln't find %s %s %s" % (s,p,o))
313         for s in statements:
314             self.failUnless(s.object.literal_value['string'] in values)
315
316
317     def check_uri_object(self, model, values, s=None, p=None, o=None):
318         statements = list(model.find_statements(
319             RDF.Statement(s,p,o)))
320         self.failUnlessEqual(len(statements), len(values),
321                         "Couln't find %s %s %s" % (s,p,o))
322         for s in statements:
323             self.failUnless(unicode(s.object.uri) in values)
324
325
326
327 def get_rdf_memory_model():
328     storage = RDF.MemoryStorage()
329     model = RDF.Model(storage)
330     return model