Skip to main content
Skip to main content

How to Test with argsh

In this document, you'll get an overview of how to test your argsh scripts.

Overview

Testing is an important part of software development. It helps you to ensure that your code works as expected and that it continues to work as expected when you make changes to it.

There are different types of tests, but in this document, we'll focus on unit tests and integration tests.

Testing Frameworks

There are different testing frameworks for bash. The most popular ones are bats. This is what argsh is using for testing.

Writing Tests

Every script should have a corresponding test file. The test file should be in the same directory as the script and should have the same name as the script, but with a .bats extension.

Easy Testing with argsh

Argsh provides bats within its docker container. You can use it to run your tests.

argsh test scripts/*.sh

Use argsh test --help to get more information about the available options.

Bats helper

Argsh provides a helper function that you can use in your tests. If you bootstrapped your project, you already have it in your project.

If not you can add it to your project like this:

mkdir test
curl -sSL https://test.arg.sh > test/helper.bash

load_source

The load_source function is used to load the source file that you want to test. It automatically loads the source file (script name with .sh extension).

load_source
Note

If the environment variable BATS_LOAD is present it will load the source file from the given path. This is useful if you want to test your minified version of your script.

stdout, stderr and status

The stdout, stderr and status variables are set before each test. You can use them to check the output of your script.

@test "Test my_script" {
(
main
) >"${stdout}" 2>"${stderr}" || status=${?}

is_empty and snapshot

The is_empty function checks if the given variable is empty. The snapshot function checks if the given variable is equal to the expected value.

  is_empty stderr
snapshot stdout
Note

load_source does also setup a environment variable PATH_FIXTURES that points to ./test/fixtures/<script name>/. snapshot will use this path to create its snapshot files.

assert

The assert function is used to check expressions. It makes the output more readable.

  assert "${status}" -eq 0
}

Examples

#!/usr/bin/env bats

load ../test/helper.bash
load_source

@test "Test my_script" {
(
main
) >"${stdout}" 2>"${stderr}" || status=${?}

assert "${status}" -eq 0
is_empty stderr
snapshot stdout
}

Examples

Argsh is using bats for testing. You can have a look at the tests in the argsh repository to see how it's done.

Was this section helpful?