encapsule-0.6.1: test/CommandSpec.hs
-- SPDX-License-Identifier: Apache-2.0
module CommandSpec (spec) where
import System.Exit (ExitCode(..))
import System.Process (readProcessWithExitCode)
import Test.Hspec
import Command (defaultCommand, withInit)
import ShellQuote (shellQuote)
spec :: Spec
spec = describe "user command" $ do
it "defaults to a login Bash shell" $
defaultCommand [] `shouldBe` ["bash", "-l"]
it "preserves an explicit command without adding login options" $
mapM_ (\command -> withInit [] (defaultCommand command) `shouldBe` command)
[["bash"], ["bash", "--noprofile"], ["printf", "%s", "hello world"]]
it "runs Bash init snippets in order and passes their exported environment" $ do
result <- runWithInit
[ "values=(hello world); export ENCAPSULE_INIT_TEST=${values[0]}"
, "export ENCAPSULE_INIT_TEST+=\" ${values[1]}\" # trailing comment"
]
["bash", "--noprofile", "--norc", "-c", "printf '%s' \"$ENCAPSULE_INIT_TEST\""]
result `shouldBe` (ExitSuccess, "hello world", "")
it "preserves empty arguments and shell metacharacters through init" $ do
let args = ["", "hello world", "a'b", "\"quoted\"", "$HOME", "$(exit 99)", "; exit 99", "line\nbreak", "-l"]
result <- runWithInit [":"] (["printf", "<%s>\n"] ++ args)
result `shouldBe` (ExitSuccess, concatMap (\arg -> "<" ++ arg ++ ">\n") args, "")
it "accepts empty and comment-only init snippets" $ do
result <- runWithInit ["", "# comment"] ["printf", "ok"]
result `shouldBe` (ExitSuccess, "ok", "")
it "stops before later snippets and the command if init fails" $ do
result <- runWithInit ["exit 7", "printf later"] ["printf", "command"]
result `shouldBe` (ExitFailure 7, "", "")
it "propagates a snippet failure without running the command" $ do
result <- runWithInit ["false"] ["printf", "command"]
result `shouldBe` (ExitFailure 1, "", "")
it "preserves the command exit status after successful init" $ do
result <- runWithInit [":"] ["bash", "-c", "exit 23"]
result `shouldBe` (ExitFailure 23, "", "")
runWithInit :: [String] -> [String] -> IO (ExitCode, String, String)
runWithInit snippets command =
case withInit snippets (defaultCommand command) of
args@(_:_) -> readProcessWithExitCode "sh"
["-c", "exec " ++ unwords (map shellQuote args)] ""
[] -> fail "empty user command"