### Setup for Echo Server Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md Defines the setup for an echo server test. It loads common setup, starts the server, and exports the port. This function runs once before all tests in the file. ```bash setup_file() { load 'test_helper/common-setup' _common_setup PORT=$(project.sh start-echo-server 2>&1 >/dev/null) export PORT } @test "server is reachable" { nc -z localhost "$PORT" } ``` -------------------------------- ### Install Bats from Source Source: https://github.com/bats-core/bats-core/blob/master/docs/source/installation.md Clone the Bats repository and use the install script to install Bats from source to a specified prefix. ```bash $ git clone https://github.com/bats-core/bats-core.git $ cd bats-core $ ./install.sh /usr/local ``` -------------------------------- ### Install Bats on Ubuntu Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs Bats on Ubuntu by adding a PPA, updating package lists, and then installing the bats package. ```bash sudo add-apt-repository ppa:duggan/bats sudo apt-get update sudo apt-get install bats ``` -------------------------------- ### Setup and Teardown Hooks Order Source: https://github.com/bats-core/bats-core/blob/master/docs/source/writing-tests.md Illustrates the execution order of setup, teardown, setup_file, teardown_file, setup_suite, and teardown_suite hooks in a multi-file test suite. ```text setup_suite # from setup_suite.bash setup_file # from file 1, on entering file 1 setup test1 teardown setup test2 teardown teardown_file # from file 1, on leaving file 1 setup_file # from file 2, on enter file 2 setup test3 teardown teardown_file # from file 2, on leaving file 2 teardown_suite # from setup_suite.bash ``` -------------------------------- ### Load helper libraries in Bats Source: https://github.com/bats-core/bats-core/blob/master/docs/source/faq.md Helper libraries like bats-assert can be loaded using the 'load' function within the setup() function. Ensure the library is installed in a 'test_helper' directory. ```bash setup() { load 'test_helper/bats-support/load' # this is required by bats-assert! load 'test_helper/bats-assert/load' } @test "test" { run echo test assert_output "test" } ``` -------------------------------- ### Install Bats from Source on Windows with Git Bash Source: https://github.com/bats-core/bats-core/blob/master/docs/source/installation.md Clone the Bats repository and use the install script to install Bats from source to the HOME directory on Windows using Git Bash. ```bash $ git clone https://github.com/bats-core/bats-core.git $ cd bats-core $ ./install.sh $HOME ``` -------------------------------- ### Main Test File Setup Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md This bats test file sets up the testing environment by loading the common setup script. It ensures that shared configurations and paths are available for tests. ```bats setup() { load 'test_helper/common-setup' _common_setup } ``` -------------------------------- ### Install Bats on openSUSE Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs Bats on openSUSE using the zypper package manager. ```bash zypper install bats ``` -------------------------------- ### Load Bats Libraries in Setup Source: https://github.com/bats-core/bats-core/blob/master/docs/source/docker-usage.md Loads the bats-support and bats-assert libraries within the setup function of a bats test file. ```bash setup() { bats_load_library bats-support bats_load_library bats-assert } ``` -------------------------------- ### Alpine Linux Package Update Example Source: https://github.com/bats-core/bats-core/blob/master/docs/releasing.md Example of how to prepare an Alpine Linux package for a new Bats version, including fetching the zip archive and calculating its SHA512 sum. ```bash curl -LOv https://github.com/bats-core/bats-core/archive/v1.1.0.zip openssl sha512 v1.1.0.zip ``` -------------------------------- ### Install Bats in Dockerfile Source: https://github.com/bats-core/bats-core/wiki/Install Integrate Bats into a Docker image by installing a specific tagged release. This example is suitable for Debian-based images. ```dockerfile ... # Set tagged release version of Bats to use. This could be also set in docker-compose. ARG BATS_VERSION="1.7.0" # Install bats RUN batstmp="$(mktemp -d bats-core-${BATS_VERSION}.XXXX)" \ && echo ${batstmp} \ && cd ${batstmp} \ && curl -SLO https://github.com/bats-core/bats-core/archive/refs/tags/v${BATS_VERSION}.tar.gz \ && tar -zxvf v${BATS_VERSION}.tar.gz \ && bash bats-core-${BATS_VERSION}/install.sh /usr/local \ && rm -rf "${batstmp}" ``` -------------------------------- ### Common Test Setup Script Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md This bash script provides common setup routines for tests, including loading bats support libraries and setting up the project root path. It's designed to be loaded by other test files. ```bash #!/usr/bin/env bash _common_setup() { load 'test_helper/bats-support/load' load 'test_helper/bats-assert/load' # get the containing directory of this file # use $BATS_TEST_FILENAME instead of ${BASH_SOURCE[0]} or $0, # as those will point to the bats executable's location or the preprocessed file respectively PROJECT_ROOT="$( cd "$( dirname "$BATS_TEST_FILENAME" )/.." >/dev/null 2>&1 && pwd )" # make executables in src/ visible to PATH PATH="$PROJECT_ROOT/src:$PATH" } ``` -------------------------------- ### Install Bats with npm Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs the bats-core npm package globally using npm. ```bash $ npm install -g bats ``` -------------------------------- ### Install Bats Core with Homebrew on macOS Source: https://github.com/bats-core/bats-core/blob/master/docs/source/installation.md Use this command to install Bats Core if you have Homebrew installed on macOS. ```bash $ brew install bats-core ``` -------------------------------- ### Setup Function to Add Script Directory to PATH Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md Define a setup function within the test file to add the script's directory to the system's PATH. This allows scripts to be called without specifying their relative path. ```bash setup() { # get the containing directory of this file # use $BATS_TEST_FILENAME instead of ${BASH_SOURCE[0]} or $0, # as those will point to the bats executable's location or the preprocessed file respectively DIR="$( cd "$( dirname "$BATS_TEST_FILENAME" )" >/dev/null 2>&1 && pwd )" # make executables in src/ visible to PATH PATH="$DIR/../src:$PATH" } @test "can run our script" { # notice the missing ./ # As we added src/ to $PATH, we can omit the relative path to `src/project.sh`. project.sh } ``` -------------------------------- ### Install Newer Bats-core on Alpine Linux Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs the newer bats-core version on Alpine Linux by downloading, unzipping, and installing from source. ```bash sudo apk add coreutils ncurses curl -#L https://github.com/bats-core/bats-core/archive/master.zip | unzip - sudo bash bats-core-master/install.sh /usr/local rm -rf ./bats-core-master ``` -------------------------------- ### Install Bats with bpkg Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs the bats-core package globally using the bpkg package manager. ```bash $ bpkg install -g bats-core/bats-core ``` -------------------------------- ### Bats Test Setup with Load Paths Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md Configures the Bats test environment by loading necessary helper libraries and setting up the PATH to include executables from the src directory. ```bash setup() { load 'test_helper/bats-support/load' load 'test_helper/bats-assert/load' # ... the remaining setup is unchanged # get the containing directory of this file # use $BATS_TEST_FILENAME instead of ${BASH_SOURCE[0]} or $0, # as those will point to the bats executable's location or the preprocessed file respectively DIR="$( cd "$( dirname "$BATS_TEST_FILENAME" )" >/dev/null 2>&1 && pwd )" # make executables in src/ visible to PATH PATH="$DIR/../src:$PATH" } ``` -------------------------------- ### Install Bats from GitHub Branch Archive Source: https://github.com/bats-core/bats-core/wiki/Install Download and install Bats from the master branch archive. Use this for the latest development version. ```bash branch=master batstmp="$(mktemp -d bats-core-"${branch}".XXXXX)" pushd "${batstmp}" &> /dev/null || return 11 curl -sSLO https://github.com/bats-core/bats-core/archive/refs/heads/"${branch}".zip unzip -qo "${branch}".zip sudo bash "${batstmp}"/bats-core-"${branch}"/install.sh /usr/local popd &> /dev/null || return 12 command -v bats && rm -rf "${batstmp}" ``` -------------------------------- ### Example Announcement Text Source: https://github.com/bats-core/bats-core/blob/master/docs/releasing.md An example announcement for a new Bats version, suitable for platforms like Gitter, highlighting availability on Homebrew and NPM, and its eventual inclusion in Alpine Linux. ```text v1.1.0 is now available via Homebrew and npm: https://github.com/bats-core/bats-core/releases/tag/v1.1.0 It'll eventually be available in Alpine via the edge branch of the community repo once alpinelinux/aports#4696 gets merged. (Check /etc/apk/repositories to ensure this repo is enabled.) ``` -------------------------------- ### Install Bats on Fedora Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs Bats on Fedora using the dnf package manager. ```bash sudo dnf install bats ``` -------------------------------- ### Install Bats on macOS Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs Bats on macOS using the Homebrew package manager. ```bash brew install bats-core ``` -------------------------------- ### Install Bats from GitHub Release Source: https://github.com/bats-core/bats-core/wiki/Install Download and install a specific tagged release of Bats from GitHub. This method is suitable for reproducible builds. ```bash tag=1.1.0 batstmp="$(mktemp -d bats-core-"${tag}".XXXXX)" pushd "${batstmp}" &> /dev/null || return 11 curl -sSLO https://github.com/bats-core/bats-core/archive/refs/tags/v"${tag}".tar.gz tar -zxvf v"${tag}".tar.gz sudo bash "${batstmp}"/bats-core-"${tag}"/install.sh /usr/local popd &> /dev/null || return 12 command -v bats && rm -rf "${batstmp}" ``` -------------------------------- ### Install Bats with Basher Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs the GIT master version of bats-core/bats-core using the Basher package manager. Set BASHER_FULL_CLONE=true for full clone. ```bash basher install bats-core/bats-core ``` -------------------------------- ### Install Bats on Arch Linux Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs the bats-core package on Arch Linux using an AUR helper like pacaur. ```bash pacaur -Sa bats-core ``` -------------------------------- ### Install Bats as Root using GNU Stow Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-GNU-Stow Installs Bats to a system-wide Stow directory. This method requires root privileges and ensures older versions are removed before installing the new one. ```bash stow=/usr/local/stow version=$(libexec/bats -v | tr A-Z a-z | tr ' ' -) # Unstow older versions of Bats. shopt -s nullglob old_bats=(`find "$stow" -type d -name bats-*") for package in "${old_bats[@]}"; do sudo stow --dir="$stow" --delete $(basename "$package") done sudo ./install.sh "${stow}/${version}" sudo stow --dir="$stow" --restow "$version" ``` -------------------------------- ### Install Bats npm Package Globally Source: https://github.com/bats-core/bats-core/blob/master/docs/source/installation.md Install the Bats npm package globally for system-wide access. ```bash # To install globally: $ npm install -g bats ``` -------------------------------- ### Test for Helper Script Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md This bats test file loads common setup and tests the `_is_first_run` function from the helper script. It uses temporary files to simulate different run states. ```bats setup() { load 'test_helper/common-setup' _common_setup source "$PROJECT_ROOT/src/helper.sh" } teardown() { rm -f "$NON_EXISTENT_FIRST_RUN_FILE" rm -f "$EXISTING_FIRST_RUN_FILE" } @test "Check first run" { NON_EXISTENT_FIRST_RUN_FILE=$(mktemp -u) # only create the name, not the file itself assert _is_first_run "$NON_EXISTENT_FIRST_RUN_FILE" refute _is_first_run "$NON_EXISTENT_FIRST_RUN_FILE" refute _is_first_run "$NON_EXISTENT_FIRST_RUN_FILE" EXISTING_FIRST_RUN_FILE=$(mktemp) refute _is_first_run "$EXISTING_FIRST_RUN_FILE" refute _is_first_run "$EXISTING_FIRST_RUN_FILE" } ``` -------------------------------- ### Load a test helper library Source: https://github.com/bats-core/bats-core/blob/master/docs/source/writing-tests.md Use `bats_load_library` to load system-wide libraries. Set `BATS_LIB_PATH` to a colon-delimited list of directories where libraries are installed. ```bash bats_load_library test_helper ``` -------------------------------- ### Echo Server Implementation Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md Provides the implementation for starting an echo server using ncat. It listens on a specified port and echoes received data. The process ID is stored for later termination. ```bash case $1 in start-echo-server) echo "Starting echo server" PORT=2000 ncat -l $PORT -k -c 'xargs -n1 echo' 2>/dev/null & echo $! > /tmp/project-echo-server.pid echo "$PORT" >&2 ;; *) echo "NOT IMPLEMENTED!" >&2 exit 1 ;; esac ``` -------------------------------- ### Install Old Bats on Alpine Linux Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-a-Package Installs the older version of Bats on Alpine Linux, requiring coreutils and optionally ncurses for pretty output. ```bash # coreutils is needed because busybox `readlink` is not supported by BATS sudo apk add coreutils bats sudo apk add ncurses # Needed to support 'pretty' output ``` -------------------------------- ### Demonstrate Locale-Specific Signal Error Source: https://github.com/bats-core/bats-core/blob/master/docs/CONTRIBUTING.md This example demonstrates how using lowercase signal names can lead to errors in specific locales, while uppercase names work correctly. ```bash echo "tr_TR.UTF-8 UTF-8" >> /etc/locale.gen && locale-gen tr_TR.UTF-8 # Ubuntu derivatives LC_CTYPE=tr_TR.UTF-8 LC_MESSAGES=C bash -c 'trap - int && echo success' bash: line 0: trap: int: invalid signal specification LC_CTYPE=tr_TR.UTF-8 LC_MESSAGES=C bash -c 'trap - INT && echo success' success ``` -------------------------------- ### Homebrew Formula Update Example Source: https://github.com/bats-core/bats-core/blob/master/docs/releasing.md Example of how to update a Homebrew formula for a new Bats version, including fetching the tarball, calculating its SHA256 sum, and using 'brew bump-formula-pr'. ```bash curl -LOv https://github.com/bats-core/bats-core/archive/v1.1.0.tar.gz openssl sha256 v1.1.0.tar.gz # Add the --dry-run flag to see the individual steps without executing. brew bump-formula-pr \ --url=https://github.com/bats-core/bats-core/archive/v1.1.0.tar.gz \ --sha256=855d8b8bed466bc505e61123d12885500ef6fcdb317ace1b668087364717ea82 ``` -------------------------------- ### Install Bats npm Package as a Dev Dependency Source: https://github.com/bats-core/bats-core/blob/master/docs/source/installation.md Install the Bats npm package into your project and save it as a dev dependency in package.json. ```bash # To install into your project and save it as one of the "devDependencies" in # your package.json: $ npm install --save-dev bats ``` -------------------------------- ### Run Bats Tests Source: https://github.com/bats-core/bats-core/blob/master/docs/source/usage.md Example of invoking Bats to run test files. Specify paths to .bats files or directories containing them. The -r flag enables recursive searching. ```bash $ bats addition.bats ``` -------------------------------- ### Example Bats Warning Output Source: https://github.com/bats-core/bats-core/blob/master/docs/source/warnings/index.md Demonstrates the typical output format for Bats warnings, which appear on stderr after all other test results. This example shows a BW01 warning. ```bash BW01.bats ✓ Trigger BW01 1 test, 0 failures The following warnings were encountered during tests: BW01: `run`'s command `=0 actually-intended-command with some args` exited with code 127, indicating 'Command not found'. Use run's return code checks, e.g. `run -127`, to fix this message. (from function `run' in file lib/bats-core/test_functions.bash, line 299, in test file test/fixtures/warnings/BW01.bats, line 3) ``` -------------------------------- ### Install Bats as User using GNU Stow Source: https://github.com/bats-core/bats-core/wiki/Install-Bats-Using-GNU-Stow Installs Bats to a user-specific Stow directory. This method does not require root privileges and allows for clean management of Bats versions within the user's home directory. ```bash mkdir ~/stow stow=~/stow version=$(libexec/bats -v | tr A-Z a-z | tr ' ' -) # Unstow older versions of Bats. shopt -s nullglob old_bats=(`find "$stow" -type d -name bats-*") for package in "${old_bats[@]}"; do stow --dir="$stow" --delete $(basename "$package") done ./install.sh "${stow}/${version}" stow --dir="$stow" --restow "$version" ``` -------------------------------- ### Travis CI - Add Bats Dependency Source: https://github.com/bats-core/bats-core/wiki/Install Configure Travis CI to install Bats from the master branch for testing builds. Ensures Bats is in the PATH. ```yaml language: bash dist: xenial #addons: # apt: # update: true # packages: # - xz-utils # - pv env: global: - export PATH="/usr/local/bin:$PATH" before_install: - | if [ "$TRAVIS_OS_NAME" = "linux" ]; then branch=master batstmp="$(mktemp -d bats-core-"${branch}".XXXX)" pushd "${batstmp}" &> /dev/null || return 11 curl -sSLO https://github.com/bats-core/bats-core/archive/refs/heads/"${branch}".zip unzip -qo "${branch}".zip sudo bash "${batstmp}"/bats-core-"${branch}"/install.sh /usr/local popd &> /dev/null || return 12 fi script: - bats test/test.bats ``` -------------------------------- ### Set test timeout Source: https://github.com/bats-core/bats-core/blob/master/docs/source/faq.md A test timeout can be set by defining the $BATS_TEST_TIMEOUT variable before setup() begins. This can be done on the command line, in free code, or in setup_file(). ```bash # Example of setting timeout in setup_file() setup_file() { export BATS_TEST_TIMEOUT=5 # 5 seconds } ``` -------------------------------- ### Bats Test with Piped Output Filtering Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md Demonstrates a common pitfall where piping the output of `run` prevents the pipe from being correctly interpreted. This example shows the incorrect usage. ```bash run project.sh 2>&1 | grep Welcome ``` -------------------------------- ### Create and Make Project Script Executable Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md Create the project script file and set its execute permissions. This is a prerequisite for the test to pass. ```console mkdir src/ echo '#!/usr/bin/env bash' > src/project.sh chmod a+x src/project.sh ``` -------------------------------- ### Run All Tests Source: https://github.com/bats-core/bats-core/blob/master/docs/CONTRIBUTING.md Execute all test suites in the project. Ensure your environment is set up correctly before running tests. ```sh bin/bats test ``` -------------------------------- ### Basic Bats Test Cases Source: https://github.com/bats-core/bats-core/blob/master/README.md Demonstrates how to define test cases in a Bats test file using special syntax for test descriptions and assertions. ```bash #!/usr/bin/env bats @test "addition using bc" { result="$(echo 2+2 | bc)" [ "$result" -eq 4 ] } @test "addition using dc" { result="$(echo 2 2+p | dc)" [ "$result" -eq 4 ] } ``` -------------------------------- ### Initial Test Case for Nonexistent Script Source: https://github.com/bats-core/bats-core/blob/master/docs/source/tutorial.md Write a basic test case to verify if a script can be executed. This test will initially fail as the script does not exist. ```bash @test "can run our script" { ./project.sh } ``` -------------------------------- ### Build and Run Bats Project Tests with Docker Source: https://github.com/bats-core/bats-core/blob/master/docs/source/docker-usage.md Clones the bats-core repository, builds the bats Docker image, and then runs tests within the container using the TAP formatter. ```bash $ git clone https://github.com/bats-core/bats-core.git Cloning into 'bats-core'... remote: Counting objects: 1222, done. remote: Compressing objects: 100% (53/53), done. remote: Total 1222 (delta 34), reused 55 (delta 21), pack-reused 1146 Receiving objects: 100% (1222/1222), 327.28 KiB | 1.70 MiB/s, done. Resolving deltas: 100% (661/661), done. $ cd bats-core/ $ docker build --tag bats/bats:latest . ... $ docker run -it bats/bats:latest --formatter tap /opt/bats/test ``` -------------------------------- ### Build and Run Bats Docker Image Source: https://github.com/bats-core/bats-core/wiki/Docker-Usage-Examples Builds the Bats Docker image from the current directory and runs its tests using the --tap option. Useful for testing the Bats framework itself. ```bash $ git clone https://github.com/bats-core/bats-core.git Cloning into 'bats-core'... remote: Counting objects: 1222, done. remote: Compressing objects: 100% (53/53), done. remote: Total 1222 (delta 34), reused 55 (delta 21), pack-reused 1146 Receiving objects: 100% (1222/1222), 327.28 KiB | 1.70 MiB/s, done. Resolving deltas: 100% (661/661), done. $ cd bats-core/ $ docker build --tag bats/bats:latest . ... $ docker run -it --rm bats/bats:latest --tap /opt/bats/test ``` -------------------------------- ### Run Local Test Suite with Docker Source: https://github.com/bats-core/bats-core/blob/master/docs/source/installation.md Run a local test suite from your machine within a Docker container by mounting the current directory. ```bash $ docker run -it -v "${PWD}:/code" bats/bats:latest test ``` -------------------------------- ### Load a specific file from a library Source: https://github.com/bats-core/bats-core/blob/master/docs/source/writing-tests.md To load a specific file or entry point within a library, append the file name to the library name, separated by a slash. This allows for more granular control over library loading. ```bash bats_load_library library_name/file_to_load ``` -------------------------------- ### Use Custom Formatter Source: https://github.com/bats-core/bats-core/blob/master/docs/source/usage.md You can use your own custom formatter by providing an absolute path to the formatter executable with the `--formatter` option. ```bash $ bats --formatter /absolute/path/to/my-formatter addition.bats addition using bc WORKED addition using dc FAILED ``` -------------------------------- ### Run a command and assert its status and output Source: https://github.com/bats-core/bats-core/blob/master/docs/source/writing-tests.md Use the `run` helper to execute a command and capture its exit status, output, and the command itself. Assertions can then be made on the `$status`, `$output`, and `$BATS_RUN_COMMAND` variables. ```bash run foo nonexistent_filename [ "$status" -eq 1 ] [ "$output" = "foo: no such file 'nonexistent_filename'" ] [ "$BATS_RUN_COMMAND" = "foo nonexistent_filename" ] ``` -------------------------------- ### Build Bats Docker Image Source: https://github.com/bats-core/bats-core/blob/master/docs/source/installation.md Build a local Docker image for Bats Core from its repository. ```bash $ git clone https://github.com/bats-core/bats-core.git $ cd bats-core $ docker build --tag bats/bats:latest . ``` -------------------------------- ### Bats Command Line Options Source: https://github.com/bats-core/bats-core/blob/master/docs/source/usage.md Displays all available command-line options for the Bats interpreter. Use -h or --help to invoke. ```text Bats 1.13.0 Usage: bats [OPTIONS] bats [-h | -v] is the path to a Bats test file, or the path to a directory containing Bats test files (ending with ".bats") --abort Stop execution of suite on first failed test -c, --count Count test cases without running any tests --code-quote-style