| 1 |
import os |
| 2 |
import subprocess |
| 3 |
import threading |
| 4 |
import errno |
| 5 |
import unittest |
| 6 |
from pysam import AlignmentFile |
| 7 |
from TestUtils import make_data_files, BAM_DATADIR |
| 8 |
|
| 9 |
|
| 10 |
def setUpModule(): |
| 11 |
make_data_files(BAM_DATADIR) |
| 12 |
|
| 13 |
|
| 14 |
def alignmentfile_writer_thread(infile, outfile): |
| 15 |
def _writer_thread(infile, outfile): |
| 16 |
"""read from infile and write to outfile""" |
| 17 |
try: |
| 18 |
i = 0 |
| 19 |
for record in infile: |
| 20 |
outfile.write(record) |
| 21 |
i += 1 |
| 22 |
except IOError as e: |
| 23 |
if e.errno != errno.EPIPE: |
| 24 |
pass |
| 25 |
finally: |
| 26 |
outfile.close() |
| 27 |
|
| 28 |
writer = threading.Thread(target=_writer_thread, args=(infile, outfile)) |
| 29 |
writer.daemon = True |
| 30 |
writer.start() |
| 31 |
return writer |
| 32 |
|
| 33 |
|
| 34 |
class StreamTest(unittest.TestCase): |
| 35 |
|
| 36 |
def stream_process(self, proc, in_stream, out_stream, writer): |
| 37 |
|
| 38 |
with AlignmentFile(proc.stdout) as infile: |
| 39 |
read = 0 |
| 40 |
for record in infile: |
| 41 |
read += 1 |
| 42 |
return 0, read |
| 43 |
|
| 44 |
def test_text_processing(self): |
| 45 |
|
| 46 |
with subprocess.Popen('head -n200', |
| 47 |
stdin=subprocess.PIPE, |
| 48 |
stdout=subprocess.PIPE, |
| 49 |
shell=True) as proc: |
| 50 |
|
| 51 |
in_stream = AlignmentFile(os.path.join(BAM_DATADIR, 'ex1.bam')) |
| 52 |
out_stream = AlignmentFile( |
| 53 |
proc.stdin, 'wh', header=in_stream.header) |
| 54 |
writer = alignmentfile_writer_thread(in_stream, |
| 55 |
out_stream) |
| 56 |
|
| 57 |
written, read = self.stream_process(proc, |
| 58 |
in_stream, |
| 59 |
out_stream, |
| 60 |
writer) |
| 61 |
self.assertEqual(read, 198) |
| 62 |
|
| 63 |
@unittest.skip("test contains bug") |
| 64 |
def test_samtools_processing(self): |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
with subprocess.Popen('samtools view -b -f 4', |
| 71 |
stdin=subprocess.PIPE, |
| 72 |
stdout=subprocess.PIPE, |
| 73 |
shell=True) as proc: |
| 74 |
|
| 75 |
in_stream = AlignmentFile(os.path.join(BAM_DATADIR, 'ex1.bam')) |
| 76 |
out_stream = AlignmentFile( |
| 77 |
proc.stdin, 'wb', header=in_stream.header) |
| 78 |
writer = alignmentfile_writer_thread(in_stream, |
| 79 |
out_stream) |
| 80 |
|
| 81 |
written, read = self.stream_process(proc, |
| 82 |
in_stream, |
| 83 |
out_stream, |
| 84 |
writer) |
| 85 |
self.assertEqual(read, 35) |
| 86 |
|
| 87 |
|
| 88 |
if __name__ == "__main__": |
| 89 |
unittest.main() |