diff --git a/README.md b/README.md index 820b368..e15c44a 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,24 @@ path : /path/to/existing-file -- ``` +### `assert_symlink_to` + +Fail if the given file is not a symbolic to a defined target. + +```bash +@test 'assert_symlink_to() { + assert_symlink_to /path/to/source-file /path/to/symlink +} +``` + +On failure, the path is displayed. + +``` +-- symbolic link does not have the correct target -- +path : /path/to/symlink +-- +``` + ## Working with temporary directories diff --git a/src/file.bash b/src/file.bash index 70e168c..f5823da 100644 --- a/src/file.bash +++ b/src/file.bash @@ -72,3 +72,36 @@ assert_file_not_exist() { | fail fi } + +# Fail and display path of the file (or directory) if it is not a symlink. +# +# Globals: +# BATSLIB_FILE_PATH_REM +# BATSLIB_FILE_PATH_ADD +# Arguments: +# $1 - source +# $2 - destination +# Returns: +# 0 - link to correct target +# 1 - otherwise +# Outputs: +# STDERR - details, on failure +assert_symlink_to() { + local -r sourcefile="$1" + local -r link="$2" + if [ ! -L $link ]; then + local -r rem="$BATSLIB_FILE_PATH_REM" + local -r add="$BATSLIB_FILE_PATH_ADD" + batslib_print_kv_single 4 'path' "${link/$rem/$add}" \ + | batslib_decorate 'file is not a symbolic link' \ + | fail + fi + local -r realsource=$( readlink -f "$link" ) + if [ ! "$realsource" = "$sourcefile" ]; then + local -r rem="$BATSLIB_FILE_PATH_REM" + local -r add="$BATSLIB_FILE_PATH_ADD" + batslib_print_kv_single 4 'path' "${link/$rem/$add}" \ + | batslib_decorate 'symbolic link does not have the correct target' \ + | fail + fi +} diff --git a/test/50-assert-12-assert_symlink_to.bats b/test/50-assert-12-assert_symlink_to.bats new file mode 100755 index 0000000..6167774 --- /dev/null +++ b/test/50-assert-12-assert_symlink_to.bats @@ -0,0 +1,25 @@ +#!/usr/bin/env bats + +load 'test_helper' +fixtures 'symlink' + +# Correctness +@test 'assert_symlink_to() : returns 0 if exists and is a symbolic link to ' { + local -r file="${TEST_FIXTURE_ROOT}/file" + local -r link="${TEST_FIXTURE_ROOT}/link" + run assert_symlink_to $file $link + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 0 ] +} + +@test 'assert_symlink_to() : returns 1 and displays path if is not a symbolic link to ' { + local -r file="${TEST_FIXTURE_ROOT}/dir/file.does_not_exist" + local -r link="${TEST_FIXTURE_ROOT}/link" + run assert_symlink_to $file $link + [ "$status" -eq 1 ] + [ "${#lines[@]}" -eq 3 ] + [ "${lines[0]}" == '-- symbolic link does not have the correct target --' ] + [ "${lines[1]}" == "path : $link" ] + [ "${lines[2]}" == '--' ] +} + diff --git a/test/fixtures/symlink/file b/test/fixtures/symlink/file new file mode 100644 index 0000000..e69de29 diff --git a/test/fixtures/symlink/symlink b/test/fixtures/symlink/symlink new file mode 120000 index 0000000..1a010b1 --- /dev/null +++ b/test/fixtures/symlink/symlink @@ -0,0 +1 @@ +file \ No newline at end of file