Debian Codegraph @

tests/TestUtils.py

raw symbols SCIP
1 import os
2 import glob
3 import gzip
4 import contextlib
5 import inspect
6 import subprocess
7 import tempfile
8 import time
9
10 import pysam
11
12 WORKDIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
13 "pysam_test_work"))
14
15 BAM_DATADIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
16 "pysam_data"))
17
18 TABIX_DATADIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
19 "tabix_data"))
20
21 CBCF_DATADIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
22 "cbcf_data"))
23
24 LINKDIR = os.path.abspath(os.path.join(
25 os.path.dirname(__file__), "..", "linker_tests"))
26
27
28 TESTS_TEMPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "tmp"))
29
30
31 from itertools import zip_longest
32 from urllib.request import urlopen
33
34
35 def force_str(s):
36 try:
37 return s.decode('ascii')
38 except AttributeError:
39 return s
40
41 def force_bytes(s):
42 try:
43 return s.encode('ascii')
44 except AttributeError:
45 return s
46
47
48 def openfile(fn):
49 if fn.endswith(".gz"):
50 try:
51 return gzip.open(fn, "rt", encoding="utf-8")
52 except TypeError:
53 return gzip.open(fn, "r")
54 else:
55 return open(fn)
56
57
58 def checkBinaryEqual(filename1, filename2):
59 '''return true if the two files are binary equal.
60 '''
61 if os.path.getsize(filename1) != os.path.getsize(filename2):
62 return False
63
64 infile1 = open(filename1, "rb")
65 infile2 = open(filename2, "rb")
66
67 def chariter(infile):
68 while 1:
69 c = infile.read(1)
70 if c == b"":
71 break
72 yield c
73
74 found = False
75 for c1, c2 in zip_longest(chariter(infile1), chariter(infile2)):
76 if c1 != c2:
77 break
78 else:
79 found = True
80
81 infile1.close()
82 infile2.close()
83 return found
84
85
86 def checkGZBinaryEqual(filename1, filename2):
87 '''return true if the decompressed contents of the two files
88 are binary equal.
89 '''
90 with gzip.open(filename1, "rb") as infile1:
91 d1 = infile1.read()
92 with gzip.open(filename2, "rb") as infile2:
93 d2 = infile2.read()
94 if d1 == d2:
95 return True
96 return False
97
98
99 def check_samtools_view_equal(
100 filename1, filename2,
101 without_header=False):
102 '''return true if the two files are equal in their
103 content through samtools view.
104 '''
105 # strip MD and NM tags, as not preserved in CRAM files
106 args = ["-x", "MD", "-x", "NM"]
107 if not without_header:
108 args.append("-h")
109
110 lines1 = pysam.samtools.view(*(args + [filename1]))
111 lines2 = pysam.samtools.view(*(args + [filename2]))
112
113 if len(lines1) != len(lines2):
114 return False
115
116 if lines1 != lines2:
117 # line by line comparison
118 # sort each line, as tags get rearranged between
119 # BAM/CRAM
120 for n, pair in enumerate(zip(lines1, lines2)):
121 l1, l2 = pair
122 l1 = sorted(l1[:-1].split("\t"))
123 l2 = sorted(l2[:-1].split("\t"))
124 if l1 != l2:
125 print("mismatch in line %i" % n)
126 print(l1)
127 print(l2)
128 return False
129 else:
130 return False
131
132 return True
133
134
135 def check_url(url):
136 '''return True if URL is available.
137
138 A URL might not be available if it is the wrong URL
139 or there is no connection to the URL.
140 '''
141 try:
142 urlopen(url, timeout=1)
143 return True
144 except:
145 return False
146
147
148 def checkFieldEqual(cls, read1, read2, exclude=[]):
149 '''check if two reads are equal by comparing each field.'''
150
151 # add the . for refactoring purposes.
152 for x in (".query_name",
153 ".query_sequence",
154 ".flag",
155 ".reference_id",
156 ".reference_start",
157 ".mapping_quality",
158 ".cigartuples",
159 ".next_reference_id",
160 ".next_reference_start",
161 ".template_length",
162 ".query_length",
163 ".query_qualities",
164 ".bin",
165 ".is_paired", ".is_proper_pair",
166 ".is_unmapped", ".is_mapped",
167 ".mate_is_unmapped", ".mate_is_mapped",
168 ".is_reverse", ".is_forward",
169 ".mate_is_reverse", ".mate_is_forward",
170 ".is_read1", ".is_read2",
171 ".is_secondary", ".is_qcfail",
172 ".is_duplicate"):
173 n = x[1:]
174 if n in exclude:
175 continue
176 cls.assertEqual(getattr(read1, n), getattr(read2, n),
177 "attribute mismatch for %s: %s != %s" %
178 (n, getattr(read1, n), getattr(read2, n)))
179
180
181 def check_lines_equal(cls, a, b, sort=False, filter_f=None, msg=None):
182 """check if contents of two files are equal comparing line-wise.
183
184 sort: bool
185 sort contents of both files before comparing.
186 filter_f:
187 remover lines in both a and b where expression is True
188 """
189 with openfile(a) as inf:
190 aa = inf.readlines()
191 with openfile(b) as inf:
192 bb = inf.readlines()
193
194 if filter_f is not None:
195 aa = [x for x in aa if not filter_f(x)]
196 bb = [x for x in bb if not filter_f(x)]
197
198 if sort:
199 cls.assertEqual(sorted(aa), sorted(bb), msg)
200 else:
201 cls.assertEqual(aa, bb, msg)
202
203
204 def get_temp_filename(suffix=""):
205 caller_name = inspect.getouterframes(inspect.currentframe(), 2)[1][3]
206 try:
207 os.makedirs(TESTS_TEMPDIR)
208 except OSError:
209 pass
210
211 f = tempfile.NamedTemporaryFile(
212 prefix="pysamtests_tmp_{}_".format(caller_name),
213 suffix=suffix,
214 delete=False,
215 dir=TESTS_TEMPDIR)
216
217 f.close()
218 return f.name
219
220 @contextlib.contextmanager
221 def get_temp_context(suffix="", keep=False):
222 caller_name = inspect.getouterframes(inspect.currentframe(), 3)[1][3]
223 try:
224 os.makedirs(TESTS_TEMPDIR)
225 except OSError:
226 pass
227
228 f = tempfile.NamedTemporaryFile(
229 prefix="pysamtests_tmp_{}_".format(caller_name),
230 suffix=suffix,
231 delete=False,
232 dir=TESTS_TEMPDIR)
233
234 f.close()
235 yield f.name
236
237 if not keep:
238 # clear up any indices as well
239 for f in glob.glob(f.name + "*"):
240 os.unlink(f)
241
242
243 def make_data_files(directory):
244 if os.path.exists(os.path.join(directory, 'all.stamp')):
245 return
246
247 make = os.environ.get('MAKE', 'make')
248
249 for attempt in range(1, 6):
250 try:
251 os.mkdir(os.path.join(directory, 'all.lock'), 0o700)
252 break
253 except FileExistsError:
254 time.sleep(attempt)
255 continue
256 else:
257 raise RuntimeError(f'Directory {directory!r} already locked: try `{make} clean` there')
258
259 try:
260 subprocess.check_output([make, '-C', directory], stderr=subprocess.STDOUT, encoding='ascii')
261 except subprocess.CalledProcessError as e:
262 raise RuntimeError(f'Making test data in {directory!r} failed:\n{e.output}') from None
263 finally:
264 os.rmdir(os.path.join(directory, 'all.lock'))
265
266
267 def load_and_convert(filename, encode=True):
268 '''load data from filename and convert all fields to string.
269
270 Filename can be either plain or compressed (ending in .gz).
271 '''
272 data = []
273 if filename.endswith(".gz"):
274 with gzip.open(filename) as inf:
275 for line in inf:
276 line = line.decode("ascii")
277 if line.startswith("#"):
278 continue
279 d = line.strip().split("\t")
280 data.append(d)
281 else:
282 with open(filename) as f:
283 for line in f:
284 if line.startswith("#"):
285 continue
286 d = line.strip().split("\t")
287 data.append(d)
288
289 return data
290
291
292 def flatten_nested_list(l):
293 return [i for ll in l for i in ll]