|
| 1 | +import sys |
| 2 | +import traceback |
| 3 | +from multiprocessing import set_start_method |
| 4 | + |
| 5 | +from avocado.core.nrunner.app import BaseRunnerApp |
| 6 | +from avocado.core.nrunner.runner import BaseRunner |
| 7 | +from avocado.core.utils import messages |
| 8 | +from avocado.utils import process |
| 9 | + |
| 10 | + |
| 11 | +class PipRunner(BaseRunner): |
| 12 | + """Runner for dependencies of type pip |
| 13 | +
|
| 14 | + This runner handles, the installation, verification and removal of |
| 15 | + packages using the pip. |
| 16 | +
|
| 17 | + Runnable attributes usage: |
| 18 | +
|
| 19 | + * kind: 'pip' |
| 20 | +
|
| 21 | + * uri: not used |
| 22 | +
|
| 23 | + * args: not used |
| 24 | +
|
| 25 | + * kwargs: |
| 26 | + - name: the package name (required) |
| 27 | + - action: one of 'install' or 'uninstall' (optional, defaults |
| 28 | + to 'install') |
| 29 | + """ |
| 30 | + |
| 31 | + name = "pip" |
| 32 | + description = "Runner for dependencies of type pip" |
| 33 | + |
| 34 | + def run(self, runnable): |
| 35 | + try: |
| 36 | + yield messages.StartedMessage.get() |
| 37 | + # check if there is a valid 'action' argument |
| 38 | + cmd = runnable.kwargs.get("action", "install") |
| 39 | + # avoid invalid arguments |
| 40 | + if cmd not in ["install", "uninstall"]: |
| 41 | + stderr = f"Invalid action {cmd}. Use one of 'install' or 'remove'" |
| 42 | + yield messages.StderrMessage.get(stderr.encode()) |
| 43 | + yield messages.FinishedMessage.get("error") |
| 44 | + return |
| 45 | + |
| 46 | + package = runnable.kwargs.get("name") |
| 47 | + # if package was passed correctly, run python -m pip |
| 48 | + if package is not None: |
| 49 | + try: |
| 50 | + cmd = f"python3 -m ensurepip && python3 -m pip {cmd} {package}" |
| 51 | + result = process.run(cmd, shell=True) |
| 52 | + except Exception as e: |
| 53 | + yield messages.StderrMessage.get(str(e)) |
| 54 | + yield messages.FinishedMessage.get("error") |
| 55 | + return |
| 56 | + |
| 57 | + yield messages.StdoutMessage.get(result.stdout) |
| 58 | + yield messages.StderrMessage.get(result.stderr) |
| 59 | + yield messages.FinishedMessage.get("pass") |
| 60 | + except Exception as e: |
| 61 | + yield messages.StderrMessage.get(traceback.format_exc()) |
| 62 | + yield messages.FinishedMessage.get( |
| 63 | + "error", |
| 64 | + fail_reason=str(e), |
| 65 | + fail_class=e.__class__.__name__, |
| 66 | + traceback=traceback.format_exc(), |
| 67 | + ) |
| 68 | + |
| 69 | + |
| 70 | +class RunnerApp(BaseRunnerApp): |
| 71 | + PROG_NAME = "avocado-runner-pip" |
| 72 | + PROG_DESCRIPTION = "nrunner application for dependencies of type pip" |
| 73 | + RUNNABLE_KINDS_CAPABLE = ["pip"] |
| 74 | + |
| 75 | + |
| 76 | +def main(): |
| 77 | + if sys.platform == "darwin": |
| 78 | + set_start_method("fork") |
| 79 | + app = RunnerApp(print) |
| 80 | + app.run() |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == "__main__": |
| 84 | + main() |
0 commit comments