<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4
#
#    Copyright 2010 OpenStack LLC
#
#    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 base64
import netaddr
import sys
import traceback

from nova.compute.manager import ComputeManager
from nova import exception
from nova.openstack.common import importutils
from nova.openstack.common import log as logging
from nova import test
from nova.tests.image import fake as fake_image
from nova.tests import utils as test_utils

LOG = logging.getLogger(__name__)


def catch_notimplementederror(f):
    """Decorator to simplify catching drivers raising NotImplementedError

    If a particular call makes a driver raise NotImplementedError, we
    log it so that we can extract this information afterwards to
    automatically generate a hypervisor/feature support matrix."""
    def wrapped_func(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except NotImplementedError:
            frame = traceback.extract_tb(sys.exc_info()[2])[-1]
            LOG.error('%(driver)s does not implement %(method)s' % {
                                               'driver': type(self.connection),
                                               'method': frame[2]})

    wrapped_func.__name__ = f.__name__
    wrapped_func.__doc__ = f.__doc__
    return wrapped_func


class _FakeDriverBackendTestCase(test.TestCase):
    def _setup_fakelibvirt(self):
        # So that the _supports_direct_io does the test based
        # on the current working directory, instead of the
        # default instances_path which doesn't exist
        self.flags(instances_path='')

        # Put fakelibvirt in place
        if 'libvirt' in sys.modules:
            self.saved_libvirt = sys.modules['libvirt']
        else:
            self.saved_libvirt = None

        import fake_imagebackend
        import fake_libvirt_utils
        import fakelibvirt

        sys.modules['libvirt'] = fakelibvirt
        import nova.virt.libvirt.driver
        import nova.virt.libvirt.firewall

        nova.virt.libvirt.driver.imagebackend = fake_imagebackend
        nova.virt.libvirt.driver.libvirt = fakelibvirt
        nova.virt.libvirt.driver.libvirt_utils = fake_libvirt_utils
        nova.virt.libvirt.firewall.libvirt = fakelibvirt

        self.flags(firewall_driver=nova.virt.libvirt.firewall.drivers[0],
                   rescue_image_id="2",
                   rescue_kernel_id="3",
                   rescue_ramdisk_id=None,
                   libvirt_snapshots_directory='./')

        def fake_extend(image, size):
            pass

        def fake_migrateToURI(*a):
            pass

        def fake_make_drive(_self, _path):
            pass

        self.stubs.Set(nova.virt.libvirt.driver.disk,
                       'extend', fake_extend)

        # Like the existing fakelibvirt.migrateToURI, do nothing,
        # but don't fail for these tests.
        self.stubs.Set(nova.virt.libvirt.driver.libvirt.Domain,
                       'migrateToURI', fake_migrateToURI)

        # We can't actually make a config drive v2 because ensure_tree has
        # been faked out
        self.stubs.Set(nova.virt.configdrive.ConfigDriveBuilder,
                       'make_drive', fake_make_drive)

    def _teardown_fakelibvirt(self):
        # Restore libvirt
        import nova.virt.libvirt.driver
        import nova.virt.libvirt.firewall
        if self.saved_libvirt:
            sys.modules['libvirt'] = self.saved_libvirt
            nova.virt.libvirt.driver.libvirt = self.saved_libvirt
            nova.virt.libvirt.driver.libvirt_utils = self.saved_libvirt
            nova.virt.libvirt.firewall.libvirt = self.saved_libvirt

    def setUp(self):
        super(_FakeDriverBackendTestCase, self).setUp()
        # TODO(sdague): it would be nice to do this in a way that only
        # the relevant backends where replaced for tests, though this
        # should not harm anything by doing it for all backends
        fake_image.stub_out_image_service(self.stubs)
        self._setup_fakelibvirt()

    def tearDown(self):
        fake_image.FakeImageService_reset()
        self._teardown_fakelibvirt()
        super(_FakeDriverBackendTestCase, self).tearDown()


class VirtDriverLoaderTestCase(_FakeDriverBackendTestCase):
    """Test that ComputeManager can successfully load both
    old style and new style drivers and end up with the correct
    final class"""

    # if your driver supports being tested in a fake way, it can go here
    #
    # both long form and short form drivers are supported
    new_drivers = {<commit_msg>Restore imagebackend in test_virt_drivers.py<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4
#
#    Copyright 2010 OpenStack LLC
#
#    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 base64
import netaddr
import sys
import traceback

from nova.compute.manager import ComputeManager
from nova import exception
from nova.openstack.common import importutils
from nova.openstack.common import log as logging
from nova import test
from nova.tests.image import fake as fake_image
from nova.tests import utils as test_utils

LOG = logging.getLogger(__name__)


def catch_notimplementederror(f):
    """Decorator to simplify catching drivers raising NotImplementedError

    If a particular call makes a driver raise NotImplementedError, we
    log it so that we can extract this information afterwards to
    automatically generate a hypervisor/feature support matrix."""
    def wrapped_func(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except NotImplementedError:
            frame = traceback.extract_tb(sys.exc_info()[2])[-1]
            LOG.error('%(driver)s does not implement %(method)s' % {
                                               'driver': type(self.connection),
                                               'method': frame[2]})

    wrapped_func.__name__ = f.__name__
    wrapped_func.__doc__ = f.__doc__
    return wrapped_func


class _FakeDriverBackendTestCase(test.TestCase):
    def _setup_fakelibvirt(self):
        # So that the _supports_direct_io does the test based
        # on the current working directory, instead of the
        # default instances_path which doesn't exist
        self.flags(instances_path='')

        # Put fakelibvirt in place
        if 'libvirt' in sys.modules:
            self.saved_libvirt = sys.modules['libvirt']
        else:
            self.saved_libvirt = None

        import fake_imagebackend
        import fake_libvirt_utils
        import fakelibvirt

        sys.modules['libvirt'] = fakelibvirt
        import nova.virt.libvirt.driver
        import nova.virt.libvirt.firewall

        self.saved_libvirt_imagebackend = nova.virt.libvirt.driver.imagebackend
        nova.virt.libvirt.driver.imagebackend = fake_imagebackend
        nova.virt.libvirt.driver.libvirt = fakelibvirt
        nova.virt.libvirt.driver.libvirt_utils = fake_libvirt_utils
        nova.virt.libvirt.firewall.libvirt = fakelibvirt

        self.flags(firewall_driver=nova.virt.libvirt.firewall.drivers[0],
                   rescue_image_id="2",
                   rescue_kernel_id="3",
                   rescue_ramdisk_id=None,
                   libvirt_snapshots_directory='./')

        def fake_extend(image, size):
            pass

        def fake_migrateToURI(*a):
            pass

        def fake_make_drive(_self, _path):
            pass

        self.stubs.Set(nova.virt.libvirt.driver.disk,
                       'extend', fake_extend)

        # Like the existing fakelibvirt.migrateToURI, do nothing,
        # but don't fail for these tests.
        self.stubs.Set(nova.virt.libvirt.driver.libvirt.Domain,
                       'migrateToURI', fake_migrateToURI)

        # We can't actually make a config drive v2 because ensure_tree has
        # been faked out
        self.stubs.Set(nova.virt.configdrive.ConfigDriveBuilder,
                       'make_drive', fake_make_drive)

    def _teardown_fakelibvirt(self):
        # Restore libvirt
        import nova.virt.libvirt.driver
        import nova.virt.libvirt.firewall
        nova.virt.libvirt.driver.imagebackend = self.saved_libvirt_imagebackend
        if self.saved_libvirt:
            sys.modules['libvirt'] = self.saved_libvirt
            nova.virt.libvirt.driver.libvirt = self.saved_libvirt
            nova.virt.libvirt.driver.libvirt_utils = self.saved_libvirt
            nova.virt.libvirt.firewall.libvirt = self.saved_libvirt

    def setUp(self):
        super(_FakeDriverBackendTestCase, self).setUp()
        # TODO(sdague): it would be nice to do this in a way that only
        # the relevant backends where replaced for tests, though this
        # should not harm anything by doing it for all backends
        fake_image.stub_out_image_service(self.stubs)
        self._setup_fakelibvirt()

    def tearDown(self):
        fake_image.FakeImageService_reset()
        self._teardown_fakelibvirt()
        super(_FakeDriverBackendTestCase, self).tearDown()


class VirtDriverLoaderTestCase(_FakeDriverBackendTestCase):
    """Test that ComputeManager can successfully load both
    old style and new style drivers and end up with the correct
    final class"""

    # if your driver supports being tested in a fake way, it can go here
    #
    # both long form and short form drivers are supported
    new_drivers = {
{'fraction_non_alphanumeric': 0.07198016970159214, 'fraction_numerical': 0.003813518924587663, 'mean_word_length': 2.5838742740006833, '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': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1761052', 'n_tokens_mistral': 2962, 'n_tokens_neox': 2908, 'n_words': 835}