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