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