From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mails.dpdk.org (mails.dpdk.org [217.70.189.124]) by inbox.dpdk.org (Postfix) with ESMTP id 68F5443DF8; Thu, 4 Apr 2024 11:25:56 +0200 (CEST) Received: from mails.dpdk.org (localhost [127.0.0.1]) by mails.dpdk.org (Postfix) with ESMTP id F15E440268; Thu, 4 Apr 2024 11:25:55 +0200 (CEST) Received: from mail-ed1-f51.google.com (mail-ed1-f51.google.com [209.85.208.51]) by mails.dpdk.org (Postfix) with ESMTP id 26D174025D for ; Thu, 4 Apr 2024 11:25:55 +0200 (CEST) Received: by mail-ed1-f51.google.com with SMTP id 4fb4d7f45d1cf-56b0af675deso800387a12.1 for ; Thu, 04 Apr 2024 02:25:55 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=pantheon.tech; s=google; t=1712222755; x=1712827555; darn=dpdk.org; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:from:to:cc:subject:date :message-id:reply-to; bh=pIwjo64W5nxcBudAbGUv7YkXkA6t7vBHEGu/1Z0CObY=; b=Zc28CUzsULdODFgFExEso/TgZGDjUFEp9jhdslOJotc4+U8/aSQie1szV2bVjOQ/NX kDj6e5hDEtMlLyoa1CG34utqdHIiv9hqJFpvFi2HmBVJ7TJJTh4m3YKNB87dUpkdz/KF jY6W12MQoj0SaQjYzQSNNQ35iUvcYVJ1yReyywqIYZjzHuCRR9LCzCWYY93U5T1QXIdE QLj5wVJ+33woDbpnj3ZL1ZlpGbpclmV7wES9hDZJZpvpCeIwyVNpT1B8FemhboZwlmZm 15Fvcv/jY7ZkRgiCcaq0Pp9gxzXlWqSyEAxhUtvbhevIqLmvNFZwRU3mRu4+H4Duxi9L uTgA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1712222755; x=1712827555; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=pIwjo64W5nxcBudAbGUv7YkXkA6t7vBHEGu/1Z0CObY=; b=WDPDVbhQK+IsoPfuxa+vCIs0p+U2habiNjhzLNn+J7WCjruOgy2CxKHLJcLvZQ0zuR P7KGENPe0+chc0m0droy/bhdIyhIhGEX5EPRUPepWZ5AFfU8xQ8RHnfvgif/3qPcaZTf t4FY2mhe5xsiHhBIsSvhgz3UIZyLbNvpuqICXK90WN/YLweVdnslJxznSDKhv7T5rQLp veSgnfS+SA/RVDbPOeKNOqbZ8DnmK8/ikdtRo+0TKa9dHfxowKoaUbyCsMG5we6OYSUb DJOe2XfrI4pA7JjrpBVD7f6YxvMCrP8gazN/yq85yN5afmzncRx7t0zKJEIarly3LisP Bd3Q== X-Gm-Message-State: AOJu0YzpgBqM4p+uK8qPFlt/vG9aylpmfTbNRsPBwliab0/75GGQAqrU 9fHCGovsXF1kQqrCgaYIhzTprsLJBkUEb+HHaXAXDxa1kLaabE+LeHJnimYjIfNZvf3jwWJo2fE NBUCFYR+DPJGYRPPIzdeYgHWAZF+xI7O2bl//Uw== X-Google-Smtp-Source: AGHT+IEZ0QM+AkBxc6NyQjN7Nc12QoWkH1XMS8txBQLk+nI8IrDel4AuN7CaDM06fQXdc8x3i90krLx3OI0GK4VnM0I= X-Received: by 2002:a17:906:29d9:b0:a4a:35bc:2588 with SMTP id y25-20020a17090629d900b00a4a35bc2588mr1325400eje.43.1712222754315; Thu, 04 Apr 2024 02:25:54 -0700 (PDT) MIME-Version: 1.0 References: <20240122182611.1904974-1-luca.vizzarro@arm.com> <20240318171704.798634-1-luca.vizzarro@arm.com> <20240318171704.798634-2-luca.vizzarro@arm.com> In-Reply-To: <20240318171704.798634-2-luca.vizzarro@arm.com> From: =?UTF-8?Q?Juraj_Linke=C5=A1?= Date: Thu, 4 Apr 2024 11:25:43 +0200 Message-ID: Subject: Re: [PATCH v2 1/3] dts: rework arguments framework To: Luca Vizzarro Cc: dev@dpdk.org, Paul Szczepanek , Jack Bond-Preston Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable X-BeenThere: dev@dpdk.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: DPDK patches and discussions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: dev-bounces@dpdk.org On Mon, Mar 18, 2024 at 6:17=E2=80=AFPM Luca Vizzarro wrote: > > The existing argument handling in the code relies on basic argparse > functionality and a custom argparse action to integrate environment > variables. This commit improves the current handling by augmenting > argparse through a custom implementation of the arguments. > > This rework implements the following improvements: > - There are duplicate expressions scattered throughout the code. To > improve readability and maintainability, these are refactored > into list/dict comprehensions or factory functions. > - Arguments are augmented with their own class allowing for more > flexibility, enabling manipulation while reducing redundancy. > - Arguments are grouped within a new class. This class would > track the origin of each argument, ensuring consistent input > handling and facilitating debugging. > - Instead of relying solely on argument flags, error messages now > accurately reference environment variables when applicable, enhancing > user experience. For instance: > > error: environment variable DTS_DPDK_TARBALL: Invalid file > > - Knowing the number of environment variables and arguments set > allow for a useful help page display when none are provided. > - A display of which environment variables have been detected and their > corresponding values in the help page, aiding user awareness. > Judging from the code, this patch seems like a convoluted way to implement: 1. An association between an Argument and the corresponding environment variable, 2. A better way to add the env vars names to the help message of each argument as well as adding the current value if set, 3. A better error message where we replace argument names with env var names for args where env vars are used. But maybe there's more. In any case, isn't there a simpler way to implement the above? I originally thought extending something in the argparse module (like the add_argument methods in ArgumentParser and _MutuallyExclusiveGroup), but that doesn't seem as simple as maybe just augmenting the actions that are returned with the add_argument methods (maybe we could subclass ArgumentParser and add some method for this, such as add_dts_argument?), where we could just add the env_var_name (and maybe arg_name if needed) and modify the help message the same way we do now (modifying the self._action.help attribute). This should also be enough for 3, but even if not, we could store what we need in the subclass. Also, what seems to be missing is the modification of actual values of SETTING with the env var values (this could be done somewhere in the add_dts_argument method). But overall I like this approach as it gives us the knowledge of whether an env var was used or not. I have some comments that illustrate why I think the patch is a bit convoluted. > Signed-off-by: Luca Vizzarro > Reviewed-by: Paul Szczepanek > Reviewed-by: Jack Bond-Preston > --- > doc/guides/tools/dts.rst | 53 +++-- > dts/framework/settings.py | 393 ++++++++++++++++++++++++++++---------- > 2 files changed, 324 insertions(+), 122 deletions(-) > > diff --git a/doc/guides/tools/dts.rst b/doc/guides/tools/dts.rst > index 47b218b2c6..6993443389 100644 > --- a/doc/guides/tools/dts.rst > +++ b/doc/guides/tools/dts.rst > @@ -215,30 +215,41 @@ DTS is run with ``main.py`` located in the ``dts`` = directory after entering Poet > .. code-block:: console > > (dts-py3.10) $ ./main.py --help > - usage: main.py [-h] [--config-file CONFIG_FILE] [--output-dir OUTPUT_= DIR] [-t TIMEOUT] [-v] [-s] [--tarball TARBALL] [--compile-timeout COMPILE_= TIMEOUT] [--test-suite TEST_SUITE [TEST_CASES ...]] [--re-run RE_RUN] > + usage: main.py [-h] [--config-file FILE_PATH] [--output-dir DIR_PATH]= [-t SECONDS] [-v] [-s] [--tarball FILE_PATH] > + [--compile-timeout SECONDS] [--test-suite TEST_SUITE [= TEST_CASES ...]] [--re-run N_TIMES] > > - Run DPDK test suites. All options may be specified with the environme= nt variables provided in brackets. Command line arguments have higher prior= ity. > + Run DPDK test suites. All options may be specified with the environme= nt variables provided in brackets. Command > + line arguments have higher priority. > > options: > - -h, --help show this help message and exit > - --config-file CONFIG_FILE > - [DTS_CFG_FILE] The configuration file that desc= ribes the test cases, SUTs and targets. (default: ./conf.yaml) > - --output-dir OUTPUT_DIR, --output OUTPUT_DIR > - [DTS_OUTPUT_DIR] Output directory where DTS log= s and results are saved. (default: output) > - -t TIMEOUT, --timeout TIMEOUT > - [DTS_TIMEOUT] The default timeout for all DTS o= perations except for compiling DPDK. (default: 15) > - -v, --verbose [DTS_VERBOSE] Specify to enable verbose output,= logging all messages to the console. (default: False) > - -s, --skip-setup [DTS_SKIP_SETUP] Specify to skip all setup step= s on SUT and TG nodes. (default: False) > - --tarball TARBALL, --snapshot TARBALL, --git-ref TARBALL > - [DTS_DPDK_TARBALL] Path to DPDK source code tar= ball or a git commit ID, tag ID or tree ID to test. To test local changes, = first commit them, then use the commit ID with this option. (default: dpdk.= tar.xz) > - --compile-timeout COMPILE_TIMEOUT > - [DTS_COMPILE_TIMEOUT] The timeout for compiling= DPDK. (default: 1200) > - --test-suite TEST_SUITE [TEST_CASES ...] > - [DTS_TEST_SUITES] A list containing a test suit= e with test cases. The first parameter is the test suite name, and the rest= are test case names, which are optional. May be specified multiple times. = To specify multiple test suites in the environment > - variable, join the lists with a comma. Examples= : --test-suite suite case case --test-suite suite case ... | DTS_TEST_SUITE= S=3D'suite case case, suite case, ...' | --test-suite suite --test-suite su= ite case ... | DTS_TEST_SUITES=3D'suite, suite case, ...' > - (default: []) > - --re-run RE_RUN, --re_run RE_RUN > - [DTS_RERUN] Re-run each test case the specified= number of times if a test failure occurs. (default: 0) > + -h, --help show this help message and exit > + --config-file FILE_PATH > + [DTS_CFG_FILE] The configuration file that de= scribes the test cases, SUTs and targets. > + (default: conf.yaml) > + --output-dir DIR_PATH, --output DIR_PATH > + [DTS_OUTPUT_DIR] Output directory where DTS l= ogs and results are saved. (default: output) > + -t SECONDS, --timeout SECONDS > + [DTS_TIMEOUT] The default timeout for all DTS= operations except for compiling DPDK. > + (default: 15) > + -v, --verbose [DTS_VERBOSE] Specify to enable verbose outpu= t, logging all messages to the console. > + (default: False) > + -s, --skip-setup [DTS_SKIP_SETUP] Specify to skip all setup st= eps on SUT and TG nodes. (default: False) > + --tarball FILE_PATH, --snapshot FILE_PATH, --git-ref FILE_PATH > + [DTS_DPDK_TARBALL] Path to DPDK source code t= arball or a git commit ID,tag ID or tree ID to > + test. To test local changes, first commit the= m, then use the commit ID with this option. > + (default: dpdk.tar.xz) > + --compile-timeout SECONDS > + [DTS_COMPILE_TIMEOUT] The timeout for compili= ng DPDK. (default: 1200) > + --test-suite TEST_SUITE [TEST_CASES ...] > + [DTS_TEST_SUITES] A list containing a test su= ite with test cases. The first parameter is > + the test suite name, and the rest are test ca= se names, which are optional. May be specified > + multiple times. To specify multiple test suit= es in the environment variable, join the lists > + with a comma. Examples: --test-suite SUITE1 C= ASE1 CASE2 --test-suite SUITE2 CASE1 ... | > + DTS_TEST_SUITES=3D'SUITE1 CASE1 CASE2, SUITE2= CASE1, ...' | --test-suite SUITE1 --test-suite SUITE2 > + CASE1 ... | DTS_TEST_SUITES=3D'SUITE1, SUITE2= CASE1, ...' (default: []) > + --re-run N_TIMES, --re_run N_TIMES > + [DTS_RERUN] Re-run each test case the specifi= ed number of times if a test failure occurs. > + (default: 0) > > > The brackets contain the names of environment variables that set the sam= e thing. > diff --git a/dts/framework/settings.py b/dts/framework/settings.py > index 688e8679a7..421a9cb15b 100644 > --- a/dts/framework/settings.py > +++ b/dts/framework/settings.py > @@ -2,6 +2,7 @@ > # Copyright(c) 2010-2021 Intel Corporation > # Copyright(c) 2022-2023 PANTHEON.tech s.r.o. > # Copyright(c) 2022 University of New Hampshire > +# Copyright(c) 2024 Arm Limited > > """Environment variables and command line arguments parsing. > > @@ -62,6 +63,7 @@ > The module provides one key module-level variable: > > Attributes: > + ARGS: The module level variable storing the state of the DTS argumen= ts. > SETTINGS: The module level variable storing framework-wide DTS setti= ngs. > > Typical usage example:: > @@ -72,14 +74,30 @@ > > import argparse > import os > +import sys > from dataclasses import dataclass, field > from pathlib import Path > -from typing import Any > +from typing import Any, Generator, NamedTuple > > from .config import TestSuiteConfig > from .utils import DPDKGitTarball > > > +#: The prefix to be added to all of the environment variables. > +ENV_PREFIX =3D "DTS_" > + > + > +DPDK_TARBALL_PATH_ARGUMENT_NAME =3D "dpdk_tarball_path" > +CONFIG_FILE_ARGUMENT_NAME =3D "config_file" > +OUTPUT_DIR_ARGUMENT_NAME =3D "output_dir" > +TIMEOUT_ARGUMENT_NAME =3D "timeout" > +VERBOSE_ARGUMENT_NAME =3D "verbose" > +SKIP_SETUP_ARGUMENT_NAME =3D "skip_setup" > +COMPILE_TIMEOUT_ARGUMENT_NAME =3D "compile_timeout" > +TEST_SUITES_ARGUMENT_NAME =3D "test_suites" > +RERUN_ARGUMENT_NAME =3D "re_run" > + > + > @dataclass(slots=3DTrue) > class Settings: > """Default framework-wide user settings. > @@ -110,126 +128,296 @@ class Settings: > SETTINGS: Settings =3D Settings() > > > -def _get_parser() -> argparse.ArgumentParser: > - """Create the argument parser for DTS. > +class ArgumentEnvPair(NamedTuple): > + """A named tuple pairing the argument identifiers with its environme= nt variable.""" > > - Command line options take precedence over environment variables, whi= ch in turn take precedence > - over default values. > + #: The argument name. > + arg_name: str > > - Returns: > - argparse.ArgumentParser: The configured argument parser with def= ined options. > - """ > + #: The argument's associated environment variable name. > + env_var_name: str > + > + #: The argument's associated :class:`argparse.Action` name. > + action_name: str | None > + > + > +@dataclass > +class Argument: > + """A class representing a DTS argument.""" > + > + #: The identifying name of the argument. > + #: It also translates into the corresponding :class:`Settings` attri= bute. > + name: str > + > + #: A list of flags to pass to :meth:`argparse.ArgumentParser.add_arg= ument`. > + flags: tuple[str, ...] > + > + #: Any other keyword arguments to pass to :meth:`argparse.ArgumentPa= rser.add_argument`. > + kwargs: dict[str, Any] > + > + #: The corresponding environment variable name. > + #: It is prefixed with the value stored in `ENV_PREFIX`. > + #: If not specified, it is automatically generated from the :attr:`~= name`. > + env_var_name: str > + > + _from_env: bool =3D False > + > + #: A reference to its corresponding :class:`argparse.Action`. > + _action: argparse.Action | None =3D None > + > + def __init__(self, name: str, *flags: str, env_var_name: str | None = =3D None, **kwargs: Any): > + """Class constructor. > + > + If the `help` argument is passed, this is prefixed with the > + argument's corresponding environment variable in square brackets= .""" > + > + self.name =3D name > + self.flags =3D flags > + self.kwargs =3D kwargs > + self.env_var_name =3D self._make_env_var(env_var_name) > + > + if "help" in self.kwargs: > + self.kwargs["help"] =3D f"[{self.env_var_name}] {self.kwargs= ['help']}" > + > + def add_to(self, parser: argparse._ActionsContainer): > + """Adds this argument to an :class:`argparse.ArgumentParser` ins= tance.""" > + self._action =3D parser.add_argument(*self.flags, dest=3Dself.na= me, **self.kwargs) > + > + def _make_env_var(self, env_var_name: str | None) -> str: > + """Make the environment variable name.""" > + return f"{ENV_PREFIX}{env_var_name or self.name.upper()}" > + > + def get_env_var(self) -> str | None: > + """Get environment variable if it was supplied instead of a comm= and line flag.""" > + > + env_var_value =3D os.environ.get(self.env_var_name) > > - def env_arg(env_var: str, default: Any) -> Any: > - """A helper function augmenting the argparse with environment va= riables. > + if env_var_value: > + # check if the user has supplied any of this argument's flag= s in the command line > + for flag in self.flags: > + if flag in sys.argv: > + return None > > - If the supplied environment variable is defined, then the defaul= t value > - of the argument is modified. This satisfies the priority order o= f > - command line argument > environment variable > default value. > + return env_var_value > > - Args: > - env_var: Environment variable name. > - default: Default value. > + @property > + def from_env(self) -> bool: > + """Indicates if the argument value originated from the environme= nt.""" > + return self._from_env > > - Returns: > - Environment variable or default value. > + def inject_env_var(self, env_value: str) -> ArgumentEnvPair: > + """Injects the environment variable as a program argument. > + > + Injects this argument's flag with the supplied environment varia= ble's value and > + returns an :class:`ArgumentEnvPair` object pairing this argument= to its environment > + variable and :class:`argparse.Action`. > + > + The help notice of the argument is updated to display that the e= nvironment variable > + has been correctly picked up by showing its recorded value. > + > + .. note:: This method **must** be called after the argument has = been added to the parser. > """ > - return os.environ.get(env_var) or default > > - parser =3D argparse.ArgumentParser( > - description=3D"Run DPDK test suites. All options may be specifie= d with the environment " > - "variables provided in brackets. Command line arguments have hig= her priority.", > - formatter_class=3Dargparse.ArgumentDefaultsHelpFormatter, > - ) > + assert self._action is not None > + > + sys.argv[1:0] =3D [self.flags[0], env_value] > + > + self._from_env =3D True > + > + if "help" in self.kwargs: > + self.kwargs["help"] =3D f"{self.kwargs['help']} (env value: = {env_value})" > + else: > + self.kwargs["help"] =3D f"(env value: {env_value})" > + > + self._action.help =3D self.kwargs["help"] > + > + return ArgumentEnvPair( > + arg_name=3Dself.name, > + env_var_name=3Dself.env_var_name, > + action_name=3Dargparse._get_action_name(self._action), > + ) > + > + > +@dataclass > +class ArgumentGroup: > + """A class grouping all the instances of :class:`Argument`. > + > + This class provides indexing to access an :class:`Argument` by name: > + > + >>> args["dpdk_revision_id"].env_var_name > + DTS_DPDK_REVISION_ID > + > + And can be iterated to access all the arguments: > + > + >>> arg_env_vars =3D [arg.env_var_name for arg in args] > + ['DPDK_TARBALL', ..] > + """ > + > + #: The arguments values as parsed by :class:`argparse.ArgumentParse`= . > + values: argparse.Namespace > + > + #: A dictionary pairing argument names to :class:`Argument` instance= s. > + _args: dict[str, Argument] > + > + #: A list of :class:`ArgumentEnvPair` containing all the successfull= y injected environment variables. > + _env_vars: list[ArgumentEnvPair] > + > + def __init__(self, *args: Argument): > + self._args =3D {arg.name: arg for arg in args} > + self._env_vars =3D [] > + > + def __getitem__(self, arg_name: str) -> Argument: > + return self._args.__getitem__(arg_name) Looking at this, this class could've been just a subclassed dict. We could set the attributes with setattr in __init__(). But at that point, it looks to be the same as the namespace returned by parser.parse_args(), apart from the environment_fed_arguments property (more below), which we could do without. > > - parser.add_argument( > + def __iter__(self) -> Generator[Argument, None, None]: > + yield from self._args.values() > + > + def add_environment_fed_argument(self, env_pair: ArgumentEnvPair): > + """Add an injected environment variable.""" > + self._env_vars.append(env_pair) > + We're already storing the arguments in the class, so we could just add whatever is in ArgumentEnvPair to the argument and we have the correspondence (looking at the Argument class again, we already have that). The pair class seems redundant. > + @property > + def environment_fed_arguments(self) -> list[ArgumentEnvPair]: > + """Returns the list of all the successfully injected environment= variables.""" > + return self._env_vars > + And then we could get all of this from the stored arguments. Could be just a tuple of (var_name, arg_name) of args with from_env =3D=3D True. > + > +ARGS =3D ArgumentGroup( > + Argument( > + CONFIG_FILE_ARGUMENT_NAME, > "--config-file", > - default=3Denv_arg("DTS_CFG_FILE", SETTINGS.config_file_path), > + default=3DSETTINGS.config_file_path, > type=3DPath, > - help=3D"[DTS_CFG_FILE] The configuration file that describes the= test cases, " > - "SUTs and targets.", > - ) > - > - parser.add_argument( > + help=3D"The configuration file that describes the test cases, SU= Ts and targets.", > + metavar=3D"FILE_PATH", > + env_var_name=3D"CFG_FILE", > + ), > + Argument( > + OUTPUT_DIR_ARGUMENT_NAME, > "--output-dir", > "--output", > - default=3Denv_arg("DTS_OUTPUT_DIR", SETTINGS.output_dir), > - help=3D"[DTS_OUTPUT_DIR] Output directory where DTS logs and res= ults are saved.", > - ) > - > - parser.add_argument( > + default=3DSETTINGS.output_dir, > + help=3D"Output directory where DTS logs and results are saved.", > + metavar=3D"DIR_PATH", > + ), > + Argument( > + TIMEOUT_ARGUMENT_NAME, > "-t", > "--timeout", > - default=3Denv_arg("DTS_TIMEOUT", SETTINGS.timeout), > + default=3DSETTINGS.timeout, > type=3Dfloat, > - help=3D"[DTS_TIMEOUT] The default timeout for all DTS operations= except for compiling DPDK.", > - ) > - > - parser.add_argument( > + help=3D"The default timeout for all DTS operations except for co= mpiling DPDK.", > + metavar=3D"SECONDS", > + ), > + Argument( > + VERBOSE_ARGUMENT_NAME, > "-v", > "--verbose", > action=3D"store_true", > - default=3Denv_arg("DTS_VERBOSE", SETTINGS.verbose), > - help=3D"[DTS_VERBOSE] Specify to enable verbose output, logging = all messages " > - "to the console.", > - ) > - > - parser.add_argument( > + help=3D"Specify to enable verbose output, logging all messages "= "to the console.", > + ), > + Argument( > + SKIP_SETUP_ARGUMENT_NAME, > "-s", > "--skip-setup", > action=3D"store_true", > - default=3Denv_arg("DTS_SKIP_SETUP", SETTINGS.skip_setup), > - help=3D"[DTS_SKIP_SETUP] Specify to skip all setup steps on SUT = and TG nodes.", > - ) > - > - parser.add_argument( > + help=3D"Specify to skip all setup steps on SUT and TG nodes.", > + ), > + Argument( > + DPDK_TARBALL_PATH_ARGUMENT_NAME, > "--tarball", > "--snapshot", > "--git-ref", > - default=3Denv_arg("DTS_DPDK_TARBALL", SETTINGS.dpdk_tarball_path= ), > type=3DPath, > - help=3D"[DTS_DPDK_TARBALL] Path to DPDK source code tarball or a= git commit ID, " > + default=3DSETTINGS.dpdk_tarball_path, > + help=3D"Path to DPDK source code tarball or a git commit ID," > "tag ID or tree ID to test. To test local changes, first commit = them, " > "then use the commit ID with this option.", > - ) > - > - parser.add_argument( > + metavar=3D"FILE_PATH", > + env_var_name=3D"DPDK_TARBALL", > + ), > + Argument( > + COMPILE_TIMEOUT_ARGUMENT_NAME, > "--compile-timeout", > - default=3Denv_arg("DTS_COMPILE_TIMEOUT", SETTINGS.compile_timeou= t), > + default=3DSETTINGS.compile_timeout, > type=3Dfloat, > - help=3D"[DTS_COMPILE_TIMEOUT] The timeout for compiling DPDK.", > - ) > - > - parser.add_argument( > + help=3D"The timeout for compiling DPDK.", > + metavar=3D"SECONDS", > + ), > + Argument( > + TEST_SUITES_ARGUMENT_NAME, > "--test-suite", > action=3D"append", > nargs=3D"+", > - metavar=3D("TEST_SUITE", "TEST_CASES"), > - default=3Denv_arg("DTS_TEST_SUITES", SETTINGS.test_suites), > - help=3D"[DTS_TEST_SUITES] A list containing a test suite with te= st cases. " > + default=3DSETTINGS.test_suites, > + help=3D"A list containing a test suite with test cases. " > "The first parameter is the test suite name, and the rest are te= st case names, " > "which are optional. May be specified multiple times. To specify= multiple test suites in " > "the environment variable, join the lists with a comma. " > "Examples: " > - "--test-suite suite case case --test-suite suite case ... | " > - "DTS_TEST_SUITES=3D'suite case case, suite case, ...' | " > - "--test-suite suite --test-suite suite case ... | " > - "DTS_TEST_SUITES=3D'suite, suite case, ...'", > - ) > - > - parser.add_argument( > + "--test-suite SUITE1 CASE1 CASE2 --test-suite SUITE2 CASE1 ... |= " > + "DTS_TEST_SUITES=3D'SUITE1 CASE1 CASE2, SUITE2 CASE1, ...' | " > + "--test-suite SUITE1 --test-suite SUITE2 CASE1 ... | " > + "DTS_TEST_SUITES=3D'SUITE1, SUITE2 CASE1, ...'", > + metavar=3D("TEST_SUITE", "TEST_CASES"), > + ), > + Argument( > + RERUN_ARGUMENT_NAME, > "--re-run", > "--re_run", > - default=3Denv_arg("DTS_RERUN", SETTINGS.re_run), > + default=3DSETTINGS.re_run, > type=3Dint, > - help=3D"[DTS_RERUN] Re-run each test case the specified number o= f times " > - "if a test failure occurs.", > + help=3D"Re-run each test case the specified number of times if a= test failure occurs.", > + env_var_name=3D"RERUN", > + metavar=3D"N_TIMES", > + ), > +) > + > + > +class ArgumentParser(argparse.ArgumentParser): > + """ArgumentParser with a custom error message. > + > + This custom version of ArgumentParser changes the error message to > + accurately reflect its origin if an environment variable is used > + as an argument. > + > + Instead of printing usage on every error, it prints instructions > + on how to do it. > + """ > + > + def error(self, message): > + for _, env_var_name, action_name in ARGS.environment_fed_argumen= ts: > + message =3D message.replace( > + f"argument {action_name}", f"environment variable {env_v= ar_name}" > + ) I think this should also contain the env var value to be consistent with the help message. > + > + print(f"{self.prog}: error: {message}\n", file=3Dsys.stderr) > + self.exit(2, "For help and usage, " "run the command with the --= help flag.\n") > + > + > +def _get_parser() -> ArgumentParser: > + """Create the argument parser for DTS. > + > + Command line options take precedence over environment variables, whi= ch in turn take precedence > + over default values. > + > + Returns: > + ArgumentParser: The configured argument parser with defined opti= ons. > + """ > + > + parser =3D ArgumentParser( > + description=3D"Run DPDK test suites. All options may be specifie= d with the environment " > + "variables provided in brackets. Command line arguments have hig= her priority.", > + formatter_class=3Dargparse.ArgumentDefaultsHelpFormatter, > + allow_abbrev=3DFalse, > ) > + for arg in ARGS: > + arg.add_to(parser) > > return parser > > > -def _process_test_suites(args: str | list[list[str]]) -> list[TestSuiteC= onfig]: > +def _process_test_suites(args: list[list[str]]) -> list[TestSuiteConfig]= : > """Process the given argument to a list of :class:`TestSuiteConfig` = to execute. > > Args: > @@ -240,17 +428,11 @@ def _process_test_suites(args: str | list[list[str]= ]) -> list[TestSuiteConfig]: > Returns: > A list of test suite configurations to execute. > """ > - if isinstance(args, str): > - # Environment variable in the form of "suite case case, suite ca= se, suite, ..." > - args =3D [suite_with_cases.split() for suite_with_cases in args.= split(",")] > - > - test_suites_to_run =3D [] > - for suite_with_cases in args: > - test_suites_to_run.append( > - TestSuiteConfig(test_suite=3Dsuite_with_cases[0], test_cases= =3Dsuite_with_cases[1:]) > - ) > + if ARGS[TEST_SUITES_ARGUMENT_NAME].from_env: > + # Environment variable in the form of "SUITE1 CASE1 CASE2, SUITE= 2 CASE1, SUITE3, ..." > + args =3D [suite_with_cases.split() for suite_with_cases in args[= 0][0].split(",")] > > - return test_suites_to_run > + return [TestSuiteConfig(test_suite, test_cases) for [test_suite, *te= st_cases] in args] > > > def get_settings() -> Settings: > @@ -261,19 +443,28 @@ def get_settings() -> Settings: > Returns: > The new settings object. > """ > - parsed_args =3D _get_parser().parse_args() > - return Settings( > - config_file_path=3Dparsed_args.config_file, > - output_dir=3Dparsed_args.output_dir, > - timeout=3Dparsed_args.timeout, > - verbose=3Dparsed_args.verbose, > - skip_setup=3Dparsed_args.skip_setup, > - dpdk_tarball_path=3DPath( > - Path(DPDKGitTarball(parsed_args.tarball, parsed_args.output_= dir)) > - if not os.path.exists(parsed_args.tarball) > - else Path(parsed_args.tarball) > - ), > - compile_timeout=3Dparsed_args.compile_timeout, > - test_suites=3D_process_test_suites(parsed_args.test_suite), > - re_run=3Dparsed_args.re_run, > + > + parser =3D _get_parser() > + > + for arg in ARGS: > + env_value =3D arg.get_env_var() > + if env_value: > + env_pair =3D arg.inject_env_var(env_value) > + ARGS.add_environment_fed_argument(env_pair) We're going through all of the args here so we could just do this when creating the argument. I guess we'd need to modify the top-level error message afterwards with the current class structure, but I'm sure even that could be done when creating the argument with some refactoring. > + > + if len(sys.argv) =3D=3D 1: > + parser.print_help() > + sys.exit(1) > + > + ARGS.values =3D parser.parse_args() > + The values attribute seems superfluous as we're only using it locally. > + ARGS.values.dpdk_tarball_path =3D Path( > + Path(DPDKGitTarball(ARGS.values.dpdk_tarball_path, ARGS.values.o= utput_dir)) > + if not os.path.exists(ARGS.values.dpdk_tarball_path) > + else Path(ARGS.values.dpdk_tarball_path) > ) > + > + ARGS.values.test_suites =3D _process_test_suites(ARGS.values.test_su= ites) > + > + kwargs =3D {k: v for k, v in vars(ARGS.values).items() if hasattr(SE= TTINGS, k)} This is here so that we don't use both arguments from the mutual group, right? We could add a short comment explaining this. Also, I think we don't need to use vars() here, the result should be the sa= me. > + return Settings(**kwargs) > -- > 2.34.1 >