Fixes tests and some PEP8.

This commit is contained in:
grossmj 2016-05-11 15:19:00 -06:00
parent 483431438a
commit ef7b4ef020
12 changed files with 39 additions and 40 deletions

View File

@ -127,7 +127,7 @@ class Controller:
""" """
return self._computes return self._computes
def getCompute(self, compute_id): def get_compute(self, compute_id):
""" """
Return an compute or raise a 404 Return an compute or raise a 404
""" """
@ -162,7 +162,7 @@ class Controller:
except KeyError: except KeyError:
raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id)) raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id))
def removeProject(self, project): def remove_project(self, project):
del self._projects[project.id] del self._projects[project.id]
@property @property

View File

@ -49,7 +49,7 @@ class Compute:
self._password = None self._password = None
self._connected = False self._connected = False
self._controller = controller self._controller = controller
self._setAuth(user, password) self._set_auth(user, password)
self._session = aiohttp.ClientSession() self._session = aiohttp.ClientSession()
self._version = None self._version = None
@ -61,7 +61,7 @@ class Compute:
def __del__(self): def __del__(self):
self._session.close() self._session.close()
def _setAuth(self, user, password): def _set_auth(self, user, password):
""" """
Set authentication parameters Set authentication parameters
""" """
@ -120,7 +120,7 @@ class Compute:
@user.setter @user.setter
def user(self, value): def user(self, value):
self._setAuth(value, self._password) self._set_auth(value, self._password)
@property @property
def password(self): def password(self):
@ -128,7 +128,7 @@ class Compute:
@user.setter @user.setter
def password(self, value): def password(self, value):
self._setAuth(self._user, value) self._set_auth(self._user, value)
def __json__(self): def __json__(self):
return { return {
@ -141,7 +141,7 @@ class Compute:
} }
@asyncio.coroutine @asyncio.coroutine
def streamFile(self, project, path): def steam_file(self, project, path):
""" """
Read file of a project and stream it Read file of a project and stream it
@ -157,12 +157,12 @@ class Compute:
return response.content return response.content
@asyncio.coroutine @asyncio.coroutine
def httpQuery(self, method, path, data=None): def http_query(self, method, path, data=None):
if not self._connected: if not self._connected:
yield from self._connect() yield from self._connect()
if not self._connected: if not self._connected:
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id)) raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
response = yield from self._runHttpQuery(method, path, data=data) response = yield from self._run_http_query(method, path, data=data)
return response return response
@asyncio.coroutine @asyncio.coroutine
@ -171,7 +171,7 @@ class Compute:
Check if remote server is accessible Check if remote server is accessible
""" """
if not self._connected: if not self._connected:
response = yield from self._runHttpQuery("GET", "/version") response = yield from self._run_http_query("GET", "/version")
if "version" not in response.json: if "version" not in response.json:
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id)) raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
@ -179,12 +179,11 @@ class Compute:
if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]: if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"])) raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))
self._notifications = asyncio.async(self._connectNotification()) self._notifications = asyncio.async(self._connect_notification())
self._connected = True self._connected = True
@asyncio.coroutine @asyncio.coroutine
def _connectNotification(self): def _connect_notification(self):
""" """
Connect to the notification stream Connect to the notification stream
""" """
@ -203,7 +202,7 @@ class Compute:
return "{}://{}:{}/v2/compute{}".format(self._protocol, self._host, self._port, path) return "{}://{}:{}/v2/compute{}".format(self._protocol, self._host, self._port, path)
@asyncio.coroutine @asyncio.coroutine
def _runHttpQuery(self, method, path, data=None): def _run_http_query(self, method, path, data=None):
with aiohttp.Timeout(10): with aiohttp.Timeout(10):
url = self._getUrl(path) url = self._getUrl(path)
headers = {'content-type': 'application/json'} headers = {'content-type': 'application/json'}
@ -237,7 +236,7 @@ class Compute:
if body and len(body): if body and len(body):
try: try:
response.json = json.loads(body) response.json = json.loads(body)
except json.JSONDecodeError: except ValueError:
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id)) raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
if response.json is None: if response.json is None:
response.json = {} response.json = {}
@ -245,18 +244,18 @@ class Compute:
@asyncio.coroutine @asyncio.coroutine
def get(self, path): def get(self, path):
return (yield from self.httpQuery("GET", path)) return (yield from self.http_query("GET", path))
@asyncio.coroutine @asyncio.coroutine
def post(self, path, data={}): def post(self, path, data={}):
response = yield from self.httpQuery("POST", path, data) response = yield from self.http_query("POST", path, data)
return response return response
@asyncio.coroutine @asyncio.coroutine
def put(self, path, data={}): def put(self, path, data={}):
response = yield from self.httpQuery("PUT", path, data) response = yield from self.http_query("PUT", path, data)
return response return response
@asyncio.coroutine @asyncio.coroutine
def delete(self, path): def delete(self, path):
return (yield from self.httpQuery("DELETE", path)) return (yield from self.http_query("DELETE", path))

View File

@ -130,7 +130,7 @@ class Node:
for key, value in response.json.items(): for key, value in response.json.items():
if key == "console": if key == "console":
self._console = value self._console = value
elif key in ["console_type", "name", "node_id", "project_id", "node_directory", "command_line", "status"]: elif key in ["console_type", "name", "node_id", "project_id", "vm_directory", "command_line", "status"]:
pass pass
else: else:
self._properties[key] = value self._properties[key] = value

View File

@ -132,4 +132,4 @@ class UDPLink(Link):
""" """
if self._capture_node: if self._capture_node:
compute = self._capture_node["node"].compute compute = self._capture_node["node"].compute
return compute.streamFile(self._project, "tmp/captures/" + self._capture_file_name) return compute.steam_file(self._project, "tmp/captures/" + self._capture_file_name)

View File

@ -41,7 +41,7 @@ class NodeHandler:
def create(request, response): def create(request, response):
controller = Controller.instance() controller = Controller.instance()
compute = controller.getCompute(request.json.pop("compute_id")) compute = controller.get_compute(request.json.pop("compute_id"))
project = controller.get_project(request.match_info["project_id"]) project = controller.get_project(request.match_info["project_id"])
node = yield from project.add_node(compute, request.json.pop("node_id", None), **request.json) node = yield from project.add_node(compute, request.json.pop("node_id", None), **request.json)
response.set_status(201) response.set_status(201)

View File

@ -112,7 +112,7 @@ class ProjectHandler:
controller = Controller.instance() controller = Controller.instance()
project = controller.get_project(request.match_info["project_id"]) project = controller.get_project(request.match_info["project_id"])
yield from project.close() yield from project.close()
controller.removeProject(project) controller.remove_project(project)
response.set_status(204) response.set_status(204)
@classmethod @classmethod
@ -131,7 +131,7 @@ class ProjectHandler:
controller = Controller.instance() controller = Controller.instance()
project = controller.get_project(request.match_info["project_id"]) project = controller.get_project(request.match_info["project_id"])
yield from project.delete() yield from project.delete()
controller.removeProject(project) controller.remove_project(project)
response.set_status(204) response.set_status(204)
@classmethod @classmethod

View File

@ -516,8 +516,8 @@ VM_OBJECT_SCHEMA = {
"maxLength": 36, "maxLength": 36,
"pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
}, },
"node_directory": { "vm_directory": {
"decription": "Path to the node working directory", "decription": "Path to the vm working directory",
"type": "string" "type": "string"
}, },
"project_id": { "project_id": {

View File

@ -123,7 +123,7 @@ def test_json(tmpdir):
assert p.__json__() == {"name": p.name, "project_id": p.id, "temporary": False} assert p.__json__() == {"name": p.name, "project_id": p.id, "temporary": False}
def test_node_working_directory(tmpdir, vm): def test_node_working_directory(tmpdir, node):
directory = Config.instance().get_section_config("Server").get("projects_path") directory = Config.instance().get_section_config("Server").get("projects_path")
with patch("gns3server.compute.project.Project.is_local", return_value=True): with patch("gns3server.compute.project.Project.is_local", return_value=True):
@ -186,7 +186,7 @@ def test_project_delete_permission_issue(loop):
os.chmod(directory, 700) os.chmod(directory, 700)
def test_project_add_vm(manager): def test_project_add_node(manager):
project = Project(project_id=str(uuid4())) project = Project(project_id=str(uuid4()))
node = VPCSVM("test", "00010203-0405-0607-0809-0a0b0c0d0e0f", project, manager) node = VPCSVM("test", "00010203-0405-0607-0809-0a0b0c0d0e0f", project, manager)
project.add_node(node) project.add_node(node)

View File

@ -164,7 +164,7 @@ def test_connectNotification(compute, async_run):
compute._session = AsyncioMagicMock(return_value=ws_mock) compute._session = AsyncioMagicMock(return_value=ws_mock)
compute._session.ws_connect = AsyncioMagicMock(return_value=ws_mock) compute._session.ws_connect = AsyncioMagicMock(return_value=ws_mock)
ws_mock.receive = receive ws_mock.receive = receive
async_run(compute._connectNotification()) async_run(compute._connect_notification())
compute._controller.emit.assert_called_with('test', {'a': 1}, compute_id=compute.id, project_id='42') compute._controller.emit.assert_called_with('test', {'a': 1}, compute_id=compute.id, project_id='42')
assert compute._connected is False assert compute._connected is False
@ -186,5 +186,5 @@ def test_streamFile(project, async_run, compute):
response = MagicMock() response = MagicMock()
response.status = 200 response.status = 200
with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock: with asyncio_patch("aiohttp.ClientSession.request", return_value=response) as mock:
async_run(compute.streamFile(project, "test/titi")) async_run(compute.steam_file(project, "test/titi"))
mock.assert_called_with("GET", "https://example.com:84/v2/compute/projects/{}/stream/test/titi".format(project.id), auth=None) mock.assert_called_with("GET", "https://example.com:84/v2/compute/projects/{}/stream/test/titi".format(project.id), auth=None)

View File

@ -103,9 +103,9 @@ def test_addComputeConfigFile(controller, controller_config_path, async_run):
def test_getCompute(controller, async_run): def test_getCompute(controller, async_run):
compute = async_run(controller.add_compute("test1")) compute = async_run(controller.add_compute("test1"))
assert controller.getCompute("test1") == compute assert controller.get_compute("test1") == compute
with pytest.raises(aiohttp.web.HTTPNotFound): with pytest.raises(aiohttp.web.HTTPNotFound):
assert controller.getCompute("dsdssd") assert controller.get_compute("dsdssd")
def test_addComputeLocal(controller, controller_config_path, async_run): def test_addComputeLocal(controller, controller_config_path, async_run):
@ -113,8 +113,8 @@ def test_addComputeLocal(controller, controller_config_path, async_run):
The local node is the controller itself you can not change the informations The local node is the controller itself you can not change the informations
""" """
Config.instance().set("Server", "local", True) Config.instance().set("Server", "local", True)
async_run(controller.addCompute("local", host="example.org")) async_run(controller.add_compute("local", host="example.org"))
assert controller.getCompute("local").host == "localhost" assert controller.get_compute("local").host == "localhost"
def test_addProject(controller, async_run): def test_addProject(controller, async_run):
@ -129,13 +129,13 @@ def test_addProject(controller, async_run):
assert len(controller.projects) == 2 assert len(controller.projects) == 2
def test_removeProject(controller, async_run): def test_remove_project(controller, async_run):
uuid1 = str(uuid.uuid4()) uuid1 = str(uuid.uuid4())
project1 = async_run(controller.addProject(project_id=uuid1)) project1 = async_run(controller.addProject(project_id=uuid1))
assert len(controller.projects) == 1 assert len(controller.projects) == 1
controller.removeProject(project1) controller.remove_project(project1)
assert len(controller.projects) == 0 assert len(controller.projects) == 0

View File

@ -71,11 +71,11 @@ def test_captures_directory(tmpdir):
def test_add_compute(async_run): def test_add_compute(async_run):
compute = MagicMock() compute = MagicMock()
project = Project() project = Project()
async_run(project.addCompute(compute)) async_run(project.add_compute(compute))
assert compute in project._computes assert compute in project._computes
def test_addVM(async_run): def test_add_node(async_run):
compute = MagicMock() compute = MagicMock()
project = Project() project = Project()
@ -83,7 +83,7 @@ def test_addVM(async_run):
response.json = {"console": 2048} response.json = {"console": 2048}
compute.post = AsyncioMagicMock(return_value=response) compute.post = AsyncioMagicMock(return_value=response)
vm = async_run(project.add_node(compute, None, name="test", node_type="vpcs", properties={"startup_config": "test.cfg"})) node = async_run(project.add_node(compute, None, name="test", node_type="vpcs", properties={"startup_config": "test.cfg"}))
compute.post.assert_any_call('/projects/{}/vpcs/nodes'.format(project.id), compute.post.assert_any_call('/projects/{}/vpcs/nodes'.format(project.id),
data={'node_id': node.id, data={'node_id': node.id,

View File

@ -173,4 +173,4 @@ def test_read_pcap_from_source(project, async_run):
assert link._capture_node is not None assert link._capture_node is not None
async_run(link.read_pcap_from_source()) async_run(link.read_pcap_from_source())
link._capture_node["node"].compute.streamFile.assert_called_with(project, "tmp/captures/" + link._capture_file_name) link._capture_node["node"].compute.steam_file.assert_called_with(project, "tmp/captures/" + link._capture_file_name)