# Path: pydatajson/catalog_readme.py
# def generate_readme(catalog, export_path=None, verify_ssl=True):
#     """Genera una descripción textual en formato Markdown sobre los
#     metadatos generales de un catálogo (título, editor, fecha de
#     publicación, et cetera), junto con:
#         - estado de los metadatos a nivel catálogo,
#         - estado global de los metadatos,
#         - cantidad de datasets federados y no federados,
#         - detalles de los datasets no federados
#         - cantidad de datasets y distribuciones incluidas
# 
#     Es utilizada por la rutina diaria de `libreria-catalogos` para generar
#     un README con información básica sobre los catálogos mantenidos.
# 
#     Args:
#         catalog (str o dict): Path a un catálogo en cualquier formato,
#             JSON, XLSX, o diccionario de python.
#         export_path (str): Path donde exportar el texto generado (en
#             formato Markdown). Si se especifica, el método no devolverá
#             nada.
# 
#     Returns:
#         str: Texto de la descripción generada.
#     """
#     # Si se paso una ruta, guardarla
#     if isinstance(catalog, string_types):
#         catalog_path_or_url = catalog
#     else:
#         catalog_path_or_url = None
# 
#     catalog = read_catalog(catalog)
#     validation = validate_catalog(catalog, verify_ssl=verify_ssl)
#     # Solo necesito indicadores para un catalogo
#     indicators = generate_catalogs_indicators(
#         catalog, CENTRAL_CATALOG)[0][0]
# 
#     with io.open(os.path.join(TEMPLATES_PATH, 'catalog_readme.txt'), 'r',
#                  encoding='utf-8') as template_file:
#         readme_template = template_file.read()
# 
#         not_federated_datasets_list = "\n".join([
#             "- [{}]({})".format(dataset[0], dataset[1])
#             for dataset in indicators["datasets_no_federados"]
#         ])
#         federated_removed_datasets_list = "\n".join([
#             "- [{}]({})".format(dataset[0], dataset[1])
#             for dataset in indicators["datasets_federados_eliminados"]
#         ])
#         federated_datasets_list = "\n".join([
#             "- [{}]({})".format(dataset[0], dataset[1])
#             for dataset in indicators["datasets_federados"]
#         ])
#         non_federated_pct = 1.0 - indicators["datasets_federados_pct"] if \
#             indicators["datasets_federados_pct"] is not None else \
#             indicators["datasets_federados_pct"]
#         content = {
#             "title": catalog.get("title"),
#             "publisher_name": traverse_dict(
#                 catalog, ["publisher", "name"]),
#             "publisher_mbox": traverse_dict(
#                 catalog, ["publisher", "mbox"]),
#             "catalog_path_or_url": catalog_path_or_url,
#             "description": catalog.get("description"),
#             "global_status": validation["status"],
#             "catalog_status": validation["error"]["catalog"]["status"],
#             "no_of_datasets": len(catalog["dataset"]),
#             "no_of_distributions": sum([len(dataset["distribution"]) for
#                                         dataset in catalog["dataset"]]),
#             "federated_datasets": indicators["datasets_federados_cant"],
#             "not_federated_datasets": indicators["datasets_no_federados_cant"],
#             "not_federated_datasets_pct": non_federated_pct,
#             "not_federated_datasets_list": not_federated_datasets_list,
#             "federated_removed_datasets_list": federated_removed_datasets_list,
#             "federated_datasets_list": federated_datasets_list,
#         }
# 
#         catalog_readme = readme_template.format(**content)
# 
#     if export_path:
#         with io.open(export_path, 'w+', encoding='utf-8') as target:
#             target.write(catalog_readme)
#     else:
#         return catalog_readme
# 
# Path: tests/support/decorators.py
# RESULTS_DIR = os.path.join("tests", "results")


import io
import os.path
import requests_mock
import vcr
    import mock
import filecmp
from nose.tools import assert_true, assert_equal
    from unittest import mock
from pydatajson.catalog_readme import generate_readme
from tests.support.decorators import RESULTS_DIR
                 cassette_library_dir=os.path.join("tests", "cassetes"),
                 record_mode='once')


class TestDataJsonTestCase(object):
    SAMPLES_DIR = os.path.join("tests", "samples")
    RESULTS_DIR = RESULTS_DIR
    TEMP_DIR = os.path.join("tests", "temp")

    @classmethod
    def get_sample(cls, sample_filename):
        return os.path.join(cls.SAMPLES_DIR, sample_filename)

    @classmethod
    def setUp(cls):
        cls.catalog = cls.get_sample("several_datasets_for_harvest.json")
        cls.requests_mock = requests_mock.Mocker()
        cls.requests_mock.start()
        cls.requests_mock.get(requests_mock.ANY, real_http=True)
        cls.requests_mock.head(requests_mock.ANY, status_code=200)

    @classmethod
    def tearDown(cls):
        cls.requests_mock.stop()

    @my_vcr.use_cassette()
    def test_generate_readme(self):
        with io.open(os.path.join(self.RESULTS_DIR, "catalog_readme.md"), 'r',
                     encoding='utf-8') as expected_readme_file:
            expected_readme = expected_readme_file.read()

# Path: pydatajson/catalog_readme.py
# def generate_readme(catalog, export_path=None, verify_ssl=True):
#     """Genera una descripción textual en formato Markdown sobre los
#     metadatos generales de un catálogo (título, editor, fecha de
#     publicación, et cetera), junto con:
#         - estado de los metadatos a nivel catálogo,
#         - estado global de los metadatos,
#         - cantidad de datasets federados y no federados,
#         - detalles de los datasets no federados
#         - cantidad de datasets y distribuciones incluidas
# 
#     Es utilizada por la rutina diaria de `libreria-catalogos` para generar
#     un README con información básica sobre los catálogos mantenidos.
# 
#     Args:
#         catalog (str o dict): Path a un catálogo en cualquier formato,
#             JSON, XLSX, o diccionario de python.
#         export_path (str): Path donde exportar el texto generado (en
#             formato Markdown). Si se especifica, el método no devolverá
#             nada.
# 
#     Returns:
#         str: Texto de la descripción generada.
#     """
#     # Si se paso una ruta, guardarla
#     if isinstance(catalog, string_types):
#         catalog_path_or_url = catalog
#     else:
#         catalog_path_or_url = None
# 
#     catalog = read_catalog(catalog)
#     validation = validate_catalog(catalog, verify_ssl=verify_ssl)
#     # Solo necesito indicadores para un catalogo
#     indicators = generate_catalogs_indicators(
#         catalog, CENTRAL_CATALOG)[0][0]
# 
#     with io.open(os.path.join(TEMPLATES_PATH, 'catalog_readme.txt'), 'r',
#                  encoding='utf-8') as template_file:
#         readme_template = template_file.read()
# 
#         not_federated_datasets_list = "\n".join([
#             "- [{}]({})".format(dataset[0], dataset[1])
#             for dataset in indicators["datasets_no_federados"]
#         ])
#         federated_removed_datasets_list = "\n".join([
#             "- [{}]({})".format(dataset[0], dataset[1])
#             for dataset in indicators["datasets_federados_eliminados"]
#         ])
#         federated_datasets_list = "\n".join([
#             "- [{}]({})".format(dataset[0], dataset[1])
#             for dataset in indicators["datasets_federados"]
#         ])
#         non_federated_pct = 1.0 - indicators["datasets_federados_pct"] if \
#             indicators["datasets_federados_pct"] is not None else \
#             indicators["datasets_federados_pct"]
#         content = {
#             "title": catalog.get("title"),
#             "publisher_name": traverse_dict(
#                 catalog, ["publisher", "name"]),
#             "publisher_mbox": traverse_dict(
#                 catalog, ["publisher", "mbox"]),
#             "catalog_path_or_url": catalog_path_or_url,
#             "description": catalog.get("description"),
#             "global_status": validation["status"],
#             "catalog_status": validation["error"]["catalog"]["status"],
#             "no_of_datasets": len(catalog["dataset"]),
#             "no_of_distributions": sum([len(dataset["distribution"]) for
#                                         dataset in catalog["dataset"]]),
#             "federated_datasets": indicators["datasets_federados_cant"],
#             "not_federated_datasets": indicators["datasets_no_federados_cant"],
#             "not_federated_datasets_pct": non_federated_pct,
#             "not_federated_datasets_list": not_federated_datasets_list,
#             "federated_removed_datasets_list": federated_removed_datasets_list,
#             "federated_datasets_list": federated_datasets_list,
#         }
# 
#         catalog_readme = readme_template.format(**content)
# 
#     if export_path:
#         with io.open(export_path, 'w+', encoding='utf-8') as target:
#             target.write(catalog_readme)
#     else:
#         return catalog_readme
# 
# Path: tests/support/decorators.py
# RESULTS_DIR = os.path.join("tests", "results")


# Path: tests/test_catalog_readme.py
import io
import os.path
import requests_mock
import vcr
    import mock
import filecmp
from nose.tools import assert_true, assert_equal
    from unittest import mock
from pydatajson.catalog_readme import generate_readme
from tests.support.decorators import RESULTS_DIR

                 cassette_library_dir=os.path.join("tests", "cassetes"),
                 record_mode='once')


class TestDataJsonTestCase(object):
    SAMPLES_DIR = os.path.join("tests", "samples")
    RESULTS_DIR = RESULTS_DIR
    TEMP_DIR = os.path.join("tests", "temp")

    @classmethod
    def get_sample(cls, sample_filename):
        return os.path.join(cls.SAMPLES_DIR, sample_filename)

    @classmethod
    def setUp(cls):
        cls.catalog = cls.get_sample("several_datasets_for_harvest.json")
        cls.requests_mock = requests_mock.Mocker()
        cls.requests_mock.start()
        cls.requests_mock.get(requests_mock.ANY, real_http=True)
        cls.requests_mock.head(requests_mock.ANY, status_code=200)

    @classmethod
    def tearDown(cls):
        cls.requests_mock.stop()

    @my_vcr.use_cassette()
    def test_generate_readme(self):
        with io.open(os.path.join(self.RESULTS_DIR, "catalog_readme.md"), 'r',
                     encoding='utf-8') as expected_readme_file:
            expected_readme = expected_readme_file.read()

            readme = generate_readme(self.catalog)