Debian Codegraph @

tests/samtools_test.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/env python
2 '''unit testing code for pysam.
3
4 Execute in the :file:`tests` directory as it requires the Makefile
5 and data files located there.
6 '''
7
8 import warnings
9 import unittest
10 import os
11 import re
12 import glob
13 import sys
14 import subprocess
15 import shutil
16 import pysam
17 import pysam.samtools
18 import pysam.bcftools
19 from TestUtils import checkBinaryEqual, check_lines_equal, \
20 check_samtools_view_equal, get_temp_filename, force_bytes, WORKDIR, \
21 make_data_files, BAM_DATADIR
22
•23 import platform
24
25 def setUpModule():
26 make_data_files(BAM_DATADIR)
27
28
29 def run_command(cmd):
30 '''run a samtools command'''
31 try:
32 retcode = subprocess.call(cmd, shell=True,
33 stderr=subprocess.PIPE)
34 if retcode < 0:
35 print("Child was terminated by signal", -retcode)
36 except OSError as e:
37 print("Execution failed:", e)
38
39
40 def get_version(executable):
41 '''return samtools/bcftools version'''
42
43 with subprocess.Popen(executable, shell=True,
44 stderr=subprocess.PIPE).stderr as pipe:
45 lines = b"".join(pipe.readlines()).decode("ascii")
46
47 try:
48 x = re.search(r"Version:\s+(\S+)", lines).groups()[0]
49 except AttributeError:
50 raise ValueError("could not get version from %s" % lines)
51 return x
52
53
54 class SamtoolsTest(unittest.TestCase):
55
56 '''test samtools command line commands and compare
57 against pysam commands.
58
59 Tests fail, if the output is not binary identical.
60 '''
61
62 requisites = [
63 "ex1.fa", "ex1.fa.fai",
64 "ex1.sam.gz",
65 "ex1.bam", "ex1.bam.bai",
66 "ex1.sam",
67 "ex1.sam",
68 "ex2.bam",
69 "ex2.sam",
70 "ex1.bed"]
71
72 # a list of statements to test
73 # should contain at least one %(out)s component indicating
74 # an output file.
75 statements = [
76 "view ex1.bam > %(out)s_ex1.view",
77 "view -c ex1.bam > %(out)s_ex1.count",
78 # ("view -bT ex1.fa -o %(out)s_ex1.view2 ex1.sam",
79 "sort ex1.bam -o %(out)s_ex1.sort.bam",
80 "mpileup ex1.bam > %(out)s_ex1.pileup",
81 "depth ex1.bam > %(out)s_ex1.depth",
82 # TODO: issues with file naming
83 # "faidx ex1.fa; %(out)s_ex1.fa.fai",
84 "index ex1.bam %(out)s_ex1.bam.fai",
85 "index -@2 ex1.bam %(out)s_ex1.bam.fai",
86 "idxstats ex1.bam > %(out)s_ex1.idxstats",
87 # TODO: fixmate behaviour changed in 1.21
88 #"fixmate ex1.bam %(out)s_ex1.fixmate.bam",
89 "flagstat ex1.bam > %(out)s_ex1.flagstat",
•90 #"calmd ex1.bam ex1.fa > %(out)s_ex1.calmd.bam",
91 # use -s option, otherwise the following error in samtools 1.2:
92 # Samtools-htslib-API: bam_get_library() not yet implemented
93 # causes downstream problems
94 # TODO: The following cause subsequent commands to fail
95 # unknown option
96 # "rmdup -s ex1.bam %(out)s_ex1.rmdup.bam",
97 # "merge -f %(out)s_ex1.merge.bam ex1.bam ex1.bam",
98 "reheader ex2.sam ex1.bam > %(out)s_ex1.reheader.bam",
99 "cat -o %(out)s_ex1.cat.bam ex1.bam ex1.bam",
100 "targetcut ex1.bam > %(out)s_ex1.targetcut",
101 "phase ex1.bam > %(out)s_ex1.phase",
102 "view -bt ex1.fa.fai ex1.sam.gz > %(out)s_ex1.bam",
103 "bam2fq ex1.bam > %(out)s_ex1.bam2fq",
104 # TODO: not the same
105 # "pad2unpad -T ex1.fa ex2.bam > %(out)s_ex2.unpad",
106 # TODO: command line option problem
107 # "bamshuf ex1.bam -O --output-fmt SAM > %(out)s_ex1.bamshuf.sam",
108 # "collate ex1.bam %(out)s_ex1.collate",
109 "bedcov ex1.bed ex1.bam > %(out)s_ex1.bedcov",
110 "stats ex1.bam > %(out)s_ex1.stats",
111 "dict ex1.bam > %(out)s_ex1.dict",
112 # TODO: not the same
113 # ("addreplacerg -r 'RG\tID:ga\tSM:hs' ex1.bam > %(out)s_ex1.addreplacerg",
114 ]
115
•116 if platform.architecture()[0] == '64bit':
117 statements.append("calmd ex1.bam ex1.fa > %(out)s_ex1.calmd.bam")
118
119 map_command = {
120 }
121
122 executable = "samtools"
123
124 module = pysam.samtools
125
126 def check_version(self):
127
128 samtools_version = get_version(self.executable)
129
130 def _r(s):
131 # patch - remove any of the alpha/beta suffixes, i.e., 0.1.12a ->
132 # 0.1.12
133 if s.count('-') > 0:
134 s = s[0:s.find('-')]
135 return re.sub("[^0-9.]", "", s)
136
137 if _r(samtools_version) != _r(pysam.__samtools_version__):
138 warnings.warn(
139 "versions of pysam.%s and %s differ: %s != %s" %
140 (self.executable,
141 self.executable,
142 pysam.__samtools_version__,
143 samtools_version))
144
145 def setUp(self):
146 '''setup tests.
147
148 For setup, all commands will be run before the first test is
149 executed. Individual tests will then just compare the output
150 files.
151
152 '''
153 self.check_version()
154
155 self.workdir = os.path.join(WORKDIR, "samtools_test")
156
157 if not os.path.exists(self.workdir):
158 os.makedirs(self.workdir)
159
160 for f in self.requisites:
161 shutil.copy(os.path.join(BAM_DATADIR, f),
162 os.path.join(self.workdir, f))
163
164 self.savedir = os.getcwd()
165 os.chdir(self.workdir)
166
167 return
168
169 def get_command(self, statement, map_to_internal=True):
170 """return samtools command from statement"""
171 parts = statement.split(" ")
172 command = parts[0]
173 if map_to_internal:
174 return self.map_command.get(command, command)
175 else:
176 return command
177
178 def check_statement(self, statement):
179
180 parts = statement.split(" ")
181 r_samtools = {"out": self.executable}
182 r_pysam = {"out": "pysam"}
183
184 command = self.get_command(statement)
185
186 targets = [x for x in parts if "%(out)s" in x]
187 samtools_targets = [x % r_samtools for x in targets]
188 pysam_targets = [x % r_pysam for x in targets]
189
190 pysam_method = getattr(self.module, command)
191
192 # run samtools
193 full_statement = re.sub(r"%\(out\)s", self.executable, statement)
194 run_command(" ".join((self.executable, full_statement)))
195 # sys.stdout.write("%s %s ok" % (command, self.executable))
196
197 # run pysam
198 if ">" in statement:
199 assert parts[-2] == ">"
200 parts = parts[:-2]
201
202 # avoid interpolation to preserve string quoting, tab chars, etc.
203 pysam_parts = [re.sub(r"%\(out\)s", "pysam", x) for x in parts[1:]]
204 output = pysam_method(*pysam_parts,
205 raw=True,
206 catch_stdout=True)
207 # sys.stdout.write(" pysam ok\n")
208 if ">" in statement:
209 with open(pysam_targets[-1], "wb") as outfile:
210 if output is not None:
211 outfile.write(force_bytes(output))
212 for samtools_target, pysam_target in zip(samtools_targets,
213 pysam_targets):
214 if os.path.isdir(samtools_target):
215 samtools_files = glob.glob(os.path.join(
216 samtools_target, "*"))
217 pysam_files = glob.glob(os.path.join(pysam_target, "*"))
218 self.assertEqual(len(samtools_files), len(pysam_files))
219 # need to be able to exclude files like README, etc.
220 continue
221 else:
222 samtools_files = [samtools_target]
223 pysam_files = [pysam_target]
224
225 for s, p in zip(samtools_files, pysam_files):
226 binary_equal = checkBinaryEqual(s, p)
227 error_msg = "%s failed: files %s and %s are not the same" % (
228 command, s, p)
229 if binary_equal:
230 continue
231 elif s.endswith(".bam"):
232 self.assertTrue(
233 check_samtools_view_equal(
234 s, p, without_header=True),
235 error_msg)
236 else:
237 check_lines_equal(
238 self, s, p,
239 filter_f=lambda x: x.startswith("#"),
240 msg=error_msg)
241
242 def testStatements(self):
243 for statement in self.statements:
244 command = self.get_command(statement, map_to_internal=False)
245 # bam2fq differs between version 1.5 and 1.6 - re-enable if
246 # bioconda samtools will be available.
247 # flagstat differs between version <=1.12 and >=1.13
248 if command in ("bedcov", "stats", "dict", "bam2fq", "flagstat"):
249 continue
250
251 self.check_statement(statement)
252
253 @unittest.skipUnless(sys.stdin.isatty(), "skipping usage tests, stdin is not a tty")
254 def testUsage(self):
255 if self.executable == "bcftools":
256 # bcftools usage messages end with exit(1)
257 return
258
259 for statement in self.statements:
260 command = self.get_command(statement, map_to_internal=False)
261 # ignore commands that exit or cause other failures
262 # TODO: check - if reheader or phase is run in testStatements, sort fails
263 # here
264 if command in ("view", "sort", "bam2fq", "flagstat", "reheader",
265 "stats", "idxstats"):
266 continue
267 mapped_command = self.get_command(statement, map_to_internal=True)
268 pysam_method = getattr(self.module, mapped_command)
269 usage_msg = pysam_method.usage()
270 expected = r"Usage:\s+{} {}".format(self.executable, command)
271 self.assertTrue(re.search(expected, usage_msg) is not None)
272
273 def tearDown(self):
274 if os.path.exists(self.workdir):
275 shutil.rmtree(self.workdir)
276 os.chdir(self.savedir)
277
278
279 class EmptyIndexTest(unittest.TestCase):
280
281 def testEmptyIndex(self):
282 self.assertRaises(IOError, pysam.samtools.index,
283 "exdoesntexist.bam")
284
285 def testEmptyIndexWithExtraFlag(self):
286 self.assertRaises(IOError, pysam.samtools.index,
287 "-c",
288 "exdoesntexist.bam")
289
290 def testEmptyIndexWithExtraArg(self):
291 self.assertRaises(IOError, pysam.samtools.index,
292 "-c",
293 "-m",
294 "14",
295 "exdoesntexist.bam")
296
297
298 class ExerciseSubcommands(unittest.TestCase):
299 def testFailingSamtools(self):
300 with self.assertRaises(pysam.SamtoolsError):
301 pysam.samtools.view("nonexistent.bam")
302
303 def testFailingBCFtools(self):
304 with self.assertRaises(pysam.SamtoolsError):
305 pysam.bcftools.view("nonexistent.vcf")
306
307
308 if sys.platform != "darwin":
309 # fails with segfault with htslib 1.5 on Osx, an issue with flockfile
310 # issue seems to be with repeated calls to interface
311
312 class TestReturnType(unittest.TestCase):
313
314 def testReturnValueString(self):
315 retval = pysam.idxstats(os.path.join(BAM_DATADIR, "ex1.bam"))
316 self.assertFalse(isinstance(retval, bytes))
317 self.assertTrue(isinstance(retval, str))
318
319 def testReturnValueData(self):
320 args = "-O BAM {}".format(os.path.join(BAM_DATADIR,
321 "ex1.bam")).split(" ")
322 retval = pysam.view(*args)
323 self.assertTrue(isinstance(retval, bytes))
324 self.assertFalse(isinstance(retval, str))
325
326 class StdoutTest(unittest.TestCase):
327 '''test if stdout can be redirected.'''
328
329 def testWithRedirectedStdout(self):
330 r = pysam.samtools.flagstat(
331 os.path.join(BAM_DATADIR, "ex1.bam"))
332 self.assertTrue(len(r) > 0)
333
334 def testWithoutRedirectedStdout(self):
335 r = pysam.samtools.flagstat(
336 os.path.join(BAM_DATADIR, "ex1.bam"),
337 catch_stdout=False)
338 self.assertEqual(r, None)
339
340 def testDoubleCalling(self):
341 # The following would fail if there is an
342 # issue with stdout being improperly caught.
343 retvals = pysam.idxstats(
344 os.path.join(BAM_DATADIR, "ex1.bam"))
345 retvals = pysam.idxstats(
346 os.path.join(BAM_DATADIR, "ex1.bam"))
347
348 def testSaveStdout(self):
349 outfile = get_temp_filename(suffix=".tsv")
350 r = pysam.samtools.flagstat(
351 os.path.join(BAM_DATADIR, "ex1.bam"),
352 save_stdout=outfile)
353 self.assertEqual(r, None)
354 with open(outfile) as inf:
355 r = inf.read()
356 self.assertTrue(len(r) > 0)
357
358 class PysamTest(SamtoolsTest):
359 """check access to samtools command in the pysam
360 main package.
361
362 This is for backwards capability.
363 """
364
365 module = pysam
366
367 # class BcftoolsTest(SamtoolsTest):
368
369 # requisites = [
370 # "ex1.fa",
371 # "ex1.vcf.gz",
372 # "ex1.vcf.gz.tbi",
373 # ]
374 # # a list of statements to test
375 # # should contain at least one %(out)s component indicating
376 # # an output file.
377 # statements = [
378 # # "index -n ex1.vcf.gz > %(out)s_ex1.index",
379
380 # "annotate -x ID ex1.vcf.gz > %(out)s_ex1.annotate",
381 # "concat -a ex1.vcf.gz ex1.vcf.gz > %(out)s_ex1.concat",
382 # "isec -p %(out)s_ex1.isec ex1.vcf.gz ex1.vcf.gz",
383 # "merge --force-samples ex1.vcf.gz ex1.vcf.gz > %(out)s_ex1.norm",
384 # "norm -m +both ex1.vcf.gz > %(out)s_ex1.norm",
385
386 # # "plugin",
387 # # "query -f '%CHROM\n' ex1.vcf.gz > %(out)s_ex1.query",
388 # # "reheader -s A > %(out)s_ex1.reheader",
389 # # "view ex1.vcf.gz > %(out)s_ex1.view",
390 # # "call -m ex1.vcf.gz > %(out)s_ex1.call",
391 # # bad file descriptor
392 # # "consensus -f ex1.fa ex1.vcf.gz > %(out)s_ex1.consensus"
393 # # need appropriate VCF file
394 # # "cnv",
395 # # segfault
396 # # "filter -s A ex1.vcf.gz > %(out)s_ex1.filter",
397 # # exit
398 # # "gtcheck -s A ex1.vcf.gz > %(out)s_ex1.gtcheck",
399 # # segfault, used to work with bcftools 1.3
400 # # "roh -s A ex1.vcf.gz > %(out)s_ex1.roh",
401 # "stats ex1.vcf.gz > %(out)s_ex1.stats",
402 # ]
403
404 # map_command = {
405 # }
406
407 # executable = "bcftools"
408
409 # module = pysam.bcftools
410
411
412 if __name__ == "__main__":
413 print("starting tests")
414 unittest.main()
415 print("completed tests")