Repository: dodie/testing-in-bash Branch: master Commit: 51c2475a1d06 Files: 93 Total size: 96.9 KB Directory structure: gitextract_0_4bgft3/ ├── CONTRIBUTING.md ├── LICENSE ├── example-bash_unit/ │ ├── .gitignore │ ├── install.sh │ ├── readme.md │ ├── src/ │ │ ├── file-report.sh │ │ ├── ice_cream_price.sh │ │ └── myfun.sh │ ├── test/ │ │ ├── assertion_showcase.sh │ │ ├── e2e_test.sh │ │ ├── mocks/ │ │ │ └── date │ │ ├── setup_and_teardown.sh │ │ ├── unit_test.sh │ │ └── util/ │ │ └── customasserts.sh │ └── test.sh ├── example-bashunit/ │ ├── .gitignore │ ├── README.md │ ├── install.sh │ ├── src/ │ │ ├── file-report.sh │ │ ├── ice_cream_price.sh │ │ └── myfun.sh │ ├── test.sh │ └── tests/ │ └── unit_test.sh ├── example-bats/ │ ├── .gitignore │ ├── install.sh │ ├── readme.md │ ├── src/ │ │ ├── file-report.sh │ │ ├── ice_cream_price.sh │ │ └── myfun.sh │ ├── test/ │ │ ├── assertion_showcase.bats │ │ ├── e2e_test.bats │ │ ├── mocks/ │ │ │ └── date │ │ ├── setup_and_teardown.bats │ │ ├── unit_test.bats │ │ ├── unit_test_strict.bats │ │ └── util/ │ │ └── customasserts.bash │ └── test.sh ├── example-shellspec/ │ ├── .gitignore │ ├── .shellspec │ ├── install.sh │ ├── readme.md │ ├── spec/ │ │ ├── assertion_showcase_spec.sh │ │ ├── e2e_test_spec.sh │ │ ├── mocks/ │ │ │ └── date │ │ ├── setup_and_teardown_spec.sh │ │ ├── spec_helper.sh │ │ ├── support/ │ │ │ └── custom_matcher.sh │ │ └── unit_test_spec.sh │ ├── src/ │ │ ├── file-report.sh │ │ ├── ice_cream_price.sh │ │ └── myfun.sh │ └── test.sh ├── example-shpec/ │ ├── .gitignore │ ├── install.sh │ ├── readme.md │ ├── shpec/ │ │ ├── e2e_test_shpec.sh │ │ ├── matchers/ │ │ │ └── ice_price.sh │ │ ├── mocks/ │ │ │ └── date │ │ ├── showcase_shpec.sh │ │ └── unit_test_shpec.sh │ ├── src/ │ │ ├── file-report.sh │ │ ├── ice_cream_price.sh │ │ └── myfun.sh │ └── test.sh ├── example-shunit2/ │ ├── .gitignore │ ├── install.sh │ ├── readme.md │ ├── src/ │ │ ├── file-report.sh │ │ ├── ice_cream_price.sh │ │ └── myfun.sh │ ├── test/ │ │ ├── assertion_showcase.sh │ │ ├── e2e_test.sh │ │ ├── mocks/ │ │ │ └── date │ │ ├── setup_and_teardown.sh │ │ └── unit_test.sh │ └── test.sh ├── mocking/ │ ├── src/ │ │ └── greeting.sh │ └── test/ │ ├── mocks/ │ │ └── date │ ├── test-alias-date.sh │ ├── test-alias-own.sh │ ├── test-export-date.sh │ ├── test-export-own.sh │ └── test-pathoverride-date.sh ├── readme.md ├── stdio/ │ ├── src/ │ │ └── interactive_greeter.sh │ └── test/ │ └── test_stdio.sh └── strictmode/ ├── readme.md ├── src/ │ ├── using_e.sh │ ├── using_no_e.sh │ ├── using_no_u.sh │ └── using_u.sh └── test/ ├── unit_test_script_using_e_o_pipefail.sh └── unit_test_script_using_u.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: CONTRIBUTING.md ================================================ Thanks for taking the time to provide corrections and additions! To add an example with a new framework please follow the structure used for the other examples: * Check the `example-` folders and create a similar folder for the new library to showcase its capabilities. * Add a new column to the main [readme.md](https://github.com/dodie/testing-in-bash/blob/master/readme.md) file for the new library. * To keep sanity while editing the huge table I disable line wrapping and use a [markdown formatter](http://markdowntable.com/). ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: example-bash_unit/.gitignore ================================================ lib build ================================================ FILE: example-bash_unit/install.sh ================================================ #!/bin/bash cd "$(dirname "$0")" rm -rf lib mkdir lib cd lib curl -L -O -J https://github.com/pgrange/bash_unit/archive/v1.7.1.tar.gz tar -zxvf bash_unit-1.7.1.tar.gz mv bash_unit-1.7.1 bash_unit ================================================ FILE: example-bash_unit/readme.md ================================================ # bash_unit test drive This framework allows to write test files in pure Bash, without custom syntax, yet provide concise syntax and many features. My only concern is that it has only a few built-in assertions, but that can be solved by writing custom ones. ## Test format ✔️ Test files are simple shell scripts, executed by the test framework. There's no need for any extra noise besides the test functions in a test file: no custom shebang line, no framework initialization code, and no custom imports. ```bash test_example(){ assert_equals "hello" "world" } ``` ✔️ Test functions are simple bash functions without custom syntax. All functions which name is starting with `test_` is considered a test function ## Test Discovery ✔️ bash_unit is parameterized with the list of test files to be executed. This means that it's trivial to focus on a single test file to execute. Moreover, it can also take a pattern to narrow test cases to be executed to the matching ones. ⚠️ Because it explicitly has to be parameterized with the list of test files, it can't discover directories. For this purpose one might wish to introduce a [lightweight wrapper](https://github.com/dodie/testing-in-bash/blob/master/example-bash_unit/test.sh). ## Assertions ⚠️ It has some assertions available like `assert_equals` but lacks other essential ones, like `assert_contains`. ✔️ All assertions provide a nice, easy to read report including the context and line number. ## Custom assertions ✔️ It’s possible to create new assertions by building functions on top of the existing assertions, although there's no dedicated lower-level API to support it. Custom assertions can be sourced from an external file. ## Skip tests ✔️ If a test function name is starting with `pending` or `todo` it will be skipped which will be properly reflected in the report. ## Mocking ✔️ Supports all [common techniques](https://github.com/dodie/testing-in-bash/tree/master/mocking) for mocking. ✔️ Additionally, it even has the [built-in `fake` command](https://github.com/pgrange/bash_unit/blob/a10751626ef0caa2bc5988a574e9a546426a2791/bash_unit#L123-L133) which is a shorthand for the function-export based mock technique, making the tests even more clear and concise. ## Activity ✔️ The project is around since 2016 and has regular releases. Overall much less popular than Bats or shUnit2, and has activity on the GitHub repository, but there's also much less forgotten issues and PRs. ## Documentation ✔️ Based on the [getting started guide](https://github.com/pgrange/bash_unit) it was really easy to get started. ================================================ FILE: example-bash_unit/src/file-report.sh ================================================ #!/bin/bash mode=$1 path=$2 if [ -z $path ]; then echo "Usage: ./file-report.sh [size|number-of-files] [path]"; >&2 exit 1 fi cd "${path}" case "${mode}" in number-of-files) ls -1 | wc -l ;; size) du -h | cut -f1 ;; *) >&2 echo "Usage: ./file-report.sh [size|number-of-files] [path]"; exit 1 ;; esac ================================================ FILE: example-bash_unit/src/ice_cream_price.sh ================================================ #!/bin/bash function main() { numberOfPortions=$1 pricePerPortion=$(calculatePrice $numberOfPortions) totalPrice=$(( $numberOfPortions * $pricePerPortion )) echo "Total $totalPrice" } function calculatePrice() { if [[ $numberOfPortions -lt 3 ]]; then echo "100" else day=$(getDay) if (( $day % 2 )); then echo "80" else echo "100" fi fi } function getDay() { date -d '+%d' } if [[ "${BASH_SOURCE[0]}" == "${0}" ]] then main $@ fi ================================================ FILE: example-bash_unit/src/myfun.sh ================================================ #!/bin/bash function myfun() { echo "Hello!" } ================================================ FILE: example-bash_unit/test/assertion_showcase.sh ================================================ # include custom assertions source "${TEST}/util/customasserts.sh" test_with_assert_equals() { result=$(${SRC}/ice_cream_price.sh 1) assert_equals 0 $? assert_equals "Total 100" "${result}" } pending_test_this_is_broken() { #... assert_equals "1" "2" } test_custom_assertion() { assert_contains "Hello" "Hello World" } ================================================ FILE: example-bash_unit/test/e2e_test.sh ================================================ function test_ice_cream_price_should_be_100_per_portion_for_low_quantities() { result=$(${SRC}/ice_cream_price.sh 1) assert_equals $? 0 # assert success assert_equals "${result}" "Total 100" } function test_there_should_be_20_percent_discount_for_large_quantities_on_odd_days() { # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="1" export PATH=${TEST}/mocks:$PATH result=$(${SRC}/ice_cream_price.sh 4) assert_equals $? 0 # assert success assert_equals "${result}" "Total 320" } function test_there_should_be_no_discount_even_for_large_quantities_on_even_days() { # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="2" export PATH=${TEST}/mocks:$PATH result=$(${SRC}/ice_cream_price.sh 4) assert_equals $? 0 # assert success assert_equals "${result}" "Total 400" } ================================================ FILE: example-bash_unit/test/mocks/date ================================================ #!/bin/bash echo "${DATE_MOCK_REPLY}" ================================================ FILE: example-bash_unit/test/setup_and_teardown.sh ================================================ source "${TEST}/util/customasserts.sh" # Create test data directories function setup_suite() { mkdir -p ${BUILD}/testdata } # Remove test data directories function teardown_suite() { rm -rf ${BUILD}/testdata } # Generate fresh example files for the tests function setup() { rm -rf ${BUILD}/testdata/* for i in {1..3} do echo "Hello $i" > "${BUILD}/testdata/${i}.txt" done } # Assert that the tests did not remove the example files function teardown() { result=$(ls ${BUILD}/testdata -1) assert_equals 0 $? # assert success assert_contains "1.txt" "${result}" assert_contains "2.txt" "${result}" assert_contains "3.txt" "${result}" } function test_number-of-files_should_return_the_number_of_files_in_the_directory() { result=$(${SRC}/file-report.sh number-of-files ${BUILD}/testdata) assert_equals 0 $? assert_equals 3 "${result}" } function test_size_should_return_the_total_size_of_the_files_in_the_directory() { result=$(${SRC}/file-report.sh size ${BUILD}/testdata) assert_equals 0 $? assert_equals "16K" "${result}" } ================================================ FILE: example-bash_unit/test/unit_test.sh ================================================ function test_ice_cream_price_should_be_100_per_portion_for_low_quantities() { source ${SRC}/ice_cream_price.sh result=$(main 1) assert_equals 0 $? assert_equals "${result}" "Total 100" } function test_there_should_be_20_percent_discount_for_large_quantities_on_odd_days() { # Mocking a function by defining an alias shopt -s expand_aliases alias "getDay"="echo '1'" source ${SRC}/ice_cream_price.sh result=$(main 4) assert_equals 0 $? assert_equals "${result}" "Total 320" } function test_there_should_be_no_discount_even_for_large_quantities_on_even_days() { source ${SRC}/ice_cream_price.sh # Mocking a function by exporting a function function getDay() { echo "2"; } export -f getDay result=$(main 4) assert_equals 0 $? assert_equals "${result}" "Total 400" } function test_mock_alternative_using_fake() { source ${SRC}/ice_cream_price.sh # Mocking a function by using bash_unit's fake fake getDay echo "2" result=$(main 4) assert_equals 0 $? assert_equals "${result}" "Total 400" } ================================================ FILE: example-bash_unit/test/util/customasserts.sh ================================================ function assert_contains() { local expected=$1 local actual=$2 if [[ "${actual}" =~ *"${expected}"* ]]; then fail "${actual} does not contain ${expected}" fi } ================================================ FILE: example-bash_unit/test.sh ================================================ #!/bin/bash # Set project root as the working directory cd "$(dirname "$0")" export PROJECT_DIR="$(realpath ".")" export SRC="${PROJECT_DIR}/src" export TEST="${PROJECT_DIR}/test" export BUILD="${PROJECT_DIR}/build" lib/bash_unit/bash_unit test/*.sh ================================================ FILE: example-bashunit/.gitignore ================================================ lib/ ================================================ FILE: example-bashunit/README.md ================================================ # bashunit 1. Install the library: `./install.sh` 2. Run the test script: `./test.sh` ================================================ FILE: example-bashunit/install.sh ================================================ #!/bin/bash #################################################### # More details about bashunit installation # # see: https://bashunit.typeddevs.com/installation # #################################################### curl -s https://bashunit.typeddevs.com/install.sh | bash -s lib 0.23.0 ================================================ FILE: example-bashunit/src/file-report.sh ================================================ #!/bin/bash mode=$1 path=$2 if [ -z $path ]; then echo "Usage: ./file-report.sh [size|number-of-files] [path]"; >&2 exit 1 fi cd "${path}" case "${mode}" in number-of-files) ls -1 | wc -l ;; size) du -h | cut -f1 ;; *) >&2 echo "Usage: ./file-report.sh [size|number-of-files] [path]"; exit 1 ;; esac ================================================ FILE: example-bashunit/src/ice_cream_price.sh ================================================ #!/bin/bash function main() { numberOfPortions=$1 pricePerPortion=$(calculatePrice $numberOfPortions) totalPrice=$(( numberOfPortions * pricePerPortion )) echo "Total $totalPrice" } function calculatePrice() { if [[ $numberOfPortions -lt 3 ]]; then echo "100" else day=$(getDay) if (( day % 2 )); then echo "80" else echo "100" fi fi } function getDay() { date -d '+%d' } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main "$@" fi ================================================ FILE: example-bashunit/src/myfun.sh ================================================ #!/bin/bash function myfun() { echo "Hello!" } ================================================ FILE: example-bashunit/test.sh ================================================ #!/bin/bash lib/bashunit tests ================================================ FILE: example-bashunit/tests/unit_test.sh ================================================ #!/bin/bash # set_up is called before executing each test function function set_up() { source "$(realpath ".")/src/ice_cream_price.sh" } function test_ice_cream_price_should_be_100_per_portion_for_low_quantities() { result=$(main 1) assert_successful_code assert_equals "${result}" "Total 100" } function test_there_should_be_20_percent_discount_for_large_quantities_on_odd_days() { function getDay() { echo "1" } result=$(main 4) assert_successful_code assert_equals "${result}" "Total 320" } function test_there_should_be_no_discount_even_for_large_quantities_on_even_days() { function getDay() { echo "2" } result=$(main 4) assert_successful_code assert_equals "${result}" "Total 400" } ================================================ FILE: example-bats/.gitignore ================================================ lib build ================================================ FILE: example-bats/install.sh ================================================ #!/bin/bash cd "$(dirname "$0")" rm -rf lib mkdir lib cd lib curl -L -O -J https://github.com/bats-core/bats-core/archive/v1.1.0.tar.gz tar -zxvf bats-core-1.1.0.tar.gz mv bats-core-1.1.0 bats-core curl -L -O -J https://github.com/bats-core/bats-support/archive/v0.3.0.tar.gz tar -zxvf bats-support-0.3.0.tar.gz mv bats-support-0.3.0 bats-support curl -L -O -J https://github.com/bats-core/bats-assert/archive/v2.0.0.tar.gz tar -zxvf bats-assert-2.0.0.tar.gz mv bats-assert-2.0.0 bats-assert ================================================ FILE: example-bats/readme.md ================================================ # Bats test drive Bats is a well established contender in the scene of Bash testing frameworks. It has many features and provides a custom `@test` annotation to make tests easier to write. ## Test format ✔️ Test files are "almost Bash". ⚠️ Bats only considers files with the `.bats` extension. This is not a huge problem, but the editor has to be adapted a bit to offer syntax highlight and the usual features for these files. ✔️ Also, tests are marked with a special `@test` annotation, which is not Bash syntax. It's is picked up by BATS which translates it into a test wrapper. Although it's special syntax, it makes really clean how tests can be defined: ```bash @test "ice cream price should be 100 per portion for low quantities" { run src/ice_cream_price.sh 1 assert_success assert_output -p "Total 100" } ``` As can be seen in this example, it also offers a special `run` construct to run the script under test and capture the results. Finally, although it's optional, BATS test files can have their own shebang line as well: `#!/usr/bin/env bats`. ## Test Discovery ✔️ By default it runs all test files in the given directory, or just a given file. It can also consider subdirectories with the `--recursive flag`. With `--filter` one can specify a regex, and only tests with a matching name will be executed. ## Assertions ⚠️ It provides no assertions by default. Instead, simply if a command exits with a non-zero code, the test will fail: ```bash @test "addition using bc" { result="$(echo 2+2 | bc)" [ "$result" -eq 4 ] } ``` All the examples promote this approach. In my opinion, it has two serious problems: - one have to be fluent in [Bash conditionals](https://tldp.org/LDP/abs/html/comparison-ops.html) in order to work with it - the report lacks important information, like the expected and actual values ```bash ✗ addition using bc (in test file test/test2.bats, line 8) `[ "$result" -eq 4 ]' failed # what was the $result? :( ``` ✔️ It has an extension called [bats-assert](https://github.com/bats-core/bats-assert) that provide assertions like equals or partial matching on the output. They provide nice error messages too: ```bash load '../lib/bats-support/load' load '../lib/bats-assert/load' @test "using asserts" { run src/ice_cream_price.sh 4 assert_success assert_output -p "Total 500" } ✗ using asserts (from function `assert_output' in file test/../lib/bats-assert/src/assert_output.bash, line 186, in test file test/asserts.bats, line 7) `assert_output -p "Total 500"' failed -- output does not contain substring -- substring : Total 500 output : Total 400 -- ``` ⚠️ Most of the asserts provided by `bats-assert` are working directly with the return code or the output of the command executed with run. There are not too many general assertions besides `assert_equal`. ## Custom assertions ✔️ It's possible to create custom assertions, and also there are some dedicated constructs in the framework to support creating them: - With `load` shared test code (e.g. assertion functions) can be imported ([doc](https://github.com/bats-core/bats-core#load-share-common-code)) - The [bats-support](https://github.com/bats-core/bats-support) library provides common functions for error reporting and output formatting. ## Report ⚠️ Report for test cases are not separated by test files. This is not a problem for small projects, but with many test files it's a bit harder to relate a failing test to the test file where it's defined: ``` ✓ this is the first test from the first test suite ✓ this is the second test from the first test suite ✓ this is the first test from the second test suite ✓ this is the second test from the second test suite ``` ## Mocking ✔️ Mocking is possible with all [three common techniques](https://github.com/dodie/testing-in-bash/tree/master/mocking): - alias - function export - PATH override ## Unit testing scripts that set Bash options ✔️ Bats itself can `source` scripts that set custom Bash options, like `-e` or `-u` without breaking test execution or causing problems for the test framework. [[1](https://github.com/bats-core/bats-core/blob/15686b3e4cbcc00dd589e4a87e42975a0501e1f8/test/bats.bats#L325)], [[2](https://github.com/bats-core/bats-core/pull/26)]. ✔️ Because a non-zero exit code for any test command results in a failed test, I thought that all unit tested functions are inherently run with the `errexit` mode set. Luckily this is not the case. The `run` construct provides a sandbox to the function under test. ⚠️ Generally, this means that unit testing functions that does not use custom Bash options, or use `nounset` will work normally. However, for some reason when a function is exercised with the `run` construct the `-e` option is always forcefully is disabled. So, if you design a script that use `set -e` and unit test its functions with Bats, in the unit tests the `-e` will not apply and the function might behave differently. For more details, see the [example tests that exercise scripts that use custom Bash options](https://github.com/dodie/testing-in-bash/tree/master/example-bats/test/unit_test_strict.bats). ## Activity ⚠️ According to the project’s GitHub repository it's been around since 2011. The [original repository](https://github.com/sstephenson/bats) was discontinued in 2016, but it was forked to the [bats-core organization](https://github.com/bats-core) to ensure the project's maintenance and collect useful thirdparty libraries. Despite this transition, there's a huge number of old open issues and PRs. ## Documentation ⚠️ The bats-core project has good documentation, and seems to be up to date, but the thirdparty libraries, including bats-assert seems to lag behind. In many cases they link to old repos from before the transition to the bats-core organization, and documents that are not updated in the last couple of years. For example the documentation recommended installing bats-assert and its dependency into the test folder, but that [did not work](https://github.com/bats-core/bats-core/issues/273) because BATS considered their files as test cases and tried to execute them. ================================================ FILE: example-bats/src/file-report.sh ================================================ #!/bin/bash mode=$1 path=$2 if [ -z $path ]; then echo "Usage: ./file-report.sh [size|number-of-files] [path]"; >&2 exit 1 fi cd "${path}" case "${mode}" in number-of-files) ls -1 | wc -l ;; size) du -h | cut -f1 ;; *) >&2 echo "Usage: ./file-report.sh [size|number-of-files] [path]"; exit 1 ;; esac ================================================ FILE: example-bats/src/ice_cream_price.sh ================================================ #!/bin/bash function main() { numberOfPortions=$1 pricePerPortion=$(calculatePrice $numberOfPortions) totalPrice=$(( $numberOfPortions * $pricePerPortion )) echo "Total $totalPrice" } function calculatePrice() { if [[ $numberOfPortions -lt 3 ]]; then echo "100" else day=$(getDay) if (( $day % 2 )); then echo "80" else echo "100" fi fi } function getDay() { date -d '+%d' } if [[ "${BASH_SOURCE[0]}" == "${0}" ]] then main $@ fi ================================================ FILE: example-bats/src/myfun.sh ================================================ #!/bin/bash function myfun() { echo "Hello!" } ================================================ FILE: example-bats/test/assertion_showcase.bats ================================================ # required for tests using bats-assert load '../lib/bats-support/load' load '../lib/bats-assert/load' # required for tests using a custom assert load util/customasserts @test "skipped test" { skip "This is broken" #... } @test "asserting with conditionals" { run src/ice_cream_price.sh 1 [ "$status" -eq 0 ] [ "${lines[0]}" = "Total 100" ] } @test "asserting with bats-assert" { run src/ice_cream_price.sh 1 assert_success assert_output -p "Total 100" } @test "asserting with custom assertion" { run src/ice_cream_price.sh 1 custom_assert_equal "${lines[0]}" "Total 100" } ================================================ FILE: example-bats/test/e2e_test.bats ================================================ load '../lib/bats-support/load' load '../lib/bats-assert/load' @test "e2e - ice cream price should be 100 per portion for low quantities" { run src/ice_cream_price.sh 1 assert_success assert_output -p "Total 100" } @test "e2e - there should be 20% discount for large quantities on odd days" { # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="1" export PATH=test/mocks:$PATH run src/ice_cream_price.sh 4 assert_success assert_output -p "Total 320" } @test "e2e - there should be no discount even for large quantities on even days" { # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="2" export PATH=test/mocks:$PATH run src/ice_cream_price.sh 4 assert_success assert_output -p "Total 400" } ================================================ FILE: example-bats/test/mocks/date ================================================ #!/bin/bash echo "${DATE_MOCK_REPLY}" ================================================ FILE: example-bats/test/setup_and_teardown.bats ================================================ load '../lib/bats-support/load' load '../lib/bats-assert/load' # Generate fresh example files for the tests setup() { rm -rf build/testdata mkdir -p build/testdata for i in {1..3} do echo "Hello $i" > "build/testdata/${i}.txt" done } # Assert that the tests did not remove the example files teardown() { run ls build/testdata -1 assert_success assert_output --partial "1.txt" assert_output --partial "2.txt" assert_output --partial "3.txt" } @test "number-of-files should return the number of files in the directory" { run src/file-report.sh number-of-files build/testdata assert_success assert_output "3" } @test "size should return the total size of the files in the directory" { run src/file-report.sh size build/testdata assert_success assert_output "16K" } ================================================ FILE: example-bats/test/unit_test.bats ================================================ load '../lib/bats-support/load' load '../lib/bats-assert/load' @test "ice cream price should be 100 per portion for low quantities" { source src/ice_cream_price.sh run main 1 assert_success assert_output -p "Total 100" } @test "there should be 20% discount for large quantities on odd days" { # Mocking a function by defining an alias shopt -s expand_aliases alias "getDay"="echo '1'" source src/ice_cream_price.sh run main 4 assert_success assert_output -p "Total 320" } @test "there should be no discount even for large quantities on even days" { source src/ice_cream_price.sh # Mocking a function by exporting a function function getDay() { echo "2"; } export -f getDay run main 4 assert_success assert_output -p "Total 400" } ================================================ FILE: example-bats/test/unit_test_strict.bats ================================================ load '../lib/bats-support/load' load '../lib/bats-assert/load' @test "e2e testing a script that relies on errexit" { # This is how the script behaves when executed directly run ../strictmode/src/using_e.sh "https://www.google.com" assert_success assert_output -p "200" run ../strictmode/src/using_e.sh "https://www.google.com/nonexistent" assert_failure assert_output -p "" } @test "unit testing a script that relies on errexit should work the same - fails because -e is not applied" { # And this is how the script behaves when it is sourced source ../strictmode/src/using_e.sh run getResponseCode "https://www.google.com" assert_success assert_output -p "200" run getResponseCode "https://www.google.com/nonexistent" assert_failure assert_output -p "" } @test "e2e testing a script that relies on no errexit" { # This is how the script behaves when executed directly run ../strictmode/src/using_no_e.sh "https://www.google.com" assert_success assert_output -p "200" run ../strictmode/src/using_no_e.sh "https://www.google.com/nonexistent" assert_success assert_output -p "404" } @test "unit testing a script that relies on no errexit should work the same" { # And this is how the script behaves when it is sourced source ../strictmode/src/using_no_e.sh run getResponseCode "https://www.google.com" assert_success assert_output -p "200" run getResponseCode "https://www.google.com/nonexistent" assert_success assert_output -p "404" } @test "e2e testing a script that relies on nounset" { # This is how the script behaves when executed directly run ../strictmode/src/using_u.sh Hello assert_success assert_output -p "The parameter is: Hello" run ../strictmode/src/using_u.sh assert_failure assert_output -p "" } @test "unit testing a script that relies on nounset should work the same" { # And this is how the script behaves when it is sourced source ../strictmode/src/using_u.sh run main Hello assert_success assert_output -p "The parameter is: Hello" run main assert_failure assert_output -p "" } @test "e2e testing a script that relies on no nounset" { # This is how the script behaves when executed directly run ../strictmode/src/using_no_u.sh Hello assert_success assert_output -p "YES" run ../strictmode/src/using_no_u.sh assert_success assert_output -p "NO" } @test "unit testing a script that relies on no nounset should work the same" { # And this is how the script behaves when it is sourced source ../strictmode/src/using_no_u.sh run main Hello assert_success assert_output -p "YES" run main assert_success assert_output -p "NO" } ================================================ FILE: example-bats/test/util/customasserts.bash ================================================ # based on https://github.com/bats-core/bats-assert/blob/master/src/assert_equal.bash function custom_assert_equal() { if [[ $1 != "$2" ]]; then batslib_print_kv_single_or_multi 8 \ 'expected' "$2" \ 'actual' "$1" \ | batslib_decorate 'values are really not the same' \ | fail fi } ================================================ FILE: example-bats/test.sh ================================================ #!/bin/bash # Set project root as the working directory cd "$(dirname "$0")" # Run tests lib/bats-core/bin/bats -r test ================================================ FILE: example-shellspec/.gitignore ================================================ lib build ================================================ FILE: example-shellspec/.shellspec ================================================ --require spec_helper ## Default kcov (coverage) options # --kcov-options "--include-path=. --path-strip-level=1" # --kcov-options "--include-pattern=.sh" # --kcov-options "--exclude-pattern=/.shellspec,/spec/,/coverage/,/report/" ## Example: Include script "myprog" with no extension # --kcov-options "--include-pattern=.sh,myprog" ## Example: Only specified files/directories # --kcov-options "--include-pattern=myprog,/lib/" ================================================ FILE: example-shellspec/install.sh ================================================ #!/bin/bash cd "$(dirname "$0")" rm -rf lib mkdir lib cd lib curl -L -O -J https://github.com/shellspec/shellspec/archive/0.23.0.tar.gz tar -zxvf shellspec-0.23.0.tar.gz mv shellspec-0.23.0 shellspec ================================================ FILE: example-shellspec/readme.md ================================================ # ShellSpec test drive ShellSpec is the latest and the most featureful test framework I've found for Bash. It has sexy syntax and new releases are coming up frequently. However, it's also pretty new, first released in 2019. I expect some rough edges to be polished and some breaking API changes here. Also, while I really like its DSL, one has to decide if this is really his thing or not. I for one prefer BDD style for more end-user facing tests only, and I like it better if the unit tests are more similar to production code, so they can be used as concrete examples. ## Test format There's a specific DSL built into the framework to support BDD style tests: ```bash Describe 'lib.sh' Include ./lib.sh # include other script Describe 'calc()' It 'calculates' When call calc 1 + 1 The output should eq 2 End End End ``` ✔️ What's really interesting is that despite this DSL, files are simple Bash files. It's possible mix simple Bash statements and functions with the DSL, so even if the DSL lacks certain features, it's usually not a limitation. ⚠️ This language looks really neat and extensible, but on the other hand it's something that one have to get used to in order to write tests efficiently. ⚠️ Also, some features of this DSL are not on par what's achievable with Bash. For example, [currently it's only possible to have beforeAll and afterAll functions with Bash snippets](https://github.com/shellspec/shellspec/issues/7). ## Test Discovery ✔️ The test runner considers all files as tests that are in the spec folder and their name contains "spec". A subset of the tests can also be executed with filters, or it’s even possible to focus on a single test case. ✔️ It also expects a specific project structure, and comes with an initializer to generate that. ## Assertions ✔️ The framework provide many customizable/combinable assertions via it's DSL, and the failures generated by these assertions contain all necessary context information. ⚠️ Assertions can not be used in all places. For example I couldn't use them in after hooks when I wanted to check a post condition for each test. Althoug I could work around the issue with Bash snippets, it made the tests a bit harder to read. ## Custom assertions ✔️ The DSL itself is extensible with custom matchers. ⚠️ Compared with other frameworks where it's simply done by defining a function it's less straightforward. If all else fails Bash functions can be directly called from the tests, and with that custom assertions can be implemented. However it might have the downside that the basy code has to interface with the DSL, which might be not so convenient, and the test code will be a mix of DSL and bash. ## Mocking ✔️ Mocking is possible with all [three common techniques](https://github.com/dodie/testing-in-bash/tree/master/mocking): - alias - function export - PATH override ## Activity ⚠️ The project is really new, it's been around since 2019. This means that the project might have some rough edges, as some features are not polished yet. (E.g. the beforeAll functionality [was removed at one point](https://github.com/shellspec/shellspec/issues/7) because it was not ready yet.) ✔️ The project is very active, and had quite some releases over the past year. The author is active answering issues and taking care of PRs. ## Documentation ✔️ The project has [detailed examples](https://github.com/shellspec/shellspec/tree/master/sample/spec) on how to use the framework. Also, it has a [getting started guide](https://github.com/shellspec/shellspec/) and [website](https://shellspec.info/) covering the basics. ✔️ The thing I like the most is the interactive help. Although it's a bit confusing at first what assertions are available in the DSL, the tool helps with interactive help when it encounters an invalid expression. For example, I got the following error message when I tried to use the non-existent "contain" keyword: ```bash #"The output should contain 'Total'" Unknown word 'contain' after should verb. The correct word is one of the following. be, end, equal, eq, has, include, match, start, satisfy ``` ================================================ FILE: example-shellspec/spec/assertion_showcase_spec.sh ================================================ Describe 'assertion showcase' # Example for Skip It 'should display 100 for the price of a portion for low quantities' Skip 'this test is broken' When call src/ice_cream_price.sh 1 The output should equal 'Total 101' End # Example for a simple 'equals' assertion It 'should display 100 for the price of a portion for low quantities' When call src/ice_cream_price.sh 1 The output should equal 'Total 100' End # Example for a different assertion It 'should display "total"' When call src/ice_cream_price.sh 1 The output should start with 'Total' End # Example for a custom assertion It 'should use my custom assertion' When call src/ice_cream_price.sh 1 The output should regexp '.*Total.*' End End ================================================ FILE: example-shellspec/spec/e2e_test_spec.sh ================================================ Describe 'ice_cream_price.sh' It 'should display 100 for the price of a portion for low quantities' When call src/ice_cream_price.sh 1 The status should be success The output should equal 'Total 100' End It 'should give 20% discount for large quantities on odd days' # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="1" export PATH=spec/mocks:$PATH When call src/ice_cream_price.sh 4 The status should be success The output should equal 'Total 320' End It 'should give no discount even for large quantities on even days' # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="2" export PATH=spec/mocks:$PATH When call src/ice_cream_price.sh 4 The status should be success The output should equal 'Total 400' End End ================================================ FILE: example-shellspec/spec/mocks/date ================================================ #!/bin/bash echo "${DATE_MOCK_REPLY}" ================================================ FILE: example-shellspec/spec/setup_and_teardown_spec.sh ================================================ # Create test data directories function setup_suite() { mkdir -p build/testdata } setup_suite Describe 'file-report.sh' # Generate fresh example files for the tests setup() { rm -rf build/testdata mkdir -p build/testdata for i in {1..3} do echo "Hello $i" > "build/testdata/${i}.txt" done } # Assert that the tests did not remove the example files teardown() { local result result=$(ls build/testdata -1) [[ 0 -eq $? ]] # assert success [[ "${result}" == *"1.txt"* ]] [[ "${result}" == *"2.txt"* ]] [[ "${result}" == *"3.txt"* ]] } Before 'setup' After 'teardown' It 'should return the number of files in the directory' When call src/file-report.sh number-of-files build/testdata The status should be success The output should equal '3' End It 'should return the total size of the files in the directory' When call src/file-report.sh size build/testdata The status should be success The output should equal '16K' End End # Remove test data directories function teardown_suite() { rm -rf build/testdata } teardown_suite ================================================ FILE: example-shellspec/spec/spec_helper.sh ================================================ #shellcheck shell=sh # set -eu shellspec_spec_helper_configure() { shellspec_import 'support/custom_matcher' } ================================================ FILE: example-shellspec/spec/support/custom_matcher.sh ================================================ #shellcheck shell=sh # imported by "spec_helper.sh" shellspec_syntax 'shellspec_matcher_regexp' shellspec_matcher_regexp() { shellspec_matcher__match() { SHELLSPEC_EXPECT="$1" [ "${SHELLSPEC_SUBJECT+x}" ] || return 1 expr "$SHELLSPEC_SUBJECT" : "$SHELLSPEC_EXPECT" > /dev/null || return 1 return 0 } # Message when the matcher fails with "should" shellspec_matcher__failure_message() { shellspec_putsn "expected: $1 match $2" } # Message when the matcher fails with "should not" shellspec_matcher__failure_message_when_negated() { shellspec_putsn "expected: $1 not match $2" } # checking for parameter count shellspec_syntax_param count [ $# -eq 1 ] || return 0 shellspec_matcher_do_match "$@" } ================================================ FILE: example-shellspec/spec/unit_test_spec.sh ================================================ Describe 'ice_cream_price.sh' Include src/ice_cream_price.sh It 'should display 100 for the price of a portion for low quantities' When call main 1 The output should equal 'Total 100' End It 'should give 20% discount for large quantities on odd days' # Mocking a function by defining an alias shopt -s expand_aliases alias "getDay"="echo '1'" When call main 4 The output should equal 'Total 320' End It 'should give no discount even for large quantities on even days' # Mocking a function by exporting a function function getDay() { echo "2"; } export -f getDay When call main 4 The output should equal 'Total 400' End End ================================================ FILE: example-shellspec/src/file-report.sh ================================================ #!/bin/bash mode=$1 path=$2 if [ -z $path ]; then echo "Usage: ./file-report.sh [size|number-of-files] [path]"; >&2 exit 1 fi cd "${path}" case "${mode}" in number-of-files) ls -1 | wc -l ;; size) du -h | cut -f1 ;; *) >&2 echo "Usage: ./file-report.sh [size|number-of-files] [path]"; exit 1 ;; esac ================================================ FILE: example-shellspec/src/ice_cream_price.sh ================================================ #!/bin/bash function main() { numberOfPortions=$1 pricePerPortion=$(calculatePrice $numberOfPortions) totalPrice=$(( $numberOfPortions * $pricePerPortion )) echo "Total $totalPrice" } function calculatePrice() { if [[ $numberOfPortions -lt 3 ]]; then echo "100" else day=$(getDay) if (( $day % 2 )); then echo "80" else echo "100" fi fi } function getDay() { date -d '+%d' } if [[ "${BASH_SOURCE[0]}" == "${0}" ]] then main $@ fi ================================================ FILE: example-shellspec/src/myfun.sh ================================================ #!/bin/bash function myfun() { echo "Hello!" } ================================================ FILE: example-shellspec/test.sh ================================================ #!/bin/bash # Set project root as the working directory cd "$(dirname "$0")" # Run tests lib/shellspec/shellspec ================================================ FILE: example-shpec/.gitignore ================================================ lib ================================================ FILE: example-shpec/install.sh ================================================ #!/bin/bash cd "$(dirname "$0")" rm -rf lib mkdir lib cd lib VERSION=0.3.1 curl -sL https://github.com/rylnd/shpec/archive/${VERSION}.tar.gz | tar zx --strip-components=1 ================================================ FILE: example-shpec/readme.md ================================================ # Shpec test drive Shpec is a quite mature testing framework with it's first release from 2013. Its DSL is looks like a simpler version of [shellspec](https://github.com/dodie/testing-in-bash/tree/master/example-shellspec)'s DSL. Shpec tries to not implement things that can be done as easily in bash it self. ## Test format There's a specific DSL built into the framework to support BDD style tests: ```bash describe "ice_cream_price.sh (e2e)" it "should display 100 for the price of a portion for low quantities" assert equal "$(src/ice_cream_price.sh 1)" "Total 100" end end ``` ✔️ What's really interesting is that despite this DSL, files are simple Bash files. It's possible mix simple Bash statements and functions with the DSL, so even if the DSL lacks certain features, it's usually not a limitation. ⚠️ This language looks really neat and extensible, but on the other hand it's something that one have to get used to in order to write tests efficiently. ## Test Discovery ✔️ The test runner considers all files as tests that are in the shpec folder and their name ends in `_spec.sh`. By default all test cases are executed, by calling shpec with a shpec-file as the first parameter, only this case is tested. ✔️ It also expects a specific project structure, test files must be in the schema of `./shpec/**/*_shpec.sh`, custom matcher should be in `./shpec/matchers/` every thing else is up to you. ## Assertions ✔️ The framework provide [many](https://github.com/rylnd/shpec#matchers) customizable/combinable assertions via it's DSL, and the failures generated by these assertions contain all necessary context information. ## Custom assertions ✔️ The DSL itself is extensible with custom matchers. You can define custom matchers simply as functions, but in order to make them reusable, you have to put them in an extra file under `shpec/matchers/`. ⚠️ If all else fails Bash functions can be directly called from the tests, and with that custom assertions can be implemented. However it might have the downside that the bashy code has to interface with the DSL, which might be not so convenient, and the test code will be a mix of DSL and bash. ## Mocking ✔️ Mocking is possible with all [three common techniques](https://github.com/dodie/testing-in-bash/tree/master/mocking): - alias - function export - PATH override ✔️ Also there is [stubbing](https://github.com/rylnd/shpec#stubbing) build in. ## Activity ⚠️ The project is not in development right now, is seems to be in a "done enough" state. ✔️ The project had quite some releases over the past year. The author is active answering issues and taking care of PRs. ## Documentation ✔️ The project test's itself, the tests are not only functional but are written to be good [examples](https://github.com/rylnd/shpec/blob/master/shpec/shpec_shpec.sh). Also, the [Readme](https://github.com/rylnd/shpec/) gives a good overview on how to use and where to read more. ================================================ FILE: example-shpec/shpec/e2e_test_shpec.sh ================================================ #!/usr/bin/env bash export DATE_MOCK_REPLY PATH="$PWD/shpec/mocks:$PATH" DATE_MOCK_REPLY=1 describe "ice_cream_price.sh (e2e)" it "should display 100 for the price of a portion for low quantities" assert equal "$(src/ice_cream_price.sh 1)" "Total 100" end it "should not fail calculating" src/ice_cream_price.sh 1 >/dev/null assert equal $? 0 end it 'should give 20% discount for large quantities on odd days' DATE_MOCK_REPLY=1 assert equal "$(src/ice_cream_price.sh 5)" "Total 400" end it 'should give no discount even for large quantities on even days' DATE_MOCK_REPLY=2 assert equal "$(src/ice_cream_price.sh 5)" "Total 500" end end ================================================ FILE: example-shpec/shpec/matchers/ice_price.sh ================================================ #!/usr/bin/env bash ice_price(){ actual="$1" expected_num="$2" assert equal "$actual" "Total $expected_num" } ================================================ FILE: example-shpec/shpec/mocks/date ================================================ #!/bin/bash echo "${DATE_MOCK_REPLY}" ================================================ FILE: example-shpec/shpec/showcase_shpec.sh ================================================ #!/usr/bin/env bash describe 'assertion showcase' # Example for a simple 'equals' assertion it 'should display 100 for the price of a portion for low quantities' assert equal "$(src/ice_cream_price.sh 1)" 'Total 100' end # Example for a different assertion it 'should display "Total"' assert glob "$(src/ice_cream_price.sh 1)" 'Total*' end # Example for a custom assertion it 'should use my custom assertion' assert ice_price "$(src/ice_cream_price.sh 1)" 100 end end ================================================ FILE: example-shpec/shpec/unit_test_shpec.sh ================================================ #!/usr/bin/env bash . ./src/ice_cream_price.sh describe "ice_cream_price.sh (unit)" it "should display 100 for the price of a portion for low quantities" assert equal "$(main 1)" "Total 100" end it "should not fail calculating" main 1 >/dev/null assert equal $? 0 end it 'should give 20% discount for large quantities on odd days' stub_command getDay "echo 1" assert equal "$(main 5)" "Total 400" end it 'should give no discount even for large quantities on even days' stub_command getDay "echo 2" assert equal "$(main 5)" "Total 500" end end ================================================ FILE: example-shpec/src/file-report.sh ================================================ #!/bin/bash mode=$1 path=$2 if [ -z $path ]; then echo "Usage: ./file-report.sh [size|number-of-files] [path]"; >&2 exit 1 fi cd "${path}" case "${mode}" in number-of-files) ls -1 | wc -l ;; size) du -h | cut -f1 ;; *) >&2 echo "Usage: ./file-report.sh [size|number-of-files] [path]"; exit 1 ;; esac ================================================ FILE: example-shpec/src/ice_cream_price.sh ================================================ #!/bin/bash function main() { numberOfPortions=$1 pricePerPortion=$(calculatePrice $numberOfPortions) totalPrice=$(( $numberOfPortions * $pricePerPortion )) echo "Total $totalPrice" } function calculatePrice() { if [[ $numberOfPortions -lt 3 ]]; then echo "100" else day=$(getDay) if (( $day % 2 )); then echo "80" else echo "100" fi fi } function getDay() { date '+%d' } if [[ "${BASH_SOURCE[0]}" == "${0}" ]] then main $@ fi ================================================ FILE: example-shpec/src/myfun.sh ================================================ #!/bin/bash function myfun() { echo "Hello!" } ================================================ FILE: example-shpec/test.sh ================================================ #!/bin/bash # Set project root as the working directory cd "$(dirname "$0")" # Run tests lib/bin/shpec ================================================ FILE: example-shunit2/.gitignore ================================================ lib build ================================================ FILE: example-shunit2/install.sh ================================================ #!/bin/bash cd "$(dirname "$0")" rm -rf lib mkdir lib cd lib curl -L -O -J https://github.com/kward/shunit2/archive/v2.1.8.tar.gz tar -zxvf shunit2-2.1.8.tar.gz mv shunit2-2.1.8 shunit2 ================================================ FILE: example-shunit2/readme.md ================================================ # shUnit2 test drive shUnit2 is the great-grandmother of all bash test frameworks. I really like that the test files are plain old Bash files, and that it has lot's of assertions by default. However, regarding other features it seems to be lagging behind it's competitors. If you are after a testing framework where you can write tests in pure Bash scripts, make sure to also check [bash_unit](https://github.com/dodie/testing-in-bash/blob/master/example-bash_unit/). ## Test format ✔️ Test files are simple Bash scripts that one can execute. Functions are picked up by the test framework based on a naming convention, and overall the look and feel of a test file is very similar to JUnit. ⚠️ What I personally don't like is that the end of each test file shunit2 has to be sourced to do it's thing. This forces you to either put its executable to the PATH or some environment variable, or hardcode its path into each of the tests. ```bash testEquality() { assertEquals 1 1 } . ./shunit2 ``` ## Test Discovery ⚠️ Because the framework is invoked from each individual test file, it also means that there's no such thing as test discovery in shunit2. If you'd like to run your whole test suite, constituting multiple test files at once, you have to create some sort of custom launch mechanism that discovers and starts the test files. It's easy to get up and running with a [simple wrapper](https://github.com/dodie/testing-in-bash/blob/master/example-shunit2/test.sh), but things can easily get more complicated if you'd like to support proper test file discovery including subdirectories, partial execution, and executing all test files regardless of failures but still emit appropriate status code to indicate failures. Related: [kward/shunit/issues/52](https://github.com/kward/shunit2/issues/52) It has the concept of a test suite, but only in a single file. It can [take test function names as an argument](https://github.com/kward/shunit2#-running-specific-tests-from-the-command-line) to focus on some dedicated tests and only execute those. It does not support wildcard matching. ## Assertions ✔️ Among the frameworks I've checked, shUnit2 has the most assertions available by default: - `assertEquals` - `assertNotEquals` - `assertContains` - `assertNotContains` - `assertNull` - `assertNotNull` - `assertTrue` - `assertFalse` (In fact, there might be a bit too many of them, some providing similar functionalities like `assertEquals` and `assertSame`.) ✔️ They can also take optional messages that will be displayed upon failures, which is quite nice. ⚠️ One problem I found with these assertions is that by default they don't report the line number where the failure happened. To include line numbers, the framework provide [macros](https://github.com/kward/shunit2#-including-line-numbers-in-asserts-macros) instead of these assertions: ```bash ${_ASSERT_EQUALS_} '"not equal"' 2 2 ``` Using macros involve quite some line noise, and it's also a bit problematic that with this test files might become mixed, using both assertion functions and macros for the same reason. ## Custom assertions ✔️ It’s possible to [create new assertions](https://github.com/kward/shunit2/wiki/Cookbook) by building functions on top of the existing assertions, although there's no dedicated no dedicated lower-level API to support it. Custom assertions can be sourced from an external file. ## Skip tests ✔️ shUnit2 has an unique approach to skipping tests: instead of skipping whole test cases, here it's possible to skip certain assertions: ```bash assertEquals 1 1 # This assertion will run startSkipping assertEquals 1 1 # This assertion will be skipped endSkipping assertEquals 1 1 # This assertion will also run ``` If the test starts with `startsSkipping`, and there are no `stopSkipping` the whole test will be skipped. This can be handy to temporarily disable some faulty assertions in a test. ⚠️ From a reporting point of view however, things are a bit lacking compared to other frameworks. Skipping can't take an optional argument, so it's not easy to tell why it's skipped. Also, in the report there's no distinction between passed and skipped tests, the report will only mention the number of skipped assertions at the end. ```bash testEquality1 testEquality2 Ran 2 tests. OK (skipped=1) # Which one was skipped? :( ``` ## Mocking ⚠️ From the [three common techniques](https://github.com/dodie/testing-in-bash/tree/master/mocking), mocking is only working by using aliases or PATH override, but [not with function exports](https://github.com/dodie/testing-in-bash/blob/master/example-shunit2/test/unit_test.sh#L25-L38). This is a bit unfortunate since this technique seems to be the most versatile. ## Activity ⚠️ The project is around since 2007. Between 2011 and 2018 there were no releases, but the project seems to be awakening since then. accept PRs again since 2018. There's a huge number of old open issues and PRs. ## Documentation ✔️ The [example tests](https://github.com/kward/shunit2/tree/master/examples) make it very clear how to use the framework, and the project's [readme](https://github.com/kward/shunit2/) does not leave out a single feature. ================================================ FILE: example-shunit2/src/file-report.sh ================================================ #!/bin/bash mode=$1 path=$2 if [ -z $path ]; then echo "Usage: ./file-report.sh [size|number-of-files] [path]"; >&2 exit 1 fi cd "${path}" case "${mode}" in number-of-files) ls -1 | wc -l ;; size) du -h | cut -f1 ;; *) >&2 echo "Usage: ./file-report.sh [size|number-of-files] [path]"; exit 1 ;; esac ================================================ FILE: example-shunit2/src/ice_cream_price.sh ================================================ #!/bin/bash function main() { numberOfPortions=$1 pricePerPortion=$(calculatePrice $numberOfPortions) totalPrice=$(( $numberOfPortions * $pricePerPortion )) echo "Total $totalPrice" } function calculatePrice() { if [[ $numberOfPortions -lt 3 ]]; then echo "100" else day=$(getDay) if (( $day % 2 )); then echo "80" else echo "100" fi fi } function getDay() { date -d '+%d' } if [[ "${BASH_SOURCE[0]}" == "${0}" ]] then main $@ fi ================================================ FILE: example-shunit2/src/myfun.sh ================================================ #!/bin/bash function myfun() { echo "Hello!" } ================================================ FILE: example-shunit2/test/assertion_showcase.sh ================================================ #!/bin/bash # This test has a nice assertion... test_equality1() { assertEquals "not equal" 2 2 } # ... but only this one reports line numbers test_equality_2() { ${_ASSERT_EQUALS_} '"not equal"' 2 2 } function test_skipped() { startSkipping # This is broken #... } function test_partially_skipped() { # this is okay assertEquals "not equal" 2 2 startSkipping # But this is broken assertEquals "not equal" 1 2 } assertCustomEquals() { msg='' if [ $# -eq 3 ]; then msg="$1 " shift fi expected=$1 actual=$2 if [[ "${expected}" != "${actual}" ]]; then fail "${msg}expected '${expected}' but got '${actual}'" fi } testWithCustomAssert() { expected='shell' actual='shell' msg="This should be equal" assertCustomEquals "${msg}" "${expected}" "${actual}" } # Load shUnit2. . lib/shunit2/shunit2 ================================================ FILE: example-shunit2/test/e2e_test.sh ================================================ #!/bin/bash function test_ice_cream_price_should_be_100_per_portion_for_low_quantities() { result=$(src/ice_cream_price.sh 1) assertEquals $? 0 # assert success assertEquals "${result}" "Total 100" } function test_there_should_be_20_percent_discount_for_large_quantities_on_odd_days() { # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="1" export PATH=test/mocks:$PATH result=$(src/ice_cream_price.sh 4) assertEquals $? 0 # assert success assertEquals "${result}" "Total 320" } function test_there_should_be_no_discount_even_for_large_quantities_on_even_days() { # Mocking date by adding a custom executable to the PATH export DATE_MOCK_REPLY="2" export PATH=test/mocks:$PATH result=$(src/ice_cream_price.sh 4) assertEquals $? 0 # assert success assertEquals "${result}" "Total 400" } . lib/shunit2/shunit2 ================================================ FILE: example-shunit2/test/mocks/date ================================================ #!/bin/bash echo "${DATE_MOCK_REPLY}" ================================================ FILE: example-shunit2/test/setup_and_teardown.sh ================================================ #!/bin/bash # Create test data directories function oneTimeSetUp() { mkdir -p build/testdata } # Remove test data directories function oneTimeTearDown() { rm -rf build/testdata } # Generate fresh example files for the tests function setUp() { rm -rf build/testdata/* for i in {1..3} do echo "Hello $i" > "build/testdata/${i}.txt" done } # Assert that the tests did not remove the example files function tearDown() { # Here I've tried to assert on some post conditions for each # test, but I've bumped into a bug that prevented it. # https://github.com/kward/shunit2/issues/112 # oneTimeTearDown()/tearDown() is being called an additional time at the end of execution startSkipping result=$(ls build/testdata -1) assertEquals 0 $? # assert success assertContains "1.txt" "${result}" assertContains "2.txt" "${result}" assertContains "3.txt" "${result}" } function test_number-of-files_should_return_the_number_of_files_in_the_directory() { result=$(src/file-report.sh number-of-files build/testdata) assertEquals 0 $? assertEquals 3 "${result}" } function test_size_should_return_the_total_size_of_the_files_in_the_directory() { result=$(src/file-report.sh size build/testdata) assertEquals 0 $? assertEquals "16K" "${result}" } . lib/shunit2/shunit2 ================================================ FILE: example-shunit2/test/unit_test.sh ================================================ #!/bin/bash function test_ice_cream_price_should_be_100_per_portion_for_low_quantities() { source src/ice_cream_price.sh result=$(main 1) assertEquals 0 $? assertContains "${result}" "Total 100" } function test_there_should_be_20_percent_discount_for_large_quantities_on_odd_days() { # Mocking a function by defining an alias shopt -s expand_aliases alias "getDay"="echo '1'" source src/ice_cream_price.sh result=$(main 4) assertEquals 0 $? assertContains "${result}" "Total 320" } function test_there_should_be_no_discount_even_for_large_quantities_on_even_days() { # Mocking by exporting functions does not work for shunit2 startSkipping source src/ice_cream_price.sh # Mocking a function by exporting a function function getDay() { echo "2"; } export -f getDay result=$(main 4) assertEquals 0 $? assertContains "${result}" "Total 400" } . lib/shunit2/shunit2 ================================================ FILE: example-shunit2/test.sh ================================================ #!/bin/bash # Set project root as the working directory cd "$(dirname "$0")" for testfile in test/*.sh do echo "Running tests in ${testfile}:" $testfile done ================================================ FILE: mocking/src/greeting.sh ================================================ #!/bin/bash function hello() { local username=$1 if [[ "$(day_of_week)" == "Friday" ]]; then echo "What a wonderful day, $username!" else echo "Hello, $username" fi } function day_of_week() { date +%A } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then hello "John" fi ================================================ FILE: mocking/test/mocks/date ================================================ #!/bin/bash echo "Friday" ================================================ FILE: mocking/test/test-alias-date.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Set up mocks shopt -s expand_aliases alias "date"="echo 'Friday';true" # Include the function to be tested SRC="${script_dir}/../src" source ${SRC}/greeting.sh # Execute test case result=$(hello "John") # Verify results expected="What a wonderful day, John!" if [[ "${result}" == "${expected}" ]]; then echo "Test passed!" else echo "Test failed!" exit 1 fi ================================================ FILE: mocking/test/test-alias-own.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Set up mocks shopt -s expand_aliases alias day_of_week="echo 'Friday'" # Include the function to be tested SRC="${script_dir}/../src" source ${SRC}/greeting.sh # Execute test case result=$(hello "John") # Verify results expected="What a wonderful day, John!" if [[ "${result}" == "${expected}" ]]; then echo "Test passed!" else echo "Test failed!" exit 1 fi ================================================ FILE: mocking/test/test-export-date.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Include the function to be tested SRC="${script_dir}/../src" source ${SRC}/greeting.sh # Set up mocks function date() { echo "Friday" } export -f day_of_week # Execute test case result=$(hello "John") # Verify results expected="What a wonderful day, John!" if [[ "${result}" == "${expected}" ]]; then echo "Test passed!" else echo "Test failed!" exit 1 fi ================================================ FILE: mocking/test/test-export-own.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Include the function to be tested SRC="${script_dir}/../src" source ${SRC}/greeting.sh # Set up mocks function day_of_week() { echo "Friday" } export -f day_of_week # Execute test case result=$(hello "John") # Verify results expected="What a wonderful day, John!" if [[ "${result}" == "${expected}" ]]; then echo "Test passed!" else echo "Test failed!" exit 1 fi ================================================ FILE: mocking/test/test-pathoverride-date.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Add mocks to the path export PATH=mocks:$PATH # Execute test case SRC="${script_dir}/../src" result=$(${SRC}/greeting.sh "John") # Verify results expected="What a wonderful day, John!" if [[ "${result}" == "${expected}" ]]; then echo "Test passed!" else echo "Test failed!" exit 1 fi ================================================ FILE: readme.md ================================================ # In search of the best test framework for Bash There are [many testing frameworks for Bash](https://stackoverflow.com/questions/1339416/unit-testing-bash-scripts). However, many of them are not actively maintained, or are used only by a small group of people. In this comparision I've included well-established and new testing frameworks that had at least recent release and have more than 50 Stars on GitHub: - [bashunit](https://github.com/TypedDevs/bashunit), a fast, simple and flexible testing library for your bash scripts - [Bats](https://github.com/bats-core/bats-core), a mature testing library with a bit of a custom syntax for more concise tests - [shUnit2](https://github.com/kward/shunit2), possibly the oldest Bash test framework around, supporting test files in pure Bash - [bash_unit](https://github.com/pgrange/bash_unit), a new and featureful test framework where test cases can be written in pure Bash - [ShellSpec](https://github.com/shellspec/shellspec), a BDD style testing framework with its own DSL - [shpec](https://github.com/rylnd/shpec), a BDD style testing framework similar to RSpec, Jasmine, and mocha ## Test drive To start fiddling with any of the test projects just run the `install.sh` to download and extract the particular testing framework to a local directory, then execute `test.sh` to start the suite. - [bashunit example project and test drive](example-bashunit) - [Bats example project and test drive](example-bats) - [shUnit2 example project and test drive](example-shunit2) - [bash_unit example project and test drive](example-bash_unit) - [ShellSpec example project and test drive](example-shellspec) - [shpec example project and test drive](example-shpec) ## Detailed comparision | | [bashunit](https://github.com/TypedDevs/bashunit) | [Bats](https://github.com/bats-core/bats-core) | [shUnit2](https://github.com/kward/shunit2) | [bash_unit](https://github.com/pgrange/bash_unit) | [ShellSpec](https://github.com/shellspec/shellspec) | [shpec](https://github.com/rylnd/shpec) | |------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|----------------------------------------------------------------------------|---------------------------------------------------------------------|-----------------------------------------| | Discover and run all tests
in the project | ✔️ | ✔️ | ❌ [?](example-shunit2#test-discovery) | ⚠ [?](example-bash_unit#test-discovery) | ✔️ [?](example-shellspec#test-discovery) | ✔️ | | Run subset of tests or
a specific test | ✔️ | ✔️ [?](example-bats#test-discovery) | ⚠ [?](example-shunit2#test-discovery) | ✔️ | ✔️ | ❌ [issue](https://github.com/rylnd/shpec/issues/31) | | Parallel test execution | ✔️ | ✔️ | ❌ | ❌ | ✔️ | ❌ | | Skip or ignore tests | ✔️ | ✔️ | ⚠ [?](example-shunit2#skip-tests) | ✔️ [?](example-bash_unit#skip-tests) | ✔️ | ❌ [issue](https://github.com/rylnd/shpec/issues/57) | | Rich assertion library | ✔️ | ⚠ [?](example-bats#assertions) | ⚠ [?](example-shunit2#assertions) | ⚠ [?](example-bash_unit#assertions) | ✔️ [?](example-shellspec#assertions) | ✔️ [?](example-shpec#assertions) | | Extensible with custom assertions | ✔️ | ✔️ [?](example-bats#custom-assertions) | ✔️ [?](example-shunit2#custom-assertions) | ✔️ [?](example-bash_unit#custom-assertions) | ✔️ [?](example-shellspec#custom-assertions) | ✔️ [?](example-shpec#custom-assertions) | | Before / After | ✔️ | ✔️ | ⚠ [issue](https://github.com/kward/shunit2/issues/112) | ✔️ | ✔️ | ❌ [issue](https://github.com/rylnd/shpec/issues/52) | | BeforeAll / AfterAll | ✔️ | ❌ [issue](example-bats#test-discovery) | ⚠ [issue](https://github.com/kward/shunit2/issues/112) | ✔️ | ✔️ [?](example-shellspec#test-format) | ❌ [issue](https://github.com/rylnd/shpec/issues/52) | | Parameterized tests
and test data | ✔️ | ❌ [issue](https://github.com/sstephenson/bats/issues/136) | ❌ | ❌ | ✔️ | ❌ | | Mocking \* | ✔️ | ✔️ [?](example-bats#mocking) | ⚠ [?](example-shunit2#mocking) | ✔️ [?](example-bash_unit#mocking) | ✔️ [?](example-shellspec#mocking) | ✔️ [?](example-shpec#mocking) | | Isolation between tests \*\* | ✔️ | ✔️ [doc](https://github.com/bats-core/bats-core/wiki/Bats-Evaluation-Process) | ❌ | ✔️ | ✔️ | | | Nice local report | ✔️ | ⚠ [?](example-bats#report) | ✔️ | ✔️ | ✔️ | ✔️ | | CI compatible report | ✔️ | ✔️ [TAP](http://testanything.org/) | ❌ [issue](https://github.com/kward/shunit2/issues/31) | ✔️ [TAP](http://testanything.org/) | ✔️ [TAP](http://testanything.org/) | ❌ | | Zero Dependency and
implemented in Bash \*\*\* | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | Easy to install \*\*\*\* | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | Tests written in Bash | ✔️ | ⚠ [almost](example-bats#test-format) | ✔️ | ✔️ | ❌ [?](example-shellspec#test-format) | ❌ [?](example-shpec#test-format) | | Compatible with the
Unofficial Bash Strict Mode \*\*\*\*\* | ✔️ | ✔️| ⚠ [?](https://github.com/dodie/testing-in-bash/tree/master/example-bats#unit-testing-scripts-that-set-bash-options) | ✔️ | ⚠ [issue](https://github.com/pgrange/bash_unit/issues/61) | ✔️ | | | Maintained | ✔️ | ⚠ [?](example-bats#activity) | ⚠ [?](example-shunit2#activity) | ✔️ [?](example-bash_unit#activity) | ✔️ [?](example-shellspec#activity) | ⚠ [?](example-shpec#activity) | | Mature | ❌ [since 2023](https://github.com/TypedDevs/bashunit/releases) | ✔️ [since 2011](https://github.com/bats-core/bats-core/releases) | ✔️ [since 2007](https://github.com/kward/shunit2/commits/master?after=0f0a77b6b257f24d2b3ef1b28096fdd154a19f22+10) | ✔️ [since 2016](https://github.com/pgrange/bash_unit/releases) | ❌ [since 2019](https://github.com/shellspec/shellspec/releases) | ✔️ [since 2013](https://github.com/rylnd/shpec/releases) | | Good documentation | ✔️ [?](https://bashunit.typeddevs.com) | ⚠ [?](example-bats#documentation) | ✔️ [?](example-shunit2#documentation) | ✔️ [?](example-bash_unit#documentation) | ✔️ [?](example-shellspec#documentation) | ✔️ [?](example-shpec#documentation) | \* **Mocking**:
The testing framework is compatible with the [common mocking techniques](https://github.com/dodie/testing-in-bash/tree/master/mocking). \*\* **Isolation between tests**:
Aliases, custom function definitions, Bash options and variables are not leaking from one test to another. \*\*\* **Zero Dependency and implemented in Bash**:
Apart from a few common tools like `coreutils` and `grep`, you don't need anything to use the framework.
The source code of the framework is itself implemented as Bash scripts. If you are comfortable with Bash, you can read and even modify it. \*\*\*\* **Easy to install**:
Many of the frameworks support more than one alternatives on how to set it up quickly. It's possible to install it with your favourite package manager and some of them even have an official Docker image. Personally, I try to avoid installing project dependencies globally as much as I can, so I just decided to grab a tar.gz file with the latest release from GitHub. \*\*\*\*\* **Compatible with the Unofficial Bash Strict Mode**:
Sourcing a script file that use the [Unofficial Bash Strict Mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) should not break the test framework. Of course, custom assertions and the test code [should also work with strict mode](https://github.com/dodie/testing-in-bash/tree/master/strictmode) but that's up for the user. Also, the test framework shouldn't set Bash options as well to ensure that executing sourced functions work similarly to when they are not sourced. ## Related posts, other comparisions - https://medium.com/wemake-services/testing-bash-applications-85512e7fe2de - https://stackoverflow.com/questions/1339416/unit-testing-bash-scripts - https://www.leadingagile.com/2018/10/unit-testing-shell-scriptspart-one/ ## Contribution guide If you know a testing framework that should be mentioned here or find that there's room for improvement feel free to open an issue or Pull Request. (See [CONTRIBUTING.md](https://github.com/dodie/testing-in-bash/blob/master/CONTRIBUTING.md).) ================================================ FILE: stdio/src/interactive_greeter.sh ================================================ #!/bin/bash echo "Please enter your name:" >&2 read name echo "Hello, ${name}!" echo "Please enter your age:" >&2 read age echo "You are ${age} years old" ================================================ FILE: stdio/test/test_stdio.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" SRC="${script_dir}/../src" echo "Test that the program takes user input and prints the result to the standard output (verifying multiple lines)" result=$(printf "John\n42\n" | ${SRC}/interactive_greeter.sh 2>/dev/null) expected=$(printf "Hello, John!\nYou are 42 years old") if [[ "${result}" == "${expected}" ]]; then echo "Test passed!" else echo "Test failed!" exit 1 fi echo "Test that the program ask questions via standard error" result=$(printf "Any\n12\n" | ${SRC}/interactive_greeter.sh 2>&1 >/dev/null) expected=$(printf "Please enter your name:\nPlease enter your age:") if [[ "${result}" == "${expected}" ]]; then echo "Test passed!" else echo "Test failed!" exit 1 fi ================================================ FILE: strictmode/readme.md ================================================ # Unit testing scripts that use the [Unofficial Bash Strict Mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) In this module there are two scripts, one that sets `-e` and `pipefail`, and one that sets `-u`. There's a test for each of these files that first executes the corresponding script to demonstrate it's behavior on edge cases, then it sources the script to exercise its functions directly. The test files demonstrate two common problems that might come up in this setup: - Bash options "leak" from the sourced file to the test file, changing its behavior. - By default, `-e` does not apply to functions executed in a subshell. This can be problematic for unit tests where the output of a function is captured by the following construct: `result=$(myfunction)`. ================================================ FILE: strictmode/src/using_e.sh ================================================ #!/bin/bash # The script makes a HTTP GET to the URL passed in the argument. # For successful queries it prints the result code (e.g. 200). # For failures the script prints nothing and exits with a non-zero code. # # This achieved by setting bash opt errexit to make the script fail early # and passig the --fail parameter to curl to fail on errors. set -e function getResponseCode() { local url=$1 local result result=$(curl --fail -o /dev/null -s -w "%{http_code}\n" "${url}") echo $result } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then getResponseCode "$1" fi ================================================ FILE: strictmode/src/using_no_e.sh ================================================ #!/bin/bash # The script makes a HTTP GET to the URL passed in the argument. # It prints the result code for (e.g. 200). # For failures the script prints ERROR. # In both cases the script exists with 0 status code. # # This achieved by not setting bash opt errexit, so the script continues even if there's an error. # However, curl uses --fail which makes it exit with a non-zero code for failures (e.g. HTTP 404). # This has no effect unless the script is executed in an environment where errexit is set. function getResponseCode() { local url=$1 local result result=$(curl --fail -o /dev/null -s -w "%{http_code}\n" "${url}") echo $result } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then getResponseCode "$1" fi ================================================ FILE: strictmode/src/using_no_u.sh ================================================ #!/bin/bash # When called with a parameter, the script will print YES. # Otherwise, it will print NO. # In either case, it will exit with 0. # | » ./using_no_u.sh # | NO # | » echo $? # | 0 # # | » ./using_no_u.sh test # | YES # | » echo $? # | 0 # # If we'd define set -u, it will make the script fail in the NO case. function main() { if [ -n "$1" ]; then echo "YES" else echo "NO" fi } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main $@ fi ================================================ FILE: strictmode/src/using_u.sh ================================================ #!/bin/bash # When called without a parameter, this script will fail due to # an unbound variable in the 'main' function. # | » ./using_u.sh # | ../src/faulty_functions.sh: line 10: 1: unbound variable # | » echo $? # | 1 # # When called with a parameter, it will finish without an error. # | » ./using_u.sh something # | The parameter is: something # | » echo $? # | 0 # # This line enables the 'nounset' Bash option. # From the man page: # -u Treat unset variables and parameters other than the special parameters "@" and "*" # as an error when performing parameter expansion. If expansion is attempted on an # unset variable or parameter, the shell prints an error message, and, if not interactive, # exits with a non-zero status. set -u function main() { # When called without a parameter it should cause the program to terminate due to -u echo "The parameter is: ${1}" } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main $@ fi ================================================ FILE: strictmode/test/unit_test_script_using_e_o_pipefail.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" SRC="${script_dir}/../src" echo "E2E Test case: early failure due to a non-zero exit status" echo "==========================================================" echo "Executing src/using_e_o_pipefail.sh without an argument does the following:" echo " - output 'Start', but not 'End'" echo " - terminate with a non-zero exit code" result=$("${SRC}/using_e_o_pipefail.sh") sc=$? echo "" echo "Output:" echo "=======" echo "${result}" echo "" echo "Exit code:" echo "==========" echo "${sc}" echo "" echo "" echo "It works as expected." echo "Let's see what happens if we source the script file and to execute it's main" echo "function directly in the same manner." echo "" echo "" source "${SRC}/using_e_o_pipefail.sh" echo "" echo "" echo "Unit Test case: -e does not apply when the function is executed in a subshell" echo "=============================================================================" echo "When executing the main function directly, we might expect that the test suite" echo "terminates early with a non-zero exit code, because we sourced a script with" echo "a line set -e, and we execute a faulty function in a subshell." echo "However, the sad reality is the following:" result=$(main) sc=$? echo "" echo "Output:" echo "=======" echo "${result}" echo "" echo "Exit code:" echo "==========" echo "${sc}" echo "" echo "The explanation is in the man page:" echo "> Subshells spawned to execute command substitutions inherit the value of" echo "> the -e option from the parent shell. When not in posix mode, bash" echo "> clears the -e option in such subshells." echo "" echo "So, although -e is leaked to the test from the sourced file, it has no effect on subshells" echo "unless posix mode (or inherit_errexit) is enabled." echo "This can cause problems with unit testing functions where one might" echo "capture the result of a function with subshells." echo "Not sure if it's a good idea, but enabling posix mode (or inherit_errexit) would fix this issue." echo " - set -o posix" echo " - shopt -s inherit_errexit" echo "" echo "" echo "Unit Test case: the leaked -e modifies the behavior of the test" echo "===============================================================" echo "Lets' conclude this demonstration with an unit test should work normally," echo "but fails because the -e mode leaks from the sourced file" # Grep will exit with a 0 exit code when there's a match, and with anon-zero exitcode otherwise # The next tests try to use this to check whether or not the output contains a certain string main special | grep special sc=$? if [ $? -eq 0 ]; then echo "Test passed, output contains 'special'" fi main special | grep somethingelse sc=$? if [ $? -ne 0 ]; then echo "Test passed, output does not contain 'somethingelse'" fi ================================================ FILE: strictmode/test/unit_test_script_using_u.sh ================================================ #!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" SRC="${script_dir}/../src" echo "E2E Test case: early failure due to a non-zero exit status" echo "==========================================================" echo "Executing src/using_u.sh without an argument does the following:" echo " - output 'Start' only" echo " - terminate with a non-zero exit code" result=$("${SRC}/using_u.sh") sc=$? echo "" echo "Output:" echo "=======" echo "${result}" echo "" echo "Exit code:" echo "==========" echo "${sc}" echo "" echo "" echo "It works as expected." echo "Let's see what happens if we source the script file and to execute it's main" echo "function directly in the same manner." echo "" echo "" source "${SRC}/using_u.sh" echo "" echo "" echo "Unit Test case: -u applies to functions invoked in a subshell" echo "=============================================================" echo "After the case of -e I expected that -u is also ignored in subshells," echo "but it seems that after all, they are considered. The following unit test" echo "works similarly to the end-to-end test." result=$(main) sc=$? echo "" echo "Output:" echo "=======" echo "${result}" echo "" echo "Exit code:" echo "==========" echo "${sc}" echo "" echo "" echo "Unit Test case: the leaked -u modifies the behavior of the test" echo "===============================================================" echo "Lets' conclude this demonstration with an unit test should work normally," echo "but fails because the -u mode leaks from the sourced file" # The next test tries to check that a hello variable is not created during the execution of the function. However, it fails, because -u changes how undefined variables can be detected. main hello if [ -n $HELLO ]; then echo "Test passed!" else echo "Test failed!" fi