本文整理汇总了Python中snf_django.utils.testing.mocked_quotaholder函数的典型用法代码示例。如果您正苦于以下问题:Python mocked_quotaholder函数的具体用法?Python mocked_quotaholder怎么用?Python mocked_quotaholder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了mocked_quotaholder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_invalid_operstate_for_action
def test_invalid_operstate_for_action(self, mrapi):
vm = mfactory.VirtualMachineFactory(operstate="STARTED")
self.assertRaises(faults.BadRequest, servers.start, vm)
vm = mfactory.VirtualMachineFactory(operstate="STOPPED")
self.assertRaises(faults.BadRequest, servers.stop, vm)
vm = mfactory.VirtualMachineFactory(operstate="STARTED")
flavor = mfactory.FlavorFactory()
self.assertRaises(faults.BadRequest, servers.resize, vm, flavor)
# Check that connect/disconnect is allowed only in STOPPED vms
# if hotplug is disabled.
vm = mfactory.VirtualMachineFactory(operstate="STARTED")
network = mfactory.NetworkFactory(state="ACTIVE")
with override_settings(settings, GANETI_USE_HOTPLUG=False):
self.assertRaises(faults.BadRequest, servers.connect, vm, network)
self.assertRaises(faults.BadRequest, servers.disconnect, vm, network)
# test valid
vm = mfactory.VirtualMachineFactory(operstate="STOPPED")
mrapi().StartupInstance.return_value = 1
with mocked_quotaholder():
servers.start(vm)
vm.task = None
vm.task_job_id = None
vm.save()
with mocked_quotaholder():
quotas.accept_resource_serial(vm)
mrapi().RebootInstance.return_value = 1
with mocked_quotaholder():
servers.reboot(vm, "HARD")
示例2: test_start_shutdown
def test_start_shutdown(self):
from synnefo.logic import backend
self.vm1 = mfactory.VirtualMachineFactory(userid=USER1)
pk = self.vm1.pk
r = self.client.post(reverse('helpdesk-vm-shutdown', args=(pk,)))
self.assertEqual(r.status_code, 403)
r = self.client.post(reverse('helpdesk-vm-shutdown', args=(pk,)),
data={'token': '0001'})
self.assertEqual(r.status_code, 403)
backend.shutdown_instance = shutdown = mock.Mock()
shutdown.return_value = 1
self.vm1.operstate = 'STARTED'
self.vm1.save()
with mocked_quotaholder():
r = self.client.post(reverse('helpdesk-vm-shutdown', args=(pk,)),
data={'token': '0001'}, user_token='0001')
self.assertEqual(r.status_code, 302)
self.assertTrue(shutdown.called)
self.assertEqual(len(shutdown.mock_calls), 1)
backend.startup_instance = startup = mock.Mock()
startup.return_value = 2
self.vm1.operstate = 'STOPPED'
self.vm1.save()
with mocked_quotaholder():
r = self.client.post(reverse('helpdesk-vm-start', args=(pk,)),
data={'token': '0001'}, user_token='0001')
self.assertEqual(r.status_code, 302)
self.assertTrue(startup.called)
self.assertEqual(len(startup.mock_calls), 1)
示例3: test_building_vm
def test_building_vm(self, mrapi):
vm1 = mfactory.VirtualMachineFactory(backend=self.backend,
backendjobid=1,
operstate="BUILD")
for status in ["queued", "waiting", "running"]:
mrapi().GetJobs.return_value = [{"id": "1", "status": status,
"end_ts": None}]
with mocked_quotaholder():
self.reconciler.reconcile()
vm1 = VirtualMachine.objects.get(id=vm1.id)
self.assertFalse(vm1.deleted)
self.assertEqual(vm1.operstate, "BUILD")
mrapi().GetJobs.return_value = [{"id": "1", "status": "error",
"end_ts": [44123, 1]}]
with mocked_quotaholder():
self.reconciler.reconcile()
vm1 = VirtualMachine.objects.get(id=vm1.id)
self.assertFalse(vm1.deleted)
self.assertEqual(vm1.operstate, "ERROR")
for status in ["success", "canceled"]:
vm1.operstate = "BUILD"
vm1.deleted = False
vm1.save()
mrapi().GetJobs.return_value = [{"id": "1", "status": status,
"end_ts": [44123, 1]}]
with mocked_quotaholder():
self.reconciler.reconcile()
vm1 = VirtualMachine.objects.get(id=vm1.id)
self.assertFalse(vm1.deleted)
self.assertEqual(vm1.operstate, "ERROR")
示例4: test_reserve_empty_body
def test_reserve_empty_body(self):
"""Test reserve FIP without specifying network."""
request = {"floatingip": {}}
# delete all pools..
IPPoolTable.objects.all().delete()
Subnet.objects.all().delete()
Network.objects.all().delete()
# CASE: no floating IP pool
with mocked_quotaholder():
response = self.post(URL, "test_user", json.dumps(request), "json")
self.assertConflict(response)
# CASE: Full floating IP pool
mf.NetworkWithSubnetFactory(floating_ip_pool=True, public=True,
subnet__pool__size=0)
with mocked_quotaholder():
response = self.post(URL, "test_user", json.dumps(request), "json")
self.assertConflict(response)
# CASE: Available floating IP pool
p1 = mf.NetworkWithSubnetFactory(floating_ip_pool=True, public=True,
subnet__cidr="192.168.2.0/30",
subnet__pool__size=1)
with mocked_quotaholder():
response = self.post(URL, "test_user", json.dumps(request), "json")
self.assertSuccess(response)
floating_ip = json.loads(response.content)["floatingip"]
db_fip = IPAddress.objects.get(id=floating_ip["id"])
self.assertEqual(db_fip.address, floating_ip["floating_ip_address"])
self.assertTrue(db_fip.floating_ip)
# Test that address is reserved
ip_pool = p1.get_ip_pools()[0]
self.assertFalse(ip_pool.is_available(db_fip.address))
示例5: test_reassign_vm_backends
def test_reassign_vm_backends(self, mrapi):
volume = mfactory.VolumeFactory()
vm = volume.machine
original_project = vm.project
another_project = "another_project"
with mocked_quotaholder():
vm = servers.reassign(vm.id, another_project, False,
credentials=self.credentials)
self.assertEqual(vm.project, another_project)
self.assertEqual(vm.shared_to_project, False)
vol = vm.volumes.get(id=volume.id)
self.assertNotEqual(vol.project, another_project)
backend = vm.backend
backend.public = False
backend.save()
with mocked_quotaholder():
self.assertRaises(faults.Forbidden, servers.reassign, vm.id,
original_project, False,
credentials=self.credentials)
self.assertEqual(vm.project, another_project)
self.assertEqual(vm.shared_to_project, False)
vol = vm.volumes.get(id=volume.id)
self.assertNotEqual(vol.project, another_project)
mfactory.ProjectBackendFactory(project=original_project,
backend=backend)
with mocked_quotaholder():
vm = servers.reassign(vm.id, original_project, False,
credentials=self.credentials)
self.assertEqual(vm.project, original_project)
self.assertEqual(vm.shared_to_project, False)
vol = vm.volumes.get(id=volume.id)
self.assertEqual(vol.project, original_project)
示例6: test_reassign_vm
def test_reassign_vm(self, mrapi):
volume = mfactory.VolumeFactory()
vm = volume.machine
another_project = "another_project"
with mocked_quotaholder():
vm = servers.reassign(vm.id, another_project, False,
credentials=self.credentials)
self.assertEqual(vm.project, another_project)
self.assertEqual(vm.shared_to_project, False)
vol = vm.volumes.get(id=volume.id)
self.assertNotEqual(vol.project, another_project)
volume = mfactory.VolumeFactory()
volume.index = 0
volume.save()
vm = volume.machine
another_project = "another_project"
with mocked_quotaholder():
vm = servers.reassign(vm.id, another_project, True,
credentials=self.credentials)
self.assertEqual(vm.project, another_project)
self.assertEqual(vm.shared_to_project, True)
vol = vm.volumes.get(id=volume.id)
self.assertEqual(vol.project, another_project)
self.assertEqual(vol.shared_to_project, True)
示例7: test_task_after
def test_task_after(self, mrapi):
return
vm = mfactory.VirtualMachineFactory()
mrapi().StartupInstance.return_value = 1
mrapi().ShutdownInstance.return_value = 2
mrapi().RebootInstance.return_value = 2
with mocked_quotaholder():
vm.task = None
vm.operstate = "STOPPED"
vm.save()
servers.start(vm.id, credentials=self.credentials)
self.assertEqual(vm.task, "START")
self.assertEqual(vm.task_job_id, 1)
with mocked_quotaholder():
vm.task = None
vm.operstate = "STARTED"
vm.save()
servers.stop(vm.id, credentials=self.credentials)
self.assertEqual(vm.task, "STOP")
self.assertEqual(vm.task_job_id, 2)
with mocked_quotaholder():
vm.task = None
vm.save()
servers.reboot(vm.id, credentials=self.credentials)
self.assertEqual(vm.task, "REBOOT")
self.assertEqual(vm.task_job_id, 3)
示例8: test_stale_server
def test_stale_server(self, mrapi):
mrapi.GetInstances = []
vm1 = mfactory.VirtualMachineFactory(backend=self.backend,
deleted=False,
operstate="ERROR")
with mocked_quotaholder():
self.reconciler.reconcile()
vm1 = VirtualMachine.objects.get(id=vm1.id)
self.assertFalse(vm1.deleted)
vm2 = mfactory.VirtualMachineFactory(backend=self.backend,
deleted=False,
action="DESTROY",
operstate="ERROR")
with mocked_quotaholder():
self.reconciler.reconcile()
vm2 = VirtualMachine.objects.get(id=vm2.id)
self.assertTrue(vm2.deleted)
vm3 = mfactory.VirtualMachineFactory(backend=self.backend,
deleted=False,
action="DESTROY",
operstate="ACTIVE")
with mocked_quotaholder():
self.reconciler.reconcile()
vm3 = VirtualMachine.objects.get(id=vm3.id)
self.assertTrue(vm3.deleted)
示例9: test_create
def test_create(self, mrapi):
flavor = mfactory.FlavorFactory()
kwargs = {
"userid": "test",
"name": "test_vm",
"password": "1234",
"flavor": flavor,
"image": {
"id": "foo",
"backend_id": "foo",
"format": "diskdump",
"checksum": "test_checksum",
"metadata": "{}",
},
"networks": [],
"metadata": {"foo": "bar"},
"personality": [],
}
# no backend!
mfactory.BackendFactory(offline=True)
self.assertRaises(faults.ServiceUnavailable, servers.create, **kwargs)
self.assertEqual(models.VirtualMachine.objects.count(), 0)
mfactory.IPv4SubnetFactory(network__public=True)
mfactory.IPv6SubnetFactory(network__public=True)
backend = mfactory.BackendFactory()
# error in nics
req = deepcopy(kwargs)
req["networks"] = [{"uuid": 42}]
self.assertRaises(faults.ItemNotFound, servers.create, **req)
self.assertEqual(models.VirtualMachine.objects.count(), 0)
# error in enqueue. check the vm is deleted and resources released
mrapi().CreateInstance.side_effect = Exception("ganeti is down")
with mocked_quotaholder():
servers.create(**kwargs)
vm = models.VirtualMachine.objects.get()
self.assertFalse(vm.deleted)
self.assertEqual(vm.operstate, "ERROR")
for nic in vm.nics.all():
self.assertEqual(nic.state, "ERROR")
# test ext settings:
req = deepcopy(kwargs)
ext_flavor = mfactory.FlavorFactory(disk_template="ext_archipelago", disk=1)
req["flavor"] = ext_flavor
mrapi().CreateInstance.return_value = 42
backend.disk_templates = ["ext"]
backend.save()
osettings = {"GANETI_DISK_PROVIDER_KWARGS": {"archipelago": {"foo": "mpaz", "lala": "lolo"}}}
with mocked_quotaholder():
with override_settings(settings, **osettings):
vm = servers.create(**req)
name, args, kwargs = mrapi().CreateInstance.mock_calls[-1]
self.assertEqual(
kwargs["disks"][0],
{"provider": "archipelago", "origin": "test_checksum", "foo": "mpaz", "lala": "lolo", "size": 1024},
)
示例10: test_commission
def test_commission(self, mrapi):
vm = mfactory.VirtualMachineFactory(operstate="STOPPED")
# Still pending
vm.serial = mfactory.QuotaHolderSerialFactory(serial=200,
resolved=False,
pending=True)
vm.save()
serial = vm.serial
mrapi().StartupInstance.return_value = 1
with mocked_quotaholder() as m:
with self.assertRaises(quotas.ResolveError):
servers.start(vm.id, credentials=self.credentials)
# Not pending, rejct
vm.task = None
vm.serial = mfactory.QuotaHolderSerialFactory(serial=400,
resolved=False,
pending=False,
accept=False)
vm.save()
serial = vm.serial
mrapi().StartupInstance.return_value = 1
with mocked_quotaholder() as m:
servers.start(vm.id, credentials=self.credentials)
m.resolve_commissions.assert_called_once_with([],
[serial.serial])
self.assertTrue(m.issue_one_commission.called)
# Not pending, accept
vm.task = None
vm.serial = mfactory.QuotaHolderSerialFactory(serial=600,
resolved=False,
pending=False,
accept=True)
vm.save()
serial = vm.serial
mrapi().StartupInstance.return_value = 1
with mocked_quotaholder() as m:
servers.start(vm.id, credentials=self.credentials)
m.resolve_commissions.assert_called_once_with([serial.serial],
[])
self.assertTrue(m.issue_one_commission.called)
mrapi().StartupInstance.side_effect = ValueError
vm.task = None
vm.serial = None
vm.save()
# Test reject if Ganeti erro
with mocked_quotaholder() as m:
try:
servers.start(vm.id, credentials=self.credentials)
except Exception:
(accept, reject), kwargs = m.resolve_commissions.call_args
self.assertEqual(accept, [])
self.assertEqual(len(reject), 1)
self.assertEqual(kwargs, {})
else:
raise AssertionError("Starting a server should raise an"
" exception.")
示例11: test_create_server
def test_create_server(self, mrapi, mimage):
"""Test if the create server call returns the expected response
if a valid request has been speficied."""
mimage.return_value = {'location': 'pithos://foo',
'checksum': '1234',
"id": 1,
"size": "41242",
"name": "test_image",
'disk_format': 'diskdump'}
mrapi().CreateInstance.return_value = 12
flavor = mfactory.FlavorFactory()
# Create public network and backend
network = mfactory.NetworkFactory(public=True)
backend = mfactory.BackendFactory()
mfactory.BackendNetworkFactory(network=network, backend=backend)
request = {
"server": {
"name": "new-server-test",
"userid": "test_user",
"imageRef": 1,
"flavorRef": flavor.id,
"metadata": {
"My Server Name": "Apache1"
},
"personality": []
}
}
with mocked_quotaholder():
response = self.mypost('servers', 'test_user',
json.dumps(request), 'json')
self.assertEqual(response.status_code, 202)
mrapi().CreateInstance.assert_called_once()
api_server = json.loads(response.content)['server']
self.assertEqual(api_server['status'], "BUILD")
self.assertEqual(api_server['progress'], 0)
self.assertEqual(api_server['metadata'],
{"My Server Name": "Apache1"})
self.assertTrue('adminPass' in api_server)
db_vm = VirtualMachine.objects.get(userid='test_user')
self.assertEqual(api_server['name'], db_vm.name)
self.assertEqual(api_server['status'], db_vm.operstate)
# Test drained flag in Network:
network.drained = True
network.save()
with mocked_quotaholder():
response = self.mypost('servers', 'test_user',
json.dumps(request), 'json')
self.assertEqual(response.status_code, 503, "serviceUnavailable")
示例12: test_remove
def test_remove(self, client):
vm = mfactory.VirtualMachineFactory(flavor__cpu=1, flavor__ram=128)
mfactory.VolumeFactory(userid=vm.userid, machine=vm, size=1)
mfactory.VolumeFactory(userid=vm.userid, machine=vm, size=3)
# Also create a NIC
ip = mfactory.IPv4AddressFactory(nic__machine=vm)
nic = ip.nic
nic.network.get_ip_pools()[0].reserve(nic.ipv4_address)
msg = self.create_msg(operation='OP_INSTANCE_REMOVE',
instance=vm.backend_vm_id)
with mocked_quotaholder() as m:
update_db(client, msg)
self.assertTrue(client.basic_ack.called)
db_vm = VirtualMachine.objects.get(id=vm.id)
self.assertEqual(db_vm.operstate, 'DESTROYED')
self.assertTrue(db_vm.deleted)
# Check that nics are deleted
self.assertFalse(db_vm.nics.all())
self.assertTrue(nic.network.get_ip_pools()[0].is_available(ip.address))
# Check that volumes are deleted
self.assertFalse(db_vm.volumes.filter(deleted=False))
# Check quotas
name, args, kwargs = m.mock_calls[0]
for (userid, res), value in args[1].items():
if res == 'cyclades.disk':
self.assertEqual(value, -4 << 30)
elif res == 'cyclades.cpu':
self.assertEqual(value, -1)
elif res == 'cyclades.ram':
self.assertEqual(value, -128 << 20)
vm2 = mfactory.VirtualMachineFactory()
fp1 = mfactory.IPv4AddressFactory(nic__machine=vm2, floating_ip=True,
network__floating_ip_pool=True)
network = fp1.network
nic1 = mfactory.NetworkInterfaceFactory(machine=vm2)
fp1.nic = nic1
fp1.save()
pool = network.get_ip_pools()[0]
pool.reserve(fp1.address)
pool.save()
msg = self.create_msg(operation='OP_INSTANCE_REMOVE',
instance=vm2.backend_vm_id)
with mocked_quotaholder():
update_db(client, msg)
client.basic_ack.assert_called_once()
db_vm = VirtualMachine.objects.get(id=vm.id)
self.assertEqual(db_vm.operstate, 'DESTROYED')
self.assertTrue(db_vm.deleted)
self.assertEqual(IPAddress.objects.get(id=fp1.id).nic, None)
pool = network.get_ip_pools()[0]
# Test that floating ips are not released
self.assertFalse(pool.is_available(fp1.address))
示例13: test_pending_task
def test_pending_task(self, mrapi):
vm = mfactory.VirtualMachineFactory(task="REBOOT", task_job_id=1)
self.assertRaises(faults.BadRequest, servers.start, vm)
vm = mfactory.VirtualMachineFactory(task="BUILD", task_job_id=1)
self.assertRaises(faults.BuildInProgress, servers.start, vm)
# Assert always succeeds
vm = mfactory.VirtualMachineFactory(task="BUILD", task_job_id=1)
mrapi().DeleteInstance.return_value = 1
with mocked_quotaholder():
servers.destroy(vm)
vm = mfactory.VirtualMachineFactory(task="REBOOT", task_job_id=1)
with mocked_quotaholder():
servers.destroy(vm)
示例14: test_delete
def test_delete(self):
"""Test if the delete action succeeds/fails properly."""
# Create a floating IP and force-attach it to a NIC instance.
vm = mfactory.VirtualMachineFactory()
nic = mfactory.NetworkInterfaceFactory(network=self.network,
machine=vm)
with mocked_quotaholder():
ip = ips.create_floating_ip(
self.credentials, network_id=self.network.id)
ip.nic = nic
ip.save()
# Test 1 - Check if we can delete an IP attached to a VM.
#
# The validate function and the action should both fail with the
# following message.
expected_msg = "IP '{}' is used by server '{}'".format(ip.id, vm.id)
# Verify that the validate function fails in silent mode.
res, msg = ips.validate_ip_action(ip, "DELETE", silent=True)
self.assertFalse(res)
self.assertEqual(msg, expected_msg)
# Verify that the validate function fails in non-silent mode.
with self.assertRaises(faults.Conflict) as cm:
ips.validate_ip_action(ip, "DELETE", silent=False)
self.assertEqual(cm.exception.message, expected_msg)
# Verify that the delete action fails with exception.
with mocked_quotaholder():
with self.assertRaises(faults.Conflict) as cm:
ips.delete_floating_ip(ip.id, self.credentials)
self.assertEqual(cm.exception.message, expected_msg)
# Test 2 - Check if we can delete a free IP.
#
# Force-detach IP from NIC.
ip.nic = None
ip.save()
# Verify that the validate function passes in silent mode.
res, _ = ips.validate_ip_action(ip, "DELETE", silent=True)
self.assertTrue(res)
# Verify that the delete action succeeds.
with mocked_quotaholder():
ips.delete_floating_ip(ip.id, self.credentials)
with self.assertRaises(ObjectDoesNotExist):
IPAddress.objects.get(id=ip.id)
示例15: test_error_opcode
def test_error_opcode(self, rapi, client):
# Mock getting network, because code will lookup if network exists
# in backend
rapi().GetNetwork.return_value = {}
mfactory.MacPrefixPoolTableFactory()
mfactory.BridgePoolTableFactory()
network = mfactory.NetworkFactory()
mfactory.BackendNetworkFactory(network=network,
operstate="ACTIVE")
for state, _ in Network.OPER_STATES:
bn = mfactory.BackendNetworkFactory(operstate="ACTIVE",
network=network)
bn.operstate = state
bn.save()
network = bn.network
network.state = state
network.save()
for opcode, _ in BackendNetwork.BACKEND_OPCODES:
if opcode in ['OP_NETWORK_REMOVE', 'OP_NETWORK_ADD']:
continue
msg = self.create_msg(operation=opcode,
network=bn.network.backend_id,
status='error',
add_reserved_ips=[],
remove_reserved_ips=[],
cluster=bn.backend.clustername)
with mocked_quotaholder():
update_network(client, msg)
self.assertTrue(client.basic_ack.called)
db_bnet = BackendNetwork.objects.get(id=bn.id)
self.assertEqual(bn.operstate, db_bnet.operstate)
self.assertEqual(bn.network.state, db_bnet.network.state)