コード例 #1
0
    def test_system_exists(self, plugin, bm_client, bg_system, bg_instance,
                           current_commands):
        bg_system.commands = [Command("test")]
        bm_client.update_system.return_value = bg_system

        existing_system = System(
            id="id",
            name="test_system",
            version="0.0.1",
            instances=[bg_instance],
            commands=current_commands,
            metadata={"foo": "bar"},
        )
        bm_client.find_unique_system.return_value = existing_system

        plugin._initialize()
        bm_client.initialize_instance.assert_called_once_with(bg_instance.id)
        bm_client.update_system.assert_called_once_with(
            existing_system.id,
            new_commands=bg_system.commands,
            metadata=bg_system.metadata,
            description=bg_system.description,
            icon_name=bg_system.icon_name,
            display_name=bg_system.display_name,
        )
        assert bm_client.create_system.called is False
        assert bm_client.create_system.return_value == plugin.system
        assert bm_client.initialize_instance.return_value == plugin.instance
コード例 #2
0
ファイル: plugin_test.py プロジェクト: beer-garden/brewtils
    def test_system_exists(self, plugin, ez_client, bg_system, bg_instance,
                           current_commands):
        existing_system = System(
            id="id",
            name="test_system",
            version="0.0.1",
            instances=[bg_instance],
            commands=current_commands,
            metadata={"foo": "bar"},
            template=None,
        )
        ez_client.find_unique_system.return_value = existing_system

        bg_system.commands = [Command("test")]
        ez_client.update_system.return_value = bg_system

        plugin._initialize_system()
        assert ez_client.create_system.called is False
        ez_client.update_system.assert_called_once_with(
            existing_system.id,
            new_commands=bg_system.commands,
            metadata=bg_system.metadata,
            description=bg_system.description,
            icon_name=bg_system.icon_name,
            display_name=bg_system.display_name,
            template="<html>template</html>",
        )
コード例 #3
0
 def test_validate_regex_nullable(self, validator):
     req = Request(system="foo", command="command1", parameters={"key1": None})
     command_parameter = Parameter(
         key="key1", multi=False, type="String", regex=r"^Hi.*", nullable=True
     )
     command = Command("test", parameters=[command_parameter])
     validator.get_and_validate_parameters(req, command)
コード例 #4
0
    def test_validate_minimum_non_sequence(self, validator):
        req = Request(system="foo", command="command1", parameters={"key1": 5})

        command_parameter = Parameter(
            key="key1", multi=False, type="Integer", optional=False, minimum=3
        )
        command = Command("test", parameters=[command_parameter])
        validator.get_and_validate_parameters(req, command)

        command_parameter = Parameter(
            key="key1", multi=False, type="Integer", optional=False, minimum=10
        )
        command = Command("test", parameters=[command_parameter])

        with pytest.raises(ModelValidationError):
            validator.get_and_validate_parameters(req, command)
コード例 #5
0
    def test_validate_regex(self, validator):
        req = Request(
            system="foo", command="command1", parameters={"key1": "Hi World!"}
        )

        command_parameter = Parameter(
            key="key1", multi=False, type="String", optional=False, regex=r"^Hi.*"
        )
        command = Command("test", parameters=[command_parameter])
        validator.get_and_validate_parameters(req, command)

        command_parameter = Parameter(
            key="key1", multi=False, type="String", optional=False, regex=r"^Hello.*"
        )
        command = Command("test", parameters=[command_parameter])

        with pytest.raises(ModelValidationError):
            validator.get_and_validate_parameters(req, command)
コード例 #6
0
    def test_validate_maximum_sequence(self, validator):
        req = BrewtilsRequest(
            system="foo", command="command1", parameters={"key1": "value"}
        )

        command_parameter = Parameter(
            key="key1", multi=False, type="String", optional=False, maximum=10
        )
        command = Command("test", parameters=[command_parameter])
        validator.get_and_validate_parameters(req, command)

        command_parameter = Parameter(
            key="key1", multi=False, type="String", optional=False, maximum=3
        )
        command = Command("test", parameters=[command_parameter])

        with pytest.raises(ModelValidationError):
            validator.get_and_validate_parameters(req, command)
コード例 #7
0
 def test_validate_maximum_nullable(self, validator):
     req = Request(system="foo", command="command1", parameters={"key1": None})
     command_parameter = Parameter(
         key="key1",
         multi=False,
         type="Integer",
         optional=False,
         minimum=3,
         nullable=True,
     )
     command = Command("test", parameters=[command_parameter])
     validator.get_and_validate_parameters(req, command)
コード例 #8
0
ファイル: models_test.py プロジェクト: hazmat345/brewtils
class TestSystem(object):
    @pytest.fixture
    def default_system(self, command1):
        return System(name='foo',
                      version='1.0.0',
                      instances=[Instance(name='foo')],
                      commands=[command1])

    def test_get_command_by_name_found(self, default_system):
        mock_name = PropertyMock(return_value='name')
        command = Mock()
        type(command).name = mock_name
        default_system.commands.append(command)
        assert default_system.get_command_by_name('name') == command

    def test_get_command_by_name_none(self, default_system):
        mock_name = PropertyMock(return_value='foo')
        command = Mock()
        type(command).name = mock_name
        default_system.commands.append(command)
        assert default_system.get_command_by_name('name') is None

    def test_has_instance(self, default_system):
        assert default_system.has_instance('foo')
        assert not default_system.has_instance('bar')

    def test_instance_names(self, default_system):
        assert default_system.instance_names == ['foo']

    def test_get_instance(self, default_system):
        assert default_system.get_instance('foo').name == 'foo'
        assert default_system.get_instance('bar') is None

    @pytest.mark.parametrize('commands', [
        ([Command(name='bar')]),
        ([Command(name='foo', parameters=[Parameter(key='blah')])]),
        ([Command(name='bar'), Command(name='baz')]),
    ])
    def test_has_different_commands(self, default_system, commands):
        assert default_system.has_different_commands(commands)

    @pytest.mark.parametrize('command', [
        (Command(name='foo', parameters=[Parameter(key='key1', type="String")
                                         ])),
        (Command(name='foo',
                 description='Different description',
                 parameters=[Parameter(key='key1', type="String")])),
    ])
    def test_has_same_commands(self, default_system, command):
        assert not default_system.has_different_commands([command])

    def test_str(self, default_system):
        assert str(default_system) == 'foo-1.0.0'

    def test_repr(self, default_system):
        assert 'foo' in repr(default_system)
        assert '1.0.0' in repr(default_system)
コード例 #9
0
    def setUp(self):
        self.app = brew_view.app.test_client()

        self.default_instance = Instance(name='default', status='RUNNING')
        self.default_command = Command(id='54ac18f778c4b57e963f3c18',
                                       name='command',
                                       description='foo')
        self.default_system = System(id='54ac18f778c4b57e963f3c18',
                                     name='default_system',
                                     version='1.0.0',
                                     instances=[self.default_instance],
                                     commands=[self.default_command])

        self.client_mock = Mock(name='client_mock')
        self.fake_context = MagicMock(
            __enter__=Mock(return_value=self.client_mock),
            __exit__=Mock(return_value=False))
コード例 #10
0
def _generate_command_from_function(func):
    """Generates a Command from a function. Uses first line of pydoc as the description."""
    # Required for Python 2/3 compatibility
    if hasattr(func, "func_name"):
        command_name = func.func_name
    else:
        command_name = func.__name__

    # Required for Python 2/3 compatibility
    if hasattr(func, "func_doc"):
        docstring = func.func_doc
    else:
        docstring = func.__doc__

    return Command(name=command_name,
                   description=docstring.split('\n')[0] if docstring else None,
                   parameters=_generate_params_from_function(func))
コード例 #11
0
    def setUp(self):
        self.app = brew_view.app.test_client()

        self.default_instance = Instance(name="default", status="RUNNING")
        self.default_command = Command(
            id="54ac18f778c4b57e963f3c18", name="command", description="foo"
        )
        self.default_system = System(
            id="54ac18f778c4b57e963f3c18",
            name="default_system",
            version="1.0.0",
            instances=[self.default_instance],
            commands=[self.default_command],
        )

        self.client_mock = Mock(name="client_mock")
        self.fake_context = MagicMock(
            __enter__=Mock(return_value=self.client_mock),
            __exit__=Mock(return_value=False),
        )
コード例 #12
0
ファイル: plugin_test.py プロジェクト: hazmat345/brewtils
    def test_initialize_system_update_metadata(self):
        self.system.commands = [Command('test')]
        self.bm_client_mock.update_system.return_value = self.system

        existing_system = System(id='id', name='test_system', version='1.0.0',
                                 instances=[self.instance],
                                 metadata={})
        self.bm_client_mock.find_unique_system.return_value = existing_system

        self.plugin._initialize()
        self.assertFalse(self.bm_client_mock.create_system.called)
        self.bm_client_mock.update_system.assert_called_once_with(self.instance.id,
                                                                  new_commands=self.system.commands,
                                                                  description=None,
                                                                  display_name=None,
                                                                  icon_name=None,
                                                                  metadata={"foo": "bar"})
        self.bm_client_mock.initialize_instance.assert_called_once_with(self.instance.id)
        self.assertEqual(self.plugin.system, self.bm_client_mock.create_system.return_value)
        self.assertEqual(self.plugin.instance, self.bm_client_mock.initialize_instance.return_value)
コード例 #13
0
        def test_positional_only(self):
            """This is invalid syntax on Python < 3.8 so we have to wrap it in exec"""
            import textwrap

            exec_locals = {}
            class_dec = textwrap.dedent("""
                class Tester(object):
                    def c(self, foo, /):
                        pass
                """)

            # Black doesn't handle this well - because we run in 2.7 mode it wants to
            # put a space after exec, but then it complains about the space after exec.
            # fmt: off
            exec(class_dec, globals(), exec_locals)
            # fmt: on

            with pytest.raises(PluginParamError):
                _signature_validate(Command(parameters=[Parameter(key="foo")]),
                                    exec_locals["Tester"].c)  # noqa
コード例 #14
0
def _initialize_command(method):
    # type: (MethodType) -> Command
    """Initialize a Command

    This takes care of ensuring a Command object is in the correct form. Things like:

    - Assigning the name from the method name
    - Pulling the description from the method docstring, if necessary
    - Resolving display modifiers (schema, form, template)

    Args:
        method: The method with the Command to initialize

    Returns:
        The initialized Command

    """
    cmd = getattr(method, "_command", Command())

    cmd.name = _method_name(method)
    cmd.description = cmd.description or _method_docstring(method)

    try:
        base_dir = os.path.dirname(inspect.getfile(method))

        cmd.schema = resolve_schema(cmd.schema, base_dir=base_dir)
        cmd.form = resolve_form(cmd.form, base_dir=base_dir)
        cmd.template = resolve_template(cmd.template, base_dir=base_dir)
    except PluginParamError as ex:
        six.raise_from(
            PluginParamError("Error initializing command '%s': %s" %
                             (cmd.name, ex)),
            ex,
        )

    return cmd
コード例 #15
0
 def test_kwarg(self, cmd_kwargs):
     _signature_validate(
         Command(parameters=[Parameter(key="foo", is_kwarg=True)]),
         cmd_kwargs)
コード例 #16
0
 def test_positional(self, cmd):
     _signature_validate(Command(parameters=[Parameter(key="foo")]),
                         cmd)
コード例 #17
0
 def test_no_kwargs_in_signature(self, cmd):
     with pytest.raises(PluginParamError):
         _signature_validate(
             Command(
                 parameters=[Parameter(key="extra", is_kwarg=True)]),
             cmd)
コード例 #18
0
def bg_command(command_dict, bg_parameter):
    """Use the bg_command fixture instead."""
    dict_copy = copy.deepcopy(command_dict)
    dict_copy['parameters'] = [bg_parameter]
    dict_copy['system'] = System(id=system_id)
    return Command(**dict_copy)
コード例 #19
0
 def test_mismatch_is_kwarg_false(self, cmd_kwargs):
     with pytest.raises(PluginParamError):
         _signature_validate(
             Command(parameters=[Parameter(key="foo", is_kwarg=False)]),
             cmd_kwargs,
         )
コード例 #20
0
 def test_has_different_parameters_different_length(self):
     c = Command(name="foo", parameters=[Parameter(key="key1")])
     assert c.has_different_parameters(
         [Parameter(key="key1"),
          Parameter(key="key2")])
コード例 #21
0
 def test_has_different_parameters(self, p1, p2):
     assert Command(parameters=[p1]).has_different_parameters([p2])
コード例 #22
0
def command1(param1):
    return Command(name="foo", description="bar", parameters=[param1])
コード例 #23
0
 def test_get_parameter_by_key(self, parameter, expected):
     command = Command(name="foo", parameters=[parameter])
     assert command.get_parameter_by_key("key1") == expected
コード例 #24
0
 def __str__(self):
     return BrewtilsCommand.__str__(self)
コード例 #25
0
class TestInitialize(object):
    def test_new_system(self, plugin, bm_client, bg_system, bg_instance):
        bm_client.find_unique_system.return_value = None

        plugin._initialize()
        bm_client.initialize_instance.assert_called_once_with(bg_instance.id)
        bm_client.create_system.assert_called_once_with(bg_system)
        assert bm_client.update_system.called is False
        assert bm_client.create_system.return_value == plugin.system
        assert bm_client.initialize_instance.return_value == plugin.instance

    @pytest.mark.parametrize("current_commands",
                             [[], [Command("test")], [Command("other_test")]])
    def test_system_exists(self, plugin, bm_client, bg_system, bg_instance,
                           current_commands):
        bg_system.commands = [Command("test")]
        bm_client.update_system.return_value = bg_system

        existing_system = System(
            id="id",
            name="test_system",
            version="0.0.1",
            instances=[bg_instance],
            commands=current_commands,
            metadata={"foo": "bar"},
        )
        bm_client.find_unique_system.return_value = existing_system

        plugin._initialize()
        bm_client.initialize_instance.assert_called_once_with(bg_instance.id)
        bm_client.update_system.assert_called_once_with(
            existing_system.id,
            new_commands=bg_system.commands,
            metadata=bg_system.metadata,
            description=bg_system.description,
            icon_name=bg_system.icon_name,
            display_name=bg_system.display_name,
        )
        assert bm_client.create_system.called is False
        assert bm_client.create_system.return_value == plugin.system
        assert bm_client.initialize_instance.return_value == plugin.instance

    def test_new_instance(self, plugin, bm_client, bg_system, bg_instance):
        plugin.instance_name = "new_instance"

        existing_system = System(
            id="id",
            name="test_system",
            version="0.0.1",
            instances=[bg_instance],
            max_instances=2,
            metadata={"foo": "bar"},
        )
        bm_client.find_unique_system.return_value = existing_system

        plugin._initialize()
        assert 2 == len(existing_system.instances)
        assert bm_client.create_system.called is True
        assert bm_client.update_system.called is True

    def test_new_instance_maximum(self, plugin, bm_client, bg_system):
        plugin.instance_name = "new_instance"
        bm_client.find_unique_system.return_value = bg_system

        with pytest.raises(PluginValidationError):
            plugin._initialize()

    def test_unregistered_instance(self, plugin, bm_client, bg_system):
        bg_system.has_instance = Mock(return_value=False)
        bm_client.find_unique_system.return_value = None

        with pytest.raises(PluginValidationError):
            plugin._initialize()
コード例 #26
0
 def test_str(self):
     assert "foo" == str(Command(name="foo"))
コード例 #27
0
 def test_has_same_parameters(self, p1, p2):
     assert not Command(parameters=p1).has_different_parameters(p2)
コード例 #28
0
 def __repr__(self):
     return BrewtilsCommand.__repr__(self)
コード例 #29
0
 def test_repr(self):
     assert "<Command: foo>" == repr(Command(name="foo"))
コード例 #30
0
class TestSystem(object):
    @pytest.fixture
    def default_system(self, command1):
        return System(
            name="foo",
            version="1.0.0",
            instances=[Instance(name="foo")],
            commands=[command1],
        )

    def test_get_command_by_name_found(self, default_system):
        mock_name = PropertyMock(return_value="name")
        command = Mock()
        type(command).name = mock_name
        default_system.commands.append(command)
        assert default_system.get_command_by_name("name") == command

    def test_get_command_by_name_none(self, default_system):
        mock_name = PropertyMock(return_value="foo")
        command = Mock()
        type(command).name = mock_name
        default_system.commands.append(command)
        assert default_system.get_command_by_name("name") is None

    def test_has_instance(self, default_system):
        assert default_system.has_instance("foo")
        assert not default_system.has_instance("bar")

    def test_instance_names(self, default_system):
        assert default_system.instance_names == ["foo"]

    def test_get_instance(self, default_system):
        assert default_system.get_instance("foo").name == "foo"
        assert default_system.get_instance("bar") is None

    @pytest.mark.parametrize(
        "commands",
        [
            ([Command(name="bar")]),
            ([Command(name="foo", parameters=[Parameter(key="blah")])]),
            ([Command(name="bar"), Command(name="baz")]),
        ],
    )
    def test_has_different_commands(self, default_system, commands):
        assert default_system.has_different_commands(commands)

    @pytest.mark.parametrize(
        "command",
        [
            (Command(name="foo",
                     parameters=[Parameter(key="key1", type="String")])),
            (Command(
                name="foo",
                description="Different description",
                parameters=[Parameter(key="key1", type="String")],
            )),
        ],
    )
    def test_has_same_commands(self, default_system, command):
        assert not default_system.has_different_commands([command])

    def test_str(self, default_system):
        assert str(default_system) == "foo-1.0.0"

    def test_repr(self, default_system):
        assert "foo" in repr(default_system)
        assert "1.0.0" in repr(default_system)