# -*- coding: UTF-8 -*-
# Copyright 2017 Red Hat, Inc.
# Part of clufter project
# Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt)
"""Common base for testing"""
__author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>"


from os.path import join, dirname; from sys import modules as m  # 2/3 compat
b = m.get('builtins', m.get('__builtin__')); e, E, h = 'exec', 'execfile', hash
c = lambda x: compile(x.read(), x.name, 'exec')
with open(join(dirname(dirname(__file__)), '_go')) as F:
    getattr(b, e, getattr(b, E, h)(F.name).__repr__.__name__.__ne__)(c(F))


from os.path import dirname, join, split
from sys import modules
from unittest import TestCase

from .filter_manager import FilterManager
from .utils import filterdict_keep


def rewrite_root(flt, new_root, **kwargs):
    # /foo/bar -> (/foo, bar)
    # /foo/bar/ -> (/foo/bar, )
    new_root_dir, new_xml_root = split(new_root)
    old_root_dir = dirname(modules[flt.__class__.__module__].__file__)
    new_root_dir = join(old_root_dir, new_root_dir)

    def _wrap(flt_cls):
        fnc = flt_cls._fnc
        def _fnc_wrapper(flt_ctxt, *args, **kws):
            flt_ctxt.update(
                filterdict_keep(kwargs, 'walk_transform',
                               root_dir=new_root_dir, xml_root=new_xml_root)
            )
            return fnc(flt_ctxt, *args, **kws)
        return _fnc_wrapper
    flt._fnc = _wrap(flt)
    return flt


class CommonFilterTestCase(TestCase):
    def setUp(self):
        self.flt_mgr = FilterManager.init_lookup(ext_plugins=False)


class TeardownFilterTestCase(CommonFilterTestCase):
    def tearDown(self):
        self.flt_mgr.registry.setup(True)  # start from scratch
        self.flt_mgr = None
