Debian Codegraph @

pyfastaq/tests/utils_test.py

raw
1 #!/usr/bin/env python3
2
3 import sys
4 import os
5 import filecmp
6 import unittest
7 from pyfastaq import utils
8
9 modules_dir = os.path.dirname(os.path.abspath(utils.__file__))
10 data_dir = os.path.join(modules_dir, 'tests', 'data')
11
12 class TestUtils(unittest.TestCase):
13 def test_write_and_read(self):
14 '''open_file_write() and open_file_read() should do the right thing depending gzipped or not'''
15 for filename in ['utils.tmp', 'utils.tmp.gz', 'utils.tmp.bgz']:
16 f = utils.open_file_write(filename)
17 for i in range(3):
18 print(i, file=f)
19 utils.close(f)
20
21 counter = 0
22
23 f = utils.open_file_read(filename)
24 for line in f:
25 self.assertEqual(counter, int(line.strip()))
26 counter += 1
27 utils.close(f)
28
29 os.unlink(filename)
30
31 f = utils.open_file_read('-')
32 self.assertEqual(sys.stdin, f)
33 f = utils.open_file_write('-')
34 self.assertEqual(sys.stdout, f)
35
36 def test_raise_exception(self):
37 '''open_file_write() and open_file_read() should raise an exception when can't do the opening'''
38 with self.assertRaises(utils.Error):
39 utils.open_file_read('this_file_is_not_here_so_throw_error')
40 with self.assertRaises(utils.Error):
41 utils.open_file_read('this_file_is_not_here_so_throw_error.gz')
42 with self.assertRaises(utils.Error):
43 utils.open_file_read(os.path.join(data_dir, 'utils_test_not_really_zipped.gz'))
44
45 with self.assertRaises(utils.Error):
46 utils.open_file_write(os.path.join('not_a_directory', 'this_file_is_not_here_so_throw_error'))
47 with self.assertRaises(utils.Error):
48 utils.open_file_write(os.path.join('not_a_directory', 'this_file_is_not_here_so_throw_error.gz'))
49
50 def test_file_transpose(self):
51 '''Test that file_transpose() does what it should'''
52 infile = os.path.join(data_dir, 'utils_test_file_transpose.txt')
53 tmp_out = 'utils_test_file_transpose.tmp'
54 correct_file = os.path.join(data_dir, 'utils_test_file_transposed.txt')
55 utils.file_transpose(infile, tmp_out)
56 self.assertTrue(filecmp.cmp(tmp_out, correct_file))
57 os.unlink(tmp_out)
58
59 def test_system_call(self):
60 '''Test that system call appears to work and die as it should'''
61 test_file = os.path.join(data_dir, 'utils_test_system_call.txt')
62 tmp_out = 'utils_test_syscall.tmp'
63 utils.syscall('cat ' + test_file + ' > ' + tmp_out)
64 self.assertTrue(filecmp.cmp(tmp_out, test_file))
65 os.unlink(tmp_out)
66
67 with self.assertRaises(utils.Error):
68 utils.syscall('thisisveryunlikelytoebarealcommandandshouldthrowerror')
69
70 utils.syscall('echo "this is not the right string" > ' + tmp_out)
71 self.assertFalse(filecmp.cmp(tmp_out, test_file))
72 os.unlink(tmp_out)
73
74 s = utils.syscall_get_stdout('echo bingo')
75 self.assertListEqual(["bingo"], s)
76 with self.assertRaises(utils.Error):
77 utils.syscall_get_stdout('thisisveryunlikelytoebarealcommandandshouldthrowerror')
78
79 if __name__ == '__main__':
80 unittest.main()