Skip to content

Commit

Permalink
Address review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
amaslenn authored Sep 14, 2023
1 parent 4ded848 commit dff3b38
Showing 1 changed file with 42 additions and 23 deletions.
65 changes: 42 additions & 23 deletions testinfra/backend/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import shlex
import subprocess
import urllib.parse
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any, Optional, Union

if TYPE_CHECKING:
import testinfra.host
Expand All @@ -35,12 +35,11 @@ class HostSpec:

@dataclasses.dataclass
class CommandResult:
backend: "BaseBackend"
exit_status: int
command: bytes
stdout_bytes: bytes
stderr_bytes: bytes
stdout: str
stderr: str
_stdout: Union[str, bytes]
_stderr: Union[str, bytes]

@property
def succeeded(self) -> bool:
Expand Down Expand Up @@ -69,6 +68,30 @@ def rc(self) -> int:
"""
return self.exit_status

@property
def stdout(self) -> str:
if isinstance(self._stdout, bytes):
return self.backend.decode(self._stdout)
return self._stdout

@property
def stderr(self) -> str:
if isinstance(self._stderr, bytes):
return self.backend.decode(self._stderr)
return self._stderr

@property
def stdout_bytes(self) -> bytes:
if isinstance(self._stdout, str):
return self.backend.encode(self._stdout)
return self._stdout

@property
def stderr_bytes(self) -> bytes:
if isinstance(self._stderr, str):
return self.backend.encode(self._stderr)
return self._stderr


class BaseBackend(metaclass=abc.ABCMeta):
"""Represent the connection to the remote or local system"""
Expand Down Expand Up @@ -258,34 +281,30 @@ def encode(self, data: str) -> bytes:
def result(self, *args: Any, **kwargs: Any) -> CommandResult:
rc, cmd = args[:2]

out, err = "", ""
out_bytes, err_bytes = b"", b""
if len(args) > 2:
out_bytes = args[2]
if isinstance(args[2], bytes):
out_bytes = args[2]
else:
out = args[2]
if len(args) > 3:
err_bytes = args[3]
if isinstance(args[3], bytes):
err_bytes = args[3]
else:
err = args[3]

out_bytes = kwargs.get("stdout_bytes", out_bytes)
err_bytes = kwargs.get("stderr_bytes", err_bytes)

out = kwargs.get("stdout", "")
if not out and out_bytes:
out = self.decode(out_bytes)
elif out and not out_bytes:
out_bytes = self.encode(out)

err = kwargs.get("stderr", "")
if not err and err_bytes:
err = self.decode(err_bytes)
elif err and not err_bytes:
err_bytes = self.encode(err)
out = kwargs.get("stdout", out)
err = kwargs.get("stderr", err)

result = CommandResult(
backend=self,
exit_status=rc,
command=cmd,
stderr=err,
stderr_bytes=err_bytes,
stdout=out,
stdout_bytes=out_bytes,
_stdout=out_bytes or out,
_stderr=err_bytes or err,
)
logger.debug("RUN %s", result)
return result

0 comments on commit dff3b38

Please sign in to comment.