コード例 #1
0
 def set_default_type(k, v):
     if Dict.is_dict(v):
         return (k, Close(v))
     elif Dict.is_list(v):
         return (k, Dict.is_type(v)([None if isinstance(i, type) else i for i in v]))
     else:
         return (k, None if isinstance(v, type) else v)
コード例 #2
0
    def test_is_dict(self):
        et = {'test': 123}
        dicts = [i(et) for i in Dict.__supported_classes__]

        for i in dicts:
            self.assertEqual(Dict.is_dict(i), True)

        for i in TestType.all_items:
            self.assertEqual(Dict.is_dict(i), False)
コード例 #3
0
 def _request(self) -> Dict:
     if self._config['kv_version'] == 2:
         return Dict(
             self._auth.v2.read_secret_version(
                 path=self._config['path'])['data']['data'])
     elif self._config['kv_version'] == 1:
         return Dict(
             self._auth.v1.read_secret(path=self._config['path'])['data'])
     else:
         return Dict()
コード例 #4
0
 def test_list_value(self):
     with unittest.mock.patch.dict(os.environ, {'FOO': '1,2,3,4,5'}):
         self.assertEqual(
             Dict(foo=[int], __env__=True).bind(Environment), {
                 'foo': [1, 2, 3, 4, 5],
                 '__env__': True
             })
コード例 #5
0
 def test_variable(self):
     with unittest.mock.patch.dict(os.environ, {'FOO': 'bar'}):
         self.assertEqual(
             Dict(foo=str, __env__=True).bind(Environment), {
                 'foo': 'bar',
                 '__env__': True
             })
コード例 #6
0
 def test_with_prefix(self):
     with unittest.mock.patch.dict(os.environ, {'FOO_BAR': 'baz'}):
         self.assertEqual(
             Dict(foo=dict(bar=str), __env__=True).bind(Environment), {
                 'foo': {
                     'bar': 'baz'
                 },
                 '__env__': True
             })
コード例 #7
0
 def test_finalize(self):
     data = test_data
     self.assertEqual(Close(Dict(data)), test_data)
コード例 #8
0
 def read(self, obj: Dict, prefix: str) -> Dict:
     return Dict([self.env(prefix, k, v) for k, v in obj.items()])
コード例 #9
0
import unittest

from abconfig import GetAttrs
from abconfig.common import Dict
from abconfig.utils import Close

test_data = dict(test1=1, test2=1, test3=Dict(a=1, b=1))


class TestClass(Dict):
    test1 = 1
    test2 = 1
    test3 = Dict(a=1, b=1)


class TestGetAttrs(unittest.TestCase):
    def test_read_attrs(self):
        self.assertEqual(GetAttrs(TestClass()), test_data)


class TestClose(unittest.TestCase):
    def test_finalize(self):
        data = test_data
        self.assertEqual(Close(Dict(data)), test_data)
コード例 #10
0
 def __init__(self, obj: Dict):
     super().__init__(Dict(obj).fmap(self.set_default_type))
コード例 #11
0
 def test_wrong_file_format(self, m):
     self.assertEqual(
         Dict(test=1, __file__=data['__file__']).bind(Json),
         dict(test=1, __file__=data['__file__']))
     m.assert_called_with(data['__file__'], 'r')
コード例 #12
0
 def test_detect_format_toml(self, m):
     self.assertEqual(
         Dict(test=1, __file__=data['__file__']).bind(File),
         dict(test=1, __file__=data['__file__']))
     m.assert_called_with(data['__file__'], 'r')
コード例 #13
0
 def test_disabled(self):
     self.assertEqual(Dict(test=1, ).bind(Json), dict(test=1))
コード例 #14
0
 def test_with_prefix(self, m):
     self.assertEqual(
         Dict(test=1, __file__=data['__file__'],
              __prefix__='test').bind(File),
         dict(test=1, __file__=data['__file__'], __prefix__='test'))
     m.assert_called_with(data['__file__'], 'r')
コード例 #15
0
 def test_toml(self, m):
     self.assertEqual(Dict(source).bind(Toml), data)
     m.assert_called_with(data['__file__'], 'r')
コード例 #16
0
class TestClass(Dict):
    test1 = 1
    test2 = 1
    test3 = Dict(a=1, b=1)
コード例 #17
0
 def test_bind(self):
     self.assertEqual(
         Dict(data=1).bind(lambda x: dict(new_data=x['data'])),
         Dict(new_data=1))
コード例 #18
0
 def test_fmap(self):
     self.assertEqual(
         Dict(data=1).fmap(lambda k, v: (k, v + 1)), Dict(data=2))
コード例 #19
0
 def test_associativity(self):
     self.assertEqual(
         Dict(Dict(data=1) + dict(data=2)) + dict(data=3),
         Dict(data=1) + (Dict(dict(data=2)) + dict(data=3)))
コード例 #20
0
 def test_mempty(self):
     self.assertEqual(
         Dict(Dict.__mempty__) + dict(data=2),
         Dict(data=2) + Dict.__mempty__, dict(data=2))
コード例 #21
0
class VaultData(OSEnviron):
    _config_scheme = Dict(auth_type='token',
                          data_type='json',
                          addr=str,
                          token=str,
                          path=str,
                          kv_version=2,
                          header_value=str,
                          role=str)

    def __init__(self, obj: Dict):
        self._required = obj.get('__vault_required__', True)
        self._config = (self._config_scheme + obj.get('__vault__')).bind(Close)
        try:
            self._cache = self._request()
        except VaultError as error:
            if self._required is True:
                raise VaultError(error)
            self._cache = {}

        if self._config['data_type'] == 'kv':
            super().__init__(obj + self.read(obj, obj.get('__prefix__')))
        elif self._config['data_type'] == 'json':
            super().__init__(obj + self._cache)
        else:
            raise ValueError(f'only supported "kv" or "json"')

    def env(self, prefix: str, k: str, v: any) -> tuple:
        key = k if k != '__vault__' else 'vault'
        if self.is_dict(v):
            return (key, self.read(v, self.concat(prefix, key)))
        else:
            return (key,
                    self._cache.get(self.concat(prefix, key).upper(), None))

    def _request(self) -> Dict:
        if self._config['kv_version'] == 2:
            return Dict(
                self._auth.v2.read_secret_version(
                    path=self._config['path'])['data']['data'])
        elif self._config['kv_version'] == 1:
            return Dict(
                self._auth.v1.read_secret(path=self._config['path'])['data'])
        else:
            return Dict()

    @property
    @ignore_warnings
    def _auth(self):
        client = VaultClient(url=self._config['addr'])
        auth = self._config['auth_type']
        token = self._config['token']

        if token and auth == 'token':
            client.token = token
        elif auth == 'aws_iam':
            session = boto3.Session()
            creds = session.get_credentials()
            kwargs = [self._config['header_value'], self._config['role']]

            client.auth_aws_iam(
                creds.access_key, creds.secret_key, creds.token,
                **{k: v
                   for k, v in self._config.items() if v and k in kwargs})

        if client.is_authenticated() is False:
            raise VaultUnauthorized(f'auth_type: {auth}')

        return client.secrets.kv

    @staticmethod
    def enabled(obj: Dict):
        return Dict.is_dict(obj.get('__vault__'))
コード例 #22
0
 def test_disabled(self):
     self.assertEqual(
         Dict(foo=1, __env__=False).bind(Environment), {
             'foo': 1,
             '__env__': False
         })
コード例 #23
0
 def enabled(obj: Dict):
     return Dict.is_dict(obj.get('__vault__'))
コード例 #24
0
 def test_json(self, m):
     self.assertEqual(Dict(source).bind(Json), data)
     m.assert_called_with(data['__file__'], 'r')