Debian Codegraph @

tests/typechecking_test.py

raw symbols SCIP
1 import inspect
2 import os
3 import pytest
4 import re
5 from typing import TYPE_CHECKING
6
7 import pysam
8 import pysam.samtools
9 import pysam.bcftools
10
11 from TestUtils import BAM_DATADIR, make_data_files
12
13 try:
14 import mypy.api
15 except ImportError:
16 pytest.skip('mypy API not available', allow_module_level=True)
17
18 PREAMBLE = """
19 import re
20 from typing import TYPE_CHECKING
21
22 import pysam
23 import pysam.samtools
24 import pysam.bcftools
25
26 def typecheck(check_locals = True): pass
27 """
28
29 MYPY_OPTIONS = ['--no-incremental', '--no-error-summary', '--follow-imports', 'silent']
30
31
32 def typecheck(check_locals: bool = True):
33 myframe = inspect.currentframe()
34 if not myframe: pytest.skip('current stack frame not available')
35 caller = myframe.f_back
36 if not caller: pytest.skip('caller stack frame not available')
37
38 code = inspect.getsource(caller)
39 stdout, stderr, status = mypy.api.run(MYPY_OPTIONS + ['--command', PREAMBLE + code])
40 assert status == 0, f'mypy failed:\n{stdout}{stderr}'
41
42 types = {}
43 for line in stdout.splitlines():
44 m = re.search(r'note: *(\w+): ([\w.]*)', line)
45 if m: types[m.group(1)] = m.group(2)
46
47 def _plain(s):
48 s = re.sub(r"<class '([^']*)'>", r'\1', s)
49 s = re.sub(r'builtins\.', '', s)
50 return s
51
52 if check_locals:
53 for var, vartype in types.items():
54 assert _plain(vartype) == _plain(repr(type(caller.f_locals[var]))), f'Incorrect type for {var!r}'
55
56 return types
57
58
59 def setUpModule():
60 make_data_files(BAM_DATADIR)
61
62
63 @pytest.fixture
64 def aln():
65 header = pysam.AlignmentHeader.from_references(['chr1', 'chr2'], [50000, 20000])
66 a = pysam.AlignedSegment(header)
67 a.query_name = 'read_one'
68 a.flag = pysam.FPAIRED | pysam.FREAD1
69 a.reference_id = 0
70 a.reference_start = 1000
71 a.mapping_quality = 20
72 a.next_reference_id = 1
73 a.next_reference_start = 5000
74 a.template_length = 0
75 a.cigartuples = ((pysam.CMATCH, 6), (pysam.CINS, 4), (pysam.CMATCH, 2))
76 a.query_sequence = 'ATGCATGCATGC'
77 a.query_qualities = pysam.qualitystring_to_array('abcdefghijkl')
78 return a
79
80
81 @pytest.fixture
82 def sam_fname():
83 return os.path.join(BAM_DATADIR, 'ex3.sam')
84
85
86 @pytest.fixture
87 def bam_fname():
88 return os.path.join(BAM_DATADIR, 'ex1.bam')
89
90
91 def test_AlignedSegment_is_mapped(aln: pysam.AlignedSegment) -> None:
92 rmap = aln.is_mapped
93 mmap = aln.mate_is_mapped
94 rfwd = aln.is_forward
95 mfwd = aln.mate_is_forward
96
97 if TYPE_CHECKING: reveal_locals()
98 types = typecheck()
99
100
101 def test_AlignmentHeader_get_reference_length(sam_fname: str) -> None:
102 inf = pysam.AlignmentFile(sam_fname)
103 n1 = inf.get_reference_length('chr1')
104 hdr = inf.header
105 n2 = hdr.get_reference_length('chr1')
106
107 if TYPE_CHECKING: reveal_locals()
108 types = typecheck()
109
110
111 def test_pileup_iterator_column(bam_fname: str) -> None:
112 inf = pysam.AlignmentFile(bam_fname)
113 pu = inf.pileup('chr1')
114 for p in pu:
115 pid = p.reference_id
116 ppos = p.reference_pos
117
118 if TYPE_CHECKING: reveal_locals()
119 types = typecheck(check_locals=False)
120 assert re.search(r'\.IteratorColumn(|All|AllRefs|Region)$', types['pu'])
121 assert types['p'].endswith('PileupColumn')
122 assert types['pid'] == 'builtins.int'
123 assert types['ppos'] == 'builtins.int'
124
125
126 def test_samtools_subcommands() -> None:
127 p1_samtools_faidx = pysam.samtools.faidx
128 p2_faidx = pysam.faidx
129 p3_view = pysam.view
130 p4_bcftools_view = pysam.bcftools.view
131
132 if TYPE_CHECKING: reveal_locals()
133 types = typecheck()
134 for var, vartype in types.items():
135 assert vartype.endswith('PysamDispatcher'), f'{var!r} is not a dispatcher'