summaryrefslogtreecommitdiff
path: root/tests/conftest.py
diff options
context:
space:
mode:
authorKevin Van Brunt <kmvanbrunt@gmail.com>2019-03-20 20:23:14 -0400
committerKevin Van Brunt <kmvanbrunt@gmail.com>2019-03-20 20:23:14 -0400
commit9ffb1ffa80724b10e5be5563fdefcf67a5abff41 (patch)
tree4df73432c1c50fc01e87847362cc12986e424686 /tests/conftest.py
parentd16a20fe14ed02e389ccde99d114e7335740e162 (diff)
downloadcmd2-git-9ffb1ffa80724b10e5be5563fdefcf67a5abff41.tar.gz
Made run_cmd return out and err
Diffstat (limited to 'tests/conftest.py')
-rw-r--r--tests/conftest.py40
1 files changed, 31 insertions, 9 deletions
diff --git a/tests/conftest.py b/tests/conftest.py
index f41afb64..56538718 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -5,6 +5,7 @@ Cmd2 unit/functional testing
Copyright 2016 Federico Ceratto <federico.ceratto@gmail.com>
Released under MIT license, see LICENSE file
"""
+import sys
from typing import Optional
from unittest import mock
@@ -13,6 +14,13 @@ from pytest import fixture
import cmd2
from cmd2.utils import StdSim
+# Python 3.4 require contextlib2 for temporarily redirecting stderr and stdout
+if sys.version_info < (3, 5):
+ # noinspection PyUnresolvedReferences
+ from contextlib2 import redirect_stdout, redirect_stderr
+else:
+ from contextlib import redirect_stdout, redirect_stderr
+
# Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit)
try:
import gnureadline as readline
@@ -126,19 +134,33 @@ def normalize(block):
def run_cmd(app, cmd):
- """ Clear StdSim buffer, run the command, extract the buffer contents, """
- app.stdout.clear()
- app.onecmd_plus_hooks(cmd)
- out = app.stdout.getvalue()
- app.stdout.clear()
- return normalize(out)
+ """ Clear out and err StdSim buffers, run the command, and return out and err """
+ saved_sysout = sys.stdout
+ sys.stdout = app.stdout
+
+ # This will be used to capture app.stdout and sys.stdout
+ copy_cmd_stdout = StdSim(app.stdout)
+
+ # This will be used to capture sys.stderr
+ copy_stderr = StdSim(sys.stderr)
+
+ try:
+ app.stdout = copy_cmd_stdout
+ with redirect_stdout(copy_cmd_stdout):
+ with redirect_stderr(copy_stderr):
+ app.onecmd_plus_hooks(cmd)
+ finally:
+ app.stdout = copy_cmd_stdout.inner_stream
+ sys.stdout = saved_sysout
+
+ out = copy_cmd_stdout.getvalue()
+ err = copy_stderr.getvalue()
+ return normalize(out), normalize(err)
@fixture
def base_app():
- c = cmd2.Cmd()
- c.stdout = StdSim(c.stdout)
- return c
+ return cmd2.Cmd()
def complete_tester(text: str, line: str, begidx: int, endidx: int, app) -> Optional[str]: