Esempio n. 1
0
def test_get_path_lists_search(iterate_mock, search_text, complementary_search,
                               search_in_fields, paths, expected_result):
    """Test `get_path_lists` functionality when using the `search` parameter.

    Parameters
    ----------
    search_text : str
        The text to search.
    complementary_search : bool
        If True, only results NOT containing `search_text` will be returned. If False, only results that contains
        `search_text` will be returned.
    search_in_fields : str
        Name of the field to search in for the `search_text`.
    paths : list of str
        A list of CDB files to read, with their relative path.
    expected_result : list of dict
        The content expected to be returned by `get_lists` when using the specified search parameters.
    """
    common.reset_context_cache()
    result = get_path_lists(filename=paths,
                            search_text=search_text,
                            complementary_search=complementary_search,
                            search_in_fields=search_in_fields,
                            sort_by=['filename'])
    assert isinstance(result, AffectedItemsWazuhResult)
    assert result.total_affected_items == len(expected_result)
    assert result.affected_items == expected_result
Esempio n. 2
0
def test_context_cached():
    """Verify that context_cached decorator correctly saves and returns saved value when called again."""

    test_context_cached.calls_to_foo = 0

    @context_cached('foobar')
    def foo(arg='bar', **data):
        test_context_cached.calls_to_foo += 1
        print(data)
        return arg

    # The result of function 'foo' is being cached and it has been called once
    assert foo(
    ) == 'bar' and test_context_cached.calls_to_foo == 1, '"bar" should be returned with 1 call to foo.'
    assert foo(
    ) == 'bar' and test_context_cached.calls_to_foo == 1, '"bar" should be returned with 1 call to foo.'
    assert isinstance(
        get_context_cache()[json.dumps({
            "key": "foobar",
            "args": [],
            "kwargs": {}
        })], ContextVar)

    # foo called with an argument
    assert foo('other_arg') == 'other_arg' and test_context_cached.calls_to_foo == 2, '"other_arg" should be ' \
                                                                                      'returned with 2 calls to foo. '
    assert isinstance(
        get_context_cache()[json.dumps({
            "key": "foobar",
            "args": ['other_arg'],
            "kwargs": {}
        })], ContextVar)

    # foo called with the same argument as default, a new context var is created in the cache
    assert foo('bar') == 'bar' and test_context_cached.calls_to_foo == 3, '"bar" should be returned with 3 calls to ' \
                                                                          'foo. '
    assert isinstance(
        get_context_cache()[json.dumps({
            "key": "foobar",
            "args": ['bar'],
            "kwargs": {}
        })], ContextVar)

    # Reset cache and calls to foo
    reset_context_cache()
    test_context_cached.calls_to_foo = 0

    # foo called with kwargs, a new context var is created with kwargs not empty
    assert foo(data='bar') == 'bar' and test_context_cached.calls_to_foo == 1, '"bar" should be returned with 1 ' \
                                                                               'calls to foo. '
    assert isinstance(
        get_context_cache()[json.dumps({
            "key": "foobar",
            "args": [],
            "kwargs": {
                "data": "bar"
            }
        })], ContextVar)
Esempio n. 3
0
 def run_local():
     self.logger.debug("Starting to execute request locally")
     common.rbac.set(self.rbac_permissions)
     common.broadcast.set(self.broadcasting)
     common.cluster_nodes.set(self.nodes)
     common.current_user.set(self.current_user)
     data = self.f(**self.f_kwargs)
     common.reset_context_cache()
     self.logger.debug("Finished executing request locally")
     return data
Esempio n. 4
0
def test_context_cached():
    """Verify that context_cached decorator correctly saves and returns saved value when called again"""
    @context_cached('foobar')
    def foo(arg='bar'):
        return arg

    assert foo() == 'bar', '"bar" should be returned.'
    assert foo('other_arg') != 'other_arg', '"bar" should be returned.'
    reset_context_cache()
    assert foo('other_arg_2') == 'other_arg_2', '"other_arg_2" should be returned.'
    assert foo() == 'other_arg_2', '"other_arg_2" should be returned.'
Esempio n. 5
0
def test_get_path_lists(iterate_mock):
    """Test `get_path_lists` functionality without any other parameter aside from `path`.

    `get_path_lists` works different than `get_lists` as it will read every CDB file from the default path (mocked to
    `DATA_PATH`) and will remove from the result any file that is not in the `path` parameter provided.
    """
    common.reset_context_cache()
    result = get_path_lists(filename=[NAME_FILE_1])

    assert isinstance(result, AffectedItemsWazuhResult)
    assert result.total_affected_items == len(RESULT_GET_PATH_LIST_FILE_1)
    assert result.affected_items == RESULT_GET_PATH_LIST_FILE_1
Esempio n. 6
0
def test_get_path_lists_offset(iterate_mock, offset):
    """Test `get__path_lists` functionality when using the `offset` parameter.

    Parameters
    ----------
    offset : int
         Indicates the first item to return.
    """
    common.reset_context_cache()
    result = get_path_lists(filename=NAME_FILES,
                            offset=offset,
                            sort_by=['filename'])

    assert isinstance(result, AffectedItemsWazuhResult)
    assert result.total_affected_items == TOTAL_LISTS
    assert result.affected_items == RESULTS_GET_PATH_LIST[offset:]
Esempio n. 7
0
def test_get_path_lists_limit(iterate_mock, limit):
    """Test `get_path_lists` functionality when using the `limit` parameter.

    Parameters
    ----------
    limit : int
        Maximum number of items to be returned by `get_path_lists`
    """
    common.reset_context_cache()
    result = get_path_lists(filename=NAME_FILES,
                            limit=limit,
                            sort_by=['filename'])

    assert isinstance(result, AffectedItemsWazuhResult)
    assert result.total_affected_items == TOTAL_LISTS
    assert result.affected_items == RESULTS_GET_PATH_LIST[:limit]
Esempio n. 8
0
    def run_local(f, f_kwargs, logger, rbac_permissions, broadcasting, nodes,
                  current_user):
        """Run framework SDK function locally in another process."""
        def debug_log(logger, message):
            if logger.name == 'wazuh-api':
                logger.debug2(message)
            else:
                logger.debug(message)

        debug_log(logger, "Starting to execute request locally")
        common.rbac.set(rbac_permissions)
        common.broadcast.set(broadcasting)
        common.cluster_nodes.set(nodes)
        common.current_user.set(current_user)
        data = f(**f_kwargs)
        common.reset_context_cache()
        debug_log(logger, "Finished executing request locally")
        return data
Esempio n. 9
0
def test_iterate_lists(only_names, path):
    """Test `iterate_lists` core functionality.

    `Iterate_list` must get the content of all CDB lists in a specified path skipping `.cdb` and `.swp` files. It will
    return a list of dictionaries.

    Parameters
    ----------
    only_names : bool
        If this parameter is true, only the name of all lists will be showed by `iterate_lists` instead of its content.
    path : str
        Path to iterate lists from.
    """
    required_fields = ['relative_dirname', 'filename'] if only_names else ['relative_dirname', 'filename', 'items']

    common.reset_context_cache()
    result = iterate_lists(absolute_path=path, only_names=only_names)
    assert isinstance(result, list)
    assert len(result) != 0
    for entry in result:
        for field in required_fields:
            assert field in entry