From 57e35aee87ca530fe57a4b971e1f7c0911f0c39c Mon Sep 17 00:00:00 2001 From: Ted Cook Date: Thu, 24 Oct 2024 10:51:12 -0600 Subject: [PATCH] Add inner_product filter --- galaxy.yml | 2 +- molecule/default/verify.yml | 10 ++++++++++ plugins/filter/custom_filter.py | 12 ++++++++++++ tests/test_filter.py | 20 ++++++++++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) diff --git a/galaxy.yml b/galaxy.yml index c17bf85..06df5ba 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -1,7 +1,7 @@ --- namespace: nephelaiio name: plugins -version: 0.0.7 +version: 0.0.8 readme: README.md authors: - Ted Cook diff --git a/molecule/default/verify.yml b/molecule/default/verify.yml index 9288a29..61da63c 100644 --- a/molecule/default/verify.yml +++ b/molecule/default/verify.yml @@ -24,3 +24,13 @@ expected: [["a"]] filter: "nephelaiio.plugins.set_difference" result: "{{ pairs | map(filter) }}" + + - name: Test inner_product + ansible.builtin.assert: + that: result == expected + fail_msg: "{{ result | to_json }}" + vars: + pairs: [[["a", "b"], ["@c", "@d"]]] + expected: [["a@c", "a@d", "b@c", "b@d"]] + filter: "nephelaiio.plugins.inner_product" + result: "{{ pairs | map(filter) | map('map', 'join') }}" diff --git a/plugins/filter/custom_filter.py b/plugins/filter/custom_filter.py index be3083e..d57d4fe 100644 --- a/plugins/filter/custom_filter.py +++ b/plugins/filter/custom_filter.py @@ -732,6 +732,17 @@ def set_difference(value): return list(set(a).difference(set(b))) +def inner_product(value): + """ + Return the inner product of an array pair: + .. sourcecode:: jinja + {{ [['a', 'b', ['c', 'd']] | map("inner_product") }} + -> [['a, 'c'], ['a', 'd'], ['b', 'c'], ['b', 'd']] + """ + [a, b] = value + return [list(x) for x in itertools.product(a, b)] + + class FilterModule: """ A class encapsulating a collection of jinja2 filters. @@ -819,4 +830,5 @@ def filters(self): "is_all_true": is_all_true, "search_regex": search_regex, "set_difference": set_difference, + "inner_product": inner_product, } diff --git a/tests/test_filter.py b/tests/test_filter.py index 5aaad01..5ccde0f 100644 --- a/tests/test_filter.py +++ b/tests/test_filter.py @@ -12,6 +12,7 @@ alias_keys, drop_attributes, filename, + inner_product, ip_range, is_all_true, is_any_true, @@ -478,3 +479,22 @@ def test_set_difference(): assert set(set_difference([["a", "b"], ["a", "d"]])).difference(set(["b"])) == set() assert set(set_difference([["a", "b"], ["b", "c"]])).difference(set(["a"])) == set() assert set(set_difference([["a", "b"], ["a", "b"]])).difference(set([])) == set() + + +def test_inner_product(): + assert inner_product([[], []]) == [] + assert inner_product([["a"], ["b"]]) == [["a", "b"]] + assert inner_product([["a", "b"], ["c"]]) == [ + ["a", "c"], + ["b", "c"], + ] + assert inner_product([["a"], ["c", "d"]]) == [ + ["a", "c"], + ["a", "d"], + ] + assert inner_product([["a", "b"], ["c", "d"]]) == [ + ["a", "c"], + ["a", "d"], + ["b", "c"], + ["b", "d"], + ]