def test_processed_output_is_written_to_file(self): with tempfile.TemporaryDirectory() as tmp_dir: file = Path(tmp_dir, "foo.bar") with subprocess.Popen(["echo", "1,2,3"], **self.default_kwargs) as proc: sutils.process_output(proc, file=file) with file.open("r") as f: self.assertEqual(["1,2,3\n"], f.readlines())
def test_stdout_is_closed_in_case_parse_func_fails(self): with subprocess.Popen(["echo", "kissa"], **self.default_kwargs) as proc: self.assertRaises( ValueError, lambda: sutils.process_output(proc, parse_func=int)) self.assertTrue(proc.stdout.closed)
def test_stdout_is_closed_in_case_text_func_fails(self): with tempfile.TemporaryDirectory() as tmp_dir: file = Path(tmp_dir, "foo.bar") with subprocess.Popen(["echo", "kissa"], **self.default_kwargs) as proc: self.assertRaises( TypeError, lambda: sutils.process_output( proc, file=file, text_func=lambda x, y: str(x + y))) self.assertTrue(proc.stdout.closed)
def test_parse_func(self): def parse_func(line): line = line.split(",") return tuple(int(x) for x in line) with subprocess.Popen(["echo", "1,2,3"], **self.default_kwargs) as proc: xs = sutils.process_output(proc, parse_func=parse_func) self.assertEqual([(1, 2, 3)], xs)
def test_multiline(self): input_file = utils.get_resource_dir() / "foils_file.txt" with tempfile.TemporaryDirectory() as tmp_dir: file = Path(tmp_dir, "foo.bar") with subprocess.Popen(["cat", str(input_file)], **self.default_kwargs) as proc: xs = sutils.process_output(proc, file=file) self.assertTrue(1 < len(xs)) with input_file.open("r") as f0, file.open("r") as f1: f0_contents = f0.readlines() f1_contents = f1.readlines() utils.assert_all_equal(xs, f0_contents, f1_contents)
def test_parse_func_is_applied_before_text_func(self): def parse_func(line): xs = line.split(",") return tuple(int(x)**2 for x in xs) def text_func(tpl): x, y, z = tpl return f"{z}-{y}-{x}" with tempfile.TemporaryDirectory() as tmp_dir: file = Path(tmp_dir, "foo.bar") with subprocess.Popen(["echo", "1,2,3"], **self.default_kwargs) as proc: xs = sutils.process_output(proc, file=file, text_func=text_func, parse_func=parse_func) self.assertEqual([(1, 4, 9)], xs) with file.open("r") as f: self.assertEqual(["9-4-1"], f.readlines())
def test_none_as_output_func_raises_exception(self): with subprocess.Popen(["echo", "hello"], **self.default_kwargs) as proc: self.assertRaises( TypeError, lambda: sutils.process_output(proc, output_func=None))
def test_tuple_as_output_func(self): with subprocess.Popen(["echo", "hello"], **self.default_kwargs) as proc: xs = sutils.process_output(proc, output_func=tuple) self.assertEqual(("hello\n", ), xs)
def test_set_as_output_func(self): with subprocess.Popen(["echo", "hello"], **self.default_kwargs) as proc: xs = sutils.process_output(proc, output_func=set) self.assertEqual({"hello\n"}, xs)
def test_basic_case(self): with subprocess.Popen(["echo", "hello"], **self.default_kwargs) as proc: xs = sutils.process_output(proc) self.assertEqual(["hello\n"], xs)