You want tests for existing scripts that call `curl`, `aws` and `systemctl`. How do you test them without touching real systems?
IntermediateScenarioScenarios: writing and hardening scripts
Answer
Situation read → External commands must be replaced with controllable fakes, and each test needs an isolated filesystem.
What I'd do →
- Use bats-core; put stub executables in
tests/stubs/and prepend that directory toPATHinsetup(). - Each stub logs its arguments to a file and returns canned output or an exit code from an environment variable (
STUB_CURL_RC=22). - Make the script configurable through environment variables for paths (
STATE_DIR,LOG_FILE,CONF), defaulting to production paths. - Assert on exit status, output, files created and the stub call log.
- Run
bats testsandshellcheckin CI on every PR.
Why → PATH stubs need no changes to the script's code and make failure paths (timeouts, 503s, AccessDenied) easy to test.
Interview tip → Point to a failure-path test, such as "upload fails, so the script exits 1 and raises an alert". That is where scripts usually break.
More on Scenarios: writing and hardening scripts
You inherit a 600-line `deploy.sh` with no error handling. It "sometimes half-deploys". Where do you start?IntermediateA script with `#!/bin/sh` works on CentOS but fails on Ubuntu with `Syntax error: "(" unexpected`. What is going on and what do you do?BeginnerYou need a deploy script that humans and CI both call with `--env`, `--version` and `--dry-run`. How do you design its interface?BeginnerA maintenance script must run as the `deploy` user, never as root, because files it creates must be owned by `deploy`. How do you enforce that?BeginnerTen scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?IntermediateA script is run both by engineers and by cron. Cron logs are full of colour codes and the script sometimes hangs waiting for input. Fix it.Beginner