Add autopep8 to tox and pre-commit

autopep8 is a code formating tool that makes python code pep8
compliant without changing everything. Unlike black it will
not radically change all code and the primary change to the
existing codebase is adding a new line after class level doc strings.

This change adds a new tox autopep8 env to manually run it on your
code before you submit a patch, it also adds autopep8 to pre-commit
so if you use pre-commit it will do it for you automatically.

This change runs autopep8 in diff mode with --exit-code in the pep8
tox env so it will fail if autopep8 would modify your code if run
in in-place mode. This allows use to gate on autopep8 not modifying
patches that are submited. This will ensure authorship of patches is
maintianed.

The intent of this change is to save the large amount of time we spend
on ensuring style guidlines are followed automatically to make it
simpler for both new and old contibutors to work on nova and save
time and effort for all involved.

Change-Id: Idd618d634cc70ae8d58fab32f322e75bfabefb9d
This commit is contained in:
Sean Mooney 2021-08-26 14:16:19 +01:00
parent f024490e95
commit f3d48000b1
83 changed files with 154 additions and 3 deletions

View File

@ -33,3 +33,9 @@ repos:
entry: flake8
files: '^.*\.py$'
exclude: '^(doc|releasenotes|tools)/.*$'
- repo: https://github.com/pre-commit/mirrors-autopep8
rev: 'v1.5.7'
hooks:
- id: autopep8
files: '^.*\.py$'

View File

@ -34,6 +34,7 @@ class Matrix(object):
* self.features is a list of MatrixFeature instances, the rows and cells
* self.targets is a dict of (MatrixTarget.key, MatrixTarget), the columns
"""
def __init__(self):
self.features = []
self.targets = {}

View File

@ -42,6 +42,7 @@ def _get_context(req):
class AggregateController(wsgi.Controller):
"""The Host Aggregates API controller for the OpenStack API."""
def __init__(self):
super(AggregateController, self).__init__()
self.api = compute.AggregateAPI()

View File

@ -33,6 +33,7 @@ LOG = logging.getLogger(__name__)
class HostController(wsgi.Controller):
"""The Hosts API controller for the OpenStack API."""
def __init__(self):
super(HostController, self).__init__()
self.api = compute.HostAPI()

View File

@ -848,6 +848,7 @@ class APIRouterV21(base_wsgi.Router):
and method. The URL mapping based on the plain list `ROUTE_LIST` is built
at here.
"""
def __init__(self, custom_routes=None):
""":param custom_routes: the additional routes can be added by this
parameter. This parameter is used to test on some fake routes

View File

@ -24,6 +24,7 @@ from nova.policies import server_password as sp_policies
class ServerPasswordController(wsgi.Controller):
"""The Server Password API controller for the OpenStack API."""
def __init__(self):
super(ServerPasswordController, self).__init__()
self.compute_api = compute.API()

View File

@ -163,6 +163,7 @@ class MoveClaim(Claim):
Move can be either a migrate/resize, live-migrate or an evacuate operation.
"""
def __init__(
self, context, instance, nodename, flavor, image_meta, tracker,
compute_node, pci_requests, migration, limits=None,

View File

@ -58,6 +58,7 @@ class RecordWrapper(object):
Implementing __lt__ is enough for heapq.merge() to do its work.
"""
def __init__(self, ctx, sort_ctx, db_record):
self.cell_uuid = ctx.cell_uuid
self._sort_ctx = sort_ctx
@ -122,6 +123,7 @@ class CrossCellLister(metaclass=abc.ABCMeta):
your data type from cell databases.
"""
def __init__(self, sort_ctx, cells=None, batch_size=None):
self.sort_ctx = sort_ctx
self.cells = cells

View File

@ -48,6 +48,7 @@ class _Provider(object):
tree should be done using the ProviderTree interface, since it controls
thread-safety.
"""
def __init__(self, name, uuid=None, generation=None, parent_uuid=None):
if uuid is None:
uuid = uuidutils.generate_uuid()

View File

@ -77,6 +77,7 @@ class TargetDBSetupTask(base.TaskBase):
This is needed before any work can be done with the instance in the target
cell, like validating the selected target compute host.
"""
def __init__(self, context, instance, source_migration,
target_cell_context):
"""Initialize this task.

View File

@ -1951,7 +1951,6 @@ def _get_regexp_ops(connection):
def _regex_instance_filter(query, filters):
"""Applies regular expression filtering to an Instance query.
Returns the updated query.

View File

@ -26,6 +26,7 @@ LOG = logging.getLogger(__name__)
class BaseFilter(object):
"""Base class for all filter classes."""
def _filter_one(self, obj, spec_obj):
"""Return True if it passes the filter, False otherwise.
Override this in a subclass.

View File

@ -186,6 +186,7 @@ NIC_NAME_LEN = 14
class Model(dict):
"""Defines some necessary structures for most of the network models."""
def __repr__(self):
return jsonutils.dumps(self)
@ -202,6 +203,7 @@ class Model(dict):
class IP(Model):
"""Represents an IP address in Nova."""
def __init__(self, address=None, type=None, **kwargs):
super(IP, self).__init__()
@ -242,6 +244,7 @@ class IP(Model):
class FixedIP(IP):
"""Represents a Fixed IP address in Nova."""
def __init__(self, floating_ips=None, **kwargs):
super(FixedIP, self).__init__(**kwargs)
self['floating_ips'] = floating_ips or []
@ -273,6 +276,7 @@ class FixedIP(IP):
class Route(Model):
"""Represents an IP Route in Nova."""
def __init__(self, cidr=None, gateway=None, interface=None, **kwargs):
super(Route, self).__init__()
@ -292,6 +296,7 @@ class Route(Model):
class Subnet(Model):
"""Represents a Subnet in Nova."""
def __init__(self, cidr=None, dns=None, gateway=None, ips=None,
routes=None, **kwargs):
super(Subnet, self).__init__()
@ -343,6 +348,7 @@ class Subnet(Model):
class Network(Model):
"""Represents a Network in Nova."""
def __init__(self, id=None, bridge=None, label=None,
subnets=None, **kwargs):
super(Network, self).__init__()
@ -397,6 +403,7 @@ class VIF8021QbhParams(Model):
class VIF(Model):
"""Represents a Virtual Interface in Nova."""
def __init__(self, id=None, address=None, network=None, type=None,
details=None, devname=None, ovs_interfaceid=None,
qbh_params=None, qbg_params=None, active=False,

View File

@ -165,6 +165,7 @@ class ClientWrapper(clientv20.Client):
Wraps the callable methods, catches Unauthorized,Forbidden from Neutron and
convert it to a 401,403 for Nova clients.
"""
def __init__(self, base_client, admin):
# Expose all attributes from the base_client instance
self.__dict__ = base_client.__dict__

View File

@ -203,6 +203,7 @@ class WhitelistPciAddress(object):
| passthrough_whitelist = {"vendor_id":"1137","product_id":"0071"}
"""
def __init__(
self, pci_addr: PCISpecAddressType, is_physical_function: bool
) -> None:

View File

@ -49,6 +49,7 @@ HOST_INSTANCE_SEMAPHORE = "host_instance"
class ReadOnlyDict(IterableUserDict):
"""A read-only dict."""
def __init__(self, source=None):
self.data = {}
if source:

View File

@ -67,6 +67,7 @@ class RBDVolumeProxy(object):
The underlying librados client and ioctx can be accessed as the attributes
'client' and 'ioctx'.
"""
def __init__(self, driver, name, pool=None, snapshot=None,
read_only=False):
client, ioctx = driver._connect_to_rados(pool)
@ -102,6 +103,7 @@ class RBDVolumeProxy(object):
class RADOSClient(object):
"""Context manager to simplify error handling for connecting to ceph."""
def __init__(self, driver, pool=None):
self.driver = driver
self.cluster, self.ioctx = driver._connect_to_rados(pool)

View File

@ -779,6 +779,7 @@ class MatchType(object):
"world",
MatchType(objects.KeyPair))
"""
def __init__(self, wanttype):
self.wanttype = wanttype
@ -794,6 +795,7 @@ class MatchType(object):
class MatchObjPrims(object):
"""Matches objects with equal primitives."""
def __init__(self, want_obj):
self.want_obj = want_obj
@ -823,6 +825,7 @@ class ContainKeyValue(object):
"world",
ContainKeyValue('hello', world))
"""
def __init__(self, wantkey, wantvalue):
self.wantkey = wantkey
self.wantvalue = wantvalue

View File

@ -25,6 +25,7 @@ from nova import config
class ConfFixture(config_fixture.Config):
"""Fixture to manage global conf settings."""
def setUp(self):
super(ConfFixture, self).setUp()

View File

@ -907,6 +907,7 @@ class libvirtError(Exception):
Alternatively, you can use the `make_libvirtError` convenience function to
allow you to specify these attributes in one shot.
"""
def __init__(self, defmsg, conn=None, dom=None, net=None, pool=None,
vol=None):
Exception.__init__(self, defmsg)
@ -2137,6 +2138,7 @@ _EventAddHandleFunc = FakeHandler
class LibvirtFixture(fixtures.Fixture):
"""Performs global setup/stubbing for all libvirt tests.
"""
def __init__(self, stub_os_vif=True):
self.stub_os_vif = stub_os_vif

View File

@ -39,6 +39,7 @@ class _FakeNeutronClient:
For all other methods, this wrapper class simply calls through to the
corresponding NeutronFixture class method without any modifications.
"""
def __init__(self, fixture, is_admin):
self.fixture = fixture
self.is_admin = is_admin

View File

@ -102,6 +102,7 @@ class NullHandler(std_logging.Handler):
log_fixture.get_logging_handle_error_fixture to detect formatting errors in
debug level logs without saving the logs.
"""
def handle(self, record):
self.format(record)
@ -352,6 +353,7 @@ class CheatingSerializer(rpc.RequestContextSerializer):
Unless we had per-service config and database layer state for
the fake services we start, this is a reasonable cheat.
"""
def serialize_context(self, context):
"""Serialize context with the db_connection inside."""
values = super(CheatingSerializer, self).serialize_context(context)
@ -380,6 +382,7 @@ class CellDatabases(fixtures.Fixture):
Passing default=True tells the fixture which database should
be given to code that doesn't target a specific cell.
"""
def __init__(self):
self._ctxt_mgrs = {}
self._last_ctxt_mgr = None
@ -963,6 +966,7 @@ class OSMetadataServer(fixtures.Fixture):
interactions needed.
"""
def setUp(self):
super(OSMetadataServer, self).setUp()
# in order to run these in tests we need to bind only to local
@ -1092,6 +1096,7 @@ class SynchronousThreadPoolExecutorFixture(fixtures.Fixture):
Replace the GreenThreadPoolExecutor with the SynchronousExecutor.
"""
def setUp(self):
super(SynchronousThreadPoolExecutorFixture, self).setUp()
self.useFixture(fixtures.MonkeyPatch(
@ -1100,6 +1105,7 @@ class SynchronousThreadPoolExecutorFixture(fixtures.Fixture):
class BannedDBSchemaOperations(fixtures.Fixture):
"""Ban some operations for migrations"""
def __init__(self, banned_resources=None):
super(BannedDBSchemaOperations, self).__init__()
self._banned_resources = banned_resources or []
@ -1123,6 +1129,7 @@ class BannedDBSchemaOperations(fixtures.Fixture):
class ForbidNewLegacyNotificationFixture(fixtures.Fixture):
"""Make sure the test fails if new legacy notification is added"""
def __init__(self):
super(ForbidNewLegacyNotificationFixture, self).__init__()
self.notifier = rpc.LegacyValidatingNotifier
@ -1216,6 +1223,7 @@ class PrivsepFixture(fixtures.Fixture):
"""Disable real privsep checking so we can test the guts of methods
decorated with sys_admin_pctxt.
"""
def setUp(self):
super(PrivsepFixture, self).setUp()
self.useFixture(fixtures.MockPatchObject(
@ -1268,6 +1276,7 @@ class DownCellFixture(fixtures.Fixture):
# List services with down cells.
self.admin_api.api_get('/os-services')
"""
def __init__(self, down_cell_mappings=None):
self.down_cell_mappings = down_cell_mappings
@ -1369,6 +1378,7 @@ class AvailabilityZoneFixture(fixtures.Fixture):
requested when creating a server otherwise the instance.availabilty_zone
or default_availability_zone is returned.
"""
def __init__(self, zones):
self.zones = zones
@ -1405,6 +1415,7 @@ class KSAFixture(fixtures.Fixture):
"""Lets us initialize an openstack.connection.Connection by stubbing the
auth plugin.
"""
def setUp(self):
super(KSAFixture, self).setUp()
self.mock_load_auth = self.useFixture(fixtures.MockPatch(
@ -1533,6 +1544,7 @@ class PropagateTestCaseIdToChildEventlets(fixtures.Fixture):
https://bugs.launchpad.net/nova/+bug/1946339
"""
def __init__(self, test_case_id):
self.test_case_id = test_case_id

View File

@ -39,6 +39,7 @@ class RealPolicyFixture(fixtures.Fixture):
``policy_file`` accordingly.
"""
def _prepare_policy(self):
"""Allow changing of the policy before we get started"""
pass
@ -92,6 +93,7 @@ class PolicyFixture(RealPolicyFixture):
be better in those cases.
"""
def _prepare_policy(self):
self.policy_dir = self.useFixture(fixtures.TempDir())
self.policy_file = os.path.join(self.policy_dir.path,

View File

@ -168,6 +168,7 @@ class LibvirtMigrationMixin(object):
scenarios more complex than this they should override _migrate_stub with
their own implementation.
"""
def setUp(self):
super().setUp()
self.useFixture(fixtures.MonkeyPatch(

View File

@ -107,6 +107,7 @@ SERVER_DISKS = {
class _FileTest(object):
"""A base class for the _FlatTest and _Qcow2Test mixin test classes"""
def setUp(self):
super(_FileTest, self).setUp()
@ -148,6 +149,7 @@ class _FlatTest(_FileTest):
mock create_image to touch a file so we can assert its existence/removal in
tests.
"""
def setUp(self):
super(_FlatTest, self).setUp()
@ -172,6 +174,7 @@ class _Qcow2Test(_FileTest):
mock create_image to touch a file so we can assert its existence/removal in
tests.
"""
def setUp(self):
super(_Qcow2Test, self).setUp()
@ -193,6 +196,7 @@ class _RbdTest(object):
create_image to store which rbd volumes would have been created, and exists
to reference that store.
"""
def setUp(self):
super(_RbdTest, self).setUp()
@ -287,6 +291,7 @@ class _LVMTest(object):
the nova.virt.libvirt.storage.lvm module immediately before starting a new
compute.
"""
def setUp(self):
super(_LVMTest, self).setUp()
@ -395,6 +400,7 @@ class _LibvirtEvacuateTest(integrated_helpers.InstanceHelperMixin):
with these mixins we get test coverage of all combinations of
shared/nonshared instanace directories and block storage.
"""
def _start_compute(self, name):
# NOTE(mdbooth): fakelibvirt's getHostname currently returns a
# hardcoded 'compute1', which is undesirable if we want multiple fake

View File

@ -31,6 +31,7 @@ class TestRequestSpecRetryReschedule(test.TestCase,
resize, it is rejected by the RetryFilter because it's already in the
RequestSpec.retry field.
"""
def setUp(self):
super(TestRequestSpecRetryReschedule, self).setUp()
self.useFixture(nova_fixtures.RealPolicyFixture())

View File

@ -31,6 +31,7 @@ class TestRescheduleWithServerGroup(test.TestCase,
we hit an exception "'NoneType' object is not iterable" in the
RequestSpec.from_primitives method and the reschedule fails.
"""
def setUp(self):
super(TestRescheduleWithServerGroup, self).setUp()

View File

@ -32,6 +32,7 @@ class TestBootFromVolumeIsolatedHostsFilter(
The regression is that the RequestSpec.image.id field is not set and the
IsolatedHostsFilter blows up trying to load the image id.
"""
def setUp(self):
super(TestBootFromVolumeIsolatedHostsFilter, self).setUp()

View File

@ -29,6 +29,7 @@ class InstanceListWithDeletedServicesTestCase(
service uuid migration routine gets a ServiceNotFound error when loading
up a deleted service by hostname.
"""
def setUp(self):
super(InstanceListWithDeletedServicesTestCase, self).setUp()
self.useFixture(nova_fixtures.RealPolicyFixture())

View File

@ -34,6 +34,7 @@ class TestMultiCreateServerGroupMemberOverQuota(
to bypass the server_group_members quota check when creating multiple
servers in the same request.
"""
def setUp(self):
super(TestMultiCreateServerGroupMemberOverQuota, self).setUp()
self.flags(server_group_members=2, group='quota')

View File

@ -32,6 +32,7 @@ class RescheduleBuildAvailabilityZoneUpCall(
trying to connect to the API DB to get availability zone (aggregate) info
about the alternate host selection.
"""
def setUp(self):
super(RescheduleBuildAvailabilityZoneUpCall, self).setUp()
# Use the standard fixtures.
@ -96,6 +97,7 @@ class RescheduleMigrateAvailabilityZoneUpCall(
"""This is a regression test for the resize/cold migrate aspect of
bug 1781286 where the cell conductor does not have access to the API DB.
"""
def setUp(self):
super(RescheduleMigrateAvailabilityZoneUpCall, self).setUp()
# Use the standard fixtures.

View File

@ -43,6 +43,7 @@ class PeriodicNodeRecreateTestCase(test.TestCase,
there is a (soft) deleted version of the ComputeNode with the same uuid
in the database.
"""
def setUp(self):
super(PeriodicNodeRecreateTestCase, self).setUp()
# We need the PlacementFixture for the compute nodes to report in but

View File

@ -24,6 +24,7 @@ class ListDeletedServersWithMarker(test.TestCase,
MarkerNotFound, but that does not mean the marker was found in the build
request list.
"""
def setUp(self):
super(ListDeletedServersWithMarker, self).setUp()
# Start standard fixtures.

View File

@ -24,6 +24,7 @@ class TestInstanceActionBuryInCell0(test.TestCase,
event was not being created for instances buried in cell0 starting in
Ocata.
"""
def setUp(self):
super(TestInstanceActionBuryInCell0, self).setUp()
# Setup common fixtures.

View File

@ -38,6 +38,7 @@ class TestServersPerUserQuota(test.TestCase,
error because the 'instances' resource count isn't being correctly scoped
per-user.
"""
def setUp(self):
super(TestServersPerUserQuota, self).setUp()
self.useFixture(nova_fixtures.RealPolicyFixture())

View File

@ -24,6 +24,7 @@ class TestCreateServerGroupWithEmptyPolicies(
Attempt to create a server group with an invalid 'policies' field. It
should fail cleanly.
"""
def setUp(self):
super().setUp()

View File

@ -40,6 +40,7 @@ class TestDeleteWhileBooting(test.TestCase,
delete request. We aim to mock only the bare minimum necessary to recreate
the bug scenarios.
"""
def setUp(self):
super(TestDeleteWhileBooting, self).setUp()
self.useFixture(nova_fixtures.RealPolicyFixture())

View File

@ -25,6 +25,7 @@ class TestNeutronExternalNetworks(test.TestCase,
"""Tests for creating a server on a neutron network with
router:external=True.
"""
def setUp(self):
super(TestNeutronExternalNetworks, self).setUp()
# Use the standard fixtures.

View File

@ -1641,6 +1641,7 @@ class TestNovaManagePlacementHealPortAllocationsExtended(
extended format. Note that this will test the extended format handling but
only with a single request group per port.
"""
def setUp(self):
super().setUp()
self.neutron = self.useFixture(
@ -1667,6 +1668,7 @@ class TestNovaManagePlacementHealPortAllocationsMultiGroup(
with the MultiGroupResourceRequestNeutronFixture to test with extended
resource request with multiple groups.
"""
def setUp(self):
super().setUp()
self.neutron = self.useFixture(

View File

@ -4546,6 +4546,7 @@ class ServerTestV256SingleCellMultiHostTestCase(ServerTestV256Common):
"""Happy path test where we create a server on one host, migrate it to
another host of our choosing and ensure it lands there.
"""
def test_migrate_server_to_host_in_same_cell(self):
server = self._create_server()
server = self._wait_for_state_change(server, 'ACTIVE')

View File

@ -1638,6 +1638,7 @@ class MultiGroupResourceRequestBasedSchedulingTest(
and packet rate resource requests. This also means that the neutron fixture
simulates the new resource_request format for all ports.
"""
def setUp(self):
super().setUp()
self.neutron = self.useFixture(
@ -2972,6 +2973,7 @@ class ExtendedResourceRequestOldCompute(
hasn't been upgraded to a version that support extended resource request.
So nova rejects the operations due to the old compute.
"""
def setUp(self):
super().setUp()
self.neutron = self.useFixture(

View File

@ -52,7 +52,7 @@ class MicroversionsController2(wsgi.Controller):
@wsgi.Controller.api_version("2.5", "3.1") # noqa
@wsgi.response(202)
def index(self, req): # noqa
def index(self, req): # noqa
data = {'param': 'controller2_val2'}
return data

View File

@ -560,6 +560,7 @@ class InterfaceAttachTestsV249(test.NoDBTestCase):
class InterfaceAttachTestsV270(test.NoDBTestCase):
"""os-interface API tests for microversion 2.70"""
def setUp(self):
super(InterfaceAttachTestsV270, self).setUp()
self.attachments = (

View File

@ -6789,6 +6789,7 @@ class ServersControllerCreateTestV237(test.NoDBTestCase):
These tests are mostly about testing the validation on the 2.37
server create request with emphasis on negative scenarios.
"""
def setUp(self):
super(ServersControllerCreateTestV237, self).setUp()
# Create the server controller.
@ -6989,6 +6990,7 @@ class ServersControllerCreateTestV257(test.NoDBTestCase):
new=lambda *args, **kwargs: 1)
class ServersControllerCreateTestV260(test.NoDBTestCase):
"""Negative tests for creating a server with a multiattach volume."""
def setUp(self):
super(ServersControllerCreateTestV260, self).setUp()
self.useFixture(nova_fixtures.NoopQuotaDriverFixture())

View File

@ -933,6 +933,7 @@ class VolumeAttachTestsV249(test.NoDBTestCase):
class VolumeAttachTestsV260(test.NoDBTestCase):
"""Negative tests for attaching a multiattach volume with version 2.60."""
def setUp(self):
super(VolumeAttachTestsV260, self).setUp()
self.controller = volumes_v21.VolumeAttachmentController()

View File

@ -2376,6 +2376,7 @@ class TestNovaManagePlacement(test.NoDBTestCase):
For more involved functional scenarios, use
nova.tests.functional.test_nova_manage.
"""
def setUp(self):
super(TestNovaManagePlacement, self).setUp()
self.output = StringIO()

View File

@ -19,5 +19,6 @@ class SyncPool(eventlet.GreenPool):
"""Synchronous pool for testing threaded code without adding sleep
waits.
"""
def spawn_n(self, func, *args, **kwargs):
func(*args, **kwargs)

View File

@ -13180,6 +13180,7 @@ class DisabledInstanceTypesTestCase(BaseTestCase):
migrations against it, but we *don't* want customers building new
instances with the phased-out instance-type.
"""
def setUp(self):
super(DisabledInstanceTypesTestCase, self).setUp()
self.compute_api = compute.API()
@ -13249,6 +13250,7 @@ class ComputeRescheduleResizeOrReraiseTestCase(BaseTestCase):
"""Test logic and exception handling around rescheduling prep resize
requests
"""
def setUp(self):
super(ComputeRescheduleResizeOrReraiseTestCase, self).setUp()
self.instance = self._create_fake_instance_obj()

View File

@ -39,6 +39,7 @@ class TestValidateExtraSpecKeys(test.NoDBTestCase):
class TestGetFlavorByFlavorID(test.TestCase):
"""Test cases for flavor code."""
def test_will_not_get_instance_by_unknown_flavor_id(self):
# Ensure get by flavor raises error with wrong flavorid.
self.assertRaises(exception.FlavorNotFound,

View File

@ -37,6 +37,7 @@ class SchemaValidationMixin(base.BaseTestCase):
the subclass that call the run_test_ methods in this class. This should
keep things simple as more schema versions are added.
"""
def setUp(self):
super(SchemaValidationMixin, self).setUp()
self.mock_load_yaml = self.useFixture(

View File

@ -147,6 +147,7 @@ class _BaseTestCase(object):
class ConductorTestCase(_BaseTestCase, test.TestCase):
"""Conductor Manager Tests."""
def setUp(self):
super(ConductorTestCase, self).setUp()
self.conductor = conductor_manager.ConductorManager()
@ -308,6 +309,7 @@ class ConductorTestCase(_BaseTestCase, test.TestCase):
class ConductorRPCAPITestCase(_BaseTestCase, test.TestCase):
"""Conductor RPC API Tests."""
def setUp(self):
super(ConductorRPCAPITestCase, self).setUp()
self.conductor_service = self.start_service(
@ -318,6 +320,7 @@ class ConductorRPCAPITestCase(_BaseTestCase, test.TestCase):
class ConductorAPITestCase(_BaseTestCase, test.TestCase):
"""Conductor API Tests."""
def setUp(self):
super(ConductorAPITestCase, self).setUp()
self.conductor_service = self.start_service(
@ -4333,6 +4336,7 @@ class ConductorTaskTestCase(_BaseTaskTestCase, test_compute.BaseTestCase):
class ConductorTaskRPCAPITestCase(_BaseTaskTestCase,
test_compute.BaseTestCase):
"""Conductor compute_task RPC namespace Tests."""
def setUp(self):
super(ConductorTaskRPCAPITestCase, self).setUp()
self.conductor_service = self.start_service(
@ -4675,6 +4679,7 @@ class ConductorTaskRPCAPITestCase(_BaseTaskTestCase,
class ConductorTaskAPITestCase(_BaseTaskTestCase, test_compute.BaseTestCase):
"""Compute task API Tests."""
def setUp(self):
super(ConductorTaskAPITestCase, self).setUp()
self.conductor_service = self.start_service(

View File

@ -540,6 +540,7 @@ class TestFlavorExtraSpecs(test.TestCase):
class TestFlavorFiltering(test.TestCase):
"""Test cases for the filter option available for FlavorList.get_all."""
def setUp(self):
super().setUp()
self.context = nova_context.get_admin_context()

View File

@ -4213,6 +4213,7 @@ class TestAggregateAddRemoveHost(SchedulerReportClientTestCase):
access the SchedulerReportClient provider_tree attribute and are called
from the nova API, not the nova compute manager/resource tracker.
"""
def setUp(self):
super(TestAggregateAddRemoveHost, self).setUp()
self.mock_get = self.useFixture(

View File

@ -51,6 +51,7 @@ class HackingTestCase(test.NoDBTestCase):
just assertTrue if the check is expected to fail and assertFalse if it
should pass.
"""
def test_virt_driver_imports(self):
expect = (0, "N311: importing code from other virt drivers forbidden")

View File

@ -44,6 +44,7 @@ class IdentityValidationTest(test.NoDBTestCase):
not exist.
"""
def setUp(self):
super(IdentityValidationTest, self).setUp()
get_adap_p = mock.patch('nova.utils.get_ksa_adapter')

View File

@ -48,6 +48,7 @@ CONF.register_opts(test_service_opts)
class FakeManager(manager.Manager):
"""Fake manager for tests."""
def test_method(self):
return 'manager'

View File

@ -42,6 +42,7 @@ class IsolationTestCase(test.TestCase):
of other tests should fail.
"""
def test_service_isolation(self):
self.useFixture(fixtures.ServiceFixture('compute'))
@ -301,6 +302,7 @@ class ContainKeyValueTestCase(test.NoDBTestCase):
class NovaExceptionReraiseFormatErrorTestCase(test.NoDBTestCase):
"""Test that format errors are reraised in tests."""
def test_format_error_in_nova_exception(self):
class FakeImageException(exception.NovaException):
msg_fmt = 'Image %(image_id)s has wrong type %(type)s.'

View File

@ -907,6 +907,7 @@ class TestObjectCallHelpers(test.NoDBTestCase):
class GetKSAAdapterTestCase(test.NoDBTestCase):
"""Tests for nova.utils.get_endpoint_data()."""
def setUp(self):
super(GetKSAAdapterTestCase, self).setUp()
self.sess = mock.create_autospec(ks_session.Session, instance=True)
@ -1072,6 +1073,7 @@ class TestGetConfGroup(test.NoDBTestCase):
class TestGetAuthAndSession(test.NoDBTestCase):
"""Tests for nova.utils._get_auth_and_session"""
def setUp(self):
super(TestGetAuthAndSession, self).setUp()

View File

@ -298,6 +298,7 @@ class ItemsMatcher(CustomMockCallMatcher):
But the following will fail::
my_mock(..., listy_kwarg=['foo', 'bar'], ...)
"""
def __init__(self, iterable):
# NOTE(gibi): we need the extra iter() call as Counter handles dicts
# directly to initialize item count. However if a dict passed to

View File

@ -20516,6 +20516,7 @@ class HostStateTestCase(test.NoDBTestCase):
class FakeConnection(libvirt_driver.LibvirtDriver):
"""Fake connection object."""
def __init__(self):
super(HostStateTestCase.FakeConnection,
self).__init__(fake.FakeVirtAPI(), True)
@ -21384,6 +21385,7 @@ class TraitsComparisonMixin(object):
@ddt.ddt
class LibvirtDriverTestCase(test.NoDBTestCase, TraitsComparisonMixin):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver."""
def setUp(self):
super(LibvirtDriverTestCase, self).setUp()
self.flags(sysinfo_serial="none", group="libvirt")
@ -28033,6 +28035,7 @@ class LibvirtSnapshotTests(_BaseSnapshotTests):
class LXCSnapshotTests(LibvirtSnapshotTests):
"""Repeat all of the Libvirt snapshot tests, but with LXC enabled"""
def setUp(self):
super(LXCSnapshotTests, self).setUp()
self.flags(virt_type='lxc', group='libvirt')

View File

@ -23,6 +23,7 @@ class FakeDiskAdapter(disk_dvr.DiskAdapter):
This is done so that the abstract methods/properties can be stubbed and the
class can be instantiated for testing.
"""
def _vios_uuids(self):
pass

View File

@ -54,6 +54,7 @@ def catch_notimplementederror(f):
If a particular call makes a driver raise NotImplementedError, we
log it so that we can extract this information afterwards as needed.
"""
def wrapped_func(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)

View File

@ -366,6 +366,7 @@ class VirtualIDEController(DataObject):
class VirtualLsiLogicController(DataObject):
"""VirtualLsiLogicController class."""
def __init__(self, key=0, scsiCtlrUnitNumber=0, busNumber=0):
self.key = key
self.busNumber = busNumber

View File

@ -2190,6 +2190,7 @@ class VMwareVMOpsTestCase(test.NoDBTestCase):
coming from the image is bigger than the maximum allowed video ram from
the flavor.
"""
def test_video_ram(self):
meta_dict = {'id': self._image_id, 'properties': {'hw_video_ram': 120}}
image_meta, flavor = self._get_image_and_flavor_for_test_video(
@ -2205,6 +2206,7 @@ class VMwareVMOpsTestCase(test.NoDBTestCase):
coming from the image is not specified. This is a success scenario,
in the case where `hw_video_ram` property is not set.
"""
def test_video_ram_if_none(self):
meta_dict = {'id': self._image_id, 'properties': {}}
image_meta, flavor = self._get_image_and_flavor_for_test_video(
@ -2218,6 +2220,7 @@ class VMwareVMOpsTestCase(test.NoDBTestCase):
coming from the flavor is not specified. This is a success scenario,
in the case where `hw_video_ram` property is not set.
"""
def test_max_video_ram_none(self):
meta_dict = {'id': self._image_id, 'properties': {'hw_video_ram': 120}}
image_meta = objects.ImageMeta.from_dict(meta_dict)
@ -2242,6 +2245,7 @@ class VMwareVMOpsTestCase(test.NoDBTestCase):
the flavor. This is a success scenario, in the case where `hw_video_ram`
property is set in the extra spec.
"""
def test_success_video_ram(self):
expected_video_ram = 90
meta_dict = {'id': self._image_id, 'properties': {
@ -2258,6 +2262,7 @@ class VMwareVMOpsTestCase(test.NoDBTestCase):
coming from the image is equal to 0. This is a success scenario, in the
case where `hw_video_ram` property is not set in the extra spec.
"""
def test_zero_video_ram(self):
meta_dict = {'id': self._image_id, 'properties': {'hw_video_ram': 0}}
image_meta, flavor = self._get_image_and_flavor_for_test_video(

View File

@ -484,6 +484,7 @@ class UndoManager(object):
"""Provides a mechanism to facilitate rolling back a series of actions
when an exception is raised.
"""
def __init__(self):
self.undo_stack = []

View File

@ -51,6 +51,7 @@ class VFSGuestFS(vfs.VFS):
the host filesystem, thus avoiding any potential for symlink
attacks from the guest filesystem.
"""
def __init__(self, image, partition=None):
"""Create a new local VFS instance

View File

@ -757,6 +757,7 @@ class PredictableNodeUUIDDriver(SmallFakeDriver):
"""SmallFakeDriver variant that reports a predictable node uuid in
get_available_resource, like IronicDriver.
"""
def get_available_resource(self, nodename):
resources = super(
PredictableNodeUUIDDriver, self).get_available_resource(nodename)
@ -798,6 +799,7 @@ class FakeBuildAbortDriver(FakeDriver):
"""FakeDriver derivative that always fails on spawn() with a
BuildAbortException so no reschedule is attempted.
"""
def spawn(self, context, instance, image_meta, injected_files,
admin_password, allocations, network_info=None,
block_device_info=None, power_on=True, accel_info=None):
@ -814,6 +816,7 @@ class FakeUnshelveSpawnFailDriver(FakeDriver):
"""FakeDriver derivative that always fails on spawn() with a
VirtualInterfaceCreateException when unshelving an offloaded instance.
"""
def spawn(self, context, instance, image_meta, injected_files,
admin_password, allocations, network_info=None,
block_device_info=None, power_on=True, accel_info=None):

View File

@ -35,6 +35,7 @@ threading = patcher.original('threading')
class SerialConsoleHandler(object):
"""Handles serial console ops related to a given instance."""
def __init__(self, instance_name):
self._vmutils = utilsfactory.get_vmutils()
self._pathutils = pathutils.PathUtils()

View File

@ -963,6 +963,7 @@ class IronicDriver(virt_driver.ComputeDriver):
If false, pull fresh data from ironic.
:returns: an InstanceInfo object
"""
def _fetch_from_ironic(self, instance):
try:
node = self._validate_instance_and_node(instance)

View File

@ -1550,6 +1550,7 @@ class LibvirtConfigGuestDiskEncryptionSecret(LibvirtConfigObject):
class LibvirtConfigGuestDiskEncryption(LibvirtConfigObject):
"""https://libvirt.org/formatstorageencryption.html
"""
def __init__(self, **kwargs):
super(LibvirtConfigGuestDiskEncryption, self).__init__(**kwargs)
self.format = None

View File

@ -196,6 +196,7 @@ def patch_tpool_proxy():
or __repr__() calls. See bug #962840 for details.
We perform a monkey patch to replace those two instance methods.
"""
def str_method(self):
return str(self._obj)
@ -3933,7 +3934,6 @@ class LibvirtDriver(driver.ComputeDriver):
accel_info)
def trigger_crash_dump(self, instance):
"""Trigger crash dump by injecting an NMI to the specified instance."""
try:
self._host.get_guest(instance).inject_nmi()

View File

@ -21,6 +21,7 @@ class LibvirtEvent(event.InstanceEvent):
class DeviceEvent(LibvirtEvent):
"""Base class for device related libvirt events"""
def __init__(self, uuid: str, dev: str, timestamp: float = None):
super().__init__(uuid, timestamp)
self.dev = dev

View File

@ -521,6 +521,7 @@ class Flat(Image):
creating an overlay. By default it creates raw files, but will use qcow2
when creating a disk from a qcow2 if force_raw_images is not set in config.
"""
def __init__(self, instance=None, disk_name=None, path=None):
self.disk_name = disk_name
path = (path or os.path.join(libvirt_utils.get_instance_path(instance),

View File

@ -23,6 +23,7 @@ CONF = nova.conf.CONF
class LibvirtISERVolumeDriver(iscsi.LibvirtISCSIVolumeDriver):
"""Driver to attach Network volumes to libvirt."""
def __init__(self, connection):
super(LibvirtISERVolumeDriver, self).__init__(connection)

View File

@ -174,6 +174,7 @@ class _HostMountState(object):
class _MountPoint(object):
"""A single mountpoint, and the set of attachments in use on it."""
def __init__(self):
# A guard for operations on this mountpoint
# N.B. Care is required using this lock, as it will be deleted

View File

@ -22,6 +22,7 @@ LOG = logging.getLogger(__name__)
class LibvirtNetVolumeDriver(libvirt_volume.LibvirtBaseVolumeDriver):
"""Driver to attach Network volumes to libvirt."""
def __init__(self, host):
super(LibvirtNetVolumeDriver,
self).__init__(host, is_block_dev=False)

View File

@ -34,6 +34,7 @@ class LibvirtScaleIOVolumeDriver(libvirt_volume.LibvirtBaseVolumeDriver):
Implements Libvirt part of volume driver for ScaleIO cinder driver.
Uses the ScaleIO connector from the os-brick projects
"""
def __init__(self, host):
super(LibvirtScaleIOVolumeDriver, self).__init__(host,
is_block_dev=False)

View File

@ -31,6 +31,7 @@ LOG = logging.getLogger(__name__)
@profiler.trace_cls("volume_api")
class LibvirtBaseVolumeDriver(object):
"""Base class for volume drivers."""
def __init__(self, host, is_block_dev):
self.host = host
self.is_block_dev = is_block_dev
@ -156,6 +157,7 @@ class LibvirtBaseVolumeDriver(object):
class LibvirtVolumeDriver(LibvirtBaseVolumeDriver):
"""Class for volumes backed by local file."""
def __init__(self, host):
super(LibvirtVolumeDriver,
self).__init__(host, is_block_dev=True)
@ -171,6 +173,7 @@ class LibvirtVolumeDriver(LibvirtBaseVolumeDriver):
class LibvirtFakeVolumeDriver(LibvirtBaseVolumeDriver):
"""Driver to attach fake volumes to libvirt."""
def __init__(self, host):
super(LibvirtFakeVolumeDriver,
self).__init__(host, is_block_dev=True)

View File

@ -724,6 +724,7 @@ class VMwareAPISession(api.VMwareAPISession):
"""Sets up a session with the VC/ESX host and handles all
the calls made to the host.
"""
def __init__(self, host_ip=CONF.vmware.host_ip,
host_port=CONF.vmware.host_port,
username=CONF.vmware.host_username,

View File

@ -47,6 +47,7 @@ def _get_ds_capacity_and_freespace(session, cluster=None,
class VCState(object):
"""Manages information about the vCenter cluster"""
def __init__(self, session, host_name, cluster, datastore_regex):
super(VCState, self).__init__()
self._session = session

View File

@ -412,6 +412,7 @@ def translate_cinder_exception(method):
def translate_create_exception(method):
"""Transforms the exception for create but keeps its traceback intact.
"""
def wrapper(self, ctx, size, *args, **kwargs):
try:
res = method(self, ctx, size, *args, **kwargs)
@ -426,6 +427,7 @@ def translate_create_exception(method):
def translate_volume_exception(method):
"""Transforms the exception for the volume but keeps its traceback intact.
"""
def wrapper(self, ctx, volume_id, *args, **kwargs):
try:
res = method(self, ctx, volume_id, *args, **kwargs)
@ -441,6 +443,7 @@ def translate_attachment_exception(method):
"""Transforms the exception for the attachment but keeps its traceback
intact.
"""
def wrapper(self, ctx, attachment_id, *args, **kwargs):
try:
res = method(self, ctx, attachment_id, *args, **kwargs)
@ -455,6 +458,7 @@ def translate_snapshot_exception(method):
"""Transforms the exception for the snapshot but keeps its traceback
intact.
"""
def wrapper(self, ctx, snapshot_id, *args, **kwargs):
try:
res = method(self, ctx, snapshot_id, *args, **kwargs)
@ -466,6 +470,7 @@ def translate_snapshot_exception(method):
def translate_mixed_exceptions(method):
"""Transforms exceptions that can come from both volumes and snapshots."""
def wrapper(self, ctx, res_id, *args, **kwargs):
try:
res = method(self, ctx, res_id, *args, **kwargs)

View File

@ -53,6 +53,7 @@ def normalize(weight_list, minval=None, maxval=None):
class WeighedObject(object):
"""Object with weight information."""
def __init__(self, obj, weight):
self.obj = obj
self.weight = weight

15
tox.ini
View File

@ -47,14 +47,29 @@ commands =
description =
Run style checks.
envdir = {toxworkdir}/shared
deps =
{[testenv]deps}
autopep8
commands =
{[testenv:mypy]commands}
# check if autopep8 would alter the formatting but don't actually change it
# so we can gate on this in the ci
autopep8 --exit-code --max-line-length=79 --diff -r nova doc setup.py
# since autopep8 only tries to make minimal changes to conform to pep8 we still need to run
# our hacking and flake8 check to keep our existing code style consistent.
# The full list of issues addressable by autopep8 can be found here
# https://pypi.org/project/autopep8/#features
bash tools/flake8wrap.sh {posargs}
# Check that all JSON files don't have \r\n in line.
bash -c "! find doc/ -type f -name *.json | xargs grep -U -n $'\r'"
# Check that all included JSON files are valid JSON
bash -c '! find doc/ -type f -name *.json | xargs -t -n1 python -m json.tool 2>&1 > /dev/null | grep -B1 -v ^python'
[testenv:autopep8]
deps = autopep8
commands =
autopep8 --exit-code --max-line-length=79 --in-place -r nova doc setup.py
[testenv:fast8]
description =
Run style checks on the changes made since HEAD~. For a full run including docs, use 'pep8'