# Path: dput/util.py
# def validate_object(schema, obj, name):
#     sobj = None
#     for root in dput.core.SCHEMA_DIRS:
#         if sobj is not None:
#             logger.debug("Skipping %s" % (root))
#             continue
# 
#         logger.debug("Loading schema %s from %s" % (schema, root))
#         spath = "%s/%s.json" % (
#             root,
#             schema
#         )
#         try:
#             if os.path.exists(spath):
#                 sobj = json.load(open(spath, 'r'))
#             else:
#                 logger.debug("No such config: %s" % (spath))
#         except ValueError as e:
#             raise DputConfigurationError("syntax error in %s: %s" % (
#                 spath,
#                 e
#             ))
# 
#     if sobj is None:
#         logger.critical("Schema not found: %s" % (schema))
#         raise DputConfigurationError("No such schema: %s" % (schema))
# 
#     try:
#         import validictory
#         validictory.validate(obj, sobj)
#     except ImportError:
#         pass
#     except validictory.validator.ValidationError as e:
#         err = str(e)
#         error = "Error with config file %s - %s" % (
#             name,
#             err
#         )
#         ex = InvalidConfigError(error)
#         ex.obj = obj
#         ex.root = e
#         ex.config_name = name
#         ex.sdir = dput.core.SCHEMA_DIRS
#         ex.schema = schema
#         raise ex
# 
# def load_config(config_class, config_name,
#                 default=None, configs=None, config_cleanup=True):
#     """
#     Load any dput configuration given a ``config_class`` (such as
#     ``hooks``), and a ``config_name`` (such as
#     ``lintian`` or ``tweet``).
# 
#     Optional kwargs:
# 
#         ``default`` is a default to return, in case the config file
#         isn't found. If this isn't provided, this function will
#         raise a :class:`dput.exceptions.NoSuchConfigError`.
# 
#         ``configs`` is a list of config files to check. When this
#         isn't provided, we check dput.core.CONFIG_LOCATIONS.
#     """
# 
#     logger.debug("Loading configuration: %s %s" % (
#         config_class,
#         config_name
#     ))
#     roots = []
#     ret = {}
#     found = False
#     template_path = "%s/%s/%s.json"
#     locations = configs or dput.core.CONFIG_LOCATIONS
#     for config in locations:
#         logger.trace("Checking for configuration: %s" % (config))
#         path = template_path % (
#             config,
#             config_class,
#             config_name
#         )
#         logger.trace("Checking - %s" % (path))
#         try:
#             if os.path.exists(path):
#                 found = True
#                 roots.append(path)
#                 ret.update(json.load(open(path, 'r')))
#         except ValueError as e:
#             raise DputConfigurationError("syntax error in %s: %s" % (
#                 path, e
#             ))
# 
#     if not found:
#         if default is not None:
#             return default
# 
#         raise NoSuchConfigError("No such config: %s/%s" % (
#             config_class,
#             config_name
#         ))
# 
#     if 'meta' in ret and (
#         config_class != 'metas' or
#         ret['meta'] != config_name
#     ):
#         metainfo = load_config(
#             "metas",
#             ret['meta'],
#             default={}
#         )  # configs=configs)
#         # Erm, is this right? For some reason, I don't think it is. Meta
#         # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it.
#         #   -- PRT
#         for key in metainfo:
#             if not key in ret:
#                 ret[key] = metainfo[key]
#             else:
#                 logger.trace("Ignoring key %s for %s (%s)" % (
#                     key,
#                     ret['meta'],
#                     metainfo[key]
#                 ))
# 
#     obj = ret
#     if config_cleanup:
#         obj = _config_cleanup(ret)
# 
#     if obj != {}:
#         return obj
# 
#     if default is not None:
#         return default
# 
#     logger.debug("Failed to load configuration %s" % (config_name))
# 
#     nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % (
#         config_name,
#         config_class
#     ))
# 
#     nsce.config_class = config_class
#     nsce.config_name = config_name
#     nsce.checked = dput.core.CONFIG_LOCATIONS
#     raise nsce
# 
# Path: dput/exceptions.py
# class InvalidConfigError(DputError):
#     """
#     Config file was loaded properly, but it was missing part of it's
#     required fields.
#     """
#     pass


from dput.util import validate_object, load_config
from dput.exceptions import InvalidConfigError
import dput.core
import os


dput.core.CONFIG_LOCATIONS = {
    os.path.abspath("./tests/dputng"): 0
}  # Isolate.


def test_config_load():
    """ Make sure we can cleanly load a config """
    obj = load_config('profiles', 'test_profile')
    comp = {
        "incoming": "/dev/null",
        "method": "local",
        "meta": "ubuntu"
    }
    for key in comp:
        assert obj[key] == comp[key]


def test_config_validate():
    """ Make sure we can validate a good config """
    obj = load_config('profiles', 'test_profile')
    validate_object('config', obj, "profiles/test_profile")


def test_config_invalidate():
    """ Make sure a bad validation breaks """
    obj = load_config('profiles', 'test_profile_bad')
    try:

# Path: dput/util.py
# def validate_object(schema, obj, name):
#     sobj = None
#     for root in dput.core.SCHEMA_DIRS:
#         if sobj is not None:
#             logger.debug("Skipping %s" % (root))
#             continue
# 
#         logger.debug("Loading schema %s from %s" % (schema, root))
#         spath = "%s/%s.json" % (
#             root,
#             schema
#         )
#         try:
#             if os.path.exists(spath):
#                 sobj = json.load(open(spath, 'r'))
#             else:
#                 logger.debug("No such config: %s" % (spath))
#         except ValueError as e:
#             raise DputConfigurationError("syntax error in %s: %s" % (
#                 spath,
#                 e
#             ))
# 
#     if sobj is None:
#         logger.critical("Schema not found: %s" % (schema))
#         raise DputConfigurationError("No such schema: %s" % (schema))
# 
#     try:
#         import validictory
#         validictory.validate(obj, sobj)
#     except ImportError:
#         pass
#     except validictory.validator.ValidationError as e:
#         err = str(e)
#         error = "Error with config file %s - %s" % (
#             name,
#             err
#         )
#         ex = InvalidConfigError(error)
#         ex.obj = obj
#         ex.root = e
#         ex.config_name = name
#         ex.sdir = dput.core.SCHEMA_DIRS
#         ex.schema = schema
#         raise ex
# 
# def load_config(config_class, config_name,
#                 default=None, configs=None, config_cleanup=True):
#     """
#     Load any dput configuration given a ``config_class`` (such as
#     ``hooks``), and a ``config_name`` (such as
#     ``lintian`` or ``tweet``).
# 
#     Optional kwargs:
# 
#         ``default`` is a default to return, in case the config file
#         isn't found. If this isn't provided, this function will
#         raise a :class:`dput.exceptions.NoSuchConfigError`.
# 
#         ``configs`` is a list of config files to check. When this
#         isn't provided, we check dput.core.CONFIG_LOCATIONS.
#     """
# 
#     logger.debug("Loading configuration: %s %s" % (
#         config_class,
#         config_name
#     ))
#     roots = []
#     ret = {}
#     found = False
#     template_path = "%s/%s/%s.json"
#     locations = configs or dput.core.CONFIG_LOCATIONS
#     for config in locations:
#         logger.trace("Checking for configuration: %s" % (config))
#         path = template_path % (
#             config,
#             config_class,
#             config_name
#         )
#         logger.trace("Checking - %s" % (path))
#         try:
#             if os.path.exists(path):
#                 found = True
#                 roots.append(path)
#                 ret.update(json.load(open(path, 'r')))
#         except ValueError as e:
#             raise DputConfigurationError("syntax error in %s: %s" % (
#                 path, e
#             ))
# 
#     if not found:
#         if default is not None:
#             return default
# 
#         raise NoSuchConfigError("No such config: %s/%s" % (
#             config_class,
#             config_name
#         ))
# 
#     if 'meta' in ret and (
#         config_class != 'metas' or
#         ret['meta'] != config_name
#     ):
#         metainfo = load_config(
#             "metas",
#             ret['meta'],
#             default={}
#         )  # configs=configs)
#         # Erm, is this right? For some reason, I don't think it is. Meta
#         # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it.
#         #   -- PRT
#         for key in metainfo:
#             if not key in ret:
#                 ret[key] = metainfo[key]
#             else:
#                 logger.trace("Ignoring key %s for %s (%s)" % (
#                     key,
#                     ret['meta'],
#                     metainfo[key]
#                 ))
# 
#     obj = ret
#     if config_cleanup:
#         obj = _config_cleanup(ret)
# 
#     if obj != {}:
#         return obj
# 
#     if default is not None:
#         return default
# 
#     logger.debug("Failed to load configuration %s" % (config_name))
# 
#     nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % (
#         config_name,
#         config_class
#     ))
# 
#     nsce.config_class = config_class
#     nsce.config_name = config_name
#     nsce.checked = dput.core.CONFIG_LOCATIONS
#     raise nsce
# 
# Path: dput/exceptions.py
# class InvalidConfigError(DputError):
#     """
#     Config file was loaded properly, but it was missing part of it's
#     required fields.
#     """
#     pass


# Path: tests/test_configs.py
from dput.util import validate_object, load_config
from dput.exceptions import InvalidConfigError
import dput.core
import os



dput.core.CONFIG_LOCATIONS = {
    os.path.abspath("./tests/dputng"): 0
}  # Isolate.


def test_config_load():
    """ Make sure we can cleanly load a config """
    obj = load_config('profiles', 'test_profile')
    comp = {
        "incoming": "/dev/null",
        "method": "local",
        "meta": "ubuntu"
    }
    for key in comp:
        assert obj[key] == comp[key]


def test_config_validate():
    """ Make sure we can validate a good config """
    obj = load_config('profiles', 'test_profile')
    validate_object('config', obj, "profiles/test_profile")


def test_config_invalidate():
    """ Make sure a bad validation breaks """
    obj = load_config('profiles', 'test_profile_bad')
    try:

        validate_object('config', obj, "profiles/test_profile_bad")