From 2fd77d18c2ee042f204f18bb7703355ecbff39ae Mon Sep 17 00:00:00 2001 From: Brian Scholer <1260690+briantist@users.noreply.github.com> Date: Tue, 23 Feb 2021 15:20:28 -0500 Subject: [PATCH] Add tests for VAULT_ADDR --- tests/unit/plugins/lookup/test_hashi_vault.py | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/tests/unit/plugins/lookup/test_hashi_vault.py b/tests/unit/plugins/lookup/test_hashi_vault.py index 1e2e3ed56..e11087f5f 100644 --- a/tests/unit/plugins/lookup/test_hashi_vault.py +++ b/tests/unit/plugins/lookup/test_hashi_vault.py @@ -5,18 +5,51 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type +import os import pytest +from ansible.errors import AnsibleError + +from ansible.plugins.loader import lookup_loader + +from ansible.module_utils.six.moves.urllib.parse import urlparse + +from ansible_collections.community.hashi_vault.tests.unit.compat import mock + from ansible_collections.community.hashi_vault.plugins.lookup.hashi_vault import LookupModule # , HashiVault from ansible_collections.community.hashi_vault.plugins.lookup.__init__ import HashiVaultLookupBase +from requests.exceptions import ConnectionError + @pytest.fixture def hashi_vault_lookup_module(): - return LookupModule() + return lookup_loader.get('community.hashi_vault.hashi_vault') class TestHashiVaultLookup(object): def test_is_hashi_vault_lookup_base(self, hashi_vault_lookup_module): assert issubclass(type(hashi_vault_lookup_module), HashiVaultLookupBase) + + @pytest.mark.parametrize( + 'envpatch,expected', + [ + ({}, 'http://127.0.0.1:8200'), + ({'VAULT_ADDR': 'http://vault:0'}, 'http://vault:0'), + ({'ANSIBLE_HASHI_VAULT_ADDR': 'https://vaultalt'}, 'https://vaultalt'), + ({'VAULT_ADDR': 'https://vaultlow:8443', 'ANSIBLE_HASHI_VAULT_ADDR': 'http://vaulthigh:8200'}, 'http://vaulthigh:8200'), + ], + ) + def test_vault_addr_low_pref(self, hashi_vault_lookup_module, envpatch, expected): + url = urlparse(expected) + host = url.hostname + port = url.port if url.port is not None else {'http': 80, 'https': 443}[url.scheme] + + with mock.patch.dict(os.environ, envpatch): + with pytest.raises(ConnectionError) as e: + hashi_vault_lookup_module.run(['secret/fake']) + + s_err = str(e) + + assert host in s_err and str(port) in s_err, "host '%s' and port '%i' not found in exception: %r" % (host, port, e.value)