diff --git a/.gitignore b/.gitignore index c7c6ce0..9c8c6c7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ CLAUDE.local.md .claude/ +test-reports/ diff --git a/kvm-install-vm b/kvm-install-vm index 69d8e32..3397d1d 100755 --- a/kvm-install-vm +++ b/kvm-install-vm @@ -387,7 +387,7 @@ function release_dhcp_lease() { local status_file="/var/lib/libvirt/dnsmasq/${bridge}.status" if [[ -f "$status_file" ]]; then # Search for any lease with matching hostname - mac=$(grep -B2 -A2 "\"hostname\": \"${vmname}\"" "$status_file" 2>/dev/null | awk -F'"' '/mac-address/ {print $4; exit}') + mac=$(grep -B2 -A2 "\"hostname\": \"${vmname}\"" "$status_file" 2>/dev/null | awk -F'"' '/mac-address/ {print $4; exit}' || true) fi fi @@ -397,7 +397,7 @@ function release_dhcp_lease() { local ip="" if [[ -f "$status_file" ]]; then - ip=$(grep -B1 -A1 "\"mac-address\": \"$mac\"" "$status_file" 2>/dev/null | awk -F'"' '/ip-address/ {print $4; exit}') + ip=$(grep -B1 -A1 "\"mac-address\": \"$mac\"" "$status_file" 2>/dev/null | awk -F'"' '/ip-address/ {print $4; exit}' || true) fi if [[ -n "$ip" ]]; then diff --git a/tests/check_dhcp_release.bats b/tests/check_dhcp_release.bats index dba56df..d66b7ed 100644 --- a/tests/check_dhcp_release.bats +++ b/tests/check_dhcp_release.bats @@ -105,4 +105,27 @@ teardown() { # Should handle gracefully without errors [ "$status" -eq 0 ] [[ "${output}" =~ "does not exist" ]] -} \ No newline at end of file +} + +@test "Handle expired DHCP lease gracefully (empty status file)" { + # This tests the fix for the issue where grep returns exit code 1 + # when the DHCP status file is empty or lease has expired + + # Test that grep with no matches doesn't cause script to exit + # when using 'set -euo pipefail' + + # Create a temporary empty DHCP status file scenario by testing + # removal of a non-existent VM (which will have no lease) + run timeout $TIMEOUT ./kvm-install-vm remove "expired-lease-test-${RANDOM}" + + # Should complete successfully even with no DHCP lease found + [ "$status" -eq 0 ] + + # Should show that domain doesn't exist (expected for non-existent VM) + [[ "${output}" =~ "does not exist" ]] + + # Should NOT fail with grep errors or exit prematurely + # The fix ensures grep failures are handled gracefully with '|| true' + [[ ! "${output}" =~ "grep" ]] + [[ ! "${output}" =~ "error" ]] +}