def test_restore(project, controller, async_run): compute = AsyncioMagicMock() compute.id = "local" controller._computes["local"] = compute response = AsyncioMagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) async_run(project.add_node(compute, "test1", None, node_type="vpcs", properties={"startup_config": "test.cfg"})) snapshot = async_run(project.snapshot(name="test")) # We add a node after the snapshots async_run(project.add_node(compute, "test2", None, node_type="vpcs", properties={"startup_config": "test.cfg"})) # project-files should be reset when reimporting test_file = os.path.join(project.path, "project-files", "test.txt") os.makedirs(os.path.join(project.path, "project-files")) open(test_file, "a+").close() assert os.path.exists(test_file) assert len(project.nodes) == 2 controller._notification = MagicMock() with patch("gns3server.config.Config.get_section_config", return_value={"local": True}): async_run(snapshot.restore()) assert "snapshot.restored" in [c[0][0] for c in controller.notification.project_emit.call_args_list] # project.closed notification should not be send when restoring snapshots assert "project.closed" not in [c[0][0] for c in controller.notification.project_emit.call_args_list] project = controller.get_project(project.id) assert not os.path.exists(test_file) assert len(project.nodes) == 1
def test_export_vm(tmpdir, project, async_run): """ If data is on a remote server export it locally before sending it in the archive. """ compute = MagicMock() compute.id = "vm" compute.list_files = AsyncioMagicMock(return_value=[{"path": "vm-1/dynamips/test"}]) # Fake file that will be download from the vm mock_response = AsyncioMagicMock() mock_response.content = AsyncioBytesIO() async_run(mock_response.content.write(b"HELLO")) mock_response.content.seek(0) compute.download_file = AsyncioMagicMock(return_value=mock_response) project._project_created_on_compute.add(compute) path = project.path os.makedirs(os.path.join(path, "vm-1", "dynamips")) # The .gns3 should be renamed project.gns3 in order to simplify import with open(os.path.join(path, "test.gns3"), 'w+') as f: f.write("{}") with aiozipstream.ZipFile() as z: async_run(export_project(z, project, str(tmpdir))) assert compute.list_files.called async_run(write_file(str(tmpdir / 'zipfile.zip'), z)) with zipfile.ZipFile(str(tmpdir / 'zipfile.zip')) as myzip: with myzip.open("vm-1/dynamips/test") as myfile: content = myfile.read() assert content == b"HELLO"
def test_connectNotificationPing(compute, async_run): """ When we receive a ping from a compute we update the compute memory and CPU usage """ ws_mock = AsyncioMagicMock() call = 0 @asyncio.coroutine def receive(): nonlocal call call += 1 if call == 1: response = MagicMock() response.data = '{"action": "ping", "event": {"cpu_usage_percent": 35.7, "memory_usage_percent": 80.7}}' response.tp = aiohttp.WSMsgType.text return response else: response = MagicMock() response.tp = aiohttp.WSMsgType.closed return response compute._controller._notification = MagicMock() compute._http_session = AsyncioMagicMock(return_value=ws_mock) compute._http_session.ws_connect = AsyncioMagicMock(return_value=ws_mock) ws_mock.receive = receive async_run(compute._connect_notification()) assert not compute._controller.notification.dispatch.called args, _ = compute._controller.notification.emit.call_args_list[0] assert args[0] == "compute.updated" assert args[1]["memory_usage_percent"] == 80.7 assert args[1]["cpu_usage_percent"] == 35.7
def test_connectNotification(compute, async_run): ws_mock = AsyncioMagicMock() call = 0 @asyncio.coroutine def receive(): nonlocal call call += 1 if call == 1: response = MagicMock() response.data = '{"action": "test", "event": {"a": 1}}' response.tp = aiohttp.WSMsgType.text return response else: response = MagicMock() response.tp = aiohttp.WSMsgType.closed return response compute._controller._notification = MagicMock() compute._http_session = AsyncioMagicMock(return_value=ws_mock) compute._http_session.ws_connect = AsyncioMagicMock(return_value=ws_mock) ws_mock.receive = receive async_run(compute._connect_notification()) compute._controller.notification.dispatch.assert_called_with('test', {'a': 1}, compute_id=compute.id) assert compute._connected is False
def test_mac_command(async_run): node = AsyncioMagicMock() node.name = "Test" node.nios = {} node.nios[0] = NIOUDP(55, "127.0.0.1", 56) node.nios[0].name = "Ethernet0" node.nios[1] = NIOUDP(55, "127.0.0.1", 56) node.nios[1].name = "Ethernet1"
def test_list_files(project, async_run, compute): res = [{"path": "test"}] response = AsyncioMagicMock() response.read = AsyncioMagicMock(return_value=json.dumps(res).encode()) response.status = 200 with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: assert async_run(compute.list_files(project)) == res mock.assert_any_call("GET", "https://example.com:84/v2/compute/projects/{}/files".format(project.id), auth=None, chunked=None, data=None, headers={'content-type': 'application/json'}, timeout=120)
def test_compute_httpQueryNotConnectedNonGNS3Server2(compute, async_run): compute._connected = False response = AsyncioMagicMock() response.read = AsyncioMagicMock(return_value=b'{}') response.status = 200 with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: with pytest.raises(aiohttp.web.HTTPConflict): async_run(compute.post("/projects", {"a": "b"})) mock.assert_any_call("GET", "https://example.com:84/v2/compute/capabilities", headers={'content-type': 'application/json'}, data=None, auth=None, chunked=None, timeout=20)
def test_compute_httpQueryNotConnected(compute, controller, async_run): controller._notification = MagicMock() compute._connected = False response = AsyncioMagicMock() response.read = AsyncioMagicMock(return_value=json.dumps({"version": __version__}).encode()) response.status = 200 with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: async_run(compute.post("/projects", {"a": "b"})) mock.assert_any_call("GET", "https://example.com:84/v2/compute/capabilities", headers={'content-type': 'application/json'}, data=None, auth=None, chunked=None, timeout=20) mock.assert_any_call("POST", "https://example.com:84/v2/compute/projects", data=b'{"a": "b"}', headers={'content-type': 'application/json'}, auth=None, chunked=None, timeout=20) assert compute._connected assert compute._capabilities["version"] == __version__ controller.notification.emit.assert_called_with("compute.updated", compute.__json__())
def test_mac_command(async_run): node = AsyncioMagicMock() node.name = "Test" node.nios = {} node.nios[0] = NIOUDP(55, "127.0.0.1", 56, {}) node.nios[0].name = "Ethernet0" node.nios[1] = NIOUDP(55, "127.0.0.1", 56, {}) node.nios[1].name = "Ethernet1" node._hypervisor.send = AsyncioMagicMock(return_value=["0050.7966.6801 1 Ethernet0", "0050.7966.6802 1 Ethernet1"]) console = EthernetSwitchConsole(node) assert async_run(console.mac()) == \ "Port Mac VLAN\n" \ "Ethernet0 00:50:79:66:68:01 1\n" \ "Ethernet1 00:50:79:66:68:02 1\n" node._hypervisor.send.assert_called_with("ethsw show_mac_addr_table Test")
def test_open_auto_start(async_run, controller): project = Project(controller=controller, name="Test", auto_start=True) assert project.status == "opened" async_run(project.close()) project.start_all = AsyncioMagicMock() async_run(project.open()) assert project.start_all.called
def test_deleteComputeProjectOpened(controller, controller_config_path, async_run): """ When you delete a compute the project using it are close """ c = async_run(controller.add_compute(compute_id="test1", connect=False)) c.post = AsyncioMagicMock() assert len(controller.computes) == 1 project1 = async_run(controller.add_project(name="Test1")) async_run(project1.open()) # We simulate that the project use this compute project1._project_created_on_compute.add(c) project2 = async_run(controller.add_project(name="Test2")) async_run(project2.open()) controller._notification = MagicMock() c._connected = True async_run(controller.delete_compute("test1")) assert len(controller.computes) == 0 controller._notification.emit.assert_called_with("compute.deleted", c.__json__()) with open(controller_config_path) as f: data = json.load(f) assert len(data["computes"]) == 0 assert c.connected is False # Project 1 use this compute it should be close before deleting the compute assert project1.status == "closed" assert project2.status == "opened"
async def test_build_command_without_display(vm): vm.manager.get_qemu_version = AsyncioMagicMock(return_value="2.5.0") os.environ["DISPLAY"] = "" with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()): cmd = await vm._build_command() assert "-nographic" in cmd
def test_list_link(http_controller, tmpdir, project, compute, async_run): response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) node1 = async_run(project.add_node(compute, "node1", None, node_type="qemu")) node1._ports = [EthernetPort("E0", 0, 0, 3)] node2 = async_run(project.add_node(compute, "node2", None, node_type="qemu")) node2._ports = [EthernetPort("E0", 0, 2, 4)] filters = { "latency": [10], "frequency_drop": [50] } nodes = [ { "node_id": node1.id, "adapter_number": 0, "port_number": 3 }, { "node_id": node2.id, "adapter_number": 2, "port_number": 4 } ] with asyncio_patch("gns3server.controller.udp_link.UDPLink.create"): response = http_controller.post("/projects/{}/links".format(project.id), { "nodes": nodes, "filters": filters }) response = http_controller.get("/projects/{}/links".format(project.id), example=True) assert response.status == 200 assert len(response.json) == 1 assert response.json[0]["filters"] == filters
def test_compute_httpQueryNotConnectedNonGNS3Server2(compute, async_run): compute._connected = False response = AsyncioMagicMock() response.read = AsyncioMagicMock(return_value=b'{}') response.status = 200 with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: with pytest.raises(aiohttp.web.HTTPConflict): async_run(compute.post("/projects", {"a": "b"})) mock.assert_any_call("GET", "https://example.com:84/v2/compute/capabilities", headers={'content-type': 'application/json'}, data=None, auth=None, chunked=False, timeout=20)
def test_delete_node(async_run, controller): """ For a local server we send the project path """ compute = MagicMock() project = Project(controller=controller, name="Test") controller._notification = MagicMock() response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) node = async_run( project.add_node(compute, "test", None, node_type="vpcs", properties={"startup_config": "test.cfg"})) assert node.id in project._nodes async_run(project.delete_node(node.id)) assert node.id not in project._nodes compute.delete.assert_any_call('/projects/{}/vpcs/nodes/{}'.format( project.id, node.id)) controller.notification.emit.assert_any_call("node.deleted", node.__json__())
async def test_build_command_two_adapters(vm, fake_qemu_binary): vm.manager.get_qemu_version = AsyncioMagicMock(return_value="2.5.0") os.environ["DISPLAY"] = "0:0" vm.adapters = 2 with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()): cmd = await vm._build_command() nio1 = vm._local_udp_tunnels[0][0] nio2 = vm._local_udp_tunnels[1][0] assert cmd == [ fake_qemu_binary, "-name", "test", "-m", "256M", "-smp", "cpus=1", "-boot", "order=c", "-uuid", vm.id, "-serial", "telnet:127.0.0.1:{},server,nowait".format(vm._internal_console_port), "-net", "none", "-device", "e1000,mac={},netdev=gns3-0".format(vm._mac_address), "-netdev", "socket,id=gns3-0,udp=127.0.0.1:{},localaddr=127.0.0.1:{}".format(nio1.rport, nio1.lport), "-device", "e1000,mac={},netdev=gns3-1".format(int_to_macaddress(macaddress_to_int(vm._mac_address) + 1)), "-netdev", "socket,id=gns3-1,udp=127.0.0.1:{},localaddr=127.0.0.1:{}".format(nio2.rport, nio2.lport), "-nographic" ]
async def test_build_command_two_adapters_mac_address(vm): """ Should support multiple base vmac address """ vm.manager.get_qemu_version = AsyncioMagicMock(return_value="2.5.0") vm.adapters = 2 vm.mac_address = "00:00:ab:0e:0f:09" mac_0 = vm._mac_address mac_1 = int_to_macaddress(macaddress_to_int(vm._mac_address) + 1) assert mac_0[:8] == "00:00:ab" with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()): cmd = await vm._build_command() assert "e1000,mac={},netdev=gns3-0".format(mac_0) in cmd assert "e1000,mac={},netdev=gns3-1".format(mac_1) in cmd vm.mac_address = "00:42:ab:0e:0f:0a" mac_0 = vm._mac_address mac_1 = int_to_macaddress(macaddress_to_int(vm._mac_address) + 1) assert mac_0[:8] == "00:42:ab" with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()): cmd = await vm._build_command() assert "e1000,mac={},netdev=gns3-0".format(mac_0) in cmd assert "e1000,mac={},netdev=gns3-1".format(mac_1) in cmd
async def test_build_command_kvm_2_4(linux_platform, vm, fake_qemu_binary): """ Qemu 2.4 introduce an issue with KVM """ vm.manager.get_qemu_version = AsyncioMagicMock(return_value="2.4.2") os.environ["DISPLAY"] = "0:0" with asyncio_patch( "gns3server.compute.qemu.qemu_vm.QemuVM._run_with_hardware_acceleration", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()) as process: cmd = await vm._build_command() nio = vm._local_udp_tunnels[0][0] assert cmd == [ fake_qemu_binary, "-name", "test", "-m", "256M", "-smp", "cpus=1,sockets=1", "-enable-kvm", "-machine", "smm=off", "-boot", "order=c", "-uuid", vm.id, "-serial", "telnet:127.0.0.1:{},server,nowait".format( vm._internal_console_port), "-net", "none", "-device", "e1000,mac={},netdev=gns3-0".format(vm._mac_address), "-netdev", "socket,id=gns3-0,udp=127.0.0.1:{},localaddr=127.0.0.1:{}". format(nio.rport, nio.lport), "-nographic" ]
def test_add_iou_node_and_check_if_gets_application_id(project, async_run): compute = MagicMock() compute.id = "local" response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) # tests if get_next_application_id is called with patch('gns3server.controller.project.get_next_application_id', return_value=222) as mocked_get_app_id: node = async_run( project.add_node(compute, "test", None, node_type="iou", properties={"startup_config": "test.cfg"})) assert mocked_get_app_id.called assert node.properties['application_id'] == 222 # tests if we can send property and it will be used node = async_run( project.add_node(compute, "test", None, node_type="iou", application_id=333, properties={"startup_config": "test.cfg"})) assert mocked_get_app_id.called assert node.properties['application_id'] == 333
def test_add_link(async_run, project, controller): compute = MagicMock() response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) vm1 = async_run( project.add_node(compute, "test1", None, node_type="vpcs", properties={"startup_config": "test.cfg"})) vm1._ports = [EthernetPort("E0", 0, 3, 1)] vm2 = async_run( project.add_node(compute, "test2", None, node_type="vpcs", properties={"startup_config": "test.cfg"})) vm2._ports = [EthernetPort("E0", 0, 4, 2)] controller._notification = MagicMock() link = async_run(project.add_link()) async_run(link.add_node(vm1, 3, 1)) with asyncio_patch("gns3server.controller.udp_link.UDPLink.create" ) as mock_udp_create: async_run(link.add_node(vm2, 4, 2)) assert mock_udp_create.called assert len(link._nodes) == 2 controller.notification.emit.assert_any_call("link.created", link.__json__())
def test_delete_node_delete_link(async_run, controller): """ Delete a node delete all the node connected """ compute = MagicMock() project = Project(controller=controller, name="Test") controller._notification = MagicMock() response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) node = async_run( project.add_node(compute, "test", None, node_type="vpcs", properties={"startup_config": "test.cfg"})) link = async_run(project.add_link()) async_run(link.add_node(node, 0, 0)) async_run(project.delete_node(node.id)) assert node.id not in project._nodes assert link.id not in project._links compute.delete.assert_any_call('/projects/{}/vpcs/nodes/{}'.format( project.id, node.id)) controller.notification.emit.assert_any_call("node.deleted", node.__json__()) controller.notification.emit.assert_any_call("link.deleted", link.__json__())
def test_add_builtin_node_from_template(async_run, controller): """ For a local server we send the project path """ compute = MagicMock() compute.id = "local" project = Project(controller=controller, name="Test") project.emit_notification = MagicMock() template = Template(str(uuid.uuid4()), { "name": "Builtin-switch", "template_type": "ethernet_switch", }, builtin=True) controller.template_manager.templates[template.id] = template template.__json__() controller._computes["local"] = compute response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) node = async_run( project.add_node_from_template(template.id, x=23, y=12, compute_id="local")) compute.post.assert_any_call('/projects', data={ "name": project._name, "project_id": project._id, "path": project._path }) assert compute in project._project_created_on_compute project.emit_notification.assert_any_call("node.created", node.__json__())
def test_query_success(loop, vm): response = MagicMock() response.status = 200 response.headers = {'CONTENT-TYPE': 'application/json'} @asyncio.coroutine def read(): return b'{"c": false}' response.read.side_effect = read vm._session.request = AsyncioMagicMock(return_value=response) data = loop.run_until_complete(asyncio. async (vm.query("POST", "test", data={"a": True}, params={"b": 1}))) vm._session.request.assert_called_with( 'POST', 'http://docker/v1.25/test', data='{"a": true}', headers={'content-type': 'application/json'}, params={'b': 1}, timeout=300) assert data == {"c": False}
async def test_bios_option(vm, tmpdir, fake_qemu_img_binary): vm.manager.get_qemu_version = AsyncioMagicMock(return_value="3.1.0") vm._bios_image = str(tmpdir / "test.img") open(vm._bios_image, "w+").close() options = await vm._build_command() assert ' '.join(['-bios', str(tmpdir / "test.img")]) in ' '.join(options)
def test_add_node_non_local(async_run, controller): """ For a non local server we do not send the project path """ compute = MagicMock() compute.id = "remote" project = Project(controller=controller, name="Test") controller._notification = MagicMock() response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) node = async_run( project.add_node(compute, "test", None, node_type="vpcs", properties={"startup_script": "test.cfg"})) compute.post.assert_any_call('/projects', data={ "name": project._name, "project_id": project._id }) compute.post.assert_any_call('/projects/{}/vpcs/nodes'.format(project.id), data={ 'node_id': node.id, 'startup_script': 'test.cfg', 'name': 'test' }, timeout=1200) assert compute in project._project_created_on_compute controller.notification.emit.assert_any_call("node.created", node.__json__())
def test_update_link(http_controller, tmpdir, project, compute, async_run): response = MagicMock() response.json = {"console": 2048} compute.post = AsyncioMagicMock(return_value=response) node1 = async_run(project.add_node(compute, "node1", None, node_type="qemu")) node1._ports = [EthernetPort("E0", 0, 0, 3)] node2 = async_run(project.add_node(compute, "node2", None, node_type="qemu")) node2._ports = [EthernetPort("E0", 0, 2, 4)] filters = { "latency": [10], "frequency_drop": [50] } with asyncio_patch("gns3server.controller.udp_link.UDPLink.create"): response = http_controller.post("/projects/{}/links".format(project.id), { "nodes": [ { "node_id": node1.id, "adapter_number": 0, "port_number": 3, "label": { "text": "Text", "x": 42, "y": 0 } }, { "node_id": node2.id, "adapter_number": 2, "port_number": 4 } ] }) link_id = response.json["link_id"] assert response.json["nodes"][0]["label"]["x"] == 42 response = http_controller.put("/projects/{}/links/{}".format(project.id, link_id), { "nodes": [ { "node_id": node1.id, "adapter_number": 0, "port_number": 3, "label": { "text": "Hello", "x": 64, "y": 0 } }, { "node_id": node2.id, "adapter_number": 2, "port_number": 4 } ], "filters": filters }, example=True) assert response.status == 201 assert response.json["nodes"][0]["label"]["x"] == 64 assert list(project.links.values())[0].filters == filters
async def test_reload_node(controller_api, project, node, compute): compute.post = AsyncioMagicMock() response = await controller_api.post("/projects/{}/nodes/{}/reload".format( project.id, node.id)) assert response.status == 200 assert response.json == node.__json__()
def dummy_engine(): engine = AsyncioMagicMock() engine.running = False engine.ip_address = "vm.local" engine.protocol = "https" engine.port = 8442 engine.user = "******" engine.password = "******" return engine
def test_compute_httpQueryConflictError(compute, async_run): response = MagicMock() with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: response.status = 409 response.read = AsyncioMagicMock(return_value=b'{"message": "Test"}') with pytest.raises(ComputeConflict): async_run(compute.post("/projects", {"a": "b"}))
def test_update_only_controller(node, controller, compute, project, async_run): """ When updating property used only on controller we don't need to call the compute """ compute.put = AsyncioMagicMock() controller._notification = AsyncioMagicMock() async_run(node.update(x=42)) assert not compute.put.called assert node.x == 42 controller._notification.emit.assert_called_with("node.updated", node.__json__()) # If nothing change a second notif should not be send controller._notification = AsyncioMagicMock() async_run(node.update(x=42)) assert not controller._notification.emit.called
def vm(project, manager, ubridge_path): vm = VPCSVM("test", "00010203-0405-0607-0809-0a0b0c0d0e0f", project, manager) vm._vpcs_version = parse_version("0.9") vm._start_ubridge = AsyncioMagicMock() vm._ubridge_hypervisor = MagicMock() vm._ubridge_hypervisor.is_running.return_value = True return vm
def test_dynamips_idle_pc(node, async_run, compute): node._node_type = "dynamips" response = MagicMock() response.json = {"idlepc": "0x60606f54"} compute.get = AsyncioMagicMock(return_value=response) async_run(node.dynamips_auto_idlepc()) compute.get.assert_called_with("/projects/{}/dynamips/nodes/{}/auto_idlepc".format(node.project.id, node.id), timeout=240)
def test_start(loop, vm, running_subprocess_mock): vm.manager.get_qemu_version = AsyncioMagicMock(return_value="3.1.0") with asyncio_patch("gns3server.compute.qemu.QemuVM.start_wrap_console"): with asyncio_patch("asyncio.create_subprocess_exec", return_value=running_subprocess_mock) as mock: loop.run_until_complete(asyncio.ensure_future(vm.start())) assert vm.is_running() assert vm.command_line == ' '.join(mock.call_args[0])
def test_delete_node(http_controller, tmpdir, project, compute, node): response = MagicMock() compute.post = AsyncioMagicMock() response = http_controller.delete("/projects/{}/nodes/{}".format( project.id, node.id), example=True) assert response.status == 204
def test_reload_all_nodes(http_controller, tmpdir, project, compute): response = MagicMock() compute.post = AsyncioMagicMock() response = http_controller.post("/projects/{}/nodes/reload".format( project.id), example=True) assert response.status == 204
def test_dynamips_idlepc_proposals(node, async_run, compute): node._node_type = "dynamips" response = MagicMock() response.json = ["0x60606f54", "0x30ff6f37"] compute.get = AsyncioMagicMock(return_value=response) async_run(node.dynamips_idlepc_proposals()) compute.get.assert_called_with("/projects/{}/dynamips/nodes/{}/idlepc_proposals".format(node.project.id, node.id), timeout=240)
async def vm(compute_project, manager, ubridge_path): vm = TraceNGVM("test", "00010203-0405-0607-0809-0a0b0c0d0e0f", compute_project, manager) vm._start_ubridge = AsyncioMagicMock() vm._ubridge_hypervisor = MagicMock() vm._ubridge_hypervisor.is_running.return_value = True return vm
def test_reload(node, compute, project, async_run): compute.post = AsyncioMagicMock() async_run(node.reload()) compute.post.assert_called_with("/projects/{}/vpcs/nodes/{}/reload".format( node.project.id, node.id), timeout=240)
def test_interfaces(project, async_run, compute): res = [ { "id": "vmnet99", "ip_address": "172.16.97.1", "mac_address": "00:50:56:c0:00:63", "name": "vmnet99", "netmask": "255.255.255.0", "type": "ethernet" } ] response = AsyncioMagicMock() response.read = AsyncioMagicMock(return_value=json.dumps(res).encode()) response.status = 200 with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: assert async_run(compute.interfaces()) == res mock.assert_any_call("GET", "https://example.com:84/v2/compute/network/interfaces", auth=None, chunked=None, data=None, headers={'content-type': 'application/json'}, timeout=20)
def test_export_images_from_vm(tmpdir, project, async_run): """ If data is on a remote server export it locally before sending it in the archive. """ compute = MagicMock() compute.id = "vm" compute.list_files = AsyncioMagicMock(return_value=[ {"path": "vm-1/dynamips/test"} ]) # Fake file that will be download from the vm mock_response = AsyncioMagicMock() mock_response.content = AsyncioBytesIO() async_run(mock_response.content.write(b"HELLO")) mock_response.content.seek(0) mock_response.status = 200 compute.download_file = AsyncioMagicMock(return_value=mock_response) mock_response = AsyncioMagicMock() mock_response.content = AsyncioBytesIO() async_run(mock_response.content.write(b"IMAGE")) mock_response.content.seek(0) mock_response.status = 200 compute.download_image = AsyncioMagicMock(return_value=mock_response) project._project_created_on_compute.add(compute) path = project.path os.makedirs(os.path.join(path, "vm-1", "dynamips")) topology = { "topology": { "nodes": [ { "compute_id": "vm", "properties": { "image": "test.image" }, "node_type": "dynamips" } ] } } # The .gns3 should be renamed project.gns3 in order to simplify import with open(os.path.join(path, "test.gns3"), 'w+') as f: f.write(json.dumps(topology)) with aiozipstream.ZipFile() as z: async_run(export_project(z, project, str(tmpdir), include_images=True)) assert compute.list_files.called async_run(write_file(str(tmpdir / 'zipfile.zip'), z)) with zipfile.ZipFile(str(tmpdir / 'zipfile.zip')) as myzip: with myzip.open("vm-1/dynamips/test") as myfile: content = myfile.read() assert content == b"HELLO" with myzip.open("images/dynamips/test.image") as myfile: content = myfile.read() assert content == b"IMAGE"
def compute(): s = AsyncioMagicMock() s.id = "http://test.com:42" return s