[PATCH 2/5] test: have pytest --interactive start interactive Qemu session

Ahmad Fatoum a.fatoum at pengutronix.de
Mon Jun 19 02:52:37 PDT 2023


test/emulate.pl duplicates a lot of what labgrid is already doing.
In preparation for phasing out emulate.pl, let's teach pytest to
replace it. As a first step we add these two new pytest options:

  --interactive	start Qemu interactively using labgrid environment
  --dry-run     print Qemu command line that would've been used

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 test/conftest.py |  8 ++++++
 test/strategy.py | 69 +++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 76 insertions(+), 1 deletion(-)

diff --git a/test/conftest.py b/test/conftest.py
index 1a043a91fa78..794574799ff7 100644
--- a/test/conftest.py
+++ b/test/conftest.py
@@ -25,3 +25,11 @@ def pytest_configure(config):
 
     if os.environ['LG_BUILDDIR'] is not None:
         os.environ['LG_BUILDDIR'] = os.path.realpath(os.environ['LG_BUILDDIR'])
+
+def pytest_addoption(parser):
+    parser.addoption('--interactive', action='store_const', const='qemu_interactive',
+        dest='lg_initial_state',
+        help=('(for debugging) skip tests and just start Qemu interactively'))
+    parser.addoption('--dry-run', action='store_const', const='qemu_dry_run',
+        dest='lg_initial_state',
+        help=('(for debugging) skip tests and just print Qemu command line'))
diff --git a/test/strategy.py b/test/strategy.py
index 1fe1b7d818e9..81650a7600bd 100644
--- a/test/strategy.py
+++ b/test/strategy.py
@@ -1,14 +1,20 @@
 import enum
 
 import attr
+import pytest
+import subprocess
+import os
+import sys
 
-from labgrid import target_factory, step
+from labgrid import target_factory, step, driver
 from labgrid.strategy import Strategy, StrategyError
 
 class Status(enum.Enum):
     unknown = 0
     off = 1
     barebox = 2
+    qemu_dry_run = 3
+    qemu_interactive = 4
 
 @target_factory.reg_driver
 @attr.s(eq=False)
@@ -21,9 +27,12 @@ class BareboxTestStrategy(Strategy):
     }
 
     status = attr.ib(default=Status.unknown)
+    qemu = None
 
     def __attrs_post_init__(self):
         super().__attrs_post_init__()
+        if isinstance(self.console, driver.QEMUDriver):
+            self.qemu = self.console
 
     @step(args=['status'])
     def transition(self, status, *, step):
@@ -51,3 +60,61 @@ class BareboxTestStrategy(Strategy):
                 format(self.status, status)
             )
         self.status = status
+
+    def force(self, state):
+        self.transition(Status.off)  # pylint: disable=missing-kwoa
+
+        if state == "qemu_dry_run" or state == "qemu_interactive":
+            cmd = self.get_qemu_base_args()
+
+            cmd.append("-serial")
+            cmd.append("mon:stdio")
+            cmd.append("-trace")
+            cmd.append("file=/dev/null")
+
+            with open("/dev/tty", "r+b", buffering=0) as tty:
+                tty.write(bytes("running: \n{}\n".format(quote_cmd(cmd)), "UTF-8"))
+                if state == "qemu_dry_run":
+                    pytest.exit('Dry run. Terminating.')
+                subprocess.run(cmd, stdin=tty, stdout=tty, stderr=tty)
+
+            pytest.exit('Interactive session terminated')
+        else:
+            pytest.exit('Can only force to: qemu_dry_run, qemu_interactive')
+
+    def get_qemu_base_args(self):
+        if self.qemu is None:
+            pytest.exit('interactive mode only supported with QEMUDriver')
+
+        try:
+            # https://github.com/labgrid-project/labgrid/pull/1212
+            cmd = self.qemu.get_qemu_base_args()
+        except AttributeError:
+            self.qemu.on_activate()
+            orig = self.qemu._cmd
+            cmd = []
+
+            list_iter = enumerate(orig)
+            for i, opt in list_iter:
+                if opt == "-S":
+                    continue
+                opt2 = double_opt(opt, orig, i)
+                if (opt2.startswith("-chardev socket,id=serialsocket") or
+                   opt2 == "-serial chardev:serialsocket" or
+                   opt2 == "-qmp stdio"):
+                    # skip over two elements at once
+                    next(list_iter, None)
+                    continue
+
+                cmd.append(opt)
+
+        return cmd
+
+def quote_cmd(cmd):
+    quoted = map(lambda s : s if s.find(" ") == -1 else "'" + s + "'", cmd)
+    return " ".join(quoted)
+
+def double_opt(opt, orig, i):
+    if opt == orig[-1]:
+        return opt
+    return " ".join([opt, orig[i + 1]])
-- 
2.39.2




More information about the barebox mailing list