def test_createDrawing_ellipse(): topology = Topology() shape_data = { "x": 42, "y": 12, "z": 0, "rotation": 0, "drawing_id": str(uuid.uuid4()), "svg": "<svg height=\"105.0\" width=\"158.0\"><ellipse cx=\"79\" cy=\"52\" rx=\"79\" ry=\"53\" style=\"stroke-width:2;stroke:#000000;fill:#ffffff;\" /></svg>", } topology._main_window = MagicMock() topology.createDrawing(shape_data) topology._main_window.uiGraphicsView.createDrawingItem.assert_called_with( "ellipse", 42, 12, 0, rotation=0, svg=shape_data["svg"], drawing_id=shape_data["drawing_id"])
def test_createDrawing_svg(): """ If SVG is more complex we consider it as an image """ topology = Topology() shape_data = { "x": 42, "y": 12, "z": 0, "locked": False, "rotation": 0, "drawing_id": str(uuid.uuid4()), "svg": "<svg height=\"105.0\" width=\"158.0\"><rect><line/></rect></svg>", } topology._main_window = MagicMock() topology.createDrawing(shape_data) topology._main_window.uiGraphicsView.createDrawingItem.assert_called_with( "image", 42, 12, 0, locked=False, rotation=0, svg=shape_data["svg"], drawing_id=shape_data["drawing_id"])
def test_randomize_id(project, tmpdir): project.setTopologyFile(str(tmpdir / "test.gns3")) project_uuid = str(uuid.uuid4()) vm_uuid1 = str(uuid.uuid4()) os.makedirs(str(tmpdir / "project-files" / "vpcs" / vm_uuid1)) open(str(tmpdir / "project-files" / "vpcs" / vm_uuid1 / "test.log"), "w+").close() vm_uuid2 = str(uuid.uuid4()) orig_topology = { "project_id": project_uuid, "topology": { "nodes": [{ "vm_id": vm_uuid1, }, { "vm_id": vm_uuid2 }] } } topology = Topology() topology.project = project top = topology._randomize_id(orig_topology) assert top["project_id"] != project_uuid assert top["topology"]["nodes"][0]["vm_id"] != vm_uuid1 assert not os.path.exists( str(tmpdir / "project-files" / "vpcs" / vm_uuid1 / "test.log")) assert os.path.exists( str(tmpdir / "project-files" / "vpcs" / top["topology"]["nodes"][0]["vm_id"] / "test.log")) assert top["topology"]["nodes"][1]["vm_id"] != vm_uuid2 assert top["topology"]["nodes"][0]["vm_id"] != top["topology"]["nodes"][1][ "vm_id"]
def test_image_in_project(tmpdir): project_dir = tmpdir / "project" / "project-files" os.makedirs(str(project_dir / "images")) project = Project() project.setFilesDir(str(tmpdir / "project")) topology = Topology() topology.project = project with open(str(project_dir / "images" / "1.jpg"), "w+") as f: f.write("AA") image1 = PixmapImageItem(None, "images/1.jpg") topology.addImage(image1) assert image1 in topology._images image2 = PixmapImageItem(None, "images/1.jpg") topology.addImage(image2) assert image1 in topology._images assert image2 in topology._images topology.removeImage(image2) assert os.path.exists(str(project_dir / "images" / "1.jpg")) # If not image use this file delete it topology.removeImage(image1) assert not os.path.exists(str(project_dir / "images" / "1.jpg"))
def test_loadFile(tmpdir): topology = Topology() topo = str(tmpdir / "test" / "test.gns3") os.makedirs(str(tmpdir / "test")) with open(topo, 'w+') as f: f.write( '{"name": "test", "type": "topology", "auto_start": false, "project_id": null, "topology": {}}' ) with patch("gns3.topology.Topology._load") as mock: project = Project() topology.loadFile(topo, project) assert mock.called args, kwargs = mock.call_args assert args[0] == { "name": "test", "auto_start": False, "project_id": None, "topology": {}, "type": "topology" } assert topology._project.filesDir() == str(tmpdir / "test") assert topology._project.name() == "test"
def _computeAutoIdlepcCallback(self, result, error=False, *args, **kwargs): """ Callback for computeAutoIdlepc. :param result: server response :param error: indicates an error (boolean) """ if self._project_created: Topology.instance().deleteProject() self._project_created = False self._router = None elif self._router: self._router.delete() self._router = None if error: QtWidgets.QMessageBox.critical( self, "Idle-PC finder", "Error: {}".format(result["message"])) else: idlepc = result["idlepc"] self.uiIdlepcLineEdit.setText(idlepc) QtWidgets.QMessageBox.information( self, "Idle-PC finder", "Idle-PC value {} has been found suitable for your IOS image". format(idlepc))
def test_randomize_id(project, tmpdir): project.setTopologyFile(str(tmpdir / "test.gns3")) project_uuid = str(uuid.uuid4()) vm_uuid1 = str(uuid.uuid4()) os.makedirs(str(tmpdir / "project-files" / "vpcs" / vm_uuid1)) open(str(tmpdir / "project-files" / "vpcs" / vm_uuid1 / "test.log"), "w+").close() vm_uuid2 = str(uuid.uuid4()) orig_topology = { "project_id": project_uuid, "topology": { "nodes": [ { "vm_id": vm_uuid1, }, { "vm_id": vm_uuid2 } ] } } topology = Topology() topology.project = project top = topology._randomize_id(orig_topology) assert top["project_id"] != project_uuid assert top["topology"]["nodes"][0]["vm_id"] != vm_uuid1 assert not os.path.exists(str(tmpdir / "project-files" / "vpcs" / vm_uuid1 / "test.log")) assert os.path.exists(str(tmpdir / "project-files" / "vpcs" / top["topology"]["nodes"][0]["vm_id"] / "test.log")) assert top["topology"]["nodes"][1]["vm_id"] != vm_uuid2 assert top["topology"]["nodes"][0]["vm_id"] != top["topology"]["nodes"][1]["vm_id"]
def test_dump_http_auth(vpcs_device, project, remote_server): remote_server.setUser("hello") remote_server.setPassword("world") from gns3.modules.vpcs.vpcs_device import VPCSDevice from gns3.modules.vpcs import VPCS vpcs_device = VPCSDevice(VPCS(), remote_server, project) vpcs_device._vpcs_device_id = str(uuid.uuid4()) vpcs_device._settings = {"name": "VPCS 1", "script_file": "", "console": None, "startup_script": None} vpcs_device.setInitialized(True) topology = Topology() topology.project = project topology.addNode(vpcs_device) dump = topology.dump(include_gui_data=False) assert dict(dump) == { "project_id": project.id(), "auto_start": False, "name": project.name(), "version": __version__, "revision": 4, "topology": { "nodes": [ { "description": "VPCS device", "id": vpcs_device.id(), "ports": [ { "id": vpcs_device.ports()[0].id(), "name": "Ethernet0", "port_number": 0, "adapter_number": 0 } ], "properties": { "name": vpcs_device.name() }, "server_id": remote_server.id(), "type": "VPCSDevice", "vm_id": None } ], "servers": [ { "vm": False, "host": "127.0.0.1", "id": remote_server.id(), "local": False, "port": 8001, "protocol": "http", "ram_limit": 0, "user": "******" } ] }, "type": "topology" }
def _idlePCFinderSlot(self): """ Slot for the idle-PC finder. """ if Topology.instance().project() is None: project = Topology.instance().createLoadProject({"project_name": str(uuid.uuid4())}) project.project_updated_signal.connect(self._projectCreatedSlot) else: self._projectCreatedSlot()
def _idlePCFinderSlot(self): """ Slot for the idle-PC finder. """ if Topology.instance().project() is None: project = Topology.instance().createLoadProject( {"project_name": str(uuid.uuid4())}) project.project_updated_signal.connect(self._projectCreatedSlot) else: self._projectCreatedSlot()
def test_topology_node(vpcs_device): topology = Topology() topology.addNode(vpcs_device) assert len(topology.nodes()) == 1 assert topology.getNode(vpcs_device.id()) == vpcs_device topology.removeNode(vpcs_device) assert len(topology.nodes()) == 0
def _projectClosedCallback(self, result, error=False, server=None, **kwargs): # Status 404 could be when someone else already closed the project if error and "status" in result and result["status"] != 404: log.error("Error while closing project {}: {}".format(self._id, result["message"])) else: self.stopListenNotifications() log.debug("Project {} closed".format(self._id)) self._closed = True self.project_closed_signal.emit() Topology.instance().setProject(None)
def test_createDrawing_text(): topology = Topology() shape_data = { "x": 42, "y": 12, "z": 0, "rotation": 0, "drawing_id": str(uuid.uuid4()), "svg": "<svg height=\"105.0\" width=\"158.0\"><text/></svg>", } topology._main_window = MagicMock() topology.createDrawing(shape_data) topology._main_window.uiGraphicsView.createDrawingItem.assert_called_with("text", 42, 12, 0, rotation=0, svg=shape_data["svg"], drawing_id=shape_data["drawing_id"])
def test_createDrawing_ellipse(): topology = Topology() shape_data = { "x": 42, "y": 12, "z": 0, "rotation": 0, "drawing_id": str(uuid.uuid4()), "svg": "<svg height=\"105.0\" width=\"158.0\"><ellipse cx=\"79\" cy=\"52\" rx=\"79\" ry=\"53\" style=\"stroke-width:2;stroke:#000000;fill:#ffffff;\" /></svg>", } topology._main_window = MagicMock() topology.createDrawing(shape_data) topology._main_window.uiGraphicsView.createDrawingItem.assert_called_with("ellipse", 42, 12, 0, rotation=0, svg=shape_data["svg"], drawing_id=shape_data["drawing_id"])
def test_dump_random_id(vpcs_device, project, local_server): topology = Topology() topology.project = project topology.addNode(vpcs_device) fake_uuid = str(uuid.uuid4()) with patch("uuid.uuid4", return_value=fake_uuid): dump = topology.dump(include_gui_data=False, random_id=True) assert dict(dump) == { "project_id": fake_uuid, "auto_start": False, "name": project.name(), "version": __version__, "revision": 4, "topology": { "nodes": [ { "id": vpcs_device.id(), "description": "VPCS device", "ports": [ { "id": vpcs_device.ports()[0].id(), "name": "Ethernet0", "port_number": 0, "adapter_number": 0 } ], "properties": { "name": vpcs_device.name() }, "server_id": local_server.id(), "type": "VPCSDevice", "vm_id": fake_uuid} ], "servers": [ { "host": "127.0.0.1", "id": local_server.id(), "local": True, "port": 8000, "protocol": "http", "ram_limit": 0, "vm": False } ] }, "type": "topology" }
def test_createDrawing_svg(): """ If SVG is more complex we consider it as an image """ topology = Topology() shape_data = { "x": 42, "y": 12, "z": 0, "rotation": 0, "drawing_id": str(uuid.uuid4()), "svg": "<svg height=\"105.0\" width=\"158.0\"><rect><line/></rect></svg>", } topology._main_window = MagicMock() topology.createDrawing(shape_data) topology._main_window.uiGraphicsView.createDrawingItem.assert_called_with("image", 42, 12, 0, rotation=0, svg=shape_data["svg"], drawing_id=shape_data["drawing_id"])
def _event_received(self, result, server=None, **kwargs): log.debug("Event received: %s", result) if result["action"] in ["vm.started", "vm.stopped"]: vm = Topology.instance().getVM(result["event"]["vm_id"]) if vm is not None: if result["action"] == "vm.started": vm.setStatus(Node.started) vm.started_signal.emit() elif result["action"] == "vm.stopped": vm.setStatus(Node.stopped) vm.stopped_signal.emit() elif result["action"] == "log.error": log.error(result["event"]["message"]) print("Error: " + result["event"]["message"]) elif result["action"] == "log.warning": log.warning(result["event"]["message"]) print("Warning: " + result["event"]["message"]) elif result["action"] == "log.info": log.info(result["event"]["message"]) print("Info: " + result["event"]["message"]) elif result["action"] == "ping": # Compatible with 1.4.0 server if "event" in result: server.setSystemUsage(result["event"])
def test_dump(vpcs_device, project, local_server): topology = Topology() topology.project = project topology.addNode(vpcs_device) dump = topology.dump(include_gui_data=False) assert dict(dump) == { "project_id": project.id(), "auto_start": False, "name": project.name(), "version": __version__, "revision": 4, "topology": { "nodes": [ { "description": "VPCS device", "id": vpcs_device.id(), "ports": [ { "id": vpcs_device.ports()[0].id(), "name": "Ethernet0", "port_number": 0, "adapter_number": 0 } ], "properties": { "name": vpcs_device.name() }, "server_id": local_server.id(), "type": "VPCSDevice", "vm_id": None } ], "servers": [ { "vm": False, "host": "127.0.0.1", "id": local_server.id(), "local": True, "port": 8000, "protocol": "http", "ram_limit": 0 } ] }, "type": "topology" }
def _listDrawingsCallback(self, result, error=False, **kwargs): if error: log.error("Error while listing drawings: {}".format(result["message"])) return topo = Topology.instance() for drawing in result: topo.createDrawing(drawing) self.project_loaded_signal.emit()
def _listLinksCallback(self, result, error=False, **kwargs): if error: log.error("Error while listing links: {}".format(result["message"])) return topo = Topology.instance() for link in result: topo.createLink(link) self.get("/drawings", self._listDrawingsCallback)
def _listNodesCallback(self, result, error=False, **kwargs): if error: log.error("Error while listing project: {}".format(result["message"])) return topo = Topology.instance() for node in result: topo.createNode(node) self.get("/links", self._listLinksCallback)
def test_loadFile(tmpdir): topology = Topology() topo = str(tmpdir / "test" / "test.gns3") os.makedirs(str(tmpdir / "test")) with open(topo, 'w+') as f: f.write('{"name": "test"}') with patch("gns3.topology.Topology._load") as mock: project = Project() topology.loadFile(topo, project) assert mock.called args, kwargs = mock.call_args assert args[0] == {"name": "test"} assert topology._project.filesDir() == str(tmpdir / "test") assert topology._project.name() == "test"
def _listDrawingsCallback(self, result, error=False, **kwargs): if error: log.error("Error while listing drawings: {}".format(result.get("message", "unknown"))) return topo = Topology.instance() for drawing in result: topo.createDrawing(drawing) self.project_loaded_signal.emit()
def _listNodesCallback(self, result, error=False, **kwargs): if error: log.error("Error while listing project: {}".format(result.get("message", "unknown"))) return topo = Topology.instance() for node in result: topo.createNode(node) self.get("/links", self._listLinksCallback)
def _listLinksCallback(self, result, error=False, **kwargs): if error: log.error("Error while listing links: {}".format(result.get("message", "unknown"))) return topo = Topology.instance() for link in result: topo.createLink(link) self.get("/drawings", self._listDrawingsCallback)
def _listDrawingsCallback(self, result, error=False, **kwargs): if error: log.error("Error while listing drawings: {}".format( result["message"])) return topo = Topology.instance() for drawing in result: topo.createDrawing(drawing)
def test_loadFile(tmpdir): topology = Topology() topo = str(tmpdir / "test" / "test.gns3") os.makedirs(str(tmpdir / "test")) with open(topo, 'w+') as f: f.write('{"name": "test", "type": "topology", "auto_start": false, "project_id": null, "topology": {}}') with patch("gns3.topology.Topology._load") as mock: project = Project() topology.loadFile(topo, project) assert mock.called args, kwargs = mock.call_args assert args[0] == {"name": "test", "auto_start": False, "project_id": None, "topology": {}, "type": "topology"} assert topology._project.filesDir() == str(tmpdir / "test") assert topology._project.name() == "test"
def test_loadFile(tmpdir): topology = Topology() topo = str(tmpdir / "test" / "test.gns3") os.makedirs(str(tmpdir / "test")) with open(topo, 'w+') as f: f.write('{"name": "test", "resources_type": "local"}') with patch("gns3.topology.Topology._load") as mock: project = Project() topology.loadFile(topo, project) assert mock.called args, kwargs = mock.call_args assert args[0] == {"name": "test", "resources_type": "local"} assert topology._project.filesDir() == str(tmpdir / "test") assert topology._project.name() == "test" assert topology._project.type() == "local"
def _projectCreatedSlot(self, *args): if Topology.instance().project() is None: return try: Topology.instance().project().project_updated_signal.disconnect(self._projectCreatedSlot) self._project_created = True except TypeError: pass # If the slot is not connected (project already created) module = Dynamips.instance() platform = self.uiPlatformComboBox.currentText() ios_image = self.uiIOSImageLineEdit.text() ram = self.uiRamSpinBox.value() router_class = PLATFORM_TO_CLASS[platform] self._router = router_class(module, ComputeManager.instance().getCompute(self._compute_id), Topology.instance().project()) self._router.create(ios_image, ram, name="AUTOIDLEPC") self._router.created_signal.connect(self.createdSlot) self._router.server_error_signal.connect(self.serverErrorSlot) self.uiIdlePCFinderPushButton.setEnabled(False)
def test_createDrawing_text(): topology = Topology() shape_data = { "x": 42, "y": 12, "z": 0, "rotation": 0, "drawing_id": str(uuid.uuid4()), "svg": "<svg height=\"105.0\" width=\"158.0\"><text/></svg>", } topology._main_window = MagicMock() topology.createDrawing(shape_data) topology._main_window.uiGraphicsView.createDrawingItem.assert_called_with( "text", 42, 12, 0, rotation=0, svg=shape_data["svg"], drawing_id=shape_data["drawing_id"])
def _computeAutoIdlepcCallback(self, result, error=False, *args, **kwargs): """ Callback for computeAutoIdlepc. :param result: server response :param error: indicates an error (boolean) """ if self._project_created: Topology.instance().deleteProject() self._project_created = False self._router = None elif self._router: self._router.delete() self._router = None if error: QtWidgets.QMessageBox.critical(self, "Idle-PC finder", "Error: {}".format(result["message"])) else: idlepc = result["idlepc"] self.uiIdlepcLineEdit.setText(idlepc) QtWidgets.QMessageBox.information(self, "Idle-PC finder", "Idle-PC value {} has been found suitable for your IOS image".format(idlepc))
def test_randomize_id(): project_uuid = str(uuid.uuid4()) vm_uuid1 = str(uuid.uuid4()) vm_uuid2 = str(uuid.uuid4()) orig_topology = { "project_id": project_uuid, "topology": { "nodes": [ { "vm_id": vm_uuid1, }, { "vm_id": vm_uuid2 } ] } } topology = Topology() top = topology._randomize_id(orig_topology) assert top["project_id"] != project_uuid assert top["topology"]["nodes"][0]["vm_id"] != vm_uuid1 assert top["topology"]["nodes"][1]["vm_id"] != vm_uuid2 assert top["topology"]["nodes"][0]["vm_id"] != top["topology"]["nodes"][1]["vm_id"]
def _projectCreatedSlot(self, *args): if Topology.instance().project() is None: return try: Topology.instance().project().project_updated_signal.disconnect( self._projectCreatedSlot) self._project_created = True except TypeError: pass # If the slot is not connected (project already created) module = Dynamips.instance() platform = self.uiPlatformComboBox.currentText() ios_image = self.uiIOSImageLineEdit.text() ram = self.uiRamSpinBox.value() router_class = PLATFORM_TO_CLASS[platform] self._router = router_class( module, ComputeManager.instance().getCompute(self._compute_id), Topology.instance().project()) self._router.create(ios_image, ram, name="AUTOIDLEPC") self._router.created_signal.connect(self.createdSlot) self._router.server_error_signal.connect(self.serverErrorSlot) self.uiIdlePCFinderPushButton.setEnabled(False)
def _event_received(self, result, **kwargs): log.debug("Event received: %s", result) if result["action"] in ["vm.started", "vm.stopped"]: vm = Topology.instance().getVM(result["event"]["vm_id"]) if vm is not None: if result["action"] == "vm.started": vm.setStatus(Node.started) vm.started_signal.emit() elif result["action"] == "vm.stopped": vm.setStatus(Node.stopped) vm.stopped_signal.emit() elif result["action"] == "log.error": log.error(result["event"]["message"]) print("Error: " + result["event"]["message"]) elif result["action"] == "log.warning": log.warning(result["event"]["message"]) print("Warning: " + result["event"]["message"])
def test_dump_random_id(vpcs_device, project, local_server): topology = Topology() topology.project = project topology.addNode(vpcs_device) fake_uuid = str(uuid.uuid4()) with patch("uuid.uuid4", return_value=fake_uuid): dump = topology.dump(include_gui_data=False, random_id=True) assert dict(dump) == { "project_id": fake_uuid, "auto_start": False, "name": project.name(), "version": __version__, "revision": 4, "topology": { "nodes": [{ "id": vpcs_device.id(), "description": "VPCS device", "ports": [{ "id": vpcs_device.ports()[0].id(), "name": "Ethernet0", "port_number": 0, "adapter_number": 0 }], "properties": { "name": vpcs_device.name() }, "server_id": local_server.id(), "type": "VPCSDevice", "vm_id": fake_uuid }], "servers": [{ "host": "127.0.0.1", "id": local_server.id(), "local": True, "port": 8000, "protocol": "http", "ram_limit": 0, "vm": False }] }, "type": "topology" }
def test_dump(vpcs_device, project, local_server): topology = Topology() topology.project = project topology.addNode(vpcs_device) dump = topology.dump(include_gui_data=False) assert dict(dump) == { "project_id": project.id(), "auto_start": False, "name": project.name(), "version": __version__, "revision": 4, "topology": { "nodes": [{ "description": "VPCS device", "id": vpcs_device.id(), "ports": [{ "id": vpcs_device.ports()[0].id(), "name": "Ethernet0", "port_number": 0, "adapter_number": 0 }], "properties": { "name": vpcs_device.name() }, "server_id": local_server.id(), "type": "VPCSDevice", "vm_id": None }], "servers": [{ "vm": False, "host": "127.0.0.1", "id": local_server.id(), "local": True, "port": 8000, "protocol": "http", "ram_limit": 0 }] }, "type": "topology" }
def test_image_outside_project(tmpdir): """ By security we do not delete image outside project. This should not append but if someone reuse the image items for something else. """ project_img_dir = tmpdir / "project" / "project-files" / "images" os.makedirs(str(project_img_dir)) project = Project() project.setFilesDir(str(tmpdir / "project")) topology = Topology() topology.project = project with open(str(tmpdir / "1.jpg"), "w+") as f: f.write("AA") image1 = PixmapImageItem(None, str(tmpdir / "1.jpg")) topology.addImage(image1) assert image1 in topology._images topology.removeImage(image1) assert os.path.exists(str(tmpdir / "1.jpg"))
def setUp(self): self.t = Topology.instance()
def _event_received(self, result, *args, **kwargs): # Log only relevant events if result["action"] not in ("ping"): log.debug("Event received from project stream: {}".format(result)) if result["action"] == "node.created": node = Topology.instance().getNodeFromUuid(result["event"]["node_id"]) if node is None: Topology.instance().createNode(result["event"]) elif result["action"] == "node.updated": node = Topology.instance().getNodeFromUuid(result["event"]["node_id"]) if node is not None: node.updateNodeCallback(result["event"]) elif result["action"] == "node.deleted": node = Topology.instance().getNodeFromUuid(result["event"]["node_id"]) if node is not None: node.delete(skip_controller=True) elif result["action"] == "link.created": link = Topology.instance().getLinkFromUuid(result["event"]["link_id"]) if link is None: Topology.instance().createLink(result["event"]) elif result["action"] == "link.updated": link = Topology.instance().getLinkFromUuid(result["event"]["link_id"]) if link is not None: link.updateLinkCallback(result["event"]) elif result["action"] == "link.deleted": link = Topology.instance().getLinkFromUuid(result["event"]["link_id"]) if link is not None: link.deleteLink(skip_controller=True) elif result["action"] == "drawing.created": drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"]) if drawing is None: Topology.instance().createDrawing(result["event"]) elif result["action"] == "drawing.updated": drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"]) if drawing is not None: drawing.updateDrawingCallback(result["event"]) elif result["action"] == "drawing.deleted": drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"]) if drawing is not None: drawing.delete(skip_controller=True) elif result["action"] == "project.closed": Topology.instance().setProject(None) elif result["action"] == "project.updated": self._projectUpdatedCallback(result["event"]) elif result["action"] == "snapshot.restored": Topology.instance().createLoadProject({"project_id": result["event"]["project_id"]}) elif result["action"] == "log.error": log.error(result["event"]["message"]) elif result["action"] == "log.warning": log.warning(result["event"]["message"]) elif result["action"] == "log.info": log.info(result["event"]["message"], extra={"show": True}) elif result["action"] == "ping": pass
def test_load_1_2_topology(project, monkeypatch, main_window, tmpdir): topo = { "auto_start": False, "name": "twovpcs", "topology": { "links": [ { "description": "Link from VPCS 1 port Ethernet0 to VPCS 2 port Ethernet0", "destination_node_id": 2, "destination_port_id": 2, "id": 1, "source_node_id": 1, "source_port_id": 1 } ], "nodes": [ { "description": "VPCS device", "id": 1, "label": { "color": "#000000", "font": "TypeWriter,10,-1,5,75,0,0,0,0,0", "text": "VPCS 1", "x": 10.75, "y": -25.0 }, "ports": [ { "description": "connected to VPCS 2 on port Ethernet0", "id": 1, "link_id": 1, "name": "Ethernet0", "nio": "NIO_UDP", "port_number": 0 } ], "properties": { "console": 4501, "name": "VPCS 1", "script_file": "startup.vpc" }, "server_id": 1, "type": "VPCSDevice", "vpcs_id": 1, "x": -349.5, "y": -206.5 }, { "description": "VPCS device", "id": 2, "label": { "color": "#000000", "font": "TypeWriter,10,-1,5,75,0,0,0,0,0", "text": "VPCS 2", "x": 10.75, "y": -25.0 }, "ports": [ { "description": "connected to VPCS 1 on port Ethernet0", "id": 2, "link_id": 1, "name": "Ethernet0", "nio": "NIO_UDP", "port_number": 0 } ], "properties": { "console": 4502, "name": "VPCS 2", "script_file": "startup.vpc" }, "server_id": 1, "type": "VPCSDevice", "vpcs_id": 2, "x": 69.5, "y": -190.5 } ], "servers": [ { "cloud": False, "host": "127.0.0.1", "id": 1, "local": True, "port": 8000 } ] }, "type": "topology", "version": "1.2.3" } monkeypatch.setattr('gns3.main_window.MainWindow.instance', lambda: main_window) project_call = 0 # We return an uuid for each HTTP post def http_loader(self, method, path, callback, body={}, **kwargs): if path == "/projects": callback({"project_id": uuid.uuid4(), "path": str(tmpdir)}, error=False, server=local_server) project_call += 1 assert project_call < 2 elif path[-14:] == "/notifications": pass else: callback({"vm_id": uuid.uuid4()}) monkeypatch.setattr("gns3.http_client.HTTPClient.createHTTPQuery", http_loader) monkeypatch.setattr("gns3.http_client.HTTPClient.connected", lambda self: True) topology = Topology() topology.project = project topology._project.setName("unsaved") topology._project.setTopologyFile(str(tmpdir)) topology.dump = MagicMock() topology._load(topo) assert topology._project.id() is not None assert len(topology.nodes()) == 2 assert len(topology._node_to_links_mapping) == 2 assert topology.getNode(1).initialized() assert topology.getNode(2).initialized() assert main_window.uiGraphicsView.addLink.called assert main_window.saveProject.called
def test_load_1_2_topology(project, monkeypatch, main_window, tmpdir): topo = { "auto_start": False, "name": "twovpcs", "resources_type": "cloud", "topology": { "links": [{ "description": "Link from VPCS 1 port Ethernet0 to VPCS 2 port Ethernet0", "destination_node_id": 2, "destination_port_id": 2, "id": 1, "source_node_id": 1, "source_port_id": 1 }], "nodes": [{ "description": "VPCS device", "id": 1, "label": { "color": "#000000", "font": "TypeWriter,10,-1,5,75,0,0,0,0,0", "text": "VPCS 1", "x": 10.75, "y": -25.0 }, "ports": [{ "description": "connected to VPCS 2 on port Ethernet0", "id": 1, "link_id": 1, "name": "Ethernet0", "nio": "NIO_UDP", "port_number": 0 }], "properties": { "console": 4501, "name": "VPCS 1", "script_file": "startup.vpc" }, "server_id": 1, "type": "VPCSDevice", "vpcs_id": 1, "x": -349.5, "y": -206.5 }, { "description": "VPCS device", "id": 2, "label": { "color": "#000000", "font": "TypeWriter,10,-1,5,75,0,0,0,0,0", "text": "VPCS 2", "x": 10.75, "y": -25.0 }, "ports": [{ "description": "connected to VPCS 1 on port Ethernet0", "id": 2, "link_id": 1, "name": "Ethernet0", "nio": "NIO_UDP", "port_number": 0 }], "properties": { "console": 4502, "name": "VPCS 2", "script_file": "startup.vpc" }, "server_id": 1, "type": "VPCSDevice", "vpcs_id": 2, "x": 69.5, "y": -190.5 }], "servers": [{ "cloud": False, "host": "127.0.0.1", "id": 1, "local": True, "port": 8000 }] }, "type": "topology", "version": "1.2.3" } monkeypatch.setattr('gns3.main_window.MainWindow.instance', lambda: main_window) # We return an uuid for each HTTP post def http_loader(self, method, path, callback, body={}, **kwargs): if path == "/projects": callback({ "project_id": uuid.uuid4(), "path": str(tmpdir) }, error=False, server=local_server) else: callback({"vm_id": uuid.uuid4()}) monkeypatch.setattr("gns3.http_client.HTTPClient.createHTTPQuery", http_loader) monkeypatch.setattr("gns3.http_client.HTTPClient.connected", lambda self: True) topology = Topology() topology.project = project topology._project.setName("unsaved") topology._project.setTopologyFile(str(tmpdir)) topology.dump = MagicMock() topology._load(topo) assert topology._project.id() is not None assert len(topology.nodes()) == 2 assert len(topology._node_to_links_mapping) == 2 assert topology.getNode(1).initialized() assert topology.getNode(2).initialized() assert main_window.uiGraphicsView.addLink.called assert main_window.saveProject.called
def _event_received(self, result, *args, **kwargs): # Log only relevant events if result["action"] not in ("ping"): log.debug("Event received from project stream: {}".format(result)) if result["action"] == "node.created": node = Topology.instance().getNodeFromUuid( result["event"]["node_id"]) if node is None: Topology.instance().createNode(result["event"]) elif result["action"] == "node.updated": node = Topology.instance().getNodeFromUuid( result["event"]["node_id"]) if node is not None: node.updateNodeCallback(result["event"]) elif result["action"] == "node.deleted": node = Topology.instance().getNodeFromUuid( result["event"]["node_id"]) if node is not None: node.delete(skip_controller=True) elif result["action"] == "link.created": link = Topology.instance().getLinkFromUuid( result["event"]["link_id"]) if link is None: Topology.instance().createLink(result["event"]) elif result["action"] == "link.updated": link = Topology.instance().getLinkFromUuid( result["event"]["link_id"]) if link is not None: link.updateLinkCallback(result["event"]) elif result["action"] == "link.deleted": link = Topology.instance().getLinkFromUuid( result["event"]["link_id"]) if link is not None: link.deleteLink(skip_controller=True) elif result["action"] == "drawing.created": drawing = Topology.instance().getDrawingFromUuid( result["event"]["drawing_id"]) if drawing is None: Topology.instance().createDrawing(result["event"]) elif result["action"] == "drawing.updated": drawing = Topology.instance().getDrawingFromUuid( result["event"]["drawing_id"]) if drawing is not None: drawing.updateDrawingCallback(result["event"]) elif result["action"] == "drawing.deleted": drawing = Topology.instance().getDrawingFromUuid( result["event"]["drawing_id"]) if drawing is not None: drawing.delete(skip_controller=True) elif result["action"] == "project.closed": Topology.instance().setProject(None) elif result["action"] == "project.updated": self._projectUpdatedCallback(result["event"]) elif result["action"] == "snapshot.restored": Topology.instance().restoreSnapshot(result["event"]["project_id"]) elif result["action"] == "log.error": log.error(result["event"]["message"]) elif result["action"] == "log.warning": log.warning(result["event"]["message"]) elif result["action"] == "log.info": log.info(result["event"]["message"], extra={"show": True}) elif result["action"] == "ping": pass
def _event_received(self, result, *args, **kwargs): # Log only relevant events if result["action"] not in ("ping", "compute.updated"): log.debug("Event received: %s", result) if result["action"] == "node.created": node = Topology.instance().getNodeFromUuid( result["event"]["node_id"]) if node is None: Topology.instance().createNode(result["event"]) elif result["action"] == "node.updated": node = Topology.instance().getNodeFromUuid( result["event"]["node_id"]) if node is not None: node.updateNodeCallback(result["event"]) elif result["action"] == "node.deleted": node = Topology.instance().getNodeFromUuid( result["event"]["node_id"]) if node is not None: node.delete(skip_controller=True) elif result["action"] == "link.created": link = Topology.instance().getLinkFromUuid( result["event"]["link_id"]) if link is None: Topology.instance().createLink(result["event"]) elif result["action"] == "link.updated": link = Topology.instance().getLinkFromUuid( result["event"]["link_id"]) if link is not None: link.updateLinkCallback(result["event"]) elif result["action"] == "link.deleted": link = Topology.instance().getLinkFromUuid( result["event"]["link_id"]) if link is not None: link.deleteLink(skip_controller=True) elif result["action"] == "drawing.created": drawing = Topology.instance().getDrawingFromUuid( result["event"]["drawing_id"]) if drawing is None: Topology.instance().createDrawing(result["event"]) elif result["action"] == "drawing.updated": drawing = Topology.instance().getDrawingFromUuid( result["event"]["drawing_id"]) if drawing is not None: drawing.updateDrawingCallback(result["event"]) elif result["action"] == "drawing.deleted": drawing = Topology.instance().getDrawingFromUuid( result["event"]["drawing_id"]) if drawing is not None: drawing.delete(skip_controller=True) elif result["action"] == "project.closed": Topology.instance().setProject(None) elif result["action"] == "project.updated": self._projectUpdatedCallback(result["event"]) elif result["action"] == "snapshot.restored": Topology.instance().createLoadProject( {"project_id": result["event"]["project_id"]}) elif result["action"] == "log.error": log.error(result["event"]["message"]) elif result["action"] == "log.warning": log.warning(result["event"]["message"]) elif result["action"] == "log.info": log.info(result["event"]["message"], extra={"show": True}) elif result["action"] == "compute.created" or result[ "action"] == "compute.updated": cm = ComputeManager.instance() cm.computeDataReceivedCallback(result["event"]) elif result["action"] == "settings.updated": LocalConfig.instance().refreshConfigFromController() ApplianceManager.instance().refresh() elif result["action"] == "ping": pass
def test_dump_http_auth(vpcs_device, project, remote_server): remote_server.setUser("hello") remote_server.setPassword("world") from gns3.modules.vpcs.vpcs_device import VPCSDevice from gns3.modules.vpcs import VPCS vpcs_device = VPCSDevice(VPCS(), remote_server, project) vpcs_device._vpcs_device_id = str(uuid.uuid4()) vpcs_device._settings = { "name": "VPCS 1", "script_file": "", "console": None, "startup_script": None } vpcs_device.setInitialized(True) topology = Topology() topology.project = project topology.addNode(vpcs_device) dump = topology.dump(include_gui_data=False) assert dict(dump) == { "project_id": project.id(), "auto_start": False, "name": project.name(), "version": __version__, "revision": 4, "topology": { "nodes": [{ "description": "VPCS device", "id": vpcs_device.id(), "ports": [{ "id": vpcs_device.ports()[0].id(), "name": "Ethernet0", "port_number": 0, "adapter_number": 0 }], "properties": { "name": vpcs_device.name() }, "server_id": remote_server.id(), "type": "VPCSDevice", "vm_id": None }], "servers": [{ "vm": False, "host": "127.0.0.1", "id": remote_server.id(), "local": False, "port": 8001, "protocol": "http", "ram_limit": 0, "user": "******" }] }, "type": "topology" }
def test_load(project, monkeypatch, main_window, tmpdir): topo = { "project_id": project.id(), "auto_start": False, "name": "twovpcs", "resources_type": "local", "topology": { "links": [ { "description": "Link from VPCS 1 port Ethernet0 to VPCS 2 port Ethernet0", "destination_node_id": 2, "destination_port_id": 2, "id": 1, "source_node_id": 1, "source_port_id": 1 } ], "nodes": [ { "description": "VPCS device", "id": 1, "label": { "color": "#000000", "font": "TypeWriter,10,-1,5,75,0,0,0,0,0", "text": "VPCS 1", "x": 10.75, "y": -25.0 }, "ports": [ { "description": "connected to VPCS 2 on port Ethernet0", "id": 1, "link_id": 1, "name": "Ethernet0", "nio": "NIO_UDP", "port_number": 0, "adapter_number": 0 } ], "properties": { "console": 4501, "name": "VPCS 1", "script_file": "startup.vpc" }, "server_id": 1, "type": "VPCSDevice", "vpcs_id": 1, "vm_id": "2b5476de-6e79-4eb5-b0eb-8c54c7821cb8", "x": -349.5, "y": -206.5 }, { "description": "VPCS device", "id": 2, "label": { "color": "#000000", "font": "TypeWriter,10,-1,5,75,0,0,0,0,0", "text": "VPCS 2", "x": 10.75, "y": -25.0 }, "ports": [ { "description": "connected to VPCS 1 on port Ethernet0", "id": 2, "link_id": 1, "name": "Ethernet0", "nio": "NIO_UDP", "port_number": 0 } ], "properties": { "console": 4502, "name": "VPCS 2", "script_file": "startup.vpc" }, "server_id": 1, "type": "VPCSDevice", "vm_id": "2b5476de-6e79-4eb5-b0eb-8c54c7821cba", "vpcs_id": 2, "x": 69.5, "y": -190.5 } ], "servers": [ { "cloud": False, "host": "127.0.0.1", "id": 1, "local": True, "port": 8000 } ] }, "type": "topology", "version": "1.3.0" } monkeypatch.setattr('gns3.main_window.MainWindow.instance', lambda: main_window) # We return an uuid for each HTTP post def http_loader(self, method, path, callback, body={}, **kwargs): if path == "/projects": callback({"project_id": uuid.uuid4(), "path": str(tmpdir)}) else: callback({"vm_id": uuid.uuid4()}) monkeypatch.setattr("gns3.http_client.HTTPClient.createHTTPQuery", http_loader) monkeypatch.setattr("gns3.http_client.HTTPClient.connected", lambda self: True) topology = Topology() topology.project = project topology._load(topo) assert topology._project.id() == project.id() assert len(topology.nodes()) == 2 assert len(topology._node_to_links_mapping) == 2 assert topology.getNode(1).initialized() assert topology.getNode(2).initialized() assert main_window.uiGraphicsView.addLink.called
def test_topology_init(): Topology()
def _event_received(self, result, *args, **kwargs): # Log only relevant events if result["action"] not in ("ping", "compute.updated"): log.debug("Event received: %s", result) if result["action"] == "node.created": node = Topology.instance().getNodeFromUuid(result["event"]["node_id"]) if node is None: Topology.instance().createNode(result["event"]) elif result["action"] == "node.updated": node = Topology.instance().getNodeFromUuid(result["event"]["node_id"]) if node is not None: node.updateNodeCallback(result["event"]) elif result["action"] == "node.deleted": node = Topology.instance().getNodeFromUuid(result["event"]["node_id"]) if node is not None: node.delete(skip_controller=True) elif result["action"] == "link.created": link = Topology.instance().getLinkFromUuid(result["event"]["link_id"]) if link is None: Topology.instance().createLink(result["event"]) elif result["action"] == "link.updated": link = Topology.instance().getLinkFromUuid(result["event"]["link_id"]) if link is not None: link.updateLinkCallback(result["event"]) elif result["action"] == "link.deleted": link = Topology.instance().getLinkFromUuid(result["event"]["link_id"]) if link is not None: link.deleteLink(skip_controller=True) elif result["action"] == "drawing.created": drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"]) if drawing is None: Topology.instance().createDrawing(result["event"]) elif result["action"] == "drawing.updated": drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"]) if drawing is not None: drawing.updateDrawingCallback(result["event"]) elif result["action"] == "drawing.deleted": drawing = Topology.instance().getDrawingFromUuid(result["event"]["drawing_id"]) if drawing is not None: drawing.delete(skip_controller=True) elif result["action"] == "project.closed": Topology.instance().setProject(None) elif result["action"] == "project.updated": self._projectUpdatedCallback(result["event"]) elif result["action"] == "snapshot.restored": Topology.instance().createLoadProject({"project_id": result["event"]["project_id"]}) elif result["action"] == "log.error": log.error(result["event"]["message"]) elif result["action"] == "log.warning": log.warning(result["event"]["message"]) elif result["action"] == "log.info": log.info(result["event"]["message"], extra={"show": True}) elif result["action"] == "compute.created" or result["action"] == "compute.updated": cm = ComputeManager.instance() cm.computeDataReceivedCallback(result["event"]) elif result["action"] == "settings.updated": LocalConfig.instance().refreshConfigFromController() ApplianceManager.instance().refresh() elif result["action"] == "ping": pass