How can I make sure a filesystem is ready for unmounting in a test script?
I'm using bats to test some bash scripts. In one of the test, I need to mount a generated iso disk image and make assertions on its content.
When I try to unmount the disk image right after the test, I get a Device or resource busy
error unless I insert a sleep-time before the unmount operation.
The script looks like this:
setup() {
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
}
teardown() {
if [ -f "$BATS_TEST_TMPDIR"/mnt/my_file.txt ]; then
sleep 1
fusermount -u "$BATS_TEST_TMPDIR"/mnt
fi
}
@test 'check iso content' {
generate_iso "$BATS_TEST_TMPDIR"/my_iso.iso
mkdir "$BATS_TEST_TMPDIR"/mnt
fuseiso "$BATS_TEST_TMPDIR"/my_iso.iso "$BATS_TEST_TMPDIR"/mnt
assert grep 'A required string' < "$BATS_TEST_TMPDIR"/mnt/my_file.txt
}
This somehow works but I'm not 100% happy with the arbitrary sleep-time that may or may not be sufficient for the unmount to be successful depending on how soon the file is closed.
I tried to kill the process accessing the mounted filesystem by using fuser -mk "$BATS_TEST_TMPDIR"/mnt
instead of sleeping but this would eventually kill the process running the tests.
Is there any way I can avoid the arbitrary sleep-time? Can I ask the OS to wait for the file to be closed before proceeding? Any help would be greatly appreciated.
That was actually really easy, I just needed to close the file in the last grep
(note the <&-
):
assert grep 'A required string' <&- "$BATS_TEST_TMPDIR"/mnt/my_file.txt
teardown() {
if [ -f "$BATS_TEST_TMPDIR"/mnt/my_file.txt ]; then
fusermount -u "$BATS_TEST_TMPDIR"/mnt
fi
}
@test 'check iso content' {
generate_iso "$BATS_TEST_TMPDIR"/my_iso.iso
mkdir "$BATS_TEST_TMPDIR"/mnt
fuseiso "$BATS_TEST_TMPDIR"/my_iso.iso "$BATS_TEST_TMPDIR"/mnt
assert grep 'A required string' <&- "$BATS_TEST_TMPDIR"/mnt/my_file.txt
}