blob: e9161505ca455c38dc49127d155561696258a2d5 [file] [log] [blame]
Henry Schreiner8b405052017-08-24 17:12:43 -07001/*
2 tests/test_iostream.cpp -- Usage of scoped_output_redirect
3
4 Copyright (c) 2017 Henry F. Schreiner
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
10
11#include <pybind11/iostream.h>
12#include "pybind11_tests.h"
13#include <iostream>
14
15
16void noisy_function(std::string msg, bool flush) {
17
18 std::cout << msg;
19 if (flush)
20 std::cout << std::flush;
21}
22
23void noisy_funct_dual(std::string msg, std::string emsg) {
24 std::cout << msg;
25 std::cerr << emsg;
26}
27
28TEST_SUBMODULE(iostream, m) {
29
30 add_ostream_redirect(m);
31
32 // test_evals
33
34 m.def("captured_output_default", [](std::string msg) {
35 py::scoped_ostream_redirect redir;
36 std::cout << msg << std::flush;
37 });
38
39 m.def("captured_output", [](std::string msg) {
Henry Schreiner6bcd2202020-10-03 13:38:03 -040040 py::scoped_ostream_redirect redir(std::cout, py::module_::import("sys").attr("stdout"));
Henry Schreiner8b405052017-08-24 17:12:43 -070041 std::cout << msg << std::flush;
42 });
43
44 m.def("guard_output", &noisy_function,
45 py::call_guard<py::scoped_ostream_redirect>(),
46 py::arg("msg"), py::arg("flush")=true);
47
48 m.def("captured_err", [](std::string msg) {
Henry Schreiner6bcd2202020-10-03 13:38:03 -040049 py::scoped_ostream_redirect redir(std::cerr, py::module_::import("sys").attr("stderr"));
Henry Schreiner8b405052017-08-24 17:12:43 -070050 std::cerr << msg << std::flush;
51 });
52
53 m.def("noisy_function", &noisy_function, py::arg("msg"), py::arg("flush") = true);
54
55 m.def("dual_guard", &noisy_funct_dual,
56 py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>(),
57 py::arg("msg"), py::arg("emsg"));
58
59 m.def("raw_output", [](std::string msg) {
60 std::cout << msg << std::flush;
61 });
62
63 m.def("raw_err", [](std::string msg) {
64 std::cerr << msg << std::flush;
65 });
66
67 m.def("captured_dual", [](std::string msg, std::string emsg) {
Henry Schreiner6bcd2202020-10-03 13:38:03 -040068 py::scoped_ostream_redirect redirout(std::cout, py::module_::import("sys").attr("stdout"));
69 py::scoped_ostream_redirect redirerr(std::cerr, py::module_::import("sys").attr("stderr"));
Henry Schreiner8b405052017-08-24 17:12:43 -070070 std::cout << msg << std::flush;
71 std::cerr << emsg << std::flush;
72 });
73}