test_iostream.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. tests/test_iostream.cpp -- Usage of scoped_output_redirect
  3. Copyright (c) 2017 Henry F. Schreiner
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include <pybind11/iostream.h>
  8. #include "pybind11_tests.h"
  9. #include <iostream>
  10. void noisy_function(std::string msg, bool flush) {
  11. std::cout << msg;
  12. if (flush)
  13. std::cout << std::flush;
  14. }
  15. void noisy_funct_dual(std::string msg, std::string emsg) {
  16. std::cout << msg;
  17. std::cerr << emsg;
  18. }
  19. TEST_SUBMODULE(iostream, m) {
  20. add_ostream_redirect(m);
  21. // test_evals
  22. m.def("captured_output_default", [](std::string msg) {
  23. py::scoped_ostream_redirect redir;
  24. std::cout << msg << std::flush;
  25. });
  26. m.def("captured_output", [](std::string msg) {
  27. py::scoped_ostream_redirect redir(std::cout, py::module::import("sys").attr("stdout"));
  28. std::cout << msg << std::flush;
  29. });
  30. m.def("guard_output", &noisy_function,
  31. py::call_guard<py::scoped_ostream_redirect>(),
  32. py::arg("msg"), py::arg("flush")=true);
  33. m.def("captured_err", [](std::string msg) {
  34. py::scoped_ostream_redirect redir(std::cerr, py::module::import("sys").attr("stderr"));
  35. std::cerr << msg << std::flush;
  36. });
  37. m.def("noisy_function", &noisy_function, py::arg("msg"), py::arg("flush") = true);
  38. m.def("dual_guard", &noisy_funct_dual,
  39. py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>(),
  40. py::arg("msg"), py::arg("emsg"));
  41. m.def("raw_output", [](std::string msg) {
  42. std::cout << msg << std::flush;
  43. });
  44. m.def("raw_err", [](std::string msg) {
  45. std::cerr << msg << std::flush;
  46. });
  47. m.def("captured_dual", [](std::string msg, std::string emsg) {
  48. py::scoped_ostream_redirect redirout(std::cout, py::module::import("sys").attr("stdout"));
  49. py::scoped_ostream_redirect redirerr(std::cerr, py::module::import("sys").attr("stderr"));
  50. std::cout << msg << std::flush;
  51. std::cerr << emsg << std::flush;
  52. });
  53. }