Unit Testing bash scripts

后端 未结 16 685
暖寄归人
暖寄归人 2020-11-30 18:51

We have a system that has some bash scripts running besides Java code. Since we are trying to Test Everything That Could Possibly Break, and those bash scripts may break, we

相关标签:
16条回答
  • 2020-11-30 19:17

    I got the following answer from a discussion group:

    it's possible to import (include, whatever) a procedure (function, whatever it's named) from an external file. That's the key to writing a testing script: you break up your script into independent procedures that can then be imported into both your running script and your testing script, and then you have your running script be as simple as possible.

    This method is like dependency injection for scripts, and sounds reasonable. Avoiding bash scripts and using more testable and less obscure language is preferable.

    0 讨论(0)
  • 2020-11-30 19:18

    There is actually a shunit2, an xUnit based unit test framework for Bourne based shell scripts. I haven't used it myself, but it might be worth checking out.

    Similar questions have been asked before:

    • Unit Testing for Shell Scripts
    • Test Anything Protocol in Shell Scripts
    0 讨论(0)
  • 2020-11-30 19:18

    Try bashtest. It`s simple way to test your scripts. For example, you have do-some-work.sh which change some config files. For example, add new line PASSWORD = 'XXXXX' to config file /etc/my.cfg.

    You write bash commands line by line and then check output.

    Install:

    pip3 install bashtest
    

    Create tests is a just writing bash commands.

    File test-do-some-work.bashtest:

    # run the script  
    $ ./do-some-work.sh > /dev/null
    
    # testing that the line "PASSWORD = 'XXXXX'" is in the file /etc/my.cfg   
    $ grep -Fxq "PASSWORD = 'XXXXX'" /etc/my.cfg && echo "YES"
    YES
    

    Run tests:

    bashtest *.bashtest
    

    You can find some examples here and here

    0 讨论(0)
  • 2020-11-30 19:18

    Give a try to assert.sh

    source "./assert.sh"
    
    local expected actual
    expected="Hello"
    actual="World!"
    assert_eq "$expected" "$actual" "not equivalent!"
    # => x Hello == World :: not equivalent!
    

    Hope it helps!

    0 讨论(0)
提交回复
热议问题