tests.test_execution module¶
Tests for the execution-control options (–time, -0/–zero-exit) and the subprocess-execution primitives (run_cli and the interrupt machinery).
- tests.test_execution.test_die_by_sigint_skips_a_stream_refusing_a_reentrant_flush(monkeypatch)[source]¶
The process still dies when a stream is mid-write in the interrupted code.
The handler of a second Ctrl+C can run inside a write to
stderr, whose buffer then refuses the flush with aRuntimeError.
- tests.test_execution.NAP_CLI = '\nimport time\n\nimport click_extra\n\n\n@click_extra.command\ndef nap():\n print("ready", flush=True)\n time.sleep(30)\n\n\nnap()\n'¶
A CLI that announces it is running, then sleeps until interrupted.
- tests.test_execution.PARSE_NAP_CLI = '\nimport time\n\nimport click_extra\n\n\ndef soak(ctx, param, value):\n print("ready", flush=True)\n time.sleep(30)\n\n\n@click_extra.command\n@click_extra.option("--beans", expose_value=False, callback=soak)\ndef stew():\n pass\n\n\nstew()\n'¶
A CLI that sleeps while it parses its options, before its context is entered.
- tests.test_execution.interrupt_cli(tmp_path, script, presses=1, launcher=())[source]¶
Run
scriptin a child, press Ctrl+Cpressestimes once it is ready.launcherholds the interpreter arguments that go before the script, to run it through another CLI.A further press waits for the child to say what one does, so it lands once the child handles it. A child that never says so is killed.
- tests.test_execution.test_ctrl_c_ends_the_process_by_sigint(tmp_path, script)[source]¶
A real Ctrl+C prints Click’s
Aborted!, then ends the process bySIGINT, which a calling shell needs to stop its own loop: a status of1, or even130, tells the shell the program handled the interrupt itself.
- tests.test_execution.PLAIN_NAP_CLI = '\nimport time\n\nimport click\n\n\n@click.command()\ndef nap():\n print("ready", flush=True)\n time.sleep(30)\n\n\nif __name__ == "__main__":\n nap()\n'¶
A plain Click CLI that sleeps until interrupted, for the
wrapcommand to run.
- tests.test_execution.test_ctrl_c_in_a_wrapped_cli_ends_the_process_by_sigint(tmp_path)[source]¶
A CLI run by
wrapaborts under Click’s ownmain(), and the wrapping process still ends bySIGINT.
- tests.test_execution.SLOW_JOBS_CLI = '\nimport threading\nimport time\n\nimport click_extra\nfrom click_extra.jobs import run_jobs\n\nBOTH_IN = threading.Barrier(2)\n\n\ndef bake(tray):\n # Reports once both trays are in, so the interrupt finds two running tasks.\n if BOTH_IN.wait(timeout=10) == 0:\n print("ready", flush=True)\n time.sleep(30)\n return tray\n\n\n@click_extra.command\ndef oven():\n list(run_jobs(bake, [0, 1], jobs=2))\n\n\noven()\n'¶
A CLI whose two parallel tasks outlast any reasonable wait.
- tests.test_execution.SLOW_THREAD_CLI = '\nimport threading\nimport time\n\nimport click_extra\n\n\n@click_extra.command\ndef kettle():\n threading.Thread(target=time.sleep, args=(30,)).start()\n print("ready", flush=True)\n time.sleep(30)\n\n\nkettle()\n'¶
A CLI whose single background thread outlasts any reasonable wait.
- tests.test_execution.test_second_ctrl_c_quits_while_tasks_finish(tmp_path, script, notice)[source]¶
After a Ctrl+C, the run says it waits for its running tasks, and what a second Ctrl+C does: quit at once, instead of waiting for the tasks.
- tests.test_execution.LOCKED_PRESS = '\nimport signal\n\nimport click\n\nfrom click_extra import execution\n\n{setup}\nwith execution._LIVE_PROCESSES_LOCK:\n signal.raise_signal(signal.SIGINT)\n'¶
A Ctrl+C that lands while the main thread holds the process registry lock.
- tests.test_execution.test_ctrl_c_while_the_registry_lock_is_held(tmp_path, setup)[source]¶
A Ctrl+C ends the process even when the main thread holds the registry lock.
Both handlers stop the running subprocesses, which takes that lock. The main thread takes it too, as when the grace period of an interrupted run ends, and a plain lock would block the handler of a press landing in that moment for good.
- tests.test_execution.STUBBORN_CHILDREN_CLI = '\nimport os\nimport sys\nimport threading\nimport time\n\nimport click_extra\nfrom click_extra import execution\nfrom click_extra.execution import run_cli\nfrom click_extra.jobs import run_jobs\n\nexecution._TERMINATE_GRACE = 0.5\n\nCHILD = (\n "import os, signal, sys, time;"\n "signal.signal(signal.SIGINT, signal.SIG_IGN);"\n "signal.signal(signal.SIGTERM, signal.SIG_IGN);"\n "open(sys.argv[1], \'w\', encoding=\'UTF-8\').write(str(os.getpid()));"\n "time.sleep(30)"\n)\nPID_FILES = [os.path.join(FOLDER, f"child-{n}.pid") for n in range(2)]\n\n\ndef spawn(pid_file):\n return run_cli((sys.executable, "-c", CHILD, pid_file))\n\n\ndef announce():\n while not all(os.path.exists(path) for path in PID_FILES):\n time.sleep(0.05)\n print("ready", flush=True)\n\n\n@click_extra.command\ndef stubborn():\n threading.Thread(target=announce, daemon=True).start()\n list(run_jobs(spawn, PID_FILES, jobs=2))\n\n\nstubborn()\n'¶
A CLI fanning out two children that ignore both
SIGINTandSIGTERM.
- tests.test_execution.test_interrupted_run_kills_children_ignoring_sigterm(tmp_path)[source]¶
One Ctrl+C is enough: the aborting run sends
SIGTERMto the children ofrun_cli, thenSIGKILLto the ones still running after the grace.
- tests.test_execution.STUBBORN_GRANDCHILDREN_CLI = '\nimport os\nimport sys\nimport threading\nimport time\n\nimport click_extra\nfrom click_extra import execution\nfrom click_extra.execution import run_cli\nfrom click_extra.jobs import run_jobs\n\nexecution._TERMINATE_GRACE = 0.5\n\nGRANDCHILD = (\n "import os, signal, sys, time;"\n "signal.signal(signal.SIGINT, signal.SIG_IGN);"\n "signal.signal(signal.SIGTERM, signal.SIG_IGN);"\n "open(sys.argv[1] + \'.tmp\', \'w\', encoding=\'UTF-8\').write(str(os.getpid()));"\n "os.replace(sys.argv[1] + \'.tmp\', sys.argv[1]);"\n "time.sleep(30)"\n)\nCHILD = (\n "import signal, subprocess, sys, time;"\n "signal.signal(signal.SIGINT, signal.SIG_IGN);"\n "signal.signal(signal.SIGTERM, signal.CHILD_ON_SIGTERM);"\n "subprocess.Popen((sys.executable, \'-c\', sys.argv[2], sys.argv[1]));"\n "time.sleep(30)"\n)\nPID_FILES = [os.path.join(FOLDER, f"grandchild-{n}.pid") for n in range(2)]\n\n\ndef spawn(pid_file):\n return run_cli(\n (sys.executable, "-c", CHILD, pid_file, GRANDCHILD),\n start_new_session=NEW_SESSION,\n )\n\n\ndef announce():\n while not all(os.path.exists(path) for path in PID_FILES):\n time.sleep(0.05)\n print("ready", flush=True)\n\n\n@click_extra.command\ndef stubborn():\n threading.Thread(target=announce, daemon=True).start()\n list(run_jobs(spawn, PID_FILES, jobs=2))\n\n\nstubborn()\n'¶
A CLI fanning out two children, each with a grandchild that ignores both
SIGINTandSIGTERMand holds the output its child was given.
- tests.test_execution.test_interrupted_run_kills_grandchildren_ignoring_sigterm(tmp_path, new_session, child_on_sigterm)[source]¶
The
SIGKILLof an aborting run reaches what the children ofrun_clistarted, so no grandchild holds the run open or outlives it.
- tests.test_execution.SELF_INTERRUPT_CLI = '\nimport signal\n\nimport click_extra\n\n\n@click_extra.command\ndef nap():\n signal.raise_signal(signal.SIGINT)\n\n\nnap()\n'¶
A CLI that interrupts itself, as a Ctrl+C does, on every platform.
- tests.test_execution.SECOND_INTERRUPT_SCRIPT = '\nimport signal\n\nfrom click_extra import execution\n\nexecution._second_interrupt(signal.SIGINT, None)\n'¶
A process handling the Ctrl+C pressed while an interrupted run waits.
- tests.test_execution.OUTLASTED_GRACE_SCRIPT = '\nimport threading\nimport time\n\nfrom click_extra import execution\n\nexecution._TERMINATE_GRACE = 0.1\nthreading.Thread(target=time.sleep, args=(1,)).start()\nexecution._exit_interrupted()\n'¶
An interrupted run whose only task outlasts the grace given to children.
- tests.test_execution.test_interrupted_run_exits_like_an_unhandled_ctrl_c(tmp_path, script, notice)[source]¶
An interrupted run ends the way an unhandled Ctrl+C does, on Windows too.
The process dies by
SIGINTon POSIX, and exits with the status Windows reports for a Ctrl+C. The tests sending a real Ctrl+C to a child are skipped on Windows, so each script here reaches one step of that exit on its own: the whole path of a command, the second Ctrl+C, and the kill of the children still running after the grace, for which Windows has noSIGKILL.
- tests.test_execution.PORTABLE_SIGNALS = frozenset({'SIGABRT', 'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM'})¶
The signal numbers Python defines on every platform, Windows included.
- tests.test_execution.POSIX_BRANCHES = {'is_windows()': 'orelse', 'not is_windows()': 'body'}¶
The branch only POSIX takes, for each platform check an
ifcan test.
- tests.test_execution.unguarded_posix_signals(source)[source]¶
Lines of
sourcethat read a signal number Windows does not define.signal.SIGKILLraisesAttributeErroron Windows, as every signal number outsidePORTABLE_SIGNALSdoes. So a module may read one only where Windows never goes: in theelseof anis_windows()check, or under anot is_windows()one, of anifstatement or a conditional expression.
- tests.test_execution.test_posix_only_signals_are_read_under_a_platform_check()[source]¶
No module of the package reads a POSIX-only signal number on Windows.
Windows runs none of the tests that send a real signal, so only the sources can tell.
unguarded_posix_signalsstates the rule.
- tests.test_execution.test_posix_only_signal_scan_finds_the_package_and_an_unguarded_read()[source]¶
The scan above reads the package, and tells a guarded read from a bare one.
- tests.test_execution.test_simulated_interrupt_keeps_click_exit_status(invoke)[source]¶
A
KeyboardInterruptraised by code, as a test runner does, keeps Click’sAborted!and status1: only a real Ctrl+C ends the process bySIGINT.
- tests.test_execution.test_abort_notice_precedes_close_callbacks(invoke, abort, notice)[source]¶
Aborted!prints as soon as the abort leaves the command: before the close callbacks of its context and of its parents, where Click prints it after them.
- tests.test_execution.test_abort_caught_around_an_invoked_command_prints_no_notice(invoke)[source]¶
A command run through
ctx.invoke()leaves its caller free to catch the abort: a run that goes on prints noAborted!.
- tests.test_execution.test_abort_without_standalone_mode_prints_no_notice(invoke)[source]¶
Without standalone mode, Click raises the abort to the caller, which reports it its own way: no
Aborted!is printed.
- tests.test_execution.test_standalone_timer_option(invoke, cmd_decorator, option_decorator, assert_output_regex)[source]¶
- tests.test_execution.test_nested_run_of_a_timed_command_keeps_the_outer_start(invoke)[source]¶
A run started from within another run of the same command times itself, and the outer run reports the time since its own start.
- tests.test_execution.test_time_with_short_circuit_sibling_still_prints(invoke)[source]¶
--time --versionstill emits a duration.--versionis an eager option that callsctx.exit()before the user command body runs, but--timeis intentionally measured even on short-circuit paths so it can probe the cost of Click Extra’s own machinery (eager callbacks, config loading, option parsing).
- tests.test_execution.test_standalone_zero_exit_option(invoke, cmd_decorator, option_decorator)[source]¶
- tests.test_execution.test_run_cli_returns_completed_process(caplog)[source]¶
run_cli mirrors subprocess.run’s result shape, with separate streams.
- tests.test_execution.test_run_cli_cwd_moves_the_child(tmp_path)[source]¶
cwdruns the child elsewhere; omitted, it inherits the caller’s.
- tests.test_execution.test_run_cli_flattens_nested_args(caplog)[source]¶
Nested iterables are flattened, None dropped, and elements stringified.
- tests.test_execution.test_run_cli_discloses_command_at_info(caplog)[source]¶
The invocation is logged up front at INFO, with its forced env vars, and the output stays out of the INFO records.
- tests.test_execution.test_run_cli_command_level_override(caplog)[source]¶
A caller can lower the disclosure line to DEBUG for internal probes.
- tests.test_execution.test_run_cli_streams_output_at_debug_with_label(caplog)[source]¶
Every output line is forwarded to the logger, tagged with the label.
The tag rides the record’s
labelattribute, not the message text: the defaultclick_extra.logging.Formatterrenders it glued to the level name (debug:probe: line1). The prompt line carries it too, so the command and its output read as one call when several children interleave.
- tests.test_execution.test_highlight_bin_name()[source]¶
Only the binary’s own name is styled; its directory stays plain, whichever separator convention the path uses.
- tests.test_execution.test_format_cli_prompt_styles_token_families()[source]¶
Each token family gets the theme slot it holds elsewhere in a CLI’s output: dim sigil, envvar/default assignment pairs, the binary name as an invoked command (directory plain), option-styled flags, plain arguments.
- tests.test_execution.test_format_cli_prompt_arguments_survive_a_shell_round_trip(argv)[source]¶
A drawn command line parses back to the arguments that produced it.
The line advertises itself as copy-pasteable, so every argument carrying a space or a shell metacharacter has to reach the shell as the single argument it started as, instead of spilling into the line as several.
- tests.test_execution.test_format_cli_prompt_environment_values_survive_a_shell_round_trip()[source]¶
An assignment prefixing the command is quoted like an argument.
A value holding a space ends the assignment early otherwise, and the rest of it reads as the command to run.
- tests.test_execution.test_format_cli_prompt_unsets_a_variable_mapped_to_none()[source]¶
A
Nonevalue removes its variable from the child, whichenv -usays.Drawn as an assignment, it read
LANGUAGE=None, and a pasted copy then set the variable to the stringNoneinstead of removing it.
- tests.test_execution.test_format_cli_prompt_honors_an_explicit_theme()[source]¶
A caller drawing the line onto a surface of its own picks the palette.
Every slot follows, the binary name included: that one is styled a level down, in
highlight_bin_name(), which would otherwise read the active theme on its own and leave a light capture’s prompt in the dark theme’s near-white.
- tests.test_execution.test_run_cli_merged_streams()[source]¶
merge_stderr interleaves stderr into stdout and nulls the stderr field.
- tests.test_execution.test_run_cli_timeout_kills_child_and_attaches_partial_output()[source]¶
An overrun raises TimeoutExpired carrying what was captured so far, and leaves no zombie in the live registry.
- tests.test_execution.test_run_cli_handles_an_interrupt_tripped_as_the_wait_began()[source]¶
A Ctrl+C the interpreter noted as the main thread blocked on the child is handled within the poll period, not when the child exits.
interrupt_main()leaves the interrupt pending without waking the main thread: the state aSIGINTleaves when it lands after the interpreter last checked for one and before the thread blocked in the C library. The child never receives it, like a child in a session of its own, or one with no console on Windows.
- tests.test_execution.test_run_cli_kill_survives_a_second_interrupt(monkeypatch, code, stop_signals)[source]¶
A Ctrl+C landing while the timeout reads the process table waits for the signals to land, so the child never outlives the interrupt.
The timeout sends
SIGTERMfirst, which a child may die of. A child ignoring it dies of theSIGKILLthat the interrupt brings forward.
By default the child stays in the caller’s process group: it keeps the controlling terminal (an interactive
sudoraised from inside the child must be able to prompt on/dev/tty) and receives the terminal’s signals with the rest of the foreground group.
- tests.test_execution.test_run_cli_new_session_makes_child_group_leader()[source]¶
With start_new_session the child leads its own session and process group, whose ID is its own PID: the property every group-kill path relies on.
- tests.test_execution.GRANDCHILD_SESSIONS = MarkDecorator(mark=Mark(name='parametrize', args=('grandchild_session', (ParameterSet(values=(False,), marks=(), id='same-group'), ParameterSet(values=(True,), marks=(), id='own-session'))), kwargs={}))¶
Run a group-kill test on a grandchild inside the child’s group and outside it.
- tests.test_execution.test_run_cli_timeout_new_session_kills_grandchildren(grandchild_session)[source]¶
A timed-out start_new_session child takes its whole process tree down: the grandchild is reaped along with it instead of surviving as an orphan holding the inherited output pipe open.
- tests.test_execution.test_run_cli_registers_live_process_then_discards_it()[source]¶
run_cli tracks its subprocess while it runs, and drops it once done.
A background call parks in a real subprocess. Once it is registered, terminate_live_processes() unblocks it, and run_cli’s
finallyclears the registry: this is the exact path the SIGINT handler drives on Ctrl+C.
- tests.test_execution.test_terminate_live_processes_signals_whole_group(tmp_path, grandchild_session)[source]¶
Interrupting a start_new_session child reaps its grandchild too: the group never received the terminal’s SIGINT (it left the foreground group), so terminate_live_processes() is its only kill path and must cover the descendants.
The child reports its grandchild’s PID through a sentinel file, polled before tearing down, so the group is never signalled mid-spawn. The sentinel is published by rename: a bare
open(..., "w")creates the file before the write is flushed, so polling for existence could tear the group down between creation and flush, leaving an empty file behind forint()to choke on.
- tests.test_execution.test_kill_signal_reaches_a_grandchild_holding_the_output(tmp_path)[source]¶
The kill signal ends what a child started too, on every platform.
The grandchild holds the pipe
run_clireads, so the call returns only once the grandchild is gone: a prompt return is the evidence.
- tests.test_execution.test_run_cli_timeout_kills_grandchildren_without_a_session(grandchild_session)[source]¶
A timed-out child sharing the caller’s process group still takes its grandchild down, killed one PID at a time since no group can be signalled without hitting the test process too.
This is the shape of a shell script running commands of its own. An escalated call has it too, but the command
sudoruns as root is out of reach of the per-PID kill: seetest_run_cli_timeout_sends_sigterm_first.
- tests.test_execution.test_run_cli_timeout_sends_sigterm_first(tmp_path)[source]¶
A timed-out child gets
SIGTERMbefore anySIGKILL, so it can clean up.This is what stops an escalated command:
sudoforwards aSIGTERMto the command it runs as root, which aSIGKILLfrom the caller cannot reach.
- tests.test_execution.test_run_cli_timeout_kills_a_child_ignoring_sigterm()[source]¶
A timed-out child ignoring
SIGTERMis killed once the grace runs out.
- tests.test_execution.test_descendant_pids_walks_the_whole_tree_deepest_first()[source]¶
Every descendant is found whatever group it moved to, and a parent never precedes its own child.
The IDs sit above the largest PID any platform allocates, so none of them can be a process the test runner owns.
- tests.test_execution.test_escaped_process_groups()[source]¶
Only the groups of descendants outside the leader’s group are returned.
The IDs sit above the largest PID any platform allocates, so none of them can be the group of the running test process.
- tests.test_execution.test_terminate_live_processes_ignores_already_reaped()[source]¶
A process gone between snapshot and signal is skipped, not raised on.
- tests.test_execution.test_install_interrupt_handler_terminates_children_and_reraises()[source]¶
The installed SIGINT handler SIGTERMs live children, then raises to abort.