Esempio n. 1
0
def test_burgers_ei_results():
    from pymordemos import burgers_ei
    app = Typer()
    app.command()(burgers_ei.main)
    args = list(map(str, [1, 2, 10, 100, 10, 30]))
    _test_demo(lambda: runner.invoke(app, args, catch_exceptions=False))
    ei_results, greedy_results = burgers_ei.test_results
    ei_results['greedy_max_errs'] = greedy_results['max_errs']
    check_results('test_burgers_ei_results', args, ei_results, (1e-13, 1e-7),
                  'errors', 'triangularity_errors', 'greedy_max_errs')
Esempio n. 2
0
def test_demos(demo_args):
    module, args = demo_args
    module = import_module(module)
    if hasattr(module, 'app'):
        app = module.app
    else:
        app = Typer()
        app.command()(module.main)
    args = [str(arg) for arg in args]
    result = _test_demo(
        lambda: runner.invoke(app, args, catch_exceptions=False))
    assert result.exit_code == 0
Esempio n. 3
0
class TestHashCredentials(TestCase):
    def setUp(self) -> None:
        self.app = Typer()
        self.app.command()(hash_credentials)

        self.runner = CliRunner()

    def test_hash_credentials(self):
        result = self.runner.invoke(self.app)
        self.assertNotEqual(result.exit_code, 0)
        self.assertTrue("Error: Missing argument 'PASSWORD'." in result.stdout)

        result = self.runner.invoke(self.app, "test_password")
        self.assertEqual(result.exit_code, 0)
        # Hash is salted, therefore exact comparison is not possible
        self.assertTrue("$2b$12$" in result.stdout)
        self.assertEqual(60, len(result.stdout.strip()))
Esempio n. 4
0
def test_thermalblock_results(thermalblock_args):
    from pymordemos import thermalblock
    app = Typer()
    app.command()(thermalblock.main)
    args = [str(arg) for arg in thermalblock_args[1]]
    _test_demo(lambda: runner.invoke(app, args, catch_exceptions=False))
    results = thermalblock.test_results
    # due to the symmetry of the problem and the random test parameters, the estimated
    # error may change a lot
    # fenics varies more than others between MPI/serial
    first_tolerance = (
        1e-13, 3.5e-6) if '--fenics' in thermalblock_args[1] else (1e-13, 1e-7)
    check_results('test_thermalblock_results', thermalblock_args[1], results,
                  first_tolerance, 'basis_sizes', 'norms', 'max_norms',
                  (1e-13, 4.), 'errors', 'max_errors', 'rel_errors',
                  'max_rel_errors', 'error_estimates', 'max_error_estimates',
                  'effectivities', 'min_effectivities', 'max_effectivities',
                  'errors')
Esempio n. 5
0
from enum import Enum
from typing import Optional

from typer import Typer, Context, Option, echo, Exit

from pms import logger, __doc__, __version__
from pms.sensor import SensorReader
from pms.sensor.cli import serial, csv
from pms.service.cli import influxdb, mqtt, bridge


main = Typer(help=__doc__)
main.command()(serial)
main.command()(csv)
main.command()(influxdb)
main.command()(mqtt)
main.command()(bridge)


class Supported(str, Enum):
    PMSx003 = "PMSx003"
    PMS3003 = "PMS3003"
    PMS5003S = "PMS5003S"
    PMS5003ST = "PMS5003ST"
    PMS5003T = "PMS5003T"
    SDS01x = "SDS01x"
    SDS198 = "SDS198"
    HPMA115S0 = "HPMA115S0"
    HPMA115C0 = "HPMA115C0"
    SPS30 = "SPS30"
    MCU680 = "MCU680"
 def _helper(command_name: str, command_function: Callable):
     main_app = Typer()
     main_app.callback()(_main_callback)
     main_app.command(name=command_name)(command_function)
     return main_app
def add_legacy_compatible_commands(app: typer.Typer):
    """
    Add commands from the restructured CLI under the previous names for the commands
    to the root ``typer`` app.
    """

    # Applications
    app.command(
        name="list-applications",
        help="LIST the available applications",
    )(list_applications)
    app.command(
        name="get-application",
        help="GET an Application.",
    )(get_application)
    app.command(
        name="create-application",
        help="CREATE an Application.",
    )(create_application)
    app.command(
        name="delete-application",
        help="DELETE an Application.",
    )(delete_application)
    app.command(
        name="update-application",
        help="UPDATE an Application.",
    )(update_application)

    # Job Scripts
    app.command(
        name="list-job-scripts",
        help="LIST job scripts",
    )(list_job_scripts)
    app.command(
        name="get-job-script",
        help="GET a job script",
    )(get_job_script)
    app.command(
        name="create-job-script",
        help="CREATE a job script",
    )(create_job_script)
    app.command(
        name="update-job-script",
        help="UPDATE a job script",
    )(update_job_script)
    app.command(
        name="delete-job-script",
        help="DELETE a job script",
    )(delete_job_script)

    # Job Submissions
    app.command(
        name="list-job-submissions",
        help="LIST job submissions",
    )(list_job_submissions)
    app.command(
        name="get-job-submission",
        help="GET a job submission",
    )(get_job_submission)
    app.command(
        name="create-job-submission",
        help="CREATE a job submission",
    )(create_job_submission)
    app.command(
        name="delete-job-submission",
        help="DELETE a job submission",
    )(delete_job_submission)
Esempio n. 8
0
    )
    # Log the beginning of the experiment
    logger.info(f"Running experiment {experiment_name}")

    # Catch possible keyyboard interrupt
    try:
        logger.info(f"Launching experiment {experiment_name}")
        # Launch the experiment
        experiment.launch()
        logger.debug(f"Successful ending for experiment {experiment_name}")
        # Save the experiment
        experiment.end()
        logger.debug(f"Cleaning data for experiment {experiment_name}")
        # Clean up the experiment
        experiment.clean()
        logger.debug(f"Experiment {experiment_name} was run successfully.")
    except KeyboardInterrupt:
        logger.info(f"Stopping experiment {experiment_name} through keyboard"
                    "interrupt.")
        experiment.stop()
    except Exception as e:
        logger.critical("Encountered exception while launching experiment"
                        f"{experiment_name}: {e}")
        experiment.fail()


cli.command()(run)

if __name__ == "__main__":
    cli()
Esempio n. 9
0
from os import path

from typer import Context, Typer

from kolombo import conf
from kolombo.console import error
from kolombo.dkim import dkim_cli
from kolombo.domain import domain_cli
from kolombo.init import init
from kolombo.run import run_cli
from kolombo.stop import stop_cli
from kolombo.user import user_cli

kolombo_cli = Typer(name="kolombo", add_completion=True)
kolombo_cli.command("init")(init)
kolombo_cli.add_typer(domain_cli, name="domain")
kolombo_cli.add_typer(dkim_cli, name="dkim")
kolombo_cli.add_typer(user_cli, name="user")
kolombo_cli.add_typer(run_cli, name="run")
kolombo_cli.add_typer(stop_cli, name="stop")


@kolombo_cli.callback()
def main(ctx: Context) -> None:
    if ctx.invoked_subcommand == "init":
        return

    if not path.exists("/etc/kolombo/kolombo.conf"):
        error("Kolombo is not initialized! Run [code]kolombo init[/] first")
        exit(1)
Esempio n. 10
0
from typer import Argument, Context, Exit, Option, Typer, echo

from pms import logger
from pms.core import MessageReader, SensorReader, Supported

main = Typer(
    help=
    "Data acquisition and logging for Air Quality Sensors with UART interface")
"""
Extra cli commands from plugins

additional Typer commands are loaded from plugins (entry points) advertized as `"pypms.extras"`
"""
for ep in metadata.entry_points(group="pypms.extras"):
    main.command(name=ep.name)(ep.load())

logging.basicConfig(level=os.getenv("LEVEL", "WARNING"))


def version_callback(value: bool):  # pragma: no cover
    if not value:
        return

    package = "PyPMS"
    echo(f"{package} version {metadata.version(package)}")
    raise Exit()


@main.callback()
def callback(
Esempio n. 11
0
import os
import signal

from pyprocs import main
from typer import Typer
from typer.testing import CliRunner

app = Typer()
app.command()(main)


runner = CliRunner()


def handler(signo, frame):
    os.kill(os.getpid(), signal.SIGINT)


def test_main():
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(2)
    runner.invoke(app, ["-s", "tests/app.py"])


def test_timeout():
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(2)
    runner.invoke(app, ["-s", "--graceful-timeout", "2", "tests/timeout_app.py"])


def test_bad():
Esempio n. 12
0
__version__ = "0.9.1"
from typer import Typer

from pyrepositoryminer.commands import analyze, branch, clone, commits

app = Typer(help="Efficient Repository Mining in Python.")
app.command()(analyze)
app.command()(branch)
app.command()(clone)
app.command()(commits)

__all__ = ("app", )
Esempio n. 13
0
class TestGenerateToken(TestCase):
    mock_config_patcher = None
    mock_cobald_config_loader_patcher = None

    @classmethod
    def setUpClass(cls) -> None:
        cls.mock_config_patcher = patch("tardis.rest.app.security.Configuration")
        cls.mock_config = cls.mock_config_patcher.start()

        cls.mock_cobald_config_loader_patcher = patch(
            "tardis.rest.token_generator.generate_token.load"
        )
        cls.mock_cobald_config_loader = cls.mock_cobald_config_loader_patcher.start()

    @classmethod
    def tearDownClass(cls) -> None:
        cls.mock_config_patcher.stop()
        cls.mock_cobald_config_loader_patcher.stop()

    def setUp(self) -> None:
        self.app = Typer()
        self.app.command()(generate_token)

        self.runner = CliRunner()

        config = self.mock_config.return_value
        config.Services.restapi.secret_key = (
            "752e003f636f402cc23728e185ce8c9eef27b7e02cf509b3015f7757e625b8e4"
        )
        config.Services.restapi.algorithm = "HS256"

    @staticmethod
    def clear_lru_cache():
        get_algorithm.cache_clear()
        get_secret_key.cache_clear()

    def test_generate_token(self):
        result = self.runner.invoke(self.app)
        self.assertNotEqual(result.exit_code, 0)
        self.assertTrue("Missing option '--user-name'" in result.stdout)

        result = self.runner.invoke(self.app, ["--user-name=test"])
        self.assertEqual(result.exit_code, 1)
        self.assertTrue(
            "Either a config-file or a secret-key and algorithm needs to be specified!"
            in result.stdout
        )

        expected_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0Iiwic2NvcGVzIjpbInJlc291cmNlczpnZXQiXX0.JtjroDVX2FlHI-DFO3XErRutDjvcZwbZF4Bqx736JTc"  # noqa: B950

        result = self.runner.invoke(
            self.app,
            [
                "--user-name=test",
                "--algorithm=HS256",
                "--secret-key=752e003f636f402cc23728e185ce8c9eef27b7e02cf509b3015f7757e625b8e4",  # noqa: B950
            ],
        )
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.stdout.strip(), expected_token)

        self.clear_lru_cache()

        result = self.runner.invoke(
            self.app, ["--user-name=test", "--config-file=test.yml"]
        )

        self.mock_cobald_config_loader.assert_called_once_with("test.yml")
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.stdout.strip(), expected_token)