Пример #1
0
def cleanup_tmp_file(path, warn=False):
    """
    Removes temporary file or directory. Optionally display a warning if unable
    to remove the file or directory.

    :arg path: Path to file or directory to be removed
    :kwarg warn: Whether or not to display a warning when the file or directory
        cannot be removed
    """
    try:
        if os.path.exists(path):
            try:
                if os.path.isdir(path):
                    shutil.rmtree(path)
                elif os.path.isfile(path):
                    os.unlink(path)
            except Exception as e:
                if warn:
                    # Importing here to avoid circular import
                    from assible.utils.display import Display
                    display = Display()
                    display.display(
                        u'Unable to remove temporary file {0}'.format(
                            to_text(e)))
    except Exception:
        pass
Пример #2
0
def test_display_basic_message(capsys, mocker):
    # Disable logging
    mocker.patch('assible.utils.display.logger', return_value=None)

    d = Display()
    d.display(u'Some displayed message')
    out, err = capsys.readouterr()
    assert out == 'Some displayed message\n'
    assert err == ''
Пример #3
0
def test_warning_no_color(capsys, mocker, warning_message):
    warning_message, expected_warning_message = warning_message

    mocker.patch('assible.utils.color.ASSIBLE_COLOR', False)

    d = Display()
    d.warning(warning_message)
    out, err = capsys.readouterr()
    assert d._warns == {expected_warning_message: 1}
    assert err == expected_warning_message
Пример #4
0
def test_Display_banner_get_text_width_fallback(monkeypatch):
    display = Display()
    display_mock = MagicMock()
    monkeypatch.setattr(display, 'display', display_mock)

    display.banner(u'🚀🐮', color=False, cows=False)
    args, kwargs = display_mock.call_args
    msg = args[0]
    stars = u' %s' % (77 * u'*')
    assert msg.endswith(stars)
Пример #5
0
def test_warning(capsys, mocker, warning_message):
    warning_message, expected_warning_message = warning_message

    mocker.patch('assible.utils.color.ASSIBLE_COLOR', True)
    mocker.patch('assible.utils.color.parsecolor',
                 return_value=u'1;35')  # value for 'bright purple'

    d = Display()
    d.warning(warning_message)
    out, err = capsys.readouterr()
    assert d._warns == {expected_warning_message: 1}
    assert err == '\x1b[1;35m{0}\x1b[0m\n'.format(
        expected_warning_message.rstrip('\n'))
Пример #6
0
def test_duplicate_yaml_dict_key_ignore(dupe_node, monkeypatch):
    monkeypatch.setattr(C, 'DUPLICATE_YAML_DICT_KEY', 'ignore')
    cap = Capture()
    monkeypatch.setattr(Display(), 'warning', cap)
    ac = AssibleConstructor()
    ac.construct_mapping(dupe_node)
    assert not cap.called
Пример #7
0
def _warning(msg):
    ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
    try:
        from assible.utils.display import Display
        Display().warning(msg)
    except Exception:
        import sys
        sys.stderr.write(' [WARNING] %s\n' % (msg))
Пример #8
0
def _deprecated(msg, version='2.8'):
    ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
    try:
        from assible.utils.display import Display
        Display().deprecated(msg, version=version)
    except Exception:
        import sys
        sys.stderr.write(' [DEPRECATED] %s, to be removed in %s\n' %
                         (msg, version))
Пример #9
0
def test_duplicate_yaml_dict_key_warn(dupe_node, monkeypatch):
    monkeypatch.setattr(C, 'DUPLICATE_YAML_DICT_KEY', 'warn')
    cap = Capture()
    monkeypatch.setattr(Display(), 'warning', cap)
    ac = AssibleConstructor()
    ac.construct_mapping(dupe_node)
    assert cap.called
    expected = [((
        'While constructing a mapping from tag:yaml.org,2002:map, line 1, column 1, '
        'found a duplicate dict key (bar). Using last defined value only.', ),
                 {})]
    assert cap.calls == expected
Пример #10
0
    def __new__(cls, obj, *args, **kwargs):
        from assible.utils.display import Display
        Display().deprecated(
            'UnsafeProxy is being deprecated. Use wrap_var or AssibleUnsafeBytes/AssibleUnsafeText directly instead',
            version='2.13', collection_name='assible.builtin'
        )
        # In our usage we should only receive unicode strings.
        # This conditional and conversion exists to sanity check the values
        # we're given but we may want to take it out for testing and sanitize
        # our input instead.
        if isinstance(obj, AssibleUnsafe):
            return obj

        if isinstance(obj, string_types):
            obj = AssibleUnsafeText(to_text(obj, errors='surrogate_or_strict'))
        return obj
Пример #11
0
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from assible import constants as C
from assible import context
from assible.cli import CLI
from assible.cli.arguments import option_helpers as opt_help
from assible.errors import AssibleError, AssibleOptionsError
from assible.executor.task_queue_manager import TaskQueueManager
from assible.module_utils._text import to_text
from assible.parsing.splitter import parse_kv
from assible.playbook import Playbook
from assible.playbook.play import Play
from assible.utils.display import Display

display = Display()


class AdHocCLI(CLI):
    ''' is an extra-simple tool/framework/API for doing 'remote things'.
        this command allows you to define and run a single task 'playbook' against a set of hosts
    '''
    def init_parser(self):
        ''' create an options parser for bin/assible '''
        super(AdHocCLI, self).init_parser(
            usage='%prog <host-pattern> [options]',
            desc="Define and run a single task 'playbook' against"
            " a set of hosts",
            epilog="Some modules do not make sense in Ad-Hoc (include,"
            " meta, etc)")
Пример #12
0
from assible.module_utils.six import PY3
from assible.module_utils._text import to_text
from assible.parsing.ajson import AssibleJSONEncoder
from assible.plugins import AssiblePlugin, get_plugin_class
from assible.utils.color import stringc
from assible.utils.display import Display
from assible.vars.clean import strip_internal_keys, module_response_deepcopy

if PY3:
    # OrderedDict is needed for a backwards compat shim on Python3.x only
    # https://github.com/assible/assible/pull/49512
    from collections import OrderedDict
else:
    OrderedDict = None

global_display = Display()

__all__ = ["CallbackBase"]

_DEBUG_ALLOWED_KEYS = frozenset(
    ('msg', 'exception', 'warnings', 'deprecations'))


class CallbackBase(AssiblePlugin):
    '''
    This is a base assible callback class that does nothing. New callbacks should
    use this class as a base and override any callback methods they wish to execute
    custom actions.
    '''
    def __init__(self, display=None, options=None):
        if display:
Пример #13
0
from assible.module_utils.six import iteritems, string_types, text_type
from assible.module_utils.six.moves import range
from assible.module_utils._text import to_native, to_text, to_bytes
from assible.module_utils.common._collections_compat import Iterator, Sequence, Mapping, MappingView, MutableMapping
from assible.module_utils.common.collections import is_sequence
from assible.module_utils.compat.importlib import import_module
from assible.plugins.loader import filter_loader, lookup_loader, test_loader
from assible.template.safe_eval import safe_eval
from assible.template.template import AssibleJ2Template
from assible.template.vars import AssibleJ2Vars
from assible.utils.collection_loader import AssibleCollectionRef
from assible.utils.display import Display
from assible.utils.collection_loader._collection_finder import _get_collection_metadata
from assible.utils.unsafe_proxy import wrap_var

display = Display()

__all__ = ['Templar', 'generate_assible_template_vars']

# A regex for checking to see if a variable we're trying to
# expand is just a single variable name.

# Primitive Types which we don't want Jinja to convert to strings.
NON_TEMPLATED_TYPES = (bool, Number)

JINJA2_OVERRIDE = '#jinja2:'

from jinja2 import __version__ as j2_version
from jinja2 import Environment
from jinja2.utils import concat as j2_concat