1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-11-11 12:46:49 +00:00

fix(networks): a network's addresses are read as libvirt writes them, and its changes keep each other

Reviewed with Codex against libvirt's network format and driver.

- Addresses: wvmNetwork found a network's <ip> by its text, so one
  written as <ip .../> or <ip><dhcp>... without whitespace had none,
  and a second address of a family overwrote the first. ip_networks
  reads every <ip> in order, its index being libvirt's parentIndex:
  family (ipv4 when written), address, subnet, DHCP (a <dhcp>, also
  with fixed addresses only), first range and fixed addresses. The
  parentIndex was guessed from the number of families, wrong when IPv6
  comes first; changes now name the address by its index.
- One read: the page read the network's XML once per getter, ten or
  more round trips; it reads it once (a cached_property of the
  request's wvmNetwork). A change starts from the saved definition
  read anew (VIR_NETWORK_XML_INACTIVE), not the running one: two QoS
  changes on a running network no longer undo the first. The XML
  editor shows and changes the saved definition, and defines this
  network only (its name, and its UUID if given), read for that with
  no entity expanded and handed to libvirt as written; an XML declaring
  its encoding is taken. The actions go back to the network's page by
  its own URL.
- Fixed addresses are found by the address they had (a hidden field),
  not by the editable box: changing it and pressing Delete deleted
  another entry or none. A change deletes the entry and adds it anew
  from a copy, keeping what the page does not show (a client id, a
  lease), and puts it back if the add fails: libvirt's own change
  finds an entry by any of its MAC, address or name, so it could
  replace another entry, and never by an IPv6 DUID. The address must
  be of the subnet, not the host's, and neither it, the MAC or DUID
  nor the name another entry's; an entry gone meanwhile is refused,
  not added anew; an unchanged one writes no audit row. They can be
  added while the network is stopped; a running network saved with
  other addresses than it runs with is not changed live, as
  parentIndex would name another <ip> of it.
- An address without a netmask or prefix takes libvirt's (IPv4 its
  class's, IPv6 /64), for its checks and the overlap check.
- The DHCP range must be in the subnet, in order and not take in the
  host's address.
- The create form takes a known mode only ("bogus" made an isolated
  network, a missing one a server error); NAT and routed networks need
  an IPv4 subnet, an isolated one may have none, a bridge or macvtap
  network needs its bridge or interface and gets no addresses; IPv6
  only with its box (whose value was "false", so never); no name or
  subnet of another network of the host. "Fixed Addresses" at create
  goes: it made a random-MAC entry for every address of the range,
  for no real VM.
- Refusals of a fixed address, the DHCP range, the XML and a QoS
  removal are messages, not server errors.
- The IPv6 forwarding of a bridge or macvtap network is the outside
  network's, not ROUTE.
- get_networks_info reads each network's XML once and gives its
  autostart and addresses too. Unused can_pxe, DHCP lease helpers,
  get_uuid and the per-family range and host getters go.
This commit is contained in:
catborise 2026-10-28 20:08:02 +03:00
parent befd1747df
commit 0c9a002ef4
19 changed files with 646 additions and 602 deletions

15
networks/tests/driver.py Normal file
View file

@ -0,0 +1,15 @@
"""libvirt's test driver for the network tests."""
from unittest.mock import patch
import libvirt
def without_inactive_flag(test):
"""The test driver refuses VIR_NETWORK_XML_INACTIVE, which real hosts take:
the saved definition is read as the running one, the same for a network
the test does not change while it runs."""
xml_desc = libvirt.virNetwork.XMLDesc
patcher = patch.object(libvirt.virNetwork, "XMLDesc", lambda net, flags=0: xml_desc(net, 0))
patcher.start()
test.addCleanup(patcher.stop)

View file

@ -1,5 +1,6 @@
"""The create-network form takes real subnets of the right IP version; one
it refuses is a field error, not a server error."""
it refuses is a field error, not a server error. Each mode needs its own
fields, a known mode only, and no subnet of another network of the host."""
from django.test import SimpleTestCase
from networks.forms import AddNetPool
@ -13,8 +14,7 @@ class SubnetTests(SimpleTestCase):
def test_subnets_are_accepted(self):
for subnet in ("192.0.2.0/24", "192.0.2.0/30", "255.255.255.252/30"):
with self.subTest(subnet=subnet):
self.assertTrue(form(subnet=subnet, subnet6="2001:db8::/64").is_valid())
self.assertTrue(form().is_valid()) # both optional
self.assertTrue(form(subnet=subnet, subnet6="2001:db8::/64", enable_ipv6=True).is_valid())
def test_a_subnet_that_is_not_one_is_refused(self):
for field, value in (
@ -35,3 +35,39 @@ class SubnetTests(SimpleTestCase):
):
with self.subTest(field=field, value=value):
self.assertIn(field, form(**{field: value}).errors)
NETWORKS = [{"name": "default", "ips": [{"subnet": __import__("ipaddress").ip_network("192.168.122.0/24")}]}]
def errors(**fields):
f = AddNetPool({"name": "wvc-test-net", **fields}, networks=NETWORKS)
f.is_valid()
return sorted(f.errors)
class ModeTests(SimpleTestCase):
def test_each_mode_needs_its_fields(self):
self.assertEqual(errors(forward="nat"), ["subnet"])
self.assertEqual(errors(forward="route"), ["subnet"])
self.assertEqual(errors(forward="none"), []) # an isolated network may have no address
self.assertEqual(errors(forward="bridge"), ["bridge_name"])
self.assertEqual(errors(forward="macvtap"), ["bridge_name"])
self.assertEqual(errors(forward="none", enable_ipv6=True), ["subnet6"])
self.assertEqual(errors(forward="bogus", subnet="192.0.2.0/24"), ["forward"])
self.assertEqual(errors(subnet="192.0.2.0/24"), ["forward"]) # no mode: an error, not a server error
def test_a_bridge_takes_no_addresses_and_ipv6_needs_its_box(self):
f = AddNetPool({"name": "br", "forward": "bridge", "bridge_name": "br0", "subnet": "192.0.2.0/24", "dhcp4": True})
self.assertTrue(f.is_valid())
self.assertEqual((f.cleaned_data["subnet"], f.cleaned_data["dhcp4"]), ("", False))
f = AddNetPool({"name": "n", "forward": "nat", "subnet": "192.0.2.0/24", "subnet6": "2001:db8::/64"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["subnet6"], "")
def test_a_network_takes_no_name_or_subnet_of_another(self):
self.assertEqual(errors(forward="nat", subnet="192.168.122.128/25"), ["subnet"])
self.assertEqual(errors(forward="nat", subnet="192.168.0.0/16"), ["subnet"])
self.assertEqual(errors(forward="nat", subnet="192.0.2.0/24"), [])
f = AddNetPool({"name": "default", "forward": "none"}, networks=NETWORKS)
self.assertTrue(f.has_error("name", "taken"))

View file

@ -8,6 +8,7 @@ from computes.models import Compute
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from networks.tests.driver import without_inactive_flag
from django.urls import reverse
from logs.models import Logs
@ -34,6 +35,7 @@ class NetworkRowTests(TestCase):
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
patcher.start()
self.addCleanup(patcher.stop)
without_inactive_flag(self)
self.compute = Compute.objects.create(name="c1", hostname="localhost", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("audit-admin", "a@example.com", "pw"))
Logs.objects.all().delete() # the login's row
@ -45,13 +47,13 @@ class NetworkRowTests(TestCase):
def test_network_actions(self):
xml = self.conn.networkLookupByName("lab").XMLDesc(0)
self.post({"stop": ""})
self.post({"modify_dhcp_range": "", "range_start": "192.0.2.30", "range_end": "192.0.2.40", "family": "ipv4"})
self.post({"modify_dhcp_range": "", "range_start": "192.0.2.30", "range_end": "192.0.2.40", "ip_index": "0"})
self.post({"start": ""})
self.post({"set_autostart": ""})
self.post({"unset_autostart": ""})
self.post({"modify_fixed_address": "", "name": "web-1", "address": "192.0.2.31",
"mac": "52:54:00:00:00:31", "family": "ipv4"})
self.post({"delete_fixed_address": "", "address": "192.0.2.31", "family": "ipv4"})
"mac": "52:54:00:00:00:31", "ip_index": "0"})
self.post({"delete_fixed_address": "", "original": "192.0.2.31", "ip_index": "0"})
self.post({"set_qos": "", "qos_direction": "inbound", "qos_average": "100"})
self.post({"unset_qos": "", "qos_direction": "inbound"})
self.post({"edit_network": "", "edit_xml": xml})
@ -59,7 +61,7 @@ class NetworkRowTests(TestCase):
self.post({"delete": ""})
self.assertEqual(rows(), [
("Network lab: stop", True),
("Network lab: set DHCP range IPV4", True),
("Network lab: set DHCP range", True),
("Network lab: start", True),
("Network lab: autostart on", True),
("Network lab: autostart off", True),
@ -94,5 +96,5 @@ class NetworkRowTests(TestCase):
"dhcp4": "on"})
self.client.post(url, {"create": "", "name": "bad name!", "forward": "nat"}) # invalid form
response = self.client.post(url, {"create": "", "name": "lab", "forward": "nat", "subnet": "203.0.113.0/24"})
self.assertIn("Network pool name already in use", [str(m) for m in get_messages(response.wsgi_request)])
self.assertIn("* This host has a network of that name", [str(m) for m in get_messages(response.wsgi_request)])
self.assertEqual(rows(), [("Network audit-net: add", True), ("Network lab: add: name already in use", False)])

View file

@ -1,8 +1,8 @@
"""A network's DHCP range is changed while the network is stopped, and the
page says so only when it was: a running network, a network without a
range or an unknown address family is refused with the reason. Runs on a
private libvirt test driver: "test:///default" is shared by the whole
process."""
range, an address it does not have or a range outside its subnet is
refused with the reason. Runs on a private libvirt test driver:
"test:///default" is shared by the whole process."""
import tempfile
from unittest.mock import patch
@ -12,6 +12,7 @@ from computes.models import Compute
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from networks.tests.driver import without_inactive_flag
from django.urls import reverse
from lxml import etree
@ -34,12 +35,13 @@ class DhcpRangeTests(TestCase):
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
patcher.start()
self.addCleanup(patcher.stop)
without_inactive_flag(self)
self.compute = Compute.objects.create(name="dhcp", hostname="localhost", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("dhcp", "dhcp@example.com", "pw"))
def change(self, network, family="ipv4"):
def change(self, network, index="0", start="192.0.2.30", end="192.0.2.40"):
response = self.client.post(reverse("network", args=[self.compute.id, network]), {
"modify_dhcp_range": "", "range_start": "192.0.2.30", "range_end": "192.0.2.40", "family": family})
"modify_dhcp_range": "", "range_start": start, "range_end": end, "ip_index": index})
return [str(m) for m in get_messages(response.wsgi_request)]
def dhcp_range(self, network):
@ -48,7 +50,7 @@ class DhcpRangeTests(TestCase):
def test_a_stopped_network_gets_the_new_range(self):
self.conn.networkLookupByName("lab").destroy()
self.assertEqual(self.change("lab"), ["IPV4 DHCP Range is Changed."])
self.assertEqual(self.change("lab"), ["The DHCP range is changed"])
self.assertEqual(self.dhcp_range("lab"), ["192.0.2.30", "192.0.2.40"])
def test_a_running_network_is_refused(self):
@ -59,6 +61,14 @@ class DhcpRangeTests(TestCase):
def test_a_network_without_a_range_or_an_unknown_family_is_refused(self):
self.conn.networkLookupByName("lab").destroy()
self.conn.networkLookupByName("plain").destroy()
self.assertEqual(self.change("plain"), ["Network plain has no ipv4 DHCP range"])
self.assertEqual(self.change("lab", family="ipx"), ["Network lab has no ipx DHCP range"])
self.assertEqual(self.change("plain")[-1], "This address of network plain has no DHCP range")
self.assertEqual(self.change("lab", index="1")[-1], "Network lab has no such address")
self.assertEqual(self.change("lab", index="x")[-1], "Network lab has no such address")
self.assertEqual(self.dhcp_range("lab"), ["192.0.2.10", "192.0.2.20"])
def test_a_range_outside_the_subnet_or_backwards_is_refused(self):
self.conn.networkLookupByName("lab").destroy()
self.assertEqual(self.change("lab", end="198.51.100.9")[-1], "The range end 198.51.100.9 is not in 192.0.2.0/24")
self.assertEqual(self.change("lab", start="192.0.2.1")[-1], "192.0.2.1 is the host's own address on the network")
self.assertEqual(self.change("lab", start="192.0.2.50")[-1], "The range starts at 192.0.2.50, after its end 192.0.2.40")
self.assertEqual(self.dhcp_range("lab"), ["192.0.2.10", "192.0.2.20"])

View file

@ -1,57 +1,183 @@
"""A new network with fixed addresses gets one per address of its DHCP range,
for any /24 or smaller subnet; a network that does not start is not left
defined; fixed addresses change on a stopped network and may have no MAC."""
"""A network's addresses are read from its XML however libvirt writes it,
each <ip> by its own index; a change starts from the saved definition, so
two in a row keep each other; a fixed address is found by the address it
had and checked against its subnet; the XML editor defines only this
network; a network that does not start is not left defined. Runs on a
private libvirt test driver: "test:///default" is shared by the whole
process."""
from unittest.mock import patch
import tempfile
from unittest.mock import MagicMock, patch
import libvirt
from django.test import SimpleTestCase
from libvirt import VIR_NETWORK_UPDATE_AFFECT_CONFIG, VIR_NETWORK_UPDATE_AFFECT_LIVE, libvirtError
from networks.tests.driver import without_inactive_flag
from lxml import etree
from networks.forms import AddNetPool
from vrtManager.network import network_size, wvmNetwork, wvmNetworks
from vrtManager.network import ip_networks, network_size, wvmNetwork, wvmNetworks
from vrtManager.util import OperationError
NET = ("<network><name>n1</name><ip address='192.0.2.1' netmask='255.255.255.0'><dhcp>"
"<range start='192.0.2.2' end='192.0.2.254'/><host name='paul' ip='192.0.2.20'/></dhcp></ip></network>")
NODE = """<node>
<network><name>lab</name><bridge name='virbr9'/>
<ip family='ipv6' address='2001:db8:1::1' prefix='64'/>
<ip family='ipv4' address='192.0.2.1' netmask='255.255.255.0'><dhcp><range start='192.0.2.10' end='192.0.2.20'/>
<host name='paul' ip='192.0.2.30'/><host mac='52:54:00:00:00:31' ip='192.0.2.31'/></dhcp></ip>
</network>
</node>"""
class AddressTests(SimpleTestCase):
def test_an_address_without_a_prefix_takes_libvirts(self):
tree = etree.fromstring("<network><ip address='192.0.2.1'/><ip address='10.1.2.3'/><ip family='ipv6' address='2001:db8::1'/></network>")
self.assertEqual([str(ip["subnet"]) for ip in ip_networks(tree)], ["192.0.2.0/24", "10.0.0.0/8", "2001:db8::/64"])
def test_every_way_libvirt_writes_an_address(self):
compact = "<network><ip address='192.0.2.1' netmask='255.255.255.0'/></network>"
static = ("<network><ip address='192.0.2.1' prefix='24'><dhcp><host mac='52:54:00:00:00:01' ip='192.0.2.5'/>"
"</dhcp></ip><ip family='ipv6' address='2001:db8::1' prefix='64'/></network>")
(ip,) = ip_networks(etree.fromstring(compact))
self.assertEqual((ip["index"], ip["family"], str(ip["subnet"]), ip["dhcp"]), (0, "ipv4", "192.0.2.0/24", False))
v4, v6 = ip_networks(etree.fromstring(static))
# DHCP with fixed addresses only is DHCP too
self.assertEqual((v4["dhcp"], v4["range"], v4["hosts"][0]["ip"]), (True, None, "192.0.2.5"))
self.assertEqual((v6["index"], v6["family"], str(v6["subnet"])), (1, "ipv6", "2001:db8::/64"))
class NetworkChangeTests(SimpleTestCase):
def setUp(self):
patcher = patch("vrtManager.connection.connection_manager.get_connection")
self.wvm = patcher.start().return_value
node = tempfile.NamedTemporaryFile("w", suffix=".xml")
self.addCleanup(node.close)
node.write(NODE)
node.flush()
self.conn = libvirt.open(f"test://{node.name}")
self.addCleanup(self.conn.close)
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
patcher.start()
self.addCleanup(patcher.stop)
without_inactive_flag(self)
def create(self, subnet):
gateway, mask, dhcp = network_size(subnet, True)
wvmNetworks("host", "login", "pw", 1).create_network(
"n1", "nat", True, gateway, mask, dhcp, False, None, None, None, "", False, fixed=True)
return etree.fromstring(self.wvm.networkDefineXML.call_args.args[0])
def network(self):
return wvmNetwork("localhost", "", "", 4, "lab")
def test_fixed_addresses_cover_the_dhcp_range(self):
ip = self.create("192.0.2.128/25").find("ip")
# the gateway is the subnet's first address, not one ending in .1
self.assertEqual((ip.get("address"), ip.get("netmask")), ("192.0.2.129", "255.255.255.128"))
hosts = ip.xpath("dhcp/host/@ip")
self.assertEqual((hosts[0], hosts[-1], len(hosts)), ("192.0.2.130", "192.0.2.254", 125))
def saved(self):
return etree.fromstring(self.conn.networkLookupByName("lab").XMLDesc(libvirt.VIR_NETWORK_XML_INACTIVE))
def test_fixed_addresses_need_a_small_subnet(self):
form = AddNetPool({"name": "n1", "forward": "nat", "subnet": "198.51.0.0/16", "dhcp4": True, "fixed": True})
self.assertIn("fixed", form.errors)
def test_the_page_reads_the_xml_once(self):
net = self.network()
with patch.object(net.net, "XMLDesc", wraps=net.net.XMLDesc) as xml:
net.get_ip_networks(), net.get_network_forward(), net.get_network_mac(), net.get_qos()
net.get_bridge_device()
self.assertEqual(xml.call_count, 1)
def test_the_ipv4_address_after_an_ipv6_one_keeps_its_index(self):
ipv6, ipv4 = self.network().get_ip_networks()
self.assertEqual((ipv6["family"], ipv4["family"], ipv4["index"]), ("ipv6", "ipv4", 1))
self.network().modify_fixed_address(1, "", "web", "192.0.2.40", "52:54:00:00:00:40")
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host[last()]/@ip"), ["192.0.2.40"])
def test_two_changes_in_a_row_keep_each_other(self):
# a running network keeps its running definition until restarted: a
# change made from it would drop the change saved before
net = self.network()
running = net.net.XMLDesc(0)
saved = [running]
net.net = MagicMock(**{"XMLDesc.side_effect": lambda flags=0: saved[0] if flags else running})
with patch.object(self.conn, "networkDefineXML", side_effect=lambda xml: saved.__setitem__(0, xml)):
net.set_qos("inbound", 100, 200, 300)
net.set_qos("outbound", 10, 20, 30)
self.assertEqual(etree.fromstring(saved[0]).xpath("bandwidth/*/@average"), ["100", "10"])
def test_a_fixed_address_is_found_by_the_address_it_had(self):
net = self.network()
# a name-only entry changes too, and the one deleted is the one it was
net.modify_fixed_address(1, "192.0.2.30", "paul", "192.0.2.32", "")
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host/@ip"), ["192.0.2.31", "192.0.2.32"])
net.modify_fixed_address(1, "192.0.2.31", "db", "192.0.2.33", "52:54:00:00:00:31")
net.delete_fixed_address(1, "192.0.2.32")
self.assertEqual([dict(h.attrib) for h in self.saved().xpath("ip[2]/dhcp/host")],
[{"mac": "52:54:00:00:00:31", "name": "db", "ip": "192.0.2.33"}])
with self.assertRaisesRegex(OperationError, "has no fixed address 192.0.2.99"):
net.delete_fixed_address(1, "192.0.2.99")
def test_a_change_keeps_what_the_page_does_not_show_and_touches_no_other_entry(self):
net = self.network()
conn = self.conn.networkLookupByName("lab")
conn.destroy()
saved = conn.XMLDesc(0).replace("<host mac='52:54:00:00:00:31' ip='192.0.2.31'/>",
"<host mac='52:54:00:00:00:31' id='01:02:03:04' ip='192.0.2.31'><lease expiry='1' unit='hours'/></host>")
self.conn.networkDefineXML(saved)
net = self.network()
# the name of another entry is refused before anything changes
with self.assertRaisesRegex(OperationError, "The name paul has another fixed address, 192.0.2.30"):
net.modify_fixed_address(1, "192.0.2.31", "paul", "192.0.2.35", "52:54:00:00:00:31")
with self.assertRaisesRegex(OperationError, "52:54:00:00:00:31 has another fixed address"):
net.modify_fixed_address(1, "192.0.2.30", "paul", "192.0.2.30", "52:54:00:00:00:31")
net.modify_fixed_address(1, "192.0.2.31", "web", "192.0.2.35", "52:54:00:00:00:31")
(host,) = self.saved().xpath("ip[2]/dhcp/host[@ip='192.0.2.35']")
self.assertEqual((host.get("id"), host.xpath("string(lease/@expiry)"), host.get("name")), ("01:02:03:04", "1", "web"))
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host/@ip"), ["192.0.2.30", "192.0.2.35"])
def test_an_ipv6_entry_known_by_its_duid_changes(self):
self.conn.networkDefineXML(
"<network><name>six</name><bridge name='virbr5'/><ip family='ipv6' address='2001:db8:5::1' prefix='64'>"
"<dhcp><host id='00:01:00:01:aa:bb' ip='2001:db8:5::10'/></dhcp></ip></network>")
net = wvmNetwork("localhost", "", "", 4, "six")
net.modify_fixed_address(0, "2001:db8:5::10", "", "2001:db8:5::11", "00:01:00:01:aa:bb")
saved = etree.fromstring(self.conn.networkLookupByName("six").XMLDesc(0))
self.assertEqual([dict(h.attrib) for h in saved.xpath("ip/dhcp/host")], [{"id": "00:01:00:01:aa:bb", "ip": "2001:db8:5::11"}])
def test_an_entry_gone_meanwhile_is_not_added_anew(self):
with self.assertRaisesRegex(OperationError, "is gone meanwhile"):
self.network().modify_fixed_address(1, "192.0.2.99", "x", "192.0.2.40", "")
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host/@ip"), ["192.0.2.30", "192.0.2.31"])
def test_a_running_network_saved_with_other_addresses_is_not_changed_live(self):
# parentIndex would name another <ip> of the running network
net = self.network()
net.net = MagicMock(**{"isActive.return_value": 1, "name.return_value": "lab",
"XMLDesc.side_effect": lambda flags=0: NODE.split("<node>")[1].split("</node>")[0]
if not flags else "<network><name>lab</name><ip address='192.0.2.1' netmask='255.255.255.0'/></network>"})
with self.assertRaisesRegex(OperationError, "runs with other addresses than it has saved"):
net.update(0, 0, "<host/>", 0)
net.net.update.assert_not_called()
def test_the_xml_editor_expands_no_entity(self):
# a file of the panel's host named by an external entity is not read into the check
net = self.network()
xml = ('<!DOCTYPE network [<!ENTITY name SYSTEM "file:///etc/hostname">]>'
"<network><name>&name;</name></network>")
with self.assertRaisesRegex(OperationError, "must define network lab"):
net.edit_network(xml)
def test_the_xml_editor_takes_an_encoding_declaration(self):
self.conn.networkLookupByName("lab").destroy()
net = self.network()
net.edit_network('<?xml version="1.0" encoding="UTF-8"?>\n' + net.config_xml().replace("virbr9", "virbr6"))
self.assertEqual(self.saved().xpath("bridge/@name"), ["virbr6"])
def test_a_fixed_address_is_of_the_subnet_and_its_own(self):
net = self.network()
for address, why in (("198.51.100.5", "is not in 192.0.2.0/24"), ("192.0.2.1", "the host's own address"),
("192.0.2.31", "another entry's fixed address"), ("x", "is not an IP address")):
with self.subTest(address=address), self.assertRaisesRegex(OperationError, why):
net.modify_fixed_address(1, "192.0.2.30", "paul", address, "")
self.assertIs(net.modify_fixed_address(1, "192.0.2.30", "paul", "192.0.2.30", ""), False)
def test_the_xml_editor_defines_this_network_only(self):
self.conn.networkLookupByName("lab").destroy() # its definition read back at once
net = self.network()
xml = net.config_xml()
for other, why in ((xml.replace("<name>lab</name>", "<name>other</name>"), "must define network lab"),
(xml.replace(net.net.UUIDString(), "11111111-2222-3333-4444-555555555555"), "keep the network's UUID"),
("<network>", "not valid")):
with self.subTest(why=why), self.assertRaisesRegex(OperationError, why):
net.edit_network(other)
net.edit_network(xml.replace("virbr9", "virbr7"))
self.assertEqual(self.saved().xpath("bridge/@name"), ["virbr7"])
def test_a_network_that_does_not_start_is_undefined(self):
net = self.wvm.networkDefineXML.return_value
net.create.side_effect = libvirtError("network is already in use by interface virbr0")
with self.assertRaises(libvirtError):
self.create("192.0.2.0/24")
net.undefine.assert_called_once_with()
net.setAutostart.assert_not_called()
def test_a_stopped_network_changes_its_configuration_only(self):
net = self.wvm.networkLookupByName.return_value
net.XMLDesc.return_value = NET
for active, flags in ((False, VIR_NETWORK_UPDATE_AFFECT_CONFIG),
(True, VIR_NETWORK_UPDATE_AFFECT_CONFIG | VIR_NETWORK_UPDATE_AFFECT_LIVE)):
with self.subTest(active=active):
net.isActive.return_value = active
wvmNetwork("host", "login", "pw", 1, "n1").delete_fixed_address("192.0.2.20")
# a host with only a name is named as it is, without an empty MAC
self.assertEqual(net.update.call_args.args[3:], ('<host name="paul" ip="192.0.2.20"/>', flags))
gateway, mask, dhcp = network_size("192.0.2.0/24", True)
with patch.object(libvirt.virNetwork, "create", side_effect=libvirt.libvirtError("in use by virbr0")):
with self.assertRaises(libvirt.libvirtError):
wvmNetworks("localhost", "", "", 4).create_network(
"n1", "nat", True, gateway, mask, dhcp, False, None, None, None, "", False)
self.assertNotIn("n1", self.conn.listDefinedNetworks() + self.conn.listNetworks())

View file

@ -11,6 +11,7 @@ from computes.models import Compute
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from networks.tests.driver import without_inactive_flag
from django.urls import reverse
NODE = """<node>
@ -31,6 +32,7 @@ class NetworkInUseTests(TestCase):
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
patcher.start()
self.addCleanup(patcher.stop)
without_inactive_flag(self)
compute = Compute.objects.create(name="net-use", hostname="localhost", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("net-use", "nu@example.com", "pw"))
self.url = reverse("network", args=[compute.id, "lab"])

View file

@ -9,12 +9,14 @@ from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from django.urls import reverse
from networks.tests.driver import without_inactive_flag
class NetworkQosTests(TestCase):
def test_a_rate_that_is_not_a_whole_number_is_refused(self):
conn = libvirt.open("test:///default")
self.addCleanup(conn.close)
without_inactive_flag(self)
compute = Compute.objects.create(name="qos-test", hostname="localhost", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("qos", "qos@example.com", "pw"))
url = reverse("network", args=[compute.id, "default"])