#    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.
"""
Tests For Scheduler hypervisor version weights.
"""

from nova.scheduler import weights
from nova.scheduler.weights import num_instances
from nova import test
from nova.tests.unit.scheduler import fakes


class NumInstancesWeigherTestCase(test.NoDBTestCase):
    def setUp(self):
        super().setUp()
        self.weight_handler = weights.HostWeightHandler()
        self.weighers = [num_instances.NumInstancesWeigher()]

    def _get_weighed_host(self, hosts, weight_properties=None):
        if weight_properties is None:
            weight_properties = {}
        return self.weight_handler.get_weighed_objects(self.weighers,
                hosts, weight_properties)[0]

    def _get_all_hosts(self):
        host_values = [
            ('host1', 'node1', {'num_instances': 2}),
            ('host2', 'node2', {'num_instances': 5}),
            ('host3', 'node3', {'num_instances': 4}),
            ('host4', 'node4', {'num_instances': 10}),
        ]
        return [fakes.FakeHostState(host, node, values)
                for host, node, values in host_values]

    def test_multiplier_default(self):
        hostinfo_list = self._get_all_hosts()
        weighed_host = self._get_weighed_host(hostinfo_list)
        self.assertEqual(0.0, weighed_host.weight)
        # Nothing changes, we just returns the first in the list
        self.assertEqual('host1', weighed_host.obj.host)

    def test_multiplier_positive(self):
        self.flags(
            num_instances_weight_multiplier=2.0,
            group='filter_scheduler'
        )
        hostinfo_list = self._get_all_hosts()
        weighed_host = self._get_weighed_host(hostinfo_list)
        self.assertEqual(2.0, weighed_host.weight)
        # Host4 wins because it has the most instances
        self.assertEqual('host4', weighed_host.obj.host)

    def test_multiplier_negative(self):
        self.flags(
            num_instances_weight_multiplier=-2.0,
            group='filter_scheduler'
        )
        hostinfo_list = self._get_all_hosts()
        weighed_host = self._get_weighed_host(hostinfo_list)
        self.assertEqual(0.0, weighed_host.weight)
        # Host1 wins because it has the less instances
        self.assertEqual('host1', weighed_host.obj.host)
