<commit_before># -*- coding: utf8 -*-
#
#    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 contextlib

from django.core import urlresolvers
from horizon import exceptions
from mock import patch, call  # noqa
from novaclient.v1_1 import servers
from openstack_dashboard.test.test_data import utils

from tuskar_ui import api
from tuskar_ui.infrastructure.flavors import utils as flavors_utils
from tuskar_ui.test import helpers as test
from tuskar_ui.test.test_data import flavor_data
from tuskar_ui.test.test_data import heat_data
from tuskar_ui.test.test_data import tuskar_data


TEST_DATA = utils.TestDataContainer()
flavor_data.data(TEST_DATA)
heat_data.data(TEST_DATA)
tuskar_data.data(TEST_DATA)
INDEX_URL = urlresolvers.reverse(
    'horizon:infrastructure:flavors:index')
CREATE_URL = urlresolvers.reverse(
    'horizon:infrastructure:flavors:create')
DETAILS_VIEW = 'horizon:infrastructure:flavors:details'


@contextlib.contextmanager
def _prepare_create():
    flavor = TEST_DATA.novaclient_flavors.first()
    all_flavors = TEST_DATA.novaclient_flavors.list()
    images = TEST_DATA.glanceclient_images.list()
    data = {'name': 'foobar',
            'vcpus': 3,
            'memory_mb': 1024,
            'disk_gb': 40,
            'arch': 'amd64',
            'kernel_image_id': images[5].id,
            'ramdisk_image_id': images[4].id}
    with contextlib.nested(
            patch('tuskar_ui.api.flavor.Flavor.create',
                  return_value=flavor),
            patch('openstack_dashboard.api.glance.image_list_detailed',
                  return_value=(TEST_DATA.glanceclient_images.list(), False)),
            # Inherited code calls this directly
            patch('openstack_dashboard.api.nova.flavor_list',
                  return_value=all_flavors),
    ) as mocks:
            yield mocks[0], data


class FlavorsTest(test.BaseAdminViewTests):

    def test_index(self):
        plans = [api.tuskar.Plan(plan, self.request)
                 for plan in TEST_DATA.tuskarclient_plans.list()]
        roles = [api.tuskar.Role(role)
                 for role in self.tuskarclient_roles.list()]

        with contextlib.nested(
                patch('tuskar_ui.api.tuskar.Plan.list',
                      return_value=plans),
                patch('tuskar_ui.api.tuskar.Role.list',
                      return_value=roles),
                patch('openstack_dashboard.api.nova.flavor_list',
                      return_value=TEST_DATA.novaclient_flavors.list()),
                patch('openstack_dashboard.api.nova.server_list',
                      return_value=([], False)),
        ) as (plans_mock, roles_mock, flavors_mock, servers_mock):
            res = self.client.get(INDEX_URL)
            self.assertEqual(plans_mock.call_count, 1)
            self.assertEqual(roles_mock.call_count, 4)
            self.assertEqual(flavors_mock.call_count, 3)
            self.assertEqual(servers_mock.call_count, 1)

        self.assertTemplateUsed(res, 'infrastructure/flavors/index.html')

    def test_index_recoverable_failure(self):
        with patch('openstack_dashboard.api.nova.flavor_list',
                   side_effect=exceptions.Conflict):
            self.client.get(INDEX_URL)
            # FIXME(dtantsur): I expected the following to work:
            # self.assertMessageCount(error=1, warning=0)

    def test_create_get(self):
        with patch('openstack_dashboard.api.glance.image_list_detailed',
                   return_value=([], False)) as mock:
            res = self.client.get(CREATE_URL)
            self.assertEqual(mock.call_count, 2)
        self.assertTemplateUsed(res, 'infrastructure/flavors/create.html')

    def test_create_get_recoverable_failure(self):
        with patch('openstack_dashboard.api.glance.image_list_detailed',
                   side_effect=exceptions.Conflict):
            self.client.get(CREATE_URL)
            # FIXME(tzumainn): I expected the following to work, seems similar
            # to comment on test_index_recoverable_failure
            # self.assertMessageCount(error=1, warning=0)

    def test_create_post_ok(self):
        images = TEST_DATA.glanceclient_images.list()
        with _prepare_create() as (create_mock, data):
            res = self.client.post(CREATE_URL, data)
            self.assertNoFormErrors(res)
            self.assertRedirectsNoFollow(res, INDEX_URL)
            request = create_mock.call_args_list[0][0][0]
            self.assertListEqual(create_mock.call_args_list, [
                call(request, name=u'foobar', memory=1024, vcpus=3, disk=40,
                     cpu_arch='amd64', kernel_image_id=images[5].id,
                     ramdisk_image_id=images[4].id)
            ])

    def test_create_post_name_exists(self):
        flavor = TEST_DATA.novaclient_flavors.first()
        with _prepare_create() as (create_mock, data):
            data['name'] = flavor.name
            res = self.client.post(CREATE_URL, data)
            self.assertFormErrors(res)

    def test_delete_ok(self):
        flavors = TEST_DATA.novaclient_flavors.list()<commit_msg>Fix message counts in flavor tests<commit_after># -*- coding: utf8 -*-
#
#    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 contextlib

from django.core import urlresolvers
from mock import patch, call  # noqa
from novaclient import exceptions as nova_exceptions
from novaclient.v1_1 import servers
from openstack_dashboard.test.test_data import utils

from tuskar_ui import api
from tuskar_ui.infrastructure.flavors import utils as flavors_utils
from tuskar_ui.test import helpers as test
from tuskar_ui.test.test_data import flavor_data
from tuskar_ui.test.test_data import heat_data
from tuskar_ui.test.test_data import tuskar_data


TEST_DATA = utils.TestDataContainer()
flavor_data.data(TEST_DATA)
heat_data.data(TEST_DATA)
tuskar_data.data(TEST_DATA)
INDEX_URL = urlresolvers.reverse(
    'horizon:infrastructure:flavors:index')
CREATE_URL = urlresolvers.reverse(
    'horizon:infrastructure:flavors:create')
DETAILS_VIEW = 'horizon:infrastructure:flavors:details'


@contextlib.contextmanager
def _prepare_create():
    flavor = TEST_DATA.novaclient_flavors.first()
    all_flavors = TEST_DATA.novaclient_flavors.list()
    images = TEST_DATA.glanceclient_images.list()
    data = {'name': 'foobar',
            'vcpus': 3,
            'memory_mb': 1024,
            'disk_gb': 40,
            'arch': 'amd64',
            'kernel_image_id': images[5].id,
            'ramdisk_image_id': images[4].id}
    with contextlib.nested(
            patch('tuskar_ui.api.flavor.Flavor.create',
                  return_value=flavor),
            patch('openstack_dashboard.api.glance.image_list_detailed',
                  return_value=(TEST_DATA.glanceclient_images.list(), False)),
            # Inherited code calls this directly
            patch('openstack_dashboard.api.nova.flavor_list',
                  return_value=all_flavors),
    ) as mocks:
            yield mocks[0], data


def _raise_nova_client_exception(*args, **kwargs):
    raise nova_exceptions.ClientException("Boom!")


class FlavorsTest(test.BaseAdminViewTests):

    def test_index(self):
        plans = [api.tuskar.Plan(plan, self.request)
                 for plan in TEST_DATA.tuskarclient_plans.list()]
        roles = [api.tuskar.Role(role)
                 for role in self.tuskarclient_roles.list()]

        with contextlib.nested(
                patch('tuskar_ui.api.tuskar.Plan.list',
                      return_value=plans),
                patch('tuskar_ui.api.tuskar.Role.list',
                      return_value=roles),
                patch('openstack_dashboard.api.nova.flavor_list',
                      return_value=TEST_DATA.novaclient_flavors.list()),
                patch('openstack_dashboard.api.nova.server_list',
                      return_value=([], False)),
        ) as (plans_mock, roles_mock, flavors_mock, servers_mock):
            res = self.client.get(INDEX_URL)
            self.assertEqual(plans_mock.call_count, 1)
            self.assertEqual(roles_mock.call_count, 4)
            self.assertEqual(flavors_mock.call_count, 3)
            self.assertEqual(servers_mock.call_count, 1)

        self.assertTemplateUsed(res, 'infrastructure/flavors/index.html')

    def test_index_recoverable_failure(self):
        with patch('openstack_dashboard.api.nova.flavor_list',
                   side_effect=_raise_nova_client_exception) as flavor_list:
            res = self.client.get(INDEX_URL)
            self.assertEqual(flavor_list.call_count, 2)
        self.assertEqual(
            [(m.message, m.tags) for m in res.context['messages']],
            [
                (u'Unable to retrieve flavor list.', u'error'),
                (u'Unable to retrieve nodes', u'error'),
            ],
        )
        self.assertMessageCount(response=res, error=2, warning=0)

    def test_create_get(self):
        with patch('openstack_dashboard.api.glance.image_list_detailed',
                   return_value=([], False)) as mock:
            res = self.client.get(CREATE_URL)
            self.assertEqual(mock.call_count, 2)
        self.assertTemplateUsed(res, 'infrastructure/flavors/create.html')

    def test_create_get_recoverable_failure(self):
        with patch('openstack_dashboard.api.glance.image_list_detailed',
                   side_effect=_raise_nova_client_exception):
            res = self.client.get(CREATE_URL)
        self.assertEqual(
            [(m.message, m.tags) for m in res.context['messages']],
            [
                (u'Unable to retrieve images list.', u'error'),
            ],
        )
        self.assertMessageCount(response=res, error=1, warning=0)

    def test_create_post_ok(self):
        images = TEST_DATA.glanceclient_images.list()
        with _prepare_create() as (create_mock, data):
            res = self.client.post(CREATE_URL, data)
            self.assertNoFormErrors(res)
            self.assertRedirectsNoFollow(res, INDEX_URL)
            request = create_mock.call_args_list[0][0][0]
            self.assertListEqual(create_mock.call_args_list, [
                call(request, name=u'foobar', memory=1024, vcpus=3, disk=40,
                     cpu_arch='amd64', kernel_image_id=images[5].id,
                     ramdisk_image_id=images[4].id)
            ])

    def test_create_post_name_exists(self):
        flavor = TEST_DATA.novaclient_flavors.first()
        with _prepare_create() as (create_mock, data):
            data['name'] = flavor.name
            res = self.client.post(CREATE_URL, data)
            self.assertFormErrors(res)

    def test_delete_ok(self):
        flavors = TEST_DATA.novaclient_flavors.list()
{'fraction_non_alphanumeric': 0.09675501189262657, 'fraction_numerical': 0.007220523275569147, 'mean_word_length': 2.7115384615384617, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5989315', 'n_tokens_mistral': 3625, 'n_tokens_neox': 3557, 'n_words': 688}