Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve empty-string-compare rule #1480

Merged
merged 1 commit into from Mar 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
67 changes: 64 additions & 3 deletions src/ansiblelint/rules/ComparisonToEmptyStringRule.py
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.