如何在bash脚本中按照声明的顺序运行所有函数而不显式调用函数?

时间:2016-05-11 18:05:06

标签: bash shell sh

让我们说我有一个脚本,它有一堆像测试用例一样的函数。例如:

#!/bin/bash

...

function testAssertEqualsWithStrings () {
    assertEquals "something" "something"
} 
testAssertEqualsWithStrings  <--- I dont want to do this

function testAssertEqualsWithIntegers () {
    assertEquals 10 10 
} 
testAssertEqualsWithIntegers  <--- I dont want to do this

function testAssertEqualsWithIntegers2 () {
    assertEquals 5 $((10 - 5))
}
testAssertEqualsWithIntegers2  <--- I dont want to do this

function testAssertEqualsWithDoubles () {
    assertEquals 5.5 5.5
}
testAssertEqualsWithDoubles  <--- I dont want to do this

...

有没有一种方法可以按顺序调用这些函数而不必在每个测试用例下实际使用那个显式函数调用?这个想法是用户不应该管理调用函数。理想情况下,测试套件库会为它们执行此操作。我只需要知道这是否可能。

编辑:我不使用断言方法的原因是我可以有意义的输出。我当前的设置允许我输出如下:

...
LineNo 14: Passed - testAssertEqualsWithStrings
LineNo 19: Passed - testAssertEqualsWithIntegers
LineNo 24: Passed - testAssertEqualsWithIntegers2
LineNo 29: Passed - testAssertEqualsWithDoubles
LineNo 34: Passed - testAssertEqualsWithDoubles2
...
LineNo 103: testAssertEqualsWithStringsFailure: assertEquals() failed. Expected "something", but got "something else".
LineNo 108: testAssertEqualsWithIntegersFailure: assertEquals() failed. Expected "5", but got "10".
LineNo 115: testAssertEqualsWithArraysFailure: assertEquals() failed. Expected "1,2,3", but got "4,5,6".
LineNo 120: testAssertNotSameWithIntegersFailure: assertNotSame() failed. Expected not "5", but got "5".
LineNo 125: testAssertNotSameWithStringsFailure: assertNotSame() failed. Expected not "same", but got "same".
...

编辑:对我有用的解决方案

function runUnitTests () {
    testNames=$(grep "^function" $0 | awk '{print $2}')
    testNamesArray=($testNames)
    beginUnitTests  #prints some pretty output
    for testCase in "${testNamesArray[@]}"
    do
        :
        eval $testCase
    done
    endUnitTests #prints some more pretty output
}

然后我在测试套件底部调用runUnitTests

1 个答案:

答案 0 :(得分:0)

如果您只是想在不调用它们的情况下运行这些函数,为什么首先将它们声明为函数?

您要么将它们作为功能,因为您多次使用它们并且每次都需要不同的呼叫,在这种情况下我没有看到问题。

否则你只想运行每个函数一次而不调用它们,这只是运行命令。删除所有函数声明,只需调用每一行。

对于这个例子

#!/bin/bash

...

assertEquals "something" "something" #testAssertEqualsWithStrings
assertEquals 10 10 #testAssertEqualsWithIntegers
assertEquals 5 $((10 - 5)) #testAssertEqualsWithIntegers2
assertEquals 5.5 5.5 #testAssertEqualsWithDoubles

...