Skip to content

Commit

Permalink
Improve empty-string-compare rule (#1480)
Browse files Browse the repository at this point in the history
- rewrite matching to avoid line processing and trigger only on when
  blocks, highly reducing the chance of false-positives
- add additional pass test to avoid future regression
- refactor rule to use embedded tests

Fixes: #1232
  • Loading branch information
ssbarnea authored Mar 18, 2021
1 parent 470e3c5 commit 333b4e0
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 42 deletions.
67 changes: 64 additions & 3 deletions src/ansiblelint/rules/ComparisonToEmptyStringRule.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
# Copyright (c) 2018, Ansible Project

import re
from typing import Union
import sys
from typing import Any, Dict, Union

from ansiblelint.rules import AnsibleLintRule
from ansiblelint.utils import nested_items


class ComparisonToEmptyStringRule(AnsibleLintRule):
Expand All @@ -20,5 +22,64 @@ class ComparisonToEmptyStringRule(AnsibleLintRule):

empty_string_compare = re.compile("[=!]= ?(\"{2}|'{2})")

def match(self, line: str) -> Union[bool, str]:
return bool(self.empty_string_compare.search(line))
def matchtask(self, task: Dict[str, Any]) -> Union[bool, str]:
for k, v, _ in nested_items(task):
if k == 'when':
if isinstance(v, str):
if self.empty_string_compare.search(v):
return True
elif isinstance(v, bool):
pass
else:
for item in v:
if isinstance(item, str) and self.empty_string_compare.search(
item
):
return True

return False


# testing code to be loaded only with pytest or when executed the rule file
if "pytest" in sys.modules:

import pytest

SUCCESS_PLAY = '''
- hosts: all
tasks:
- name: shut down
shell: |
/sbin/shutdown -t now
echo $var == ""
when: ansible_os_family
'''

FAIL_PLAY = '''
- hosts: all
tasks:
- name: shut down
command: /sbin/shutdown -t now
when: ansible_os_family == ""
- name: shut down
command: /sbin/shutdown -t now
when: ansible_os_family !=""
'''

@pytest.mark.parametrize(
'rule_runner', (ComparisonToEmptyStringRule,), indirect=['rule_runner']
)
def test_rule_empty_string_compare_fail(rule_runner: Any) -> None:
"""Test rule matches."""
results = rule_runner.run_playbook(FAIL_PLAY)
assert len(results) == 2
for result in results:
assert result.message == ComparisonToEmptyStringRule.shortdesc

@pytest.mark.parametrize(
'rule_runner', (ComparisonToEmptyStringRule,), indirect=['rule_runner']
)
def test_rule_empty_string_compare_pass(rule_runner: Any) -> None:
"""Test rule matches."""
results = rule_runner.run_playbook(SUCCESS_PLAY)
assert len(results) == 0, results
39 changes: 0 additions & 39 deletions test/TestComparisonToEmptyString.py

This file was deleted.

0 comments on commit 333b4e0

Please sign in to comment.