diff --git a/advanced/Scripts/utils.sh b/advanced/Scripts/utils.sh index 37516472..f655e56c 100755 --- a/advanced/Scripts/utils.sh +++ b/advanced/Scripts/utils.sh @@ -57,7 +57,11 @@ addKey(){ # touch file to prevent grep error if file does not exist yet touch "${file}" - if ! grep -q "^${key}" "${file}"; then + # Match key against entire line, using both anchors. We assume + # that the file's keys never have bounding whitespace. Anchors + # are necessary to ensure the key is considered absent when it + # is a substring of another key present in the file. + if ! grep -q "^${key}$" "${file}"; then # Key does not exist, add it. echo "${key}" >> "${file}" fi diff --git a/test/test_any_utils.py b/test/test_any_utils.py index 5b4075d9..b3fabe6c 100644 --- a/test/test_any_utils.py +++ b/test/test_any_utils.py @@ -40,6 +40,26 @@ def test_key_addition_works(host): assert expected_stdout == output.stdout +def test_key_addition_substr(host): + """Confirms addKey adds substring keys (no value) to a file""" + host.run( + """ + source /opt/pihole/utils.sh + addKey "./testoutput" "KEY_ONE" + addKey "./testoutput" "KEY_O" + addKey "./testoutput" "KEY_TWO" + addKey "./testoutput" "Y_TWO" + """ + ) + output = host.run( + """ + cat ./testoutput + """ + ) + expected_stdout = "KEY_ONE\nKEY_O\nKEY_TWO\nY_TWO\n" + assert expected_stdout == output.stdout + + def test_key_removal_works(host): """Confirms removeKey removes a key or key/value pair""" host.run(