# Copyright (c) 2013 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import uuid

import mock
import six
import testtools

from sahara import exceptions as ex
from sahara import main
from sahara.service import api
from sahara.service.validations.edp import job_execution as je
from sahara.service.validations.edp import job_execution_schema as je_schema
from sahara.tests.unit.service.validation import utils as u
from sahara.tests.unit import testutils as tu
from sahara.utils import edp


def wrap_it(data):
    je.check_job_execution(data, 0)


class TestJobExecCreateValidation(u.ValidationTestCase):

    def setUp(self):
        super(TestJobExecCreateValidation, self).setUp()
        self._create_object_fun = wrap_it
        self.scheme = je_schema.JOB_EXEC_SCHEMA
        # Make sure that the spark plugin is loaded
        if 'spark' not in main.CONF['plugins']:
            self.override_config('plugins', main.CONF['plugins'] + ['spark'])
        api.plugin_base.setup_plugins()

    @mock.patch('sahara.conductor.api.LocalApi.cluster_get')
    @mock.patch('sahara.conductor.api.LocalApi.data_source_get')
    @mock.patch('sahara.conductor.api.LocalApi.job_get')
    def test_streaming(self, get_job, get_data_source, get_cluster):
        get_job.return_value = mock.Mock(
            type=edp.JOB_TYPE_MAPREDUCE_STREAMING, libs=[], interface=[])

        ds1_id = six.text_type(uuid.uuid4())
        ds2_id = six.text_type(uuid.uuid4())

        data_sources = {
            ds1_id: mock.Mock(type="swift", url="http://swift/test"),
            ds2_id: mock.Mock(type="swift", url="http://swift/test2"),
        }

        get_data_source.side_effect = lambda ctx, x: data_sources[x]

        ng = tu.make_ng_dict('master', 42, ['oozie'], 1,
                             instances=[tu.make_inst_dict('id', 'name')])
        get_cluster.return_value = tu.create_cluster("cluster", "tenant1",
                                                     "vanilla", "1.2.1", [ng])

        self._assert_create_object_validation(
            data={
                "cluster_id": six.text_type(uuid.uuid4()),
                "input_id": ds1_id,