sstephenson / bats

Bash Automated Testing System
MIT License
7.12k stars 519 forks source link

How do you test your scripts? #230

Open edouard-lopez opened 7 years ago

edouard-lopez commented 7 years ago

Hi,

I'm looking for ways to test my scripts, some patterns you use/recommend. For instance, how would you test a script such as this one:

#!/usr/bin/env bash
build="$1"

# check that build number is passed
[[ -z $build ]] && { echo "missing argument: build"; exit 1; }

cd ./visual || exit 1

curl "https://" | grep -o 'https://[^"]*' > artifacts.txt

awk -v TOKEN="$TOKEN" '/current/ {print $0 "?token=" TOKEN;}' artifacts.txt \
| xargs -P4 -l1 wget \
  --content-disposition \
  --force-directories \
  --no-host-directories \
  --cut-dirs=5

# let's remove our token from the filename
shopt -s globstar
for file in **/*; do
  mv $file ${file/\?*/}
done

rm artifacts.txt

How do I check I have been cd to the correct directory?

Currently I stub cd to check how it's call.

  cd() { echo "cd $*"; exit; }  # mock
  export -f cd
  run my-script.bash "1234"

  [[ "${lines[0]}" == "cd ./visual" ]]

But then the script continue to run everything after that.

How to test a pipe?

curl "https://" | grep -o 'https://[^"]*' > artifacts.txt

or

awk -v TOKEN="$TOKEN" '/current/ {print $0 "?token=" TOKEN;}' artifacts.txt \
| xargs -P4 -l1 wget \
  --content-disposition \
  --force-directories \
  --no-host-directories \
  --cut-dirs=5

What would you test and how? Is it possible to test part of the pipe?

How would you check value of an env var

awk -v TOKEN="$TOKEN" '/current/ {print $0 "?token=" TOKEN;}' artifacts.txt \

How would you chek that we use globstar?

shopt -s globstar
for file in **/*; do
  mv $file ${file/\?*/}
done

related: stackexchange question

sayanee commented 6 years ago

@edouard-lopez could you try with run eval "{INSERT_QUERY_WITH_PIPES}":

run eval "ls foobar | grep foo"
[ "$status" -eq 0 ]
edouard-lopez commented 6 years ago

Thanks @sayanee, however I'm looking for some best practices to write my script to help me tests them.