]> git.sur5r.net Git - u-boot/blobdiff - test/py/u_boot_utils.py
include: reset: Change to use CONFIG_IS_ENABLED(DM_RESET)
[u-boot] / test / py / u_boot_utils.py
index d71348f70e9aceb5e29a86b504c357ce1d2b78ca..bb31e57b279993e3de4055bee6d0ff6a2a8d1dd0 100644 (file)
@@ -1,16 +1,16 @@
-# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
-#
 # SPDX-License-Identifier: GPL-2.0
+# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
 
 # Utility code shared across multiple tests.
 
 import hashlib
+import inspect
 import os
 import os.path
 import pytest
 import sys
 import time
-import pytest
+import re
 
 def md5sum_data(data):
     """Calculate the MD5 hash of some data.
@@ -158,7 +158,9 @@ def run_and_log(u_boot_console, cmd, ignore_errors=False):
 
     Args:
         u_boot_console: A console connection to U-Boot.
-        cmd: The command to run, as an array of argv[].
+        cmd: The command to run, as an array of argv[], or a string.
+            If a string, note that it is split up so that quoted spaces
+            will not be preserved. E.g. "fred and" becomes ['"fred', 'and"']
         ignore_errors: Indicate whether to ignore errors. If True, the function
             will simply return if the command cannot be executed or exits with
             an error code, otherwise an exception will be raised if such
@@ -167,26 +169,15 @@ def run_and_log(u_boot_console, cmd, ignore_errors=False):
     Returns:
         The output as a string.
     """
-
+    if isinstance(cmd, str):
+        cmd = cmd.split()
     runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
     output = runner.run(cmd, ignore_errors=ignore_errors)
     runner.close()
     return output
 
-def cmd(u_boot_console, cmd_str):
-    """Run a single command string and log its output.
-
-    Args:
-        u_boot_console: A console connection to U-Boot.
-        cmd: The command to run, as a string.
-
-    Returns:
-        The output as a string.
-    """
-    return run_and_log(u_boot_console, cmd_str.split())
-
 def run_and_log_expect_exception(u_boot_console, cmd, retcode, msg):
-    """Run a command which is expected to fail.
+    """Run a command that is expected to fail.
 
     This runs a command and checks that it fails with the expected return code
     and exception method. If not, an exception is raised.
@@ -195,7 +186,7 @@ def run_and_log_expect_exception(u_boot_console, cmd, retcode, msg):
         u_boot_console: A console connection to U-Boot.
         cmd: The command to run, as an array of argv[].
         retcode: Expected non-zero return code from the command.
-        msg: String which should be contained within the command's output.
+        msg: String that should be contained within the command's output.
     """
     try:
         runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
@@ -246,3 +237,98 @@ def find_ram_base(u_boot_console):
             raise Exception('Failed to find RAM bank start in `bdinfo`')
 
     return ram_base
+
+class PersistentFileHelperCtxMgr(object):
+    """A context manager for Python's "with" statement, which ensures that any
+    generated file is deleted (and hence regenerated) if its mtime is older
+    than the mtime of the Python module which generated it, and gets an mtime
+    newer than the mtime of the Python module which generated after it is
+    generated. Objects of this type should be created by factory function
+    persistent_file_helper rather than directly."""
+
+    def __init__(self, log, filename):
+        """Initialize a new object.
+
+        Args:
+            log: The Logfile object to log to.
+            filename: The filename of the generated file.
+
+        Returns:
+            Nothing.
+        """
+
+        self.log = log
+        self.filename = filename
+
+    def __enter__(self):
+        frame = inspect.stack()[1]
+        module = inspect.getmodule(frame[0])
+        self.module_filename = module.__file__
+        self.module_timestamp = os.path.getmtime(self.module_filename)
+
+        if os.path.exists(self.filename):
+            filename_timestamp = os.path.getmtime(self.filename)
+            if filename_timestamp < self.module_timestamp:
+                self.log.action('Removing stale generated file ' +
+                    self.filename)
+                os.unlink(self.filename)
+
+    def __exit__(self, extype, value, traceback):
+        if extype:
+            try:
+                os.path.unlink(self.filename)
+            except:
+                pass
+            return
+        logged = False
+        for i in range(20):
+            filename_timestamp = os.path.getmtime(self.filename)
+            if filename_timestamp > self.module_timestamp:
+                break
+            if not logged:
+                self.log.action(
+                    'Waiting for generated file timestamp to increase')
+                logged = True
+            os.utime(self.filename)
+            time.sleep(0.1)
+
+def persistent_file_helper(u_boot_log, filename):
+    """Manage the timestamps and regeneration of a persistent generated
+    file. This function creates a context manager for Python's "with"
+    statement
+
+    Usage:
+        with persistent_file_helper(u_boot_console.log, filename):
+            code to generate the file, if it's missing.
+
+    Args:
+        u_boot_log: u_boot_console.log.
+        filename: The filename of the generated file.
+
+    Returns:
+        A context manager object.
+    """
+
+    return PersistentFileHelperCtxMgr(u_boot_log, filename)
+
+def crc32(u_boot_console, address, count):
+    """Helper function used to compute the CRC32 value of a section of RAM.
+
+    Args:
+        u_boot_console: A U-Boot console connection.
+        address: Address where data starts.
+        count: Amount of data to use for calculation.
+
+    Returns:
+        CRC32 value
+    """
+
+    bcfg = u_boot_console.config.buildconfig
+    has_cmd_crc32 = bcfg.get('config_cmd_crc32', 'n') == 'y'
+    assert has_cmd_crc32, 'Cannot compute crc32 without CONFIG_CMD_CRC32.'
+    output = u_boot_console.run_command('crc32 %08x %x' % (address, count))
+
+    m = re.search('==> ([0-9a-fA-F]{8})$', output)
+    assert m, 'CRC32 operation failed.'
+
+    return m.group(1)