770d90a8e8925c81c3e77465bfb750fecf2527f3
[htsworkflow.git] / htsworkflow / frontend / samples / tests.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
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
56         for lib in Library.objects.all():
57             lib_dict = library_dict(lib.id)
58             url = '/samples/library/%s/json' % (lib.id,)
59             lib_response = self.client.get(url, apidata)
60             self.failUnlessEqual(lib_response.status_code, 200)
61             lib_json = json.loads(lib_response.content)
62
63             for d in [lib_dict, lib_json]:
64                 # amplified_from_sample is a link to the library table,
65                 # I want to use the "id" for the data lookups not
66                 # the embedded primary key.
67                 # It gets slightly confusing on how to implement sending the right id
68                 # since amplified_from_sample can be null
69                 #self.failUnlessEqual(d['amplified_from_sample'], lib.amplified_from_sample)
70                 self.failUnlessEqual(d['antibody_id'], lib.antibody_id)
71                 self.failUnlessEqual(d['cell_line_id'], lib.cell_line_id)
72                 self.failUnlessEqual(d['cell_line'], unicode_or_none(lib.cell_line))
73                 self.failUnlessEqual(d['experiment_type'], lib.experiment_type.name)
74                 self.failUnlessEqual(d['experiment_type_id'], lib.experiment_type_id)
75                 self.failUnlessEqual(d['gel_cut_size'], lib.gel_cut_size)
76                 self.failUnlessEqual(d['hidden'], lib.hidden)
77                 self.failUnlessEqual(d['id'], lib.id)
78                 self.failUnlessEqual(d['insert_size'], lib.insert_size)
79                 self.failUnlessEqual(d['library_name'], lib.library_name)
80                 self.failUnlessEqual(d['library_species'], lib.library_species.scientific_name)
81                 self.failUnlessEqual(d['library_species_id'], lib.library_species_id)
82                 self.failUnlessEqual(d['library_type_id'], lib.library_type_id)
83                 if lib.library_type_id is not None:
84                     self.failUnlessEqual(d['library_type'], lib.library_type.name)
85                 else:
86                     self.failUnlessEqual(d['library_type'], None)
87                     self.failUnlessEqual(d['made_for'], lib.made_for)
88                     self.failUnlessEqual(d['made_by'], lib.made_by)
89                     self.failUnlessEqual(d['notes'], lib.notes)
90                     self.failUnlessEqual(d['replicate'], lib.replicate)
91                     self.failUnlessEqual(d['stopping_point'], lib.stopping_point)
92                     self.failUnlessEqual(d['successful_pM'], lib.successful_pM)
93                     self.failUnlessEqual(d['undiluted_concentration'],
94                                          unicode(lib.undiluted_concentration))
95                 # some specific tests
96                 if lib.id == '10981':
97                     # test a case where there is no known status
98                     lane_set = {u'status': u'Unknown',
99                                 u'paired_end': True,
100                                 u'read_length': 75,
101                                 u'lane_number': 1,
102                                 u'lane_id': 1193,
103                                 u'flowcell': u'303TUAAXX',
104                                 u'status_code': None}
105                     self.failUnlessEqual(len(d['lane_set']), 1)
106                     self.failUnlessEqual(d['lane_set'][0], lane_set)
107                 elif lib.id == '11016':
108                     # test a case where there is a status
109                     lane_set = {u'status': 'Good',
110                                 u'paired_end': True,
111                                 u'read_length': 75,
112                                 u'lane_number': 5,
113                                 u'lane_id': 1197,
114                                 u'flowcell': u'303TUAAXX',
115                                 u'status_code': 2}
116                     self.failUnlessEqual(len(d['lane_set']), 1)
117                     self.failUnlessEqual(d['lane_set'][0], lane_set)
118
119
120     def test_invalid_library_json(self):
121         """
122         Make sure we get a 404 if we request an invalid library id
123         """
124         response = self.client.get('/samples/library/nottheone/json', apidata)
125         self.failUnlessEqual(response.status_code, 404)
126
127
128     def test_invalid_library(self):
129         response = self.client.get('/library/nottheone/')
130         self.failUnlessEqual(response.status_code, 404)
131
132
133     def test_library_no_key(self):
134         """
135         Make sure we get a 302 if we're not logged in
136         """
137         response = self.client.get('/samples/library/10981/json')
138         self.failUnlessEqual(response.status_code, 403)
139         response = self.client.get('/samples/library/10981/json', apidata)
140         self.failUnlessEqual(response.status_code, 200)
141
142     def test_library_rdf(self):
143         import RDF
144         from htsworkflow.util.rdfhelp import get_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         load_string_into_model(model, 'rdfa', response.content)
154
155         body = """prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
156         prefix libns: <http://jumpgate.caltech.edu/wiki/LibraryOntology#>
157
158         select ?library ?name ?library_id ?gel_cut ?made_by
159         where {
160            ?library a libns:library ;
161                     libns:name ?name ;
162                     libns:library_id ?library_id ;
163                     libns:gel_cut ?gel_cut ;
164                     libns:made_by ?made_by
165         }"""
166         query = RDF.SPARQLQuery(body)
167         for r in query.execute(model):
168             self.assertEqual(fromTypedNode(r['library_id']), u'10981')
169             self.assertEqual(fromTypedNode(r['name']),
170                              u'Paired End Multiplexed Sp-BAC')
171             self.assertEqual(fromTypedNode(r['gel_cut']), 400)
172             self.assertEqual(fromTypedNode(r['made_by']), u'Igor')
173
174 # The django test runner flushes the database between test suites not cases,
175 # so to be more compatible with running via nose we flush the database tables
176 # of interest before creating our sample data.
177 def create_db(obj):
178     obj.species_human = Species.objects.get(pk=8)
179     obj.experiment_rna_seq = ExperimentType.objects.get(pk=4)
180     obj.affiliation_alice = Affiliation.objects.get(pk=1)
181     obj.affiliation_bob = Affiliation.objects.get(pk=2)
182
183     Library.objects.all().delete()
184     obj.library_10001 = Library(
185         id = "10001",
186         library_name = 'C2C12 named poorly',
187         library_species = obj.species_human,
188         experiment_type = obj.experiment_rna_seq,
189         creation_date = datetime.datetime.now(),
190         made_for = 'scientist unit 2007',
191         made_by = 'microfludics system 7321',
192         stopping_point = '2A',
193         undiluted_concentration = '5.01',
194         hidden = False,
195     )
196     obj.library_10001.save()
197     obj.library_10002 = Library(
198         id = "10002",
199         library_name = 'Worm named poorly',
200         library_species = obj.species_human,
201         experiment_type = obj.experiment_rna_seq,
202         creation_date = datetime.datetime.now(),
203         made_for = 'scientist unit 2007',
204         made_by = 'microfludics system 7321',
205         stopping_point = '2A',
206         undiluted_concentration = '5.01',
207         hidden = False,
208     )
209     obj.library_10002.save()
210
211 try:
212     import RDF
213     HAVE_RDF = True
214
215     rdfNS = RDF.NS("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
216     xsdNS = RDF.NS("http://www.w3.org/2001/XMLSchema#")
217     libNS = RDF.NS("http://jumpgate.caltech.edu/wiki/LibraryOntology#")
218 except ImportError,e:
219     HAVE_RDF = False
220
221
222 class TestRDFaLibrary(TestCase):
223     fixtures = ['test_samples.json']
224
225     def test_parse_rdfa(self):
226         model = get_rdf_memory_model()
227         parser = RDF.Parser(name='rdfa')
228         url = '/library/10981/'
229         lib_response = self.client.get(url)
230         self.failIfEqual(len(lib_response.content), 0)
231
232         parser.parse_string_into_model(model,
233                                        lib_response.content,
234                                        'http://localhost'+url)
235         # http://jumpgate.caltech.edu/wiki/LibraryOntology#affiliation>
236         self.check_literal_object(model, ['Bob'], p=libNS['affiliation'])
237         self.check_literal_object(model, ['Multiplexed'], p=libNS['experiment_type'])
238         self.check_literal_object(model, ['400'], p=libNS['gel_cut'])
239         self.check_literal_object(model, ['Igor'], p=libNS['made_by'])
240         self.check_literal_object(model, ['Paired End Multiplexed Sp-BAC'], p=libNS['name'])
241         self.check_literal_object(model, ['Drosophila melanogaster'], p=libNS['species'])
242
243         self.check_uri_object(model,
244                               [u'http://localhost/lane/1193'],
245                               p=libNS['has_lane'])
246
247         fc_uri = RDF.Uri('http://localhost/flowcell/303TUAAXX/')
248         self.check_literal_object(model,
249                                   [u"303TUAAXX"],
250                                   s=fc_uri, p=libNS['flowcell_id'])
251
252     def check_literal_object(self, model, values, s=None, p=None, o=None):
253         statements = list(model.find_statements(
254             RDF.Statement(s,p,o)))
255         self.failUnlessEqual(len(statements), len(values),
256                         "Couln't find %s %s %s" % (s,p,o))
257         for s in statements:
258             self.failUnless(s.object.literal_value['string'] in values)
259
260
261     def check_uri_object(self, model, values, s=None, p=None, o=None):
262         statements = list(model.find_statements(
263             RDF.Statement(s,p,o)))
264         self.failUnlessEqual(len(statements), len(values),
265                         "Couln't find %s %s %s" % (s,p,o))
266         for s in statements:
267             self.failUnless(unicode(s.object.uri) in values)
268
269
270
271 def get_rdf_memory_model():
272     storage = RDF.MemoryStorage()
273     model = RDF.Model(storage)
274     return model
275