diff mbox series

[-next,07/14] kddv/cmd: Add command to create/remove mockup device

Message ID 20231118104040.386381-8-zhangxiaoxu@huaweicloud.com (mailing list archive)
State New, archived
Headers show
Series Implement a ligth weight device driver test framework | expand

Commit Message

huaweicloud Nov. 18, 2023, 10:40 a.m. UTC
From: Zhang Xiaoxu <zhangxiaoxu5@huawei.com>

Add command kddv.cmds.mock to create/remove mockup device which support
by the test framework. Usage:

Create device:
  $ python3 -m kddv.cmds.mock --bus spi --devid mchp23k256
  create spi device mchp23k256 success!

Then the mockup device can be accessed by exists user space tools.
  $ ls /dev/mtd0
  mtd0    mtd0ro
  $ hexdump /dev/mtd0
  0000000 0000 0000 0000 0000 0000 0000 0000 0000
  *
  0008000

Remove the mockup device:
 $ python3 -m kddv.cmds.mock --bus spi --devid mchp23k256 -r
 [  198.718172] Deleting MTD partitions on "spi0.0":
 remove spi device mchp23k256 success!

Signed-off-by: Wei Yongjun <weiyongjun1@huawei.com>
Signed-off-by: Zhang Xiaoxu <zhangxiaoxu5@huawei.com>
---
 tools/testing/kddv/kddv/Makefile         |   1 +
 tools/testing/kddv/kddv/cmds/__init__.py |   0
 tools/testing/kddv/kddv/cmds/mock.py     | 105 +++++++++++++++++++++++
 tools/testing/kddv/kddv/cmds/utils.py    |  28 ++++++
 4 files changed, 134 insertions(+)
 create mode 100755 tools/testing/kddv/kddv/cmds/__init__.py
 create mode 100755 tools/testing/kddv/kddv/cmds/mock.py
 create mode 100755 tools/testing/kddv/kddv/cmds/utils.py
diff mbox series

Patch

diff --git a/tools/testing/kddv/kddv/Makefile b/tools/testing/kddv/kddv/Makefile
index a68112154669..a5c91fcb0e9a 100644
--- a/tools/testing/kddv/kddv/Makefile
+++ b/tools/testing/kddv/kddv/Makefile
@@ -12,6 +12,7 @@  install:
 	$(INSTALL) -m 0755 -d $(INSTALL_PATH)
 	$(INSTALL) __init__.py $(INSTALL_PATH)
 	cp -rf core/ $(INSTALL_PATH)
+	cp -rf cmds/ $(INSTALL_PATH)
 	cp -rf tests/ $(INSTALL_PATH)
 
 clean:
diff --git a/tools/testing/kddv/kddv/cmds/__init__.py b/tools/testing/kddv/kddv/cmds/__init__.py
new file mode 100755
index 000000000000..e69de29bb2d1
diff --git a/tools/testing/kddv/kddv/cmds/mock.py b/tools/testing/kddv/kddv/cmds/mock.py
new file mode 100755
index 000000000000..2ec5e45219a0
--- /dev/null
+++ b/tools/testing/kddv/kddv/cmds/mock.py
@@ -0,0 +1,105 @@ 
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+#
+# Kernel device driver verification
+#
+# Copyright (C) 2022-2023 Huawei Technologies Co., Ltd
+# Author: Wei Yongjun <weiyongjun1@huawei.com>
+
+import os
+import sys
+import logging
+import argparse
+import unittest
+import subprocess
+
+from kddv.core.mockup import Mockup
+from kddv.core.ddunit import DriverTest
+from kddv.core.buses import *
+from . import utils
+
+ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+logger = logging.getLogger()
+
+def search(suite, bus: str, devid: str):
+    mdrv = None
+    for t in suite:
+        if isinstance(t, unittest.TestSuite):
+            driver = search(t, bus, devid)
+            if driver:
+                if driver.device_id == devid:
+                    return driver
+                mdrv = driver
+        elif isinstance(t, DriverTest):
+            if not hasattr(t, 'bus') or not hasattr(t, 'device_id'):
+                logger.debug(f"not a driver test case: {t}")
+                continue
+            if t.bus != bus:
+                continue
+            if t.device_id == devid:
+                return t
+            if  t.driver_name == devid:
+                mdrv = t
+        else:
+            return mdrv
+
+def do_mockup_device(t):
+    mock = Mockup.create(t.bus, t)
+    try:
+        subprocess.check_output(
+            ["/sbin/modprobe", t.module_name], stderr=subprocess.STDOUT
+        )
+    except:
+        logger.warning(f"Module {t.module_name} not found")
+        sys.exit(1)
+
+    mock.load()
+    logger.warning(f"create {t.bus} device {t.device_id} success!")
+
+def do_remove_device(t):
+    mock = Mockup.create(t.bus, t)
+    try:
+        mock.unload()
+        logger.warning(f"remove {t.bus} device {t.device_id} success!")
+    except:
+        logger.warning(f"{t.bus} device {t.device_id} not found")
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--bus", "-b", type=str, required=True,
+        choices=["i2c", "spi", "pci", "platform"], help="Bus Types"
+    )
+    parser.add_argument(
+        "--devid", "-d", type=str, required=True, help="Device ID"
+    )
+    parser.add_argument(
+        "--log-level", "-l", type=str, default=None,
+        choices=utils.LOG_LEVELS, help="Log level"
+    )
+    parser.add_argument(
+        "--remove", "-r", action='store_true', default=False,
+        help="Remove device",
+    )
+    args = parser.parse_args()
+
+    if args.log_level:
+        utils.setup_logger(args.log_level)
+
+    loader = unittest.defaultTestLoader
+    suites = loader.discover(os.path.join(ROOT_DIR, 'tests'))
+    driver = search(suites, args.bus, args.devid)
+    if driver is None:
+        logger.error(f"{args.bus} device {args.devid} not support")
+        sys.exit(1)
+
+    if not args.remove:
+        do_mockup_device(driver)
+    else:
+        do_remove_device(driver)
+
+    sys.exit(0)
+
+if __name__ == "__main__":
+    main()
diff --git a/tools/testing/kddv/kddv/cmds/utils.py b/tools/testing/kddv/kddv/cmds/utils.py
new file mode 100755
index 000000000000..8130d7a57a36
--- /dev/null
+++ b/tools/testing/kddv/kddv/cmds/utils.py
@@ -0,0 +1,28 @@ 
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+#
+# Kernel device driver verification
+#
+# Copyright (C) 2022-2023 Huawei Technologies Co., Ltd
+# Author: Wei Yongjun <weiyongjun1@huawei.com>
+
+import sys
+import logging
+
+logger = logging.getLogger()
+
+LOG_FORMAT = "%(asctime)-15s [%(levelname)-7s] %(message)s"
+LOG_LEVELS = {
+    'ERROR': logging.ERROR,
+    'WARN': logging.WARN,
+    'INFO': logging.INFO,
+    'DEBUG': logging.DEBUG
+}
+
+def setup_logger(level):
+    logger.setLevel(LOG_LEVELS.get(level))
+    handler = logging.StreamHandler(sys.stdout)
+    handler.setFormatter(logging.Formatter(
+        fmt=LOG_FORMAT, datefmt="%Y-%m-%d %H:%M:%S"
+    ))
+    logger.addHandler(handler)