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