1 from __future__ import absolute_import, print_function
7 from django.test import TestCase, RequestFactory
8 from django.conf import settings
10 from .models import Affiliation, ExperimentType, Species, Library
11 from .views import library_dict, library_json, library
12 from .samples_factory import *
14 from htsworkflow.auth import apidata
15 from htsworkflow.util.conversion import unicode_or_none
16 from htsworkflow.util.ethelp import validate_xhtml
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')
25 def testAddingOneAffiliation(self):
26 affiliation = AffiliationFactory.create(name='Alice')
27 library = LibraryFactory()
28 library.affiliations.add(affiliation)
30 self.assertEqual(len(library.affiliations.all()), 1)
31 self.assertEqual(library.affiliation(), 'Alice (contact name)')
33 def testMultipleAffiliations(self):
34 alice = AffiliationFactory.create(name='Alice')
35 bob = AffiliationFactory.create(name='Bob')
37 library = LibraryFactory()
38 library.affiliations.add(alice, bob)
40 self.assertEqual(len(library.affiliations.all()), 2)
41 self.assertEqual(library.affiliation(),
42 'Alice (contact name), Bob (contact name)')
45 class SampleWebTestCase(TestCase):
47 Test returning data from our database in rest like ways.
48 (like returning json objects)
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)['result']
57 for d in [lib_dict, lib_json]:
58 # amplified_from_sample is a link to the library table,
59 # I want to use the "id" for the data lookups not
60 # the embedded primary key.
61 # It gets slightly confusing on how to implement sending the right id
62 # since amplified_from_sample can be null
63 #self.failUnlessEqual(d['amplified_from_sample'], lib.amplified_from_sample)
64 self.failUnlessEqual(d['antibody_id'], library.antibody_id)
65 self.failUnlessEqual(d['cell_line_id'], library.cell_line_id)
66 self.failUnlessEqual(d['cell_line'], unicode_or_none(library.cell_line))
67 self.failUnlessEqual(d['experiment_type'], library.experiment_type.name)
68 self.failUnlessEqual(d['experiment_type_id'], library.experiment_type_id)
69 self.failUnlessEqual(d['gel_cut_size'], library.gel_cut_size)
70 self.failUnlessEqual(d['hidden'], library.hidden)
71 self.failUnlessEqual(d['id'], library.id)
72 self.failUnlessEqual(d['insert_size'], library.insert_size)
73 self.failUnlessEqual(d['library_name'], library.library_name)
74 self.failUnlessEqual(d['library_species'], library.library_species.scientific_name)
75 self.failUnlessEqual(d['library_species_id'], library.library_species_id)
76 self.failUnlessEqual(d['library_type_id'], library.library_type_id)
77 self.assertTrue(d['library_type'].startswith('library type'))
78 self.failUnlessEqual(d['made_for'], library.made_for)
79 self.failUnlessEqual(d['made_by'], library.made_by)
80 self.failUnlessEqual(d['notes'], library.notes)
81 self.failUnlessEqual(d['replicate'], library.replicate)
82 self.failUnlessEqual(d['stopping_point'], library.stopping_point)
83 self.failUnlessEqual(d['successful_pM'], library.successful_pM)
84 self.failUnlessEqual(d['undiluted_concentration'],
85 unicode(library.undiluted_concentration))
90 if library.id == '10981':
91 # test a case where there is no known status
92 lane_set = {u'status': u'Unknown',
97 u'flowcell': u'303TUAAXX',
99 self.failUnlessEqual(len(d['lane_set']), 1)
100 self.failUnlessEqual(d['lane_set'][0], lane_set)
101 elif library.id == '11016':
102 # test a case where there is a status
103 lane_set = {u'status': 'Good',
108 u'flowcell': u'303TUAAXX',
110 self.failUnlessEqual(len(d['lane_set']), 1)
111 self.failUnlessEqual(d['lane_set'][0], lane_set)
114 def test_invalid_library_json(self):
116 Make sure we get a 404 if we request an invalid library id
118 response = self.client.get('/samples/library/nottheone/json', apidata)
119 self.failUnlessEqual(response.status_code, 404)
122 def test_invalid_library(self):
123 response = self.client.get('/library/nottheone/')
124 self.failUnlessEqual(response.status_code, 404)
127 def test_library_no_key(self):
129 Make sure we get a 403 if we're not logged in
131 library = LibraryFactory.create()
133 url = '/samples/library/{}/json'.format(library.id)
134 response = self.client.get(url, apidata)
135 self.failUnlessEqual(response.status_code, 200)
136 response = self.client.get(url)
137 self.failUnlessEqual(response.status_code, 403)
139 def test_library_rdf(self):
140 library = LibraryFactory.create()
143 from htsworkflow.util.rdfhelp import get_model, \
146 load_string_into_model, \
151 response = self.client.get(library.get_absolute_url())
152 self.assertEqual(response.status_code, 200)
153 content = response.content
154 load_string_into_model(model, 'rdfa', content)
156 body = """prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
157 prefix libns: <http://jumpgate.caltech.edu/wiki/LibraryOntology#>
159 select ?library ?name ?library_id ?gel_cut ?made_by
161 ?library a libns:library ;
163 libns:library_id ?library_id ;
164 libns:gel_cut ?gel_cut ;
165 libns:made_by ?made_by
167 query = RDF.SPARQLQuery(body)
168 for r in query.execute(model):
169 self.assertEqual(fromTypedNode(r['library_id']),
171 self.assertEqual(fromTypedNode(r['name']),
173 self.assertEqual(fromTypedNode(r['gel_cut']),
175 self.assertEqual(fromTypedNode(r['made_by']),
178 state = validate_xhtml(content)
179 if state is not None:
180 self.assertTrue(state)
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)
190 def test_library_index_rdfa(self):
191 from htsworkflow.util.rdfhelp import \
192 add_default_schemas, get_model, load_string_into_model, \
194 from htsworkflow.util.rdfinfer import Infer
197 add_default_schemas(model)
198 inference = Infer(model)
200 response = self.client.get('/library/')
201 self.assertEqual(response.status_code, 200)
202 load_string_into_model(model, 'rdfa', response.content)
204 errmsgs = list(inference.run_validation())
205 self.assertEqual(len(errmsgs), 0)
207 body = """prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
208 prefix libns: <http://jumpgate.caltech.edu/wiki/LibraryOntology#>
210 select ?library ?library_id ?name ?species ?species_name
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 . }
218 bindings = set(['library', 'library_id', 'name', 'species', 'species_name'])
219 query = RDF.SPARQLQuery(body)
221 for r in query.execute(model):
223 for name, value in r.items():
224 self.assertTrue(name in bindings)
225 self.assertTrue(value is not None)
227 self.assertEqual(count, len(Library.objects.filter(hidden=False)))
229 state = validate_xhtml(response.content)
230 if state is not None: self.assertTrue(state)
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.
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)
242 Library.objects.all().delete()
243 obj.library_10001 = Library(
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',
255 obj.library_10001.save()
256 obj.library_10002 = Library(
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',
268 obj.library_10002.save()
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#")
278 from htsworkflow.util.rdfhelp import dump_model
279 except ImportError,e:
283 class TestRDFaLibrary(TestCase):
286 self.request = RequestFactory()
288 def test_parse_rdfa(self):
290 model = get_rdf_memory_model()
291 parser = RDF.Parser(name='rdfa')
293 bob = AffiliationFactory.create(name='Bob')
295 lib_object = LibraryFactory()
296 lib_object.affiliations.add(bob)
297 url = '/library/{}/'.format(lib_object.id)
298 ## request = self.request.get(url)
299 ## lib_response = library(request)
300 lib_response = self.client.get(url)
301 with open('/tmp/body.html', 'w') as outstream:
302 outstream.write(lib_response.content)
303 self.failIfEqual(len(lib_response.content), 0)
305 parser.parse_string_into_model(model,
306 lib_response.content,
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'],
320 self.check_literal_object(model,
321 [lib_object.library_name],
323 self.check_literal_object(model,
324 [lib_object.library_species.scientific_name],
325 p=libNS['species_name'])
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))
334 self.failUnless(s.object.literal_value['string'] in values)
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))
343 self.failUnless(unicode(s.object.uri) in values)
347 def get_rdf_memory_model():
348 storage = RDF.MemoryStorage()
349 model = RDF.Model(storage)
353 from unittest import TestSuite, defaultTestLoader
355 suite.addTests(defaultTestLoader.loadTestsFromTestCase(LibraryTestCase))
356 suite.addTests(defaultTestLoader.loadTestsFromTestCase(SampleWebTestCase))
357 suite.addTests(defaultTestLoader.loadTestsFromTestCase(TestRDFaLibrary))
360 if __name__ == "__main__":
361 from unittest import main
362 main(defaultTest="suite")