Debian Codegraph @

tests/test_models_report.py

raw symbols SCIP
1 import json
2 import logging
3 import os.path
4 import re
5 from pprint import pformat
6
7 import avro
8 import pytest
9
10 from base_utils import get_data_file_from_subdir, DATA_DIR
11 from pbcommand.pb_io import load_report_from_json, load_report_from, load_report_spec_from_json
12 from pbcommand.models.report import (Report, Attribute, PlotGroup, Plot, Table,
13 Column, PbReportError, format_metric)
14 from pbcommand.schemas import validate_report
15
16 _SERIALIZED_JSON_DIR = 'example-reports'
17
18
19 log = logging.getLogger(__name__)
20
21
22 def _to_report(name):
23 file_name = get_data_file_from_subdir(_SERIALIZED_JSON_DIR, name)
24 log.info("loading json report from {f}".format(f=file_name))
25 r = load_report_from_json(file_name)
26 return r
27
28
29 class TestReportModel:
30
31 def test_from_simple_dict(self):
32 r = Report.from_simple_dict("pbcommand_test", {"n_reads": 50},
33 "pbcommand")
34 json_dict = json.loads(r.to_json())
35 assert json_dict['attributes'] == [
36 {
37 "id": "pbcommand_test.pbcommand_n_reads",
38 "name": "n_reads",
39 "value": 50
40 },
41 ]
42
43 def test_report_null_ns(self):
44 """Can't create a report without a namespace."""
45 with pytest.raises(PbReportError):
46 r = Report(None)
47
48 def test_report_empty_ns(self):
49 """Can't create a report with an empty namespace."""
50 with pytest.raises(PbReportError):
51 r = Report("")
52
53 def test_duplicate_ids(self):
54 """Can't add elements with the same id."""
55 with pytest.raises(PbReportError):
56 r = Report('redfang')
57 r.add_attribute(Attribute('a', 'b'))
58 r.add_attribute(Attribute('a', 'c'))
59
60 def test_illegal_id(self):
61 """Ids must be alphanumberic with underscores"""
62 with pytest.raises(PbReportError):
63 r = Report('redfang')
64 r.add_attribute(Attribute('a b', 'b'))
65 r.add_attribute(Attribute('a', 'c'))
66
67 def test_empty_id(self):
68 with pytest.raises(PbReportError):
69 r = Report('')
70
71 def test_uppercase_id(self):
72 with pytest.raises(PbReportError):
73 r = Report('A')
74
75 def test_to_dict(self):
76 """
77 The id of report sub elements is prepended with the id of the parent
78 element when to_dict is called.
79 """
80 r = Report('redfang')
81 a = Attribute('a', 'b')
82 a2 = Attribute('a2', 'b2')
83 r.add_attribute(a)
84 r.add_attribute(a2)
85
86 pg = PlotGroup('pgid')
87 pg.add_plot(Plot('pid', 'anImg'))
88 pg.add_plot(Plot('pid2', 'anImg2'))
89 r.add_plotgroup(pg)
90
91 t = Table('tabid')
92 t.add_column(Column('c1'))
93 r.add_table(t)
94
95 d = r.to_dict()
96
97 log.debug("\n" + pformat(d))
98
99 r2 = load_report_from(d)
100 assert r.uuid == r2.uuid
101
102 assert 'redfang' == d['id']
103 assert 'redfang.a' == d['attributes'][0]['id']
104 assert 'redfang.a2' == d['attributes'][1]['id']
105 assert 'redfang.pgid' == d['plotGroups'][0]['id']
106 assert 'redfang.pgid.pid' == d['plotGroups'][0]['plots'][0]['id']
107 assert 'redfang.pgid.pid2' == d['plotGroups'][0]['plots'][1]['id']
108
109 assert 'redfang.tabid' == d['tables'][0]['id']
110 assert 'redfang.tabid.c1' == d['tables'][0]['columns'][0]['id']
111
112 def test_version_and_changelist(self):
113 r = Report('example')
114 d = r.to_dict()
115 log.info("\n" + pformat(d))
116
117 fields = ('version', 'uuid', 'plotGroups', 'tables', 'dataset_uuids')
118 for field in fields:
119 assert field in d
120
121 def test_load_from_file(self):
122 rpt_id = 'test_report'
123 name = "test_report.json"
124 path = get_data_file_from_subdir(_SERIALIZED_JSON_DIR, name)
125
126 r = load_report_from(path)
127 assert r.id == rpt_id
128
129 r2 = load_report_from(r.to_dict())
130 assert r2.id == rpt_id
131
132 def test_to_dict_multi(self):
133 """
134 Multiple complex elements.
135 The id of report sub elements is prepended with the id of the parent
136 element when to_dict is called.
137 """
138 tags = ["alpha", "beta", "gamma"]
139 r = Report('redfang', tags=tags)
140 a = Attribute('a', 'b')
141 a2 = Attribute('a2', 'b2')
142 r.add_attribute(a)
143 r.add_attribute(a2)
144
145 pg = PlotGroup('pgid')
146 pg.add_plot(Plot('pid', 'anImg'))
147 pg.add_plot(Plot('pid2', 'anImg2'))
148 r.add_plotgroup(pg)
149
150 pg = PlotGroup('pgid2')
151 pg.add_plot(Plot('pid2', 'anImg2'))
152 pg.add_plot(Plot('pid22', 'anImg22'))
153 r.add_plotgroup(pg)
154
155 t = Table('tabid')
156 t.add_column(Column('c1'))
157 r.add_table(t)
158
159 t = Table('tabid2')
160 t.add_column(Column('c2'))
161 r.add_table(t)
162
163 d = r.to_dict()
164
165 log.debug(str(d))
166
167 assert 'redfang' == d['id']
168 assert 'redfang.a' == d['attributes'][0]['id']
169 assert 'redfang.a2' == d['attributes'][1]['id']
170
171 assert 'redfang.pgid' == d['plotGroups'][0]['id']
172 assert 'redfang.pgid.pid' == d['plotGroups'][0]['plots'][0]['id']
173 assert 'redfang.pgid.pid2' == d['plotGroups'][0]['plots'][1]['id']
174
175 assert 'redfang.pgid2' == d['plotGroups'][1]['id']
176 assert 'redfang.pgid2.pid2' == d['plotGroups'][1]['plots'][0]['id']
177 assert 'redfang.pgid2.pid22' == d['plotGroups'][1]['plots'][1]['id']
178
179 assert 'redfang.tabid' == d['tables'][0]['id']
180 assert 'redfang.tabid.c1' == d['tables'][0]['columns'][0]['id']
181
182 assert 'redfang.tabid2' == d['tables'][1]['id']
183 assert 'redfang.tabid2.c2' == d['tables'][1]['columns'][0]['id']
184
185 assert list(sorted(d['tags'])) == list(sorted(tags))
186
187 loaded_report = load_report_from(d)
188 assert list(sorted(loaded_report.tags)) == list(sorted(tags))
189
190 log.info(repr(r))
191 assert repr(r) is not None
192
193 def test_get_attribute_by_id(self):
194 a = Attribute('a', 'b')
195 a2 = Attribute('b', 'b2')
196 attributes = [a, a2]
197 r = Report('redfang', attributes=attributes)
198
199 a1 = r.get_attribute_by_id('a')
200
201 assert a == a1
202
203 def test_get_attribute_by_id_with_bad_id(self):
204 a1 = Attribute('a', 'b')
205 a2 = Attribute('b', 'b2')
206 attributes = [a1, a2]
207 report = Report('redfang', attributes=attributes)
208
209 a = report.get_attribute_by_id('a')
210 assert a.value == 'b'
211
212 bad_a = report.get_attribute_by_id('id_that_does_not_exist')
213 assert bad_a is None
214
215 def test_get_table_by_id(self):
216 r = Report('redfang')
217 t1 = Table('tabid1')
218 t1.add_column(Column('c1'))
219 r.add_table(t1)
220
221 t = r.get_table_by_id('tabid1')
222 assert t == t1
223 columns_d = t.to_columns_d()
224 assert len(columns_d) == 0
225
226 def test_get_table_by_id_with_bad_id(self):
227 r = Report('redfang')
228 t1 = Table('tabid1')
229 t1.add_column(Column('c1'))
230 r.add_table(t1)
231
232 bad_t = r.get_table_by_id('id_that_does_not_exist')
233 assert bad_t is None
234
235 def test_get_column_by_id(self):
236 r = Report('redfang')
237 t1 = Table('tabid1')
238 c1 = Column('c1')
239 t1.add_column(c1)
240 r.add_table(t1)
241
242 c = r.get_table_by_id('tabid1').get_column_by_id('c1')
243 assert c == c1
244
245 def test_get_column_by_id_with_bad_id(self):
246 r = Report('redfang')
247 t1 = Table('tabid1')
248 c1 = Column('c1')
249 t1.add_column(c1)
250 r.add_table(t1)
251
252 bad_c = r.get_table_by_id('tabid1').get_column_by_id(
253 'id_that_does_not_exist')
254 assert bad_c is None
255
256 def test_get_plotgroup_by_id(self):
257 r = Report('redfang')
258 pg1 = PlotGroup('pgid1')
259 pg1.add_plot(Plot('pid1', 'anImg'))
260 r.add_plotgroup(pg1)
261
262 pg = r.get_plotgroup_by_id('pgid1')
263 assert pg == pg1
264
265 def test_get_plotgroup_by_id_with_bad_id(self):
266 r = Report('redfang')
267 pg1 = PlotGroup('pgid1')
268 pg1.add_plot(Plot('pid1', 'anImg'))
269 r.add_plotgroup(pg1)
270
271 bad_pg = r.get_plotgroup_by_id('id_that_does_not_exist')
272 assert bad_pg is None
273
274 def test_get_plot_by_id(self):
275 r = Report('redfang')
276 pg1 = PlotGroup('pgid1')
277 p1 = Plot('pid1', 'anImg')
278 pg1.add_plot(p1)
279 r.add_plotgroup(pg1)
280
281 p = r.get_plotgroup_by_id('pgid1').get_plot_by_id('pid1')
282 assert p == p1
283
284 def test_get_plot_by_id_with_bad_id(self):
285 r = Report('redfang')
286 pg1 = PlotGroup('pgid1')
287 p1 = Plot('pid1', 'anImg')
288 pg1.add_plot(p1)
289 r.add_plotgroup(pg1)
290
291 bad_p = r.get_plotgroup_by_id(
292 'pgid1').get_plot_by_id('id_that_does_not_exist')
293 assert bad_p is None
294
295 def test_merge(self):
296 EXPECTED_VALUES = {
297 "n_reads": 300,
298 "n_zmws": 60,
299 "sample": "Person1,Person2"
300 }
301 NAMES = {
302 "n_reads": "Number of reads",
303 "n_zmws": "Number of ZMWs",
304 "sample": "Sample"
305 }
306 chunks = [
307 Report("pbcommand_test",
308 attributes=[
309 Attribute(id_="n_reads", value=50,
310 name="Number of reads"),
311 Attribute(id_="n_zmws", value=10, name="Number of ZMWs"),
312 Attribute(id_="sample", value="Person1", name="Sample")],
313 dataset_uuids=["12345"]),
314 Report("pbcommand_test",
315 attributes=[
316 Attribute(id_="n_reads", value=250,
317 name="Number of reads"),
318 Attribute(id_="n_zmws", value=50, name="Number of ZMWs"),
319 Attribute(id_="sample", value="Person2", name="Sample")]),
320 ]
321 r = Report.merge(chunks)
322 assert [a.id for a in r.attributes] == ["n_reads", "n_zmws", "sample"]
323 assert r._dataset_uuids == ["12345"]
324 for attr in r.attributes:
325 assert attr.value == EXPECTED_VALUES[attr.id]
326 assert attr.name == NAMES[attr.id]
327 for table in r.tables:
328 for column in table.columns:
329 assert column.header == NAMES[column.id]
330
331 def test_merge_tables(self):
332 names = ['laa_report1.json', 'laa_report2.json']
333 r = Report.merge([_to_report(names[0]), _to_report(names[1])])
334 table = r.tables[0]
335 assert len(table.columns) == 7
336 assert [col.header for col in table.columns] == [
337 'BarcodeName', 'FastaName', 'CoarseCluster', 'Phase',
338 'TotalCoverage', 'SequenceLength', 'PredictedAccuracy']
339 for col in table.columns:
340 assert len(col.values) == 4
341 if col.header == 'BarcodeName':
342 assert col.values == [
343 'Barcode1', 'Barcode2', 'Barcode4', 'Barcode3']
344 elif col.header == 'FastaName':
345 assert col.values == [
346 'BarcodeFasta1', 'BarcodeFasta2', 'BarcodeFasta4',
347 'BarcodeFasta3']
348 else:
349 assert col.values == [1, 2, 4, 3]
350
351 column_list_d = table.to_columns_d()
352 assert len(column_list_d) == 4
353
354
355 class TestMalformedReport:
356
357 def test_bad_01(self):
358 r = Report("stuff", uuid=1234)
359 d = r.to_dict()
360
361 def fx():
362 # when the Report validation is enabled, use to_json
363 # r.to_json()
364 return validate_report(d)
365
366 with pytest.raises(IOError):
367 fx()
368
369
370 class TestReportSchemaVersion100:
371
372 name = "example_version_1_0_0.json"
373
374 def test_sanity(self):
375 r = _to_report(self.name)
376 assert isinstance(r, Report)
377
378
379 class TestRepotSchemaVersion100WithPlots(TestReportSchemaVersion100):
380 name = "example_with_plot.json"
381
382
383 class TestReportSpec:
384
385 def setup_method(self, method):
386 self.spec = load_report_spec_from_json(
387 os.path.join(DATA_DIR, "report-specs", "report_spec.json"))
388
389 def test_report_validation(self):
390 rpt = _to_report("test_report.json")
391 r = self.spec.validate_report(rpt)
392 assert isinstance(r, Report)
393 rpt.attributes.append(Attribute("attribute5", value=12345))
394 def error_len(e): return len(str(e).split("\n"))
395 try:
396 self.spec.validate_report(rpt)
397 except ValueError as e:
398 assert error_len(e) == 2
399 else:
400 self.fail("Expected exception")
401 assert not self.spec.is_valid_report(rpt)
402 rpt.attributes[0] = Attribute("attribute1", value=1.2345)
403 try:
404 self.spec.validate_report(rpt)
405 except ValueError as e:
406 print(e)
407 assert error_len(e) == 3
408 else:
409 self.fail("Expected exception")
410 assert not self.spec.is_valid_report(rpt)
411
412 def test_format_metric(self):
413 s = format_metric("{:,d}", 123456789)
414 assert s == "123,456,789"
415 s = format_metric("{:.4g}", 1.2345678)
416 assert s == "1.235"
417 s = format_metric("{M:.2f} Mb", 123456789)
418 assert s == "123.46 Mb"
419 s = format_metric("{p:.5g}%", 0.987654321)
420 assert s == "98.765%"
421 s = format_metric("{p:g}", 0.000001)
422 assert s == "0.0001%"
423 s = format_metric("{:,.3f}", 1000000.2345678)
424 assert s == "1,000,000.235"
425
426 def test_apply_view(self):
427 rpt = _to_report("test_report2.json")
428 rpt = self.spec.apply_view(rpt)
429 assert all([a.name is not None for a in rpt.attributes])
430 assert all([t.title is not None for t in rpt.tables])
431 assert all([c.header is not None for c in rpt.tables[0].columns])
432 assert all([pg.title is not None for pg in rpt.plotGroups])
433 assert all([p.title is not None for p in rpt.plotGroups[0].plots])