Exemplo n.º 1
0
    def test_extend_accepts_a_store_class(self):
        cache = CacheManager({
            'default': 'my-driver',
            'stores': {
                'my-driver': {
                    'driver': 'my-driver'
                }
            }
        })

        cache.extend('my-driver', CustomStore)

        self.assertIsInstance(cache.store().get_store(), CustomStore)
Exemplo n.º 2
0
    def test_extend_accepts_a_store_class(self):
        cache = CacheManager({
            'default': 'my-driver',
            'stores': {
                'my-driver': {
                    'driver': 'my-driver'
                }
            }
        })

        cache.extend('my-driver', CustomStore)

        self.assertIsInstance(cache.store().get_store(), CustomStore)
Exemplo n.º 3
0
    def test_extend_accepts_a_callable_returning_a_repository(self):
        cache = CacheManager({
            'default': 'my-driver',
            'stores': {
                'my-driver': {
                    'driver': 'my-driver'
                }
            }
        })

        cache.extend('my-driver', lambda config: Repository(CustomStore()))

        self.assertIsInstance(cache.store().get_store(), CustomStore)
Exemplo n.º 4
0
    def test_extend_accepts_a_callable_returning_a_repository(self):
        cache = CacheManager({
            'default': 'my-driver',
            'stores': {
                'my-driver': {
                    'driver': 'my-driver'
                }
            }
        })

        cache.extend('my-driver', lambda config: Repository(CustomStore()))

        self.assertIsInstance(cache.store().get_store(), CustomStore)
Exemplo n.º 5
0
class Configuration(Mapping):
    DEFAULT_CONFIG_PATH = Path(user_config_dir("adr")) / "config.toml"
    DEFAULTS = {
        "cache": {
            "retention": 1440
        },  # minutes
        "debug": False,
        "debug_url":
        "https://activedata.allizom.org/tools/query.html#query_id={}",
        "fmt": "table",
        "sources": [os.getcwd(),
                    Path(adr.__file__).parent.parent.as_posix()],
        "url": "http://localhost:5000/query",
        "verbose": False,
    }
    locked = False

    def __init__(self, path=None):
        self.path = Path(path or os.environ.get("ADR_CONFIG_PATH")
                         or self.DEFAULT_CONFIG_PATH)

        self._config = self.DEFAULTS.copy()
        if self.path.is_file():
            with open(self.path, "r") as fh:
                content = fh.read()
                self.merge(parse(content)["adr"])
        else:
            logger.warning(f"Configuration path {self.path} is not a file.")

        self._config["sources"] = sorted(
            map(os.path.expanduser, set(self._config["sources"])))

        # Use the NullStore by default. This allows us to control whether
        # caching is enabled or not at runtime.
        self._config["cache"].setdefault("stores",
                                         {"null": {
                                             "driver": "null"
                                         }})
        self.cache = CacheManager(self._config["cache"])
        self.cache.extend("null", lambda driver: NullStore())
        self.locked = True

    def __len__(self):
        return len(self._config)

    def __iter__(self):
        return iter(self._config)

    def __getitem__(self, key):
        return self._config[key]

    def __getattr__(self, key):
        if key in vars(self):
            return vars(self)[key]
        return self.__getitem__(key)

    def __setattr__(self, key, value):
        if self.locked:
            raise AttributeError(
                "Don't set attributes directly, use `config.set(key=value)` instead."
            )
        super(Configuration, self).__setattr__(key, value)

    def set(self, **kwargs):
        """Set data on the config object."""
        self._config.update(kwargs)

    def merge(self, other):
        """Merge data into config (updates dicts and lists instead of
        overwriting them).

        Args:
            other (dict): Dictionary to merge configuration with.
        """
        merge_to(other, self._config)

    def dump(self):
        return "\n".join(flatten(self._config))