Debian Codegraph @

tests/samtools_test.py

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