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