"""
Copyright (c) 2020 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""

from __future__ import absolute_import

from flexmock import flexmock
from osbs.utils.yaml import read_yaml, read_yaml_from_file_path
from osbs.exceptions import OsbsValidationException
from osbs.constants import PY3

import json
import os
import pkg_resources
import pytest
import yaml


def test_read_yaml_file_ioerrors(tmpdir):
    config_path = os.path.join(str(tmpdir), 'nosuchfile.yaml')
    with pytest.raises(IOError):
        read_yaml_from_file_path(config_path, 'schemas/nosuchfile.json')


@pytest.mark.parametrize('from_file', [True, False])
@pytest.mark.parametrize('config', [
    ("""\
      compose:
          modules:
          - mod_name:mod_stream:mod_version
    """),
])
def test_read_yaml_file_or_yaml(tmpdir, from_file, config):
    expected = yaml.safe_load(config)

    if from_file:
        config_path = os.path.join(str(tmpdir), 'config.yaml')
        with open(config_path, 'w') as fp:
            fp.write(config)
        output = read_yaml_from_file_path(config_path, 'schemas/container.json')
    else:
        output = read_yaml(config, 'schemas/container.json')

    assert output == expected


def test_read_yaml_bad_package(caplog):
    with pytest.raises(ImportError):
        read_yaml("", 'schemas/container.json', package='bad_package')
    assert 'Unable to find package bad_package' in caplog.text


def test_read_yaml_file_bad_extract(tmpdir, caplog):
    class FakeProvider(object):
        def get_resource_stream(self, pkg, rsc):
            raise IOError

    # pkg_resources.resource_stream() cannot be mocked directly
    # Instead mock the module-level function it calls.
    (flexmock(pkg_resources)
        .should_receive('get_provider')
        .and_return(FakeProvider()))

    config_path = os.path.join(str(tmpdir), 'config.yaml')
    with open(config_path, 'w'):
        pass

    with pytest.raises(IOError):
        read_yaml_from_file_path(config_path, 'schemas/container.json')
    assert "unable to extract JSON schema, cannot validate" in caplog.text


def test_read_yaml_file_bad_decode(tmpdir, caplog):
    (flexmock(json)
        .should_receive('load')
        .and_raise(ValueError))

    config_path = os.path.join(str(tmpdir), 'config.yaml')
    with open(config_path, 'w'):
        pass

    with pytest.raises(ValueError):
        read_yaml_from_file_path(config_path, 'schemas/container.json')
    assert "unable to decode JSON schema, cannot validate" in caplog.text


@pytest.mark.parametrize(('config', 'expected'), [
    ("""\
        operator_manifests:
            enable_digest_pinning: true
            repo_replacements: [] """,
     ("at top level: validating 'anyOf' has failed "
      "({}'manifests_dir' is a required property)"
      ).format('' if PY3 else 'u')),
    ("""\
        compose:
            packages: []
            pulp_repos: true
        mage_build_method: "imagebuilder" """,
     ("at top level: validating 'anyOf' has failed "
      "(Additional properties are not allowed ('mage_build_method' was unexpected))")),
])
def test_read_yaml_validation_error(config, expected, caplog):
    with pytest.raises(OsbsValidationException) as exc_info:
        read_yaml(config, 'schemas/container.json')

    assert "schema validation error" in caplog.text
    assert expected == str(exc_info.value)

@@ -309,91 +309,8 @@
 path
-%0Afrom osbs.exceptions import OsbsValidationException%0Afrom osbs.constants import PY3
 %0A%0Aim
@@ -2536,859 +2536,4 @@
 ext%0A
-%0A%0A@pytest.mark.parametrize(('config', 'expected'), %5B%0A    (%22%22%22%5C%0A        operator_manifests:%0A            enable_digest_pinning: true%0A            repo_replacements: %5B%5D %22%22%22,%0A     (%22at top level: validating 'anyOf' has failed %22%0A      %22(%7B%7D'manifests_dir' is a required property)%22%0A      ).format('' if PY3 else 'u')),%0A    (%22%22%22%5C%0A        compose:%0A            packages: %5B%5D%0A            pulp_repos: true%0A        mage_build_method: %22imagebuilder%22 %22%22%22,%0A     (%22at top level: validating 'anyOf' has failed %22%0A      %22(Additional properties are not allowed ('mage_build_method' was unexpected))%22)),%0A%5D)%0Adef test_read_yaml_validation_error(config, expected, caplog):%0A    with pytest.raises(OsbsValidationException) as exc_info:%0A        read_yaml(config, 'schemas/container.json')%0A%0A    assert %22schema validation error%22 in caplog.text%0A    assert expected == str(exc_info.value)%0A

Revert "Add testing of validation errors"