def test_stop(loop, vm, async_run): process = MagicMock() # Wait process kill success future = asyncio.Future() future.set_result(True) process.wait.return_value = future process.returncode = None vm.ip_address = "192.168.1.1" with NotificationManager.instance().queue() as queue: with patch("sys.platform", return_value="win"): with asyncio_patch("gns3server.compute.traceng.traceng_vm.TraceNGVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process): nio = TraceNG.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1", "filters": {}}) async_run(vm.port_add_nio_binding(0, nio)) vm._ubridge_send = AsyncioMagicMock() async_run(vm.start("192.168.1.2")) assert vm.is_running() with asyncio_patch("gns3server.utils.asyncio.wait_for_process_termination"): loop.run_until_complete(asyncio.ensure_future(vm.stop())) assert vm.is_running() is False process.terminate.assert_called_with() async_run(queue.get(1)) # Ping async_run(queue.get(1)) # Started (action, event, kwargs) = async_run(queue.get(1)) assert action == "node.updated" assert event == vm
def test_reload(loop, vm, async_run): process = MagicMock() # Wait process kill success future = asyncio.Future() future.set_result(True) process.wait.return_value = future process.returncode = None with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process): nio = VPCS.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) async_run(vm.port_add_nio_binding(0, nio)) async_run(vm.start()) assert vm.is_running() with asyncio_patch("gns3server.utils.asyncio.wait_for_process_termination"): async_run(vm.reload()) assert vm.is_running() is True if sys.platform.startswith("win"): process.send_signal.assert_called_with(1) else: process.terminate.assert_called_with()
def test_start(loop, vm, async_run): process = MagicMock() process.returncode = None with NotificationManager.instance().queue() as queue: async_run(queue.get(1)) # Ping vm.ip_address = "192.168.1.1" with patch("sys.platform", return_value="win"): with asyncio_patch("gns3server.compute.traceng.traceng_vm.TraceNGVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec: loop.run_until_complete(asyncio.ensure_future(vm.start("192.168.1.2"))) assert mock_exec.call_args[0] == (vm._traceng_path(), '-u', '-c', ANY, '-v', ANY, '-b', '127.0.0.1', '-s', 'ICMP', '-f', '192.168.1.1', '192.168.1.2') assert vm.is_running() assert vm.command_line == ' '.join(mock_exec.call_args[0]) (action, event, kwargs) = async_run(queue.get(1)) assert action == "node.updated" assert event == vm
def test_start(loop, vm): process = MagicMock() process.returncode = None queue = vm.project.get_listen_queue() with asyncio_patch("gns3server.modules.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec: nio = VPCS.instance().create_nio(vm.vpcs_path, {"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) vm.port_add_nio_binding(0, nio) loop.run_until_complete(asyncio.async(vm.start())) assert mock_exec.call_args[0] == (vm.vpcs_path, '-p', str(vm.console), '-m', '1', '-i', '1', '-F', '-R', '-s', '4242', '-c', '4243', '-t', '127.0.0.1') assert vm.is_running() assert vm.command_line == ' '.join(mock_exec.call_args[0]) (action, event) = queue.get_nowait() assert action == "vm.started" assert event == vm
def test_get_container_state(loop, vm): response = { "State": { "Error": "", "ExitCode": 9, "FinishedAt": "2015-01-06T15:47:32.080254511Z", "OOMKilled": False, "Paused": False, "Pid": 0, "Restarting": False, "Running": True, "StartedAt": "2015-01-06T15:47:32.072697474Z" } } with asyncio_patch("gns3server.modules.docker.Docker.query", return_value=response) as mock: assert loop.run_until_complete(asyncio.async(vm._get_container_state())) == "running" response["State"]["Running"] = False response["State"]["Paused"] = True with asyncio_patch("gns3server.modules.docker.Docker.query", return_value=response) as mock: assert loop.run_until_complete(asyncio.async(vm._get_container_state())) == "paused" response["State"]["Running"] = False response["State"]["Paused"] = False with asyncio_patch("gns3server.modules.docker.Docker.query", return_value=response) as mock: assert loop.run_until_complete(asyncio.async(vm._get_container_state())) == "exited"
def test_look_for_interface(gns3vm, async_run): showvminfo = """ nic1="hostonly" nictype1="82540EM" nicspeed1="0" nic2="nat" nictype2="82540EM" nicspeed2="0" nic3="none" nic4="none" nic5="none" nic6="none" nic7="none" nic8="none" vcpwidth=1024 vcpheight=768 vcprate=512 vcpfps=25 GuestMemoryBalloon=0 """ with asyncio_patch("gns3server.controller.gns3vm.virtualbox_gns3_vm.VirtualBoxGNS3VM._execute", return_value=showvminfo) as mock: res = async_run(gns3vm._look_for_interface("nat")) mock.assert_called_with('showvminfo', ['GNS3 VM', '--machinereadable']) assert res == 2 with asyncio_patch("gns3server.controller.gns3vm.virtualbox_gns3_vm.VirtualBoxGNS3VM._execute", return_value=showvminfo) as mock: res = async_run(gns3vm._look_for_interface("dummy")) assert res == -1
def test_start_unpause(loop, vm, manager, free_console_port): with asyncio_patch("gns3server.modules.docker.DockerVM._get_container_state", return_value="paused"): with asyncio_patch("gns3server.modules.docker.DockerVM.unpause", return_value="paused") as mock: loop.run_until_complete(asyncio.async(vm.start())) assert mock.called assert vm.status == "started"
def test_stop(loop, vm): process = MagicMock() # Wait process kill success future = asyncio.Future() future.set_result(True) process.wait.return_value = future process.returncode = None with asyncio_patch("gns3server.modules.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process): nio = VPCS.instance().create_nio(vm.vpcs_path, {"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) vm.port_add_nio_binding(0, nio) loop.run_until_complete(asyncio.async(vm.start())) assert vm.is_running() queue = vm.project.get_listen_queue() with asyncio_patch("gns3server.utils.asyncio.wait_for_process_termination"): loop.run_until_complete(asyncio.async(vm.stop())) assert vm.is_running() is False if sys.platform.startswith("win"): process.send_signal.assert_called_with(1) else: process.terminate.assert_called_with() (action, event) = queue.get_nowait() assert action == "vm.stopped" assert event == vm
def test_start_0_6_1(loop, vm): """ Version 0.6.1 doesn't have the -R options. It's not require because GNS3 provide a patch for this. """ process = MagicMock() process.returncode = None queue = vm.project.get_listen_queue() vm._vpcs_version = parse_version("0.6.1") with asyncio_patch("gns3server.modules.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec: nio = VPCS.instance().create_nio(vm.vpcs_path, {"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) vm.port_add_nio_binding(0, nio) loop.run_until_complete(asyncio.async(vm.start())) assert mock_exec.call_args[0] == (vm.vpcs_path, '-p', str(vm.console), '-m', '1', '-i', '1', '-F', '-s', '4242', '-c', '4243', '-t', '127.0.0.1') assert vm.is_running() (action, event) = queue.get_nowait() assert action == "vm.started" assert event == vm
def test_reload(loop, vm, async_run): process = MagicMock() # Wait process kill success future = asyncio.Future() future.set_result(True) process.wait.return_value = future process.returncode = None vm.ip_address = "192.168.1.1" with patch("sys.platform", return_value="win"): with asyncio_patch("gns3server.compute.traceng.traceng_vm.TraceNGVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process): nio = TraceNG.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1", "filters": {}}) async_run(vm.port_add_nio_binding(0, nio)) vm._ubridge_send = AsyncioMagicMock() async_run(vm.start("192.168.1.2")) assert vm.is_running() with asyncio_patch("gns3server.utils.asyncio.wait_for_process_termination"): async_run(vm.reload()) assert vm.is_running() is True #if sys.platform.startswith("win"): # process.send_signal.assert_called_with(1) #else: process.terminate.assert_called_with()
def test_stop(loop, vm, async_run): process = MagicMock() # Wait process kill success future = asyncio.Future() future.set_result(True) process.wait.return_value = future process.returncode = None with NotificationManager.instance().queue() as queue: with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process): nio = VPCS.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) async_run(vm.port_add_nio_binding(0, nio)) async_run(vm.start()) assert vm.is_running() with asyncio_patch("gns3server.utils.asyncio.wait_for_process_termination"): loop.run_until_complete(asyncio.async(vm.stop())) assert vm.is_running() is False if sys.platform.startswith("win"): process.send_signal.assert_called_with(1) else: process.terminate.assert_called_with() async_run(queue.get(0)) # Ping async_run(queue.get(0)) # Started (action, event, kwargs) = async_run(queue.get(0)) assert action == "node.updated" assert event == vm
def test_pull_image(loop): class Response: """ Simulate a response splitted in multiple packets """ def __init__(self): self._read = -1 async def read(self, size): self._read += 1 if self._read == 0: return b'{"progress": "0/100",' elif self._read == 1: return '"id": 42}' else: None mock_query = MagicMock() mock_query.content.return_value = Response() with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=DockerHttp404Error("404")): with asyncio_patch("gns3server.compute.docker.Docker.http_query", return_value=mock_query) as mock: images = loop.run_until_complete(asyncio.ensure_future(Docker.instance().pull_image("ubuntu"))) mock.assert_called_with("POST", "images/create", params={"fromImage": "ubuntu"}, timeout=None)
def test_start_0_6_1(loop, vm, async_run): """ Version 0.6.1 doesn't have the -R options. It's not require because GNS3 provide a patch for this. """ process = MagicMock() process.returncode = None vm._vpcs_version = parse_version("0.6.1") with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec: nio = VPCS.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) async_run(vm.port_add_nio_binding(0, nio)) async_run(vm.start()) assert mock_exec.call_args[0] == (vm._vpcs_path(), '-p', str(vm._internal_console_port), '-m', '1', '-i', '1', '-F', '-s', ANY, '-c', ANY, '-t', '127.0.0.1') assert vm.is_running()
def test_start(loop, vm, async_run): process = MagicMock() process.returncode = None with NotificationManager.instance().queue() as queue: async_run(queue.get(0)) # Ping with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process) as mock_exec: with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"): nio = VPCS.instance().create_nio({"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) async_run(vm.port_add_nio_binding(0, nio)) loop.run_until_complete(asyncio.async(vm.start())) assert mock_exec.call_args[0] == (vm._vpcs_path(), '-p', str(vm._internal_console_port), '-m', '1', '-i', '1', '-F', '-R', '-s', ANY, '-c', ANY, '-t', '127.0.0.1') assert vm.is_running() assert vm.command_line == ' '.join(mock_exec.call_args[0]) (action, event, kwargs) = async_run(queue.get(0)) assert action == "node.updated" assert event == vm
def test_stop_paused_container(loop, vm): with asyncio_patch("gns3server.modules.docker.DockerVM._get_container_state", return_value="paused"): with asyncio_patch("gns3server.modules.docker.DockerVM.unpause") as mock_unpause: with asyncio_patch("gns3server.modules.docker.Docker.query") as mock_query: loop.run_until_complete(asyncio.async(vm.stop())) mock_query.assert_called_with("POST", "containers/e90e34656842/stop", params={"t": 5}) assert mock_unpause.called
def test_close(vm, port_manager, loop): with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()): with asyncio_patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_wrap_console"): loop.run_until_complete(asyncio.ensure_future(vm.start())) loop.run_until_complete(asyncio.ensure_future(vm.close())) assert vm.is_running() is False
def test_close(vm, port_manager, loop): vm.ip_address = "192.168.1.1" with patch("sys.platform", return_value="win"): with asyncio_patch("gns3server.compute.traceng.traceng_vm.TraceNGVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()): loop.run_until_complete(asyncio.ensure_future(vm.start("192.168.1.2"))) loop.run_until_complete(asyncio.ensure_future(vm.close())) assert vm.is_running() is False
def mock_ubridge(): """ Avoid all interaction with ubridge """ with asyncio_patch("gns3server.compute.builtin.nodes.nat.Nat._start_ubridge"): with asyncio_patch("gns3server.compute.builtin.nodes.nat.Nat._add_ubridge_connection"): with asyncio_patch("gns3server.compute.builtin.nodes.nat.Nat._delete_ubridge_connection"): yield
def vm(server, project, base_params): with asyncio_patch("gns3server.modules.docker.Docker.list_images", return_value=[{"image": "nginx"}]) as mock_list: with asyncio_patch("gns3server.modules.docker.Docker.query", return_value={"Id": "8bd8153ea8f5"}) as mock: response = server.post("/projects/{project_id}/docker/vms".format(project_id=project.id), base_params) if response.status != 201: print(response.body) assert response.status == 201 return response.json
def vm(http_compute, project, base_params): with asyncio_patch("gns3server.compute.docker.Docker.list_images", return_value=[{"image": "nginx"}]) as mock_list: with asyncio_patch("gns3server.compute.docker.Docker.query", return_value={"Id": "8bd8153ea8f5"}) as mock: with asyncio_patch("gns3server.compute.docker.DockerVM._get_container_state", return_value="exited") as mock: response = http_compute.post("/projects/{project_id}/docker/nodes".format(project_id=project.id), base_params) if response.status != 201: print(response.body) assert response.status == 201 return response.json
def test_close(vm, port_manager, loop): with asyncio_patch("gns3server.modules.iou.iou_vm.IOUVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()): vm.start() port = vm.console loop.run_until_complete(asyncio.async(vm.close())) # Raise an exception if the port is not free port_manager.reserve_tcp_port(port, vm.project) assert vm.is_running() is False
def test_start_vnc(vm, loop): vm.console_resolution = "1280x1024" with patch("shutil.which", return_value="/bin/Xtigervnc"): with asyncio_patch("gns3server.compute.docker.docker_vm.wait_for_file_creation") as mock_wait: with asyncio_patch("asyncio.create_subprocess_exec") as mock_exec: loop.run_until_complete(asyncio.ensure_future(vm._start_vnc())) assert vm._display is not None assert mock_exec.call_args[0] == ("Xtigervnc", "-geometry", vm.console_resolution, "-depth", "16", "-interface", "127.0.0.1", "-rfbport", str(vm.console), "-AlwaysShared", "-SecurityTypes", "None", ":{}".format(vm._display)) mock_wait.assert_called_with("/tmp/.X11-unix/X{}".format(vm._display))
def test_library_check(loop, vm): with asyncio_patch("gns3server.utils.asyncio.subprocess_check_output", return_value="") as mock: loop.run_until_complete(asyncio.async(vm._library_check())) with asyncio_patch("gns3server.utils.asyncio.subprocess_check_output", return_value="libssl => not found") as mock: with pytest.raises(IOUError): loop.run_until_complete(asyncio.async(vm._library_check()))
def test_start(loop, vm): process = MagicMock() process.returncode = None with asyncio_patch("gns3server.modules.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process): nio = VPCS.instance().create_nio(vm.vpcs_path, {"type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1"}) vm.port_add_nio_binding(0, nio) loop.run_until_complete(asyncio.async(vm.start())) assert vm.is_running()
def test_start_vnc(vm, loop): vm.console_resolution = "1280x1024" with patch("shutil.which", return_value="/bin/x"): with asyncio_patch("gns3server.modules.docker.docker_vm.wait_for_file_creation") as mock_wait: with asyncio_patch("asyncio.create_subprocess_exec") as mock_exec: loop.run_until_complete(asyncio.async(vm._start_vnc())) assert vm._display is not None mock_exec.assert_any_call("Xvfb", "-nolisten", "tcp", ":{}".format(vm._display), "-screen", "0", "1280x1024x16") mock_exec.assert_any_call("x11vnc", "-forever", "-nopw", "-shared", "-geometry", "1280x1024", "-display", "WAIT:{}".format(vm._display), "-rfbport", str(vm.console), "-rfbportv6", str(vm.console), "-noncache", "-listen", "127.0.0.1") mock_wait.assert_called_with("/tmp/.X11-unix/X{}".format(vm._display))
def test_fix_permission_not_running(vm, loop): vm._volumes = ["/etc"] vm._get_container_state = AsyncioMagicMock(return_value="stopped") process = MagicMock() with asyncio_patch("gns3server.compute.docker.Docker.query") as mock_start: with asyncio_patch("asyncio.subprocess.create_subprocess_exec", return_value=process) as mock_exec: loop.run_until_complete(vm._fix_permissions()) mock_exec.assert_called_with('docker', 'exec', 'e90e34656842', '/gns3/bin/busybox', 'sh', '-c', '(/gns3/bin/busybox find "/etc" -depth -print0 | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c \'%a:%u:%g:%n\' > "/etc/.gns3_perms") && /gns3/bin/busybox chmod -R u+rX "/etc" && /gns3/bin/busybox chown {}:{} -R "/etc"'.format(os.getuid(), os.getgid())) assert mock_start.called assert process.wait.called
def test_create_with_extra_volumes_duplicate_4_backslash(loop, project, manager): response = { "Id": "e90e34656806", "Warnings": [], } with asyncio_patch("gns3server.compute.docker.Docker.list_images", return_value=[{"image": "ubuntu"}]) as mock_list_images: with asyncio_patch("gns3server.compute.docker.Docker.query", return_value=response) as mock: vm = DockerVM("test", str(uuid.uuid4()), project, manager, "ubuntu:latest", extra_volumes=["/vol//", "/vol"]) with pytest.raises(DockerError): loop.run_until_complete(asyncio.ensure_future(vm.create()))
def test_nat_delete_nio(http_compute, vm): with asyncio_patch("gns3server.compute.builtin.nodes.nat.Nat.add_nio"): http_compute.post("/projects/{project_id}/nat/nodes/{node_id}/adapters/0/ports/0/nio".format(project_id=vm["project_id"], node_id=vm["node_id"]), {"type": "nio_udp", "lport": 4242, "rport": 4343, "rhost": "127.0.0.1"}) with asyncio_patch("gns3server.compute.builtin.nodes.nat.Nat.remove_nio") as mock_remove_nio: response = http_compute.delete("/projects/{project_id}/nat/nodes/{node_id}/adapters/0/ports/0/nio".format(project_id=vm["project_id"], node_id=vm["node_id"]), example=True) assert mock_remove_nio.called assert response.status == 204 assert response.route == r"/projects/{project_id}/nat/nodes/{node_id}/adapters/{adapter_number:\d+}/ports/{port_number:\d+}/nio"
def test_stop(loop, vm): vm._ubridge_hypervisor = MagicMock() vm._ubridge_hypervisor.is_running.return_value = True vm._fix_permissions = MagicMock() with asyncio_patch("gns3server.modules.docker.DockerVM._get_container_state", return_value="running"): with asyncio_patch("gns3server.modules.docker.Docker.query") as mock_query: loop.run_until_complete(asyncio.async(vm.stop())) mock_query.assert_called_with("POST", "containers/e90e34656842/stop", params={"t": 5}) assert vm._ubridge_hypervisor.stop.called assert vm._fix_permissions.called
def test_start(loop, vm, monkeypatch): mock_process = MagicMock() with patch("gns3server.modules.iou.iou_vm.IOUVM._check_requirements", return_value=True): with asyncio_patch("gns3server.modules.iou.iou_vm.IOUVM._check_iou_licence", return_value=True): with asyncio_patch("gns3server.modules.iou.iou_vm.IOUVM._start_ioucon", return_value=True): with asyncio_patch("gns3server.modules.iou.iou_vm.IOUVM._start_iouyap", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=mock_process): mock_process.returncode = None loop.run_until_complete(asyncio.async(vm.start())) assert vm.is_running()
def test_downloadFile(project, async_run, compute): response = MagicMock() response.status = 200 with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: async_run(compute.download_file(project, "test/titi")) mock.assert_called_with( "GET", "https://example.com:84/v2/compute/projects/{}/files/test/titi".format( project.id), auth=None)
def test_vbox_delete_nio(http_compute, vm): with asyncio_patch('gns3server.compute.virtualbox.virtualbox_vm.VirtualBoxVM.adapter_remove_nio_binding') as mock: response = http_compute.delete("/projects/{project_id}/virtualbox/nodes/{node_id}/adapters/0/ports/0/nio".format(project_id=vm["project_id"], node_id=vm["node_id"]), example=True) assert mock.called args, kwgars = mock.call_args assert args[0] == 0 assert response.status == 204 assert response.route == "/projects/{project_id}/virtualbox/nodes/{node_id}/adapters/{adapter_number:\d+}/ports/{port_number:\d+}/nio"
def test_fix_permission(vm, loop): vm._volumes = ["/etc"] process = MagicMock() with asyncio_patch("asyncio.subprocess.create_subprocess_exec", return_value=process) as mock_exec: loop.run_until_complete(vm._fix_permissions()) mock_exec.assert_called_with( 'docker', 'exec', 'e90e34656842', '/gns3/bin/busybox', 'sh', '-c', '(/gns3/bin/busybox find "/etc" -depth -print0 | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c \'%a:%u:%g:%n\' > "/etc/.gns3_perms") && /gns3/bin/busybox chmod -R u+rX "/etc" && /gns3/bin/busybox chown {}:{} -R "/etc"' .format(os.getuid(), os.getgid())) assert process.wait.called
async def test_qemu_stop_capture(compute_api, vm): with patch("gns3server.compute.qemu.qemu_vm.QemuVM.is_running", return_value=True): with asyncio_patch( "gns3server.compute.qemu.qemu_vm.QemuVM.stop_capture") as mock: response = await compute_api.post( "/projects/{project_id}/qemu/nodes/{node_id}/adapters/0/ports/0/stop_capture" .format(project_id=vm["project_id"], node_id=vm["node_id"])) assert response.status == 204 assert mock.called
async def test_load_project(controller_api, project, config): config.set("Server", "local", "true") with asyncio_patch("gns3server.controller.Controller.load_project", return_value=project) as mock: response = await controller_api.post( "/projects/load".format(project_id=project.id), {"path": "/tmp/test.gns3"}) assert response.status == 201 mock.assert_called_with("/tmp/test.gns3") assert response.json["project_id"] == project.id
def test_get_log(loop, vm): @asyncio.coroutine def read(): return b'Hello\nWorld' mock_query = MagicMock() mock_query.read = read with asyncio_patch("gns3server.compute.docker.Docker.http_query", return_value=mock_query) as mock: images = loop.run_until_complete(asyncio.async(vm._get_log())) mock.assert_called_with("GET", "containers/e90e34656842/logs", params={"stderr": 1, "stdout": 1}, data={})
def test_control_vm(vm, loop): vm._process = MagicMock() reader = MagicMock() writer = MagicMock() with asyncio_patch("asyncio.open_connection", return_value=(reader, writer)) as open_connect: res = loop.run_until_complete( asyncio.ensure_future(vm._control_vm("test"))) assert writer.write.called_with("test") assert res is None
async def test_nat_create(compute_api, compute_project, on_gns3vm): with asyncio_patch( "gns3server.compute.builtin.nodes.nat.Nat._start_ubridge"): response = await compute_api.post( "/projects/{project_id}/nat/nodes".format( project_id=compute_project.id), {"name": "Nat 1"}) assert response.status == 201 assert response.route == "/projects/{project_id}/nat/nodes" assert response.json["name"] == "Nat 1" assert response.json["project_id"] == compute_project.id
async def test_set_process_priority(vm, fake_qemu_img_binary): with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()) as process: vm._process = MagicMock() vm._process.pid = 42 vm._process_priority = "low" await vm._set_process_priority() assert process.called args, kwargs = process.call_args assert args == ("renice", "-n", "5", "-p", "42")
def test_docker_check_connection_docker_preferred_version_against_older( vm, loop): response = { 'ApiVersion': '1.27', } with patch("gns3server.compute.docker.Docker.connector"), \ asyncio_patch("gns3server.compute.docker.Docker.query", return_value=response): vm._connected = False loop.run_until_complete(asyncio.ensure_future(vm._check_connection())) assert vm._api_version == DOCKER_MINIMUM_API_VERSION
def test_close_project_two_client_connected(http_compute, project): ProjectHandler._notifications_listening = {project.id: 2} with asyncio_patch("gns3server.compute.project.Project.close", return_value=True) as mock: response = http_compute.post( "/projects/{project_id}/close".format(project_id=project.id), example=True) assert response.status == 204 assert not mock.called
def test_stop(loop, vm): process = MagicMock() # Wait process kill success future = asyncio.Future() future.set_result(True) process.wait.return_value = future process.returncode = None with asyncio_patch( "gns3server.modules.vpcs.vpcs_vm.VPCSVM._check_requirements", return_value=True): with asyncio_patch("asyncio.create_subprocess_exec", return_value=process): nio = VPCS.instance().create_nio( vm.vpcs_path, { "type": "nio_udp", "lport": 4242, "rport": 4243, "rhost": "127.0.0.1" }) vm.port_add_nio_binding(0, nio) loop.run_until_complete(asyncio. async (vm.start())) assert vm.is_running() queue = vm.project.get_listen_queue() with asyncio_patch( "gns3server.utils.asyncio.wait_for_process_termination"): loop.run_until_complete(asyncio. async (vm.stop())) assert vm.is_running() is False if sys.platform.startswith("win"): process.send_signal.assert_called_with(1) else: process.terminate.assert_called_with() (action, event) = queue.get_nowait() assert action == "vm.stopped" assert event == vm
def test_iou_start_capture(server, vm, tmpdir, project): with patch("gns3server.modules.iou.iou_vm.IOUVM.is_running", return_value=True) as mock: with asyncio_patch("gns3server.modules.iou.iou_vm.IOUVM.start_capture") as start_capture: params = {"capture_file_name": "test.pcap", "data_link_type": "DLT_EN10MB"} response = server.post("/projects/{project_id}/iou/vms/{vm_id}/adapters/0/ports/0/start_capture".format(project_id=vm["project_id"], vm_id=vm["vm_id"]), body=params, example=True) assert response.status == 200 assert start_capture.called assert "test.pcap" in response.json["pcap_file_path"]
def test_create_image_relative_path(loop, tmpdir, fake_qemu_img_binary): options = {"format": "raw", "size": 100} with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()) as process: with patch("gns3server.modules.qemu.Qemu.get_images_directory", return_value=str(tmpdir)): loop.run_until_complete(asyncio. async ( Qemu.instance().create_disk(fake_qemu_img_binary, "hda.qcow2", options))) args, kwargs = process.call_args assert args == (fake_qemu_img_binary, "create", "-f", "raw", str(tmpdir / "hda.qcow2"), "100M")
def test_build_command(vm, loop, fake_qemu_binary, port_manager): os.environ["DISPLAY"] = "0:0" with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()) as process: cmd = loop.run_until_complete(asyncio. async (vm._build_command())) assert cmd == [ fake_qemu_binary, "-name", "test", "-m", "256M", "-smp", "cpus=1", "-boot", "order=c", "-serial", "telnet:127.0.0.1:{},server,nowait".format(vm.console), "-net", "none", "-device", "e1000,mac={}".format(vm._mac_address) ]
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)] with asyncio_patch("gns3server.controller.udp_link.UDPLink.create") as mock: 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 } ] }) assert response.status == 201 assert response.json["nodes"][0]["label"]["x"] == 64
async def test_create_image_exist(tmpdir, fake_qemu_img_binary): open(str(tmpdir / "hda.qcow2"), "w+").close() options = {"format": "raw", "size": 100} with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()) as process: with patch("gns3server.compute.qemu.Qemu.get_images_directory", return_value=str(tmpdir)): with pytest.raises(QemuError): await Qemu.instance().create_disk(fake_qemu_img_binary, "hda.qcow2", options) assert not process.called
def test_import_iou_non_linux(windows_platform, async_run, tmpdir, controller): """ On non linux host IOU should be moved to the GNS3 VM """ project_id = str(uuid.uuid4()) controller._computes["vm"] = AsyncioMagicMock() topology = { "project_id": str(uuid.uuid4()), "name": "test", "type": "topology", "topology": { "nodes": [ { "compute_id": "local", "node_id": "0fd3dd4d-dc93-4a04-a9b9-7396a9e22e8b", "node_type": "iou", "name": "test", "properties": {} }, { "compute_id": "local", "node_type": "vpcs", "name": "test2", "properties": {} } ], "links": [], "computes": [], "drawings": [] }, "revision": 5, "version": "2.0.0" } with open(str(tmpdir / "project.gns3"), 'w+') as f: json.dump(topology, f) zip_path = str(tmpdir / "project.zip") with zipfile.ZipFile(zip_path, 'w') as myzip: myzip.write(str(tmpdir / "project.gns3"), "project.gns3") with open(zip_path, "rb") as f: with asyncio_patch("gns3server.controller.import_project._move_files_to_compute") as mock: project = async_run(import_project(controller, project_id, f)) controller._computes["vm"].post.assert_called_with('/projects', data={'name': 'test', 'project_id': project_id}) with open(os.path.join(project.path, "test.gns3")) as f: topo = json.load(f) assert topo["topology"]["nodes"][0]["compute_id"] == "vm" assert topo["topology"]["nodes"][1]["compute_id"] == "local" mock.assert_called_with(controller._computes["vm"], project_id, project.path, os.path.join('project-files', 'iou', topo["topology"]["nodes"][0]['node_id']))
async def test_enable_l1_keepalives(vm): with asyncio_patch( "gns3server.utils.asyncio.subprocess_check_output", return_value= "***************************************************************\n\n-l Enable Layer 1 keepalive messages\n-u <n> UDP port base for distributed networks\n" ): command = ["test"] await vm._enable_l1_keepalives(command) assert command == ["test", "-l"] with asyncio_patch( "gns3server.utils.asyncio.subprocess_check_output", return_value= "***************************************************************\n\n-u <n> UDP port base for distributed networks\n" ): command = ["test"] with pytest.raises(IOUError): await vm._enable_l1_keepalives(command) assert command == ["test"]
def test_create_environment(loop, project, manager): """ Allow user to pass an environnement. User can't override our internal variables """ response = {"Id": "e90e34656806", "Warnings": []} with asyncio_patch("gns3server.compute.docker.Docker.list_images", return_value=[{ "image": "ubuntu" }]): with asyncio_patch("gns3server.compute.docker.Docker.query", return_value=response) as mock: vm = DockerVM("test", str(uuid.uuid4()), project, manager, "ubuntu") vm.environment = "YES=1\nNO=0\nGNS3_MAX_ETHERNET=eth2" loop.run_until_complete(asyncio. async (vm.create())) assert mock.call_args[1]['data']['Env'] == [ "container=docker", "GNS3_MAX_ETHERNET=eth0", "GNS3_VOLUMES=/etc/network", "YES=1", "NO=0" ]
async def test_cloud_start_capture(compute_api, vm): params = { "capture_file_name": "test.pcap", "data_link_type": "DLT_EN10MB" } with asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud.start_capture") as mock: response = await compute_api.post("/projects/{project_id}/cloud/nodes/{node_id}/adapters/0/ports/0/start_capture".format(project_id=vm["project_id"], node_id=vm["node_id"]), params) assert response.status == 200 assert mock.called assert "test.pcap" in response.json["pcap_file_path"]
async def test_docker_create(compute_api, compute_project, base_params): with asyncio_patch("gns3server.compute.docker.Docker.list_images", return_value=[{ "image": "nginx" }]): with asyncio_patch("gns3server.compute.docker.Docker.query", return_value={"Id": "8bd8153ea8f5"}): response = await compute_api.post( "/projects/{project_id}/docker/nodes".format( project_id=compute_project.id), base_params) assert response.status == 201 assert response.route == "/projects/{project_id}/docker/nodes" assert response.json["name"] == "PC TEST 1" assert response.json["project_id"] == compute_project.id assert response.json["container_id"] == "8bd8153ea8f5" assert response.json["image"] == "nginx:latest" assert response.json["adapters"] == 2 assert response.json["environment"] == "YES=1\nNO=0" assert response.json["console_resolution"] == "1280x1024" assert response.json["extra_hosts"] == "test:127.0.0.1"
def test_close_vnc(loop, vm, port_manager): vm._console_type = "vnc" vm._x11vnc_process = MagicMock() vm._xvfb_process = MagicMock() with asyncio_patch( "gns3server.compute.docker.DockerVM._get_container_state", return_value="stopped"): with asyncio_patch( "gns3server.compute.docker.Docker.query") as mock_query: loop.run_until_complete(asyncio. async (vm.close())) mock_query.assert_called_with("DELETE", "containers/e90e34656842", params={ "force": 1, "v": 1 }) assert vm._closed is True assert vm._xvfb_process.terminate.called
async def test_get_qemu_version(): with asyncio_patch( "gns3server.compute.qemu.subprocess_check_output", return_value= "QEMU emulator version 2.2.0, Copyright (c) 2003-2008 Fabrice Bellard" ): version = await Qemu.get_qemu_version("/tmp/qemu-test") if sys.platform.startswith("win"): assert version == "" else: assert version == "2.2.0"
async def test_update_ubridge_udp_connection(node): filters = {"latency": [10]} snio = NIOUDP(1245, "localhost", 1246) dnio = NIOUDP(1245, "localhost", 1244) dnio.filters = filters with asyncio_patch( "gns3server.compute.base_node.BaseNode._ubridge_apply_filters" ) as mock: await node.update_ubridge_udp_connection('VPCS-10', snio, dnio) mock.assert_called_with("VPCS-10", filters)
async def test_iou_start_capture(compute_api, vm): params = { "capture_file_name": "test.pcap", "data_link_type": "DLT_EN10MB" } with patch("gns3server.compute.iou.iou_vm.IOUVM.is_running", return_value=True): with asyncio_patch("gns3server.compute.iou.iou_vm.IOUVM.start_capture") as mock: response = await compute_api.post("/projects/{project_id}/iou/nodes/{node_id}/adapters/0/ports/0/start_capture".format(project_id=vm["project_id"], node_id=vm["node_id"]), params) assert response.status == 200 assert mock.called assert "test.pcap" in response.json["pcap_file_path"]
def test_start_vm(controller, async_run): """ Start the controller with a GNS3 VM """ controller.gns3vm.settings = { "enable": True, "engine": "vmware", "vmname": "GNS3 VM" } with asyncio_patch( "gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.start" ) as mock: with asyncio_patch("gns3server.controller.gns3vm.GNS3VM._check_network" ) as mock_check_network: with asyncio_patch("gns3server.controller.compute.Compute.connect" ) as mock_connect: async_run(controller.start()) assert mock.called assert "local" in controller.computes assert "vm" in controller.computes assert len(controller.computes) == 2 # Local compute and vm are created
def test_compute_httpQueryAuth(compute, async_run): response = MagicMock() with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: response.status = 200 compute.user = "******" compute.password = "******" async_run(compute.post("/projects", {"a": "b"})) async_run(compute.close()) mock.assert_called_with("POST", "https://example.com:84/v2/compute/projects", data=b'{"a": "b"}', headers={'content-type': 'application/json'}, auth=compute._auth, chunked=None, timeout=20) assert compute._auth.login == "root" assert compute._auth.password == "toor"
async def test_cloud_delete_nio(compute_api, vm): params = {"type": "nio_udp", "lport": 4242, "rport": 4343, "rhost": "127.0.0.1"} await compute_api.post("/projects/{project_id}/cloud/nodes/{node_id}/adapters/0/ports/0/nio".format(project_id=vm["project_id"], node_id=vm["node_id"]), params) with asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud._start_ubridge"): response = await compute_api.delete("/projects/{project_id}/cloud/nodes/{node_id}/adapters/0/ports/0/nio".format(project_id=vm["project_id"], node_id=vm["node_id"])) assert response.status == 204 assert response.route == r"/projects/{project_id}/cloud/nodes/{node_id}/adapters/{adapter_number:\d+}/ports/{port_number:\d+}/nio"
def test_set_process_priority(vm, loop, fake_qemu_img_binary): with asyncio_patch("asyncio.create_subprocess_exec", return_value=MagicMock()) as process: vm._process = MagicMock() vm._process.pid = 42 vm._process_priority = "low" loop.run_until_complete( asyncio.ensure_future(vm._set_process_priority())) assert process.called args, kwargs = process.call_args assert args == ("renice", "-n", "5", "-p", "42")