kward / shunit2

shUnit2 is a xUnit based unit test framework for Bourne based shell scripts.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't use shell parameters when "source"ing shunit2

jbrains opened this issue · comments

I want to parameterize some data in my tests, but I can't, because when I add source shunit2 to the bottom of my test suite, shunit2 interprets my parameter as a filename and tries to run tests in it.

It appears that this section of the code contains the assumption I'm breaking:

# determine the operating mode
if [ $# -eq 0 ]; then
  __shunit_script=${__SHUNIT_PARENT}
  __shunit_mode=${__SHUNIT_MODE_SOURCED}
else
  __shunit_script=$1
  [ -r "${__shunit_script}" ] || \
      _shunit_fatal "unable to read from ${__shunit_script}"
  __shunit_mode=${__SHUNIT_MODE_STANDALONE}
fi

Which is happening here?

  1. We intentionally don't allow passing shell parameters to test scripts in order to simplify things.
  2. Nobody ever tried this before, so I'm the lucky one who has run into this problem.
  3. Something else.

If you haven't made a conscious choice to disallow passing shell parameters to test scripts, then I might try fixing this.

Thanks.

So you want to test calling your script with some params? Is that what you're trying to achieve?

I'm guessing that all you are missing is the need to shift all the command-line arguments off the stack before calling shunit2.

The following test code (saved as test_date_cmd.sh) demonstrates what I'm talking about. Notice the shift $# line just before shunit2 is called.

#!/bin/bash

# Echo any provided arguments.
[ $# -gt 0 ] && echo "#:$# 1:$1 2:$2 3:$3"

test_date_cmd() {
  ( date '+%a' >/dev/null 2>&1 )
  local rtrn=$?
  assertTrue "unexpected date error; ${rtrn}" ${rtrn}
}

# Eat all command-line arguments before calling shunit2.
shift $#
. ~/lib/sh/shunit2

Running the command without arguments:

$ ./test_date_cmd.sh 
test_date_cmd

Ran 1 test.

OK

Running the same command with arguments:

$ ./test_date_cmd.sh a b c
#:3 1:a 2:b 3:c
test_date_cmd

Ran 1 test.

OK