diff options
| author | jc0b <j@jc0b.computer> | 2020-06-30 14:12:07 +0200 |
|---|---|---|
| committer | Fabian Mastenbroek <mail.fabianm@gmail.com> | 2020-08-24 19:43:10 +0200 |
| commit | 66b2d85385d05abb590535da60341876ecdbab71 (patch) | |
| tree | 0656f64a4179d419adac86e488e21def7a7fa2b8 /web-server/opendc/api | |
| parent | 88d8a9cbeae3466230db6bd13120bd4438abbc66 (diff) | |
| parent | c99ef7504a1374170f88b89faeb7e6dec6a55253 (diff) | |
Merge changes with upstream
Diffstat (limited to 'web-server/opendc/api')
33 files changed, 382 insertions, 653 deletions
diff --git a/web-server/opendc/api/v2/experiments/experimentId/endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/endpoint.py index bc2b139e..103c24ac 100644 --- a/web-server/opendc/api/v2/experiments/experimentId/endpoint.py +++ b/web-server/opendc/api/v2/experiments/experimentId/endpoint.py @@ -1,113 +1,65 @@ -from opendc.models_old.experiment import Experiment -from opendc.util import exceptions +from opendc.models.experiment import Experiment +from opendc.models.simulation import Simulation from opendc.util.rest import Response def GET(request): """Get this Experiment.""" - try: - request.check_required_parameters(path={'experimentId': 'int'}) + request.check_required_parameters(path={'experimentId': 'string'}) - except exceptions.ParameterError as e: - return Response(400, str(e)) + experiment = Experiment.from_id(request.params_path['experimentId']) - # Instantiate an Experiment from the database + experiment.check_exists() + experiment.check_user_access(request.google_id, False) - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - # Make sure this Experiment exists - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) - - # Make sure this user is authorized to view this Experiment - - if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from retrieving {}.'.format(experiment)) - - # Return this Experiment - - experiment.read() - - return Response(200, 'Successfully retrieved {}.'.format(experiment), experiment.to_JSON()) + return Response(200, 'Successfully retrieved Experiment.', experiment.obj) def PUT(request): - """Update this Experiment's Path, Trace, Scheduler, and/or name.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters( - path={'experimentId': 'int'}, - body={'experiment': { - 'pathId': 'int', - 'traceId': 'int', - 'schedulerName': 'string', - 'name': 'string' - }}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment from the database + """Update this Experiment.""" - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) + request.check_required_parameters(path={'experimentId': 'string'}, + body={ + 'experiment': { + 'topologyId': 'string', + 'traceId': 'string', + 'schedulerName': 'string', + 'name': 'string', + } + }) - # Make sure this Experiment exists + experiment = Experiment.from_id(request.params_path['experimentId']) - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) + experiment.check_exists() + experiment.check_user_access(request.google_id, True) - # Make sure this user is authorized to edit this Experiment + experiment.set_property('topologyId', request.params_body['experiment']['topologyId']) + experiment.set_property('traceId', request.params_body['experiment']['traceId']) + experiment.set_property('schedulerName', request.params_body['experiment']['schedulerName']) + experiment.set_property('name', request.params_body['experiment']['name']) - if not experiment.google_id_has_at_least(request.google_id, 'EDIT'): - return Response(403, 'Forbidden from updating {}.'.format(experiment)) + experiment.update() - # Update this Experiment - - experiment.path_id = request.params_body['experiment']['pathId'] - experiment.trace_id = request.params_body['experiment']['traceId'] - experiment.scheduler_name = request.params_body['experiment']['schedulerName'] - experiment.name = request.params_body['experiment']['name'] - - try: - experiment.update() - - except exceptions.ForeignKeyError: - return Response(400, 'Foreign key error.') - - # Return this Experiment - - return Response(200, 'Successfully updated {}.'.format(experiment), experiment.to_JSON()) + return Response(200, 'Successfully updated experiment', experiment.obj) def DELETE(request): """Delete this Experiment.""" - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'experimentId': 'int'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment and make sure it exists - - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) + request.check_required_parameters(path={'experimentId': 'string'}) - # Make sure this user is authorized to delete this Experiment + experiment = Experiment.from_id(request.params_path['experimentId']) - if not experiment.google_id_has_at_least(request.google_id, 'EDIT'): - return Response(403, 'Forbidden from deleting {}.'.format(experiment)) + experiment.check_exists() + experiment.check_user_access(request.google_id, True) - # Delete and return this Experiment + simulation = Simulation.from_id(experiment.obj['simulationId']) + simulation.check_exists() + if request.params_path['experimentId'] in simulation.obj['experimentIds']: + simulation.obj['experimentIds'].remove(request.params_path['experimentId']) + simulation.update() experiment.delete() - return Response(200, 'Successfully deleted {}.'.format(experiment), experiment.to_JSON()) + return Response(200, 'Successfully deleted experiment.', experiment.obj) diff --git a/web-server/opendc/api/v2/experiments/experimentId/last-simulated-tick/__init__.py b/web-server/opendc/api/v2/experiments/experimentId/last-simulated-tick/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/last-simulated-tick/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/experiments/experimentId/last-simulated-tick/endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/last-simulated-tick/endpoint.py deleted file mode 100644 index 3309502c..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/last-simulated-tick/endpoint.py +++ /dev/null @@ -1,32 +0,0 @@ -from opendc.models_old.experiment import Experiment -from opendc.util import exceptions -from opendc.util.rest import Response - - -def GET(request): - """Get this Experiment's last simulated tick.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'experimentId': 'int'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment from the database - - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - # Make sure this Experiment exists - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) - - # Make sure this user is authorized to view this Experiment's last simulated tick - - if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from viewing last simulated tick for {}.'.format(experiment)) - - return Response(200, 'Successfully retrieved last simulated tick for {}.'.format(experiment), - {'lastSimulatedTick': experiment.last_simulated_tick}) diff --git a/web-server/opendc/api/v2/experiments/experimentId/machine-states/__init__.py b/web-server/opendc/api/v2/experiments/experimentId/machine-states/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/machine-states/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/experiments/experimentId/machine-states/endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/machine-states/endpoint.py deleted file mode 100644 index c7dcad9a..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/machine-states/endpoint.py +++ /dev/null @@ -1,42 +0,0 @@ -from opendc.models_old.experiment import Experiment -from opendc.models_old.machine_state import MachineState -from opendc.util import exceptions -from opendc.util.rest import Response - - -def GET(request): - """Get this Experiment's Machine States.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'experimentId': 'int'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment from the database - - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - # Make sure this Experiment exists - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) - - # Make sure this user is authorized to view this Experiment's Machine States - - if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from viewing Machine States for {}.'.format(experiment)) - - # Get and return the Machine States - - if 'tick' in request.params_query: - machine_states = MachineState.from_experiment_id_and_tick(request.params_path['experimentId'], - request.params_query['tick']) - - else: - machine_states = MachineState.from_experiment_id(request.params_path['experimentId']) - - return Response(200, 'Successfully retrieved Machine States for {}.'.format(experiment), - [x.to_JSON() for x in machine_states]) diff --git a/web-server/opendc/api/v2/experiments/experimentId/rack-states/__init__.py b/web-server/opendc/api/v2/experiments/experimentId/rack-states/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/rack-states/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/experiments/experimentId/rack-states/endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/rack-states/endpoint.py deleted file mode 100644 index f3acf56a..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/rack-states/endpoint.py +++ /dev/null @@ -1,42 +0,0 @@ -from opendc.models_old.experiment import Experiment -from opendc.models_old.rack_state import RackState -from opendc.util import exceptions -from opendc.util.rest import Response - - -def GET(request): - """Get this Experiment's Tack States.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'experimentId': 'int'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment from the database - - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - # Make sure this Experiment exists - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) - - # Make sure this user is authorized to view this Experiment's Rack States - - if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from viewing Rack States for {}.'.format(experiment)) - - # Get and return the Rack States - - if 'tick' in request.params_query: - rack_states = RackState.from_experiment_id_and_tick(request.params_path['experimentId'], - request.params_query['tick']) - - else: - rack_states = RackState.from_experiment_id(request.params_path['experimentId']) - - return Response(200, 'Successfully retrieved Rack States for {}.'.format(experiment), - [x.to_JSON() for x in rack_states]) diff --git a/web-server/opendc/api/v2/experiments/experimentId/room-states/__init__.py b/web-server/opendc/api/v2/experiments/experimentId/room-states/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/room-states/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/experiments/experimentId/room-states/endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/room-states/endpoint.py deleted file mode 100644 index db3f8b14..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/room-states/endpoint.py +++ /dev/null @@ -1,42 +0,0 @@ -from opendc.models_old.experiment import Experiment -from opendc.models_old.room_state import RoomState -from opendc.util import exceptions -from opendc.util.rest import Response - - -def GET(request): - """Get this Experiment's Room States.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'experimentId': 'int'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment from the database - - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - # Make sure this Experiment exists - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) - - # Make sure this user is authorized to view this Experiment's Room States - - if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from viewing Room States for {}.'.format(experiment)) - - # Get and return the Room States - - if 'tick' in request.params_query: - room_states = RoomState.from_experiment_id_and_tick(request.params_path['experimentId'], - request.params_query['tick']) - - else: - room_states = RoomState.from_experiment_id(request.params_path['experimentId']) - - return Response(200, 'Successfully retrieved Room States for {}.'.format(experiment), - [x.to_JSON() for x in room_states]) diff --git a/web-server/opendc/api/v2/experiments/experimentId/statistics/__init__.py b/web-server/opendc/api/v2/experiments/experimentId/statistics/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/statistics/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/experiments/experimentId/statistics/task-durations/__init__.py b/web-server/opendc/api/v2/experiments/experimentId/statistics/task-durations/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/statistics/task-durations/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/experiments/experimentId/statistics/task-durations/endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/statistics/task-durations/endpoint.py deleted file mode 100644 index 498db239..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/statistics/task-durations/endpoint.py +++ /dev/null @@ -1,37 +0,0 @@ -from opendc.models_old.experiment import Experiment -from opendc.models_old.task_duration import TaskDuration -from opendc.util import exceptions -from opendc.util.rest import Response - - -def GET(request): - """Get this Experiment's Task Durations.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'experimentId': 'int'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment from the database - - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - # Make sure this Experiment exists - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) - - # Make sure this user is authorized to view this Experiment's Task Durations - - if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from viewing Task Durations for {}.'.format(experiment)) - - # Get and return the Task Durations - - task_durations = TaskDuration.from_experiment_id(request.params_path['experimentId']) - - return Response(200, 'Successfully retrieved Task Durations for {}.'.format(experiment), - [x.to_JSON() for x in task_durations]) diff --git a/web-server/opendc/api/v2/experiments/experimentId/task-states/__init__.py b/web-server/opendc/api/v2/experiments/experimentId/task-states/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/task-states/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/experiments/experimentId/task-states/endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/task-states/endpoint.py deleted file mode 100644 index c0ae47fc..00000000 --- a/web-server/opendc/api/v2/experiments/experimentId/task-states/endpoint.py +++ /dev/null @@ -1,42 +0,0 @@ -from opendc.models_old.experiment import Experiment -from opendc.models_old.task_state import TaskState -from opendc.util import exceptions -from opendc.util.rest import Response - - -def GET(request): - """Get this Experiment's Task States.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'experimentId': 'int'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Experiment from the database - - experiment = Experiment.from_primary_key((request.params_path['experimentId'], )) - - # Make sure this Experiment exists - - if not experiment.exists(): - return Response(404, '{} not found.'.format(experiment)) - - # Make sure this user is authorized to view Task States for this Experiment - - if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from viewing Task States for {}.'.format(experiment)) - - # Get and return the Task States - - if 'tick' in request.params_query: - task_states = TaskState.from_experiment_id_and_tick(request.params_path['experimentId'], - request.params_query['tick']) - - else: - task_states = TaskState.query('experiment_id', request.params_path['experimentId']) - - return Response(200, 'Successfully retrieved Task States for {}.'.format(experiment), - [x.to_JSON() for x in task_states]) diff --git a/web-server/opendc/api/v2/experiments/experimentId/test_endpoint.py b/web-server/opendc/api/v2/experiments/experimentId/test_endpoint.py new file mode 100644 index 00000000..c460585f --- /dev/null +++ b/web-server/opendc/api/v2/experiments/experimentId/test_endpoint.py @@ -0,0 +1,146 @@ +from opendc.util.database import DB + + +def test_get_experiment_non_existing(client, mocker): + mocker.patch.object(DB, 'fetch_one', return_value=None) + assert '404' in client.get('/api/v2/experiments/1').status + + +def test_get_experiment_no_authorizations(client, mocker): + mocker.patch.object(DB, 'fetch_one', return_value={'simulationId': '1', 'authorizations': []}) + res = client.get('/api/v2/experiments/1') + assert '403' in res.status + + +def test_get_experiment_not_authorized(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + 'simulationId': '1', + '_id': '1', + 'authorizations': [{ + 'simulationId': '2', + 'authorizationLevel': 'OWN' + }] + }) + res = client.get('/api/v2/experiments/1') + assert '403' in res.status + + +def test_get_experiment(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + 'simulationId': '1', + '_id': '1', + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'EDIT' + }] + }) + res = client.get('/api/v2/experiments/1') + assert '200' in res.status + + +def test_update_experiment_missing_parameter(client): + assert '400' in client.put('/api/v2/experiments/1').status + + +def test_update_experiment_non_existing(client, mocker): + mocker.patch.object(DB, 'fetch_one', return_value=None) + assert '404' in client.put('/api/v2/experiments/1', + json={ + 'experiment': { + 'topologyId': '1', + 'traceId': '1', + 'schedulerName': 'default', + 'name': 'test', + } + }).status + + +def test_update_experiment_not_authorized(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'simulationId': '1', + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'VIEW' + }] + }) + mocker.patch.object(DB, 'update', return_value={}) + assert '403' in client.put('/api/v2/experiments/1', + json={ + 'experiment': { + 'topologyId': '1', + 'traceId': '1', + 'schedulerName': 'default', + 'name': 'test', + } + }).status + + +def test_update_experiment(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'simulationId': '1', + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'OWN' + }] + }) + mocker.patch.object(DB, 'update', return_value={}) + + res = client.put( + '/api/v2/experiments/1', + json={'experiment': { + 'topologyId': '1', + 'traceId': '1', + 'schedulerName': 'default', + 'name': 'test', + }}) + assert '200' in res.status + + +def test_delete_simulation_non_existing(client, mocker): + mocker.patch.object(DB, 'fetch_one', return_value=None) + assert '404' in client.delete('/api/v2/experiments/1').status + + +def test_delete_simulation_different_user(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'simulationId': '1', + 'googleId': 'other_test', + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'VIEW' + }] + }) + mocker.patch.object(DB, 'delete_one', return_value=None) + assert '403' in client.delete('/api/v2/experiments/1').status + + +def test_delete_simulation(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'simulationId': '1', + 'googleId': 'test', + 'experimentIds': ['1'], + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'OWN' + }] + }) + mocker.patch.object(DB, 'delete_one', return_value={}) + mocker.patch.object(DB, 'update', return_value=None) + res = client.delete('/api/v2/experiments/1') + assert '200' in res.status diff --git a/web-server/opendc/api/v2/paths.json b/web-server/opendc/api/v2/paths.json index ce054a8c..d6f1db82 100644 --- a/web-server/opendc/api/v2/paths.json +++ b/web-server/opendc/api/v2/paths.json @@ -5,11 +5,9 @@ "/simulations/{simulationId}", "/simulations/{simulationId}/authorizations", "/simulations/{simulationId}/topologies", - "/experiments/{experimentId}/last-simulated-tick", "/experiments/{experimentId}/machine-states", "/experiments/{experimentId}/rack-states", "/experiments/{experimentId}/room-states", - "/experiments/{experimentId}/task-states", "/topologies/{topologyId}", "/simulations/{simulationId}/experiments", "/experiments/{experimentId}", diff --git a/web-server/opendc/api/v2/simulations/endpoint.py b/web-server/opendc/api/v2/simulations/endpoint.py index 232df2ff..c978fad7 100644 --- a/web-server/opendc/api/v2/simulations/endpoint.py +++ b/web-server/opendc/api/v2/simulations/endpoint.py @@ -3,7 +3,6 @@ from datetime import datetime from opendc.models.simulation import Simulation from opendc.models.topology import Topology from opendc.models.user import User -from opendc.util import exceptions from opendc.util.database import Database from opendc.util.rest import Response @@ -13,18 +12,18 @@ def POST(request): request.check_required_parameters(body={'simulation': {'name': 'string'}}) - topology = Topology({'name': 'Default topology'}) + topology = Topology({'name': 'Default topology', 'rooms': []}) topology.insert() simulation = Simulation({'simulation': request.params_body['simulation']}) simulation.set_property('datetimeCreated', Database.datetime_to_string(datetime.now())) simulation.set_property('datetimeLastEdited', Database.datetime_to_string(datetime.now())) - simulation.set_property('topologyIds', [topology.obj['_id']]) + simulation.set_property('topologyIds', [topology.get_id()]) simulation.set_property('experimentIds', []) simulation.insert() user = User.from_google_id(request.google_id) - user.obj['authorizations'].append({'simulationId': simulation.obj['_id'], 'authorizationLevel': 'OWN'}) + user.obj['authorizations'].append({'simulationId': simulation.get_id(), 'authorizationLevel': 'OWN'}) user.update() return Response(200, 'Successfully created simulation.', simulation.obj) diff --git a/web-server/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py index df2b5cfd..49d0fc20 100644 --- a/web-server/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py +++ b/web-server/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py @@ -1,37 +1,17 @@ -from opendc.models_old.authorization import Authorization -from opendc.models_old.simulation import Simulation -from opendc.util import exceptions +from opendc.models.simulation import Simulation from opendc.util.rest import Response def GET(request): """Find all authorizations for a Simulation.""" - # Make sure required parameters are there + request.check_required_parameters(path={'simulationId': 'string'}) - try: - request.check_required_parameters(path={'simulationId': 'string'}) + simulation = Simulation.from_id(request.params_path['simulationId']) - except exceptions.ParameterError as e: - return Response(400, str(e)) + simulation.check_exists() + simulation.check_user_access(request.google_id, False) - # Instantiate a Simulation and make sure it exists + authorizations = simulation.get_all_authorizations() - simulation = Simulation.from_primary_key((request.params_path['simulationId'], )) - - if not simulation.exists(): - return Response(404, '{} not found.'.format(simulation)) - - # Make sure this User is allowed to view this Simulation's Authorizations - - if not simulation.google_id_has_at_least(request.google_id, 'VIEW'): - return Response(403, 'Forbidden from retrieving Authorizations for {}.'.format(simulation)) - - # Get the Authorizations - - authorizations = Authorization.query('simulation_id', request.params_path['simulationId']) - - # Return the Authorizations - - return Response(200, 'Successfully retrieved Authorizations for {}.'.format(simulation), - [x.to_JSON() for x in authorizations]) + return Response(200, 'Successfully retrieved simulation authorizations', authorizations) diff --git a/web-server/opendc/api/v2/simulations/simulationId/authorizations/test_endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/authorizations/test_endpoint.py new file mode 100644 index 00000000..4369d807 --- /dev/null +++ b/web-server/opendc/api/v2/simulations/simulationId/authorizations/test_endpoint.py @@ -0,0 +1,40 @@ +from opendc.util.database import DB + + +def test_get_authorizations_non_existing(client, mocker): + mocker.patch.object(DB, 'fetch_one', return_value=None) + mocker.patch.object(DB, 'fetch_all', return_value=None) + assert '404' in client.get('/api/v2/simulations/1/authorizations').status + + +def test_get_authorizations_not_authorized(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'name': 'test trace', + 'authorizations': [{ + 'simulationId': '2', + 'authorizationLevel': 'OWN' + }] + }) + mocker.patch.object(DB, 'fetch_all', return_value=[]) + res = client.get('/api/v2/simulations/1/authorizations') + assert '403' in res.status + + +def test_get_authorizations(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'name': 'test trace', + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'OWN' + }] + }) + mocker.patch.object(DB, 'fetch_all', return_value=[]) + res = client.get('/api/v2/simulations/1/authorizations') + assert len(res.json['content']) == 0 + assert '200' in res.status diff --git a/web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/__init__.py b/web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/__init__.py +++ /dev/null diff --git a/web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py deleted file mode 100644 index 121530db..00000000 --- a/web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py +++ /dev/null @@ -1,178 +0,0 @@ -from opendc.models_old.authorization import Authorization -from opendc.models_old.simulation import Simulation -from opendc.models_old.user import User -from opendc.util import exceptions -from opendc.util.rest import Response - - -def DELETE(request): - """Delete a user's authorization level over a simulation.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'simulationId': 'string', 'userId': 'string'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Authorization - - authorization = Authorization.from_primary_key((request.params_path['userId'], request.params_path['simulationId'])) - - # Make sure this Authorization exists in the database - - if not authorization.exists(): - return Response(404, '{} not found.'.format(authorization)) - - # Make sure this User is allowed to delete this Authorization - - if not authorization.google_id_has_at_least(request.google_id, 'OWN'): - return Response(403, 'Forbidden from deleting {}.'.format(authorization)) - - # Delete this Authorization - - authorization.delete() - - return Response(200, 'Successfully deleted {}.'.format(authorization), authorization.to_JSON()) - - -def GET(request): - """Get this User's Authorization over this Simulation.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'simulationId': 'string', 'userId': 'string'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Authorization - - authorization = Authorization.from_primary_key((request.params_path['userId'], request.params_path['simulationId'])) - - # Make sure this Authorization exists in the database - - if not authorization.exists(): - return Response(404, '{} not found.'.format(authorization)) - - # Read this Authorization from the database - - authorization.read() - - # Return this Authorization - - return Response(200, 'Successfully retrieved {}'.format(authorization), authorization.to_JSON()) - - -def POST(request): - """Add an authorization for a user's access to a simulation.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={ - 'userId': 'string', - 'simulationId': 'string' - }, - body={'authorization': { - 'authorizationLevel': 'string' - }}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate an Authorization - - authorization = Authorization.from_JSON({ - 'userId': - request.params_path['userId'], - 'simulationId': - request.params_path['simulationId'], - 'authorizationLevel': - request.params_body['authorization']['authorizationLevel'] - }) - - # Make sure the Simulation and User exist - - user = User.from_primary_key((authorization.user_id, )) - if not user.exists(): - return Response(404, '{} not found.'.format(user)) - - simulation = Simulation.from_primary_key((authorization.simulation_id, )) - if not simulation.exists(): - return Response(404, '{} not found.'.format(simulation)) - - # Make sure this User is allowed to add this Authorization - - if not simulation.google_id_has_at_least(request.google_id, 'OWN'): - return Response(403, 'Forbidden from creating {}.'.format(authorization)) - - # Make sure this Authorization does not already exist - - if authorization.exists(): - return Response(409, '{} already exists.'.format(authorization)) - - # Try to insert this Authorization into the database - - try: - authorization.insert() - - except exceptions.ForeignKeyError: - return Response(400, 'Invalid authorizationLevel') - - # Return this Authorization - - return Response(200, 'Successfully added {}'.format(authorization), authorization.to_JSON()) - - -def PUT(request): - """Change a user's authorization level over a simulation.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={ - 'simulationId': 'string', - 'userId': 'string' - }, - body={'authorization': { - 'authorizationLevel': 'string' - }}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate and Authorization - - authorization = Authorization.from_JSON({ - 'userId': - request.params_path['userId'], - 'simulationId': - request.params_path['simulationId'], - 'authorizationLevel': - request.params_body['authorization']['authorizationLevel'] - }) - - # Make sure this Authorization exists - - if not authorization.exists(): - return Response(404, '{} not found.'.format(authorization)) - - # Make sure this User is allowed to edit this Authorization - - if not authorization.google_id_has_at_least(request.google_id, 'OWN'): - return Response(403, 'Forbidden from updating {}.'.format(authorization)) - - # Try to update this Authorization - - try: - authorization.update() - - except exceptions.ForeignKeyError as e: - return Response(400, 'Invalid authorization level.') - - # Return this Authorization - - return Response(200, 'Successfully updated {}.'.format(authorization), authorization.to_JSON()) diff --git a/web-server/opendc/api/v2/simulations/simulationId/endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/endpoint.py index 282e3291..05b38686 100644 --- a/web-server/opendc/api/v2/simulations/simulationId/endpoint.py +++ b/web-server/opendc/api/v2/simulations/simulationId/endpoint.py @@ -1,5 +1,6 @@ from datetime import datetime +from opendc.models.experiment import Experiment from opendc.models.simulation import Simulation from opendc.models.topology import Topology from opendc.util.database import Database @@ -50,8 +51,10 @@ def DELETE(request): topology = Topology.from_id(topology_id) topology.delete() - # TODO remove all experiments + for experiment_id in simulation.obj['experimentIds']: + experiment = Experiment.from_id(experiment_id) + experiment.delete() simulation.delete() - return Response(200, f'Successfully deleted simulation.', simulation.obj) + return Response(200, 'Successfully deleted simulation.', simulation.obj) diff --git a/web-server/opendc/api/v2/simulations/simulationId/experiments/endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/experiments/endpoint.py index 9df84838..0d7c208d 100644 --- a/web-server/opendc/api/v2/simulations/simulationId/experiments/endpoint.py +++ b/web-server/opendc/api/v2/simulations/simulationId/experiments/endpoint.py @@ -1,97 +1,35 @@ -from opendc.models_old.experiment import Experiment -from opendc.models_old.simulation import Simulation -from opendc.util import exceptions +from opendc.models.experiment import Experiment +from opendc.models.simulation import Simulation from opendc.util.rest import Response -def GET(request): - """Get this Simulation's Experiments.""" - - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'simulationId': 'string'}) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Instantiate a Simulation from the database - - simulation = Simulation.from_primary_key((request.params_path['simulationId'], )) - - # Make sure this Simulation exists - - if not simulation.exists(): - return Response(404, '{} not found.'.format(simulation)) - - # Make sure this user is authorized to view this Simulation's Experiments - - if not simulation.google_id_has_at_least(request.google_id, 'VIEW'): - return Reponse(403, 'Forbidden from viewing Experiments for {}.'.format(simulation)) - - # Get and return the Experiments - - experiments = Experiment.query('simulation_id', request.params_path['simulationId']) - - return Response(200, 'Successfully retrieved Experiments for {}.'.format(simulation), - [x.to_JSON() for x in experiments]) - - def POST(request): """Add a new Experiment for this Simulation.""" - # Make sure required parameters are there - - try: - request.check_required_parameters(path={'simulationId': 'string'}, - body={ - 'experiment': { - 'simulationId': 'string', - 'pathId': 'int', - 'traceId': 'int', - 'schedulerName': 'string', - 'name': 'string' - } - }) - - except exceptions.ParameterError as e: - return Response(400, str(e)) - - # Make sure the passed object's simulation id matches the path simulation id - - if request.params_path['simulationId'] != request.params_body['experiment']['simulationId']: - return Response(403, 'ID mismatch.') - - # Instantiate a Simulation from the database - - simulation = Simulation.from_primary_key((request.params_path['simulationId'], )) - - # Make sure this Simulation exists - - if not simulation.exists(): - return Response(404, '{} not found.'.format(simulation)) - - # Make sure this user is authorized to edit this Simulation's Experiments - - if not simulation.google_id_has_at_least(request.google_id, 'EDIT'): - return Response(403, 'Forbidden from adding an experiment to {}.'.format(simulation)) - - # Instantiate an Experiment + request.check_required_parameters(path={'simulationId': 'string'}, + body={ + 'experiment': { + 'topologyId': 'string', + 'traceId': 'string', + 'schedulerName': 'string', + 'name': 'string', + } + }) - experiment = Experiment.from_JSON(request.params_body['experiment']) - experiment.state = 'QUEUED' - experiment.last_simulated_tick = 0 + simulation = Simulation.from_id(request.params_path['simulationId']) - # Try to insert this Experiment + simulation.check_exists() + simulation.check_user_access(request.google_id, True) - try: - experiment.insert() + experiment = Experiment(request.params_body['experiment']) - except exceptions.ForeignKeyError as e: - return Response(400, 'Foreign key constraint not met.' + e) + experiment.set_property('simulationId', request.params_path['simulationId']) + experiment.set_property('state', 'QUEUED') + experiment.set_property('lastSimulatedTick', 0) - # Return this Experiment + experiment.insert() - experiment.read() + simulation.obj['experimentIds'].append(experiment.get_id()) + simulation.update() - return Response(200, 'Successfully added {}.'.format(experiment), experiment.to_JSON()) + return Response(200, 'Successfully added Experiment.', experiment.obj) diff --git a/web-server/opendc/api/v2/simulations/simulationId/experiments/test_endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/experiments/test_endpoint.py new file mode 100644 index 00000000..1fe09b10 --- /dev/null +++ b/web-server/opendc/api/v2/simulations/simulationId/experiments/test_endpoint.py @@ -0,0 +1,78 @@ +from opendc.util.database import DB + + +def test_add_experiment_missing_parameter(client): + assert '400' in client.post('/api/v2/simulations/1/experiments').status + + +def test_add_experiment_non_existing_simulation(client, mocker): + mocker.patch.object(DB, 'fetch_one', return_value=None) + assert '404' in client.post('/api/v2/simulations/1/experiments', + json={ + 'experiment': { + 'topologyId': '1', + 'traceId': '1', + 'schedulerName': 'default', + 'name': 'test', + } + }).status + + +def test_add_experiment_not_authorized(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'simulationId': '1', + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'VIEW' + }] + }) + assert '403' in client.post('/api/v2/simulations/1/experiments', + json={ + 'experiment': { + 'topologyId': '1', + 'traceId': '1', + 'schedulerName': 'default', + 'name': 'test', + } + }).status + + +def test_add_experiment(client, mocker): + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'simulationId': '1', + 'experimentIds': ['1'], + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'EDIT' + }] + }) + mocker.patch.object(DB, + 'insert', + return_value={ + '_id': '1', + 'topologyId': '1', + 'traceId': '1', + 'schedulerName': 'default', + 'name': 'test', + 'state': 'QUEUED', + 'lastSimulatedTick': 0, + }) + mocker.patch.object(DB, 'update', return_value=None) + res = client.post( + '/api/v2/simulations/1/experiments', + json={'experiment': { + 'topologyId': '1', + 'traceId': '1', + 'schedulerName': 'default', + 'name': 'test', + }}) + assert 'topologyId' in res.json['content'] + assert 'state' in res.json['content'] + assert 'lastSimulatedTick' in res.json['content'] + assert '200' in res.status diff --git a/web-server/opendc/api/v2/simulations/simulationId/test_endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/test_endpoint.py index 7038f1b0..7aa7ebfc 100644 --- a/web-server/opendc/api/v2/simulations/simulationId/test_endpoint.py +++ b/web-server/opendc/api/v2/simulations/simulationId/test_endpoint.py @@ -110,7 +110,8 @@ def test_delete_simulation(client, mocker): 'simulationId': '1', 'authorizationLevel': 'OWN' }], - 'topologyIds': [] + 'topologyIds': [], + 'experimentIds': [], }) mocker.patch.object(DB, 'delete_one', return_value={'googleId': 'test'}) res = client.delete('/api/v2/simulations/1') diff --git a/web-server/opendc/api/v2/simulations/simulationId/topologies/endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/topologies/endpoint.py index ab7b7006..952959ca 100644 --- a/web-server/opendc/api/v2/simulations/simulationId/topologies/endpoint.py +++ b/web-server/opendc/api/v2/simulations/simulationId/topologies/endpoint.py @@ -2,7 +2,6 @@ from datetime import datetime from opendc.models.simulation import Simulation from opendc.models.topology import Topology -from opendc.util import exceptions from opendc.util.rest import Response from opendc.util.database import Database @@ -22,7 +21,7 @@ def POST(request): topology.set_property('datetimeLastEdited', Database.datetime_to_string(datetime.now())) topology.insert() - simulation.obj['topologyIds'].append(topology.obj['_id']) + simulation.obj['topologyIds'].append(topology.get_id()) simulation.set_property('datetimeLastEdited', Database.datetime_to_string(datetime.now())) simulation.update() diff --git a/web-server/opendc/api/v2/simulations/simulationId/topologies/test_endpoint.py b/web-server/opendc/api/v2/simulations/simulationId/topologies/test_endpoint.py index 10b5e3c9..cc26e1b0 100644 --- a/web-server/opendc/api/v2/simulations/simulationId/topologies/test_endpoint.py +++ b/web-server/opendc/api/v2/simulations/simulationId/topologies/test_endpoint.py @@ -6,7 +6,16 @@ def test_add_topology_missing_parameter(client): def test_add_topology(client, mocker): - mocker.patch.object(DB, 'fetch_one', return_value={'_id': '1', 'authorizations': [{'simulationId': '1', 'authorizationLevel': 'OWN'}], 'topologyIds': []}) + mocker.patch.object(DB, + 'fetch_one', + return_value={ + '_id': '1', + 'authorizations': [{ + 'simulationId': '1', + 'authorizationLevel': 'OWN' + }], + 'topologyIds': [] + }) mocker.patch.object(DB, 'insert', return_value={ @@ -22,5 +31,6 @@ def test_add_topology(client, mocker): assert 'topologyIds' in res.json['content'] assert '200' in res.status + def test_add_topology_no_authorizations(client, mocker): - pass
\ No newline at end of file + pass diff --git a/web-server/opendc/api/v2/topologies/topologyId/endpoint.py b/web-server/opendc/api/v2/topologies/topologyId/endpoint.py index fb7b1c59..05bf27aa 100644 --- a/web-server/opendc/api/v2/topologies/topologyId/endpoint.py +++ b/web-server/opendc/api/v2/topologies/topologyId/endpoint.py @@ -1,5 +1,4 @@ from opendc.models.topology import Topology -from opendc.util import exceptions from opendc.util.rest import Response diff --git a/web-server/opendc/api/v2/topologies/topologyId/test_endpoint.py b/web-server/opendc/api/v2/topologies/topologyId/test_endpoint.py index e8cfdd99..b210479e 100644 --- a/web-server/opendc/api/v2/topologies/topologyId/test_endpoint.py +++ b/web-server/opendc/api/v2/topologies/topologyId/test_endpoint.py @@ -1,39 +1,48 @@ from opendc.util.database import DB - ''' GET /topologies/{topologyId} ''' + def test_get_topology(client, mocker): - mocker.patch.object(DB, 'fetch_one', return_value={ + mocker.patch.object(DB, + 'fetch_one', + return_value={ '_id': '1', + 'simulationId': '1', 'authorizations': [{ - 'topologyId': '1', + 'simulationId': '1', 'authorizationLevel': 'EDIT' }] }) - res = client.get('/api/v2/topologies/1') - assert '200' in res.status + res = client.get('/api/v2/topologies/1') + assert '200' in res.status + def test_get_topology_non_existing(client, mocker): - mocker.patch.object(DB, 'fetch_one', return_value=None) - assert '404' in client.get('/api/v2/topologies/1').status + mocker.patch.object(DB, 'fetch_one', return_value=None) + assert '404' in client.get('/api/v2/topologies/1').status + def test_get_topology_not_authorized(client, mocker): - mocker.patch.object(DB, 'fetch_one', return_value={ + mocker.patch.object(DB, + 'fetch_one', + return_value={ '_id': '1', + 'simulationId': '1', 'authorizations': [{ - 'topologyId': '2', + 'simulationId': '2', 'authorizationLevel': 'OWN' }] }) - res = client.get('/api/v2/topologies/1') - assert '403' in res.status + res = client.get('/api/v2/topologies/1') + assert '403' in res.status + def test_get_topology_no_authorizations(client, mocker): - mocker.patch.object(DB, 'fetch_one', return_value={'authorizations': []}) - res = client.get('/api/v2/topologies/1') - assert '403' in res.status + mocker.patch.object(DB, 'fetch_one', return_value={'authorizations': []}) + res = client.get('/api/v2/topologies/1') + assert '403' in res.status ''' @@ -44,8 +53,3 @@ PUT /topologies/{topologyId} ''' DELETE /topologies/{topologyId} ''' - -def test_delete_topology(client, mocker): - mocker.patch.object(DB, 'fetch_one', return_value={'_id': '1'}) - res = client.delete('/api/v2/topologies/1') - assert '200' in res.status
\ No newline at end of file diff --git a/web-server/opendc/api/v2/traces/endpoint.py b/web-server/opendc/api/v2/traces/endpoint.py index 720c6a1e..ee699e02 100644 --- a/web-server/opendc/api/v2/traces/endpoint.py +++ b/web-server/opendc/api/v2/traces/endpoint.py @@ -2,7 +2,7 @@ from opendc.models.trace import Trace from opendc.util.rest import Response -def GET(request): +def GET(_): """Get all available Traces.""" traces = Trace.get_all() diff --git a/web-server/opendc/api/v2/traces/traceId/endpoint.py b/web-server/opendc/api/v2/traces/traceId/endpoint.py index 672e256c..670f88d1 100644 --- a/web-server/opendc/api/v2/traces/traceId/endpoint.py +++ b/web-server/opendc/api/v2/traces/traceId/endpoint.py @@ -11,4 +11,4 @@ def GET(request): trace.check_exists() - return Response(200, f'Successfully retrieved trace.', trace.obj) + return Response(200, 'Successfully retrieved trace.', trace.obj) diff --git a/web-server/opendc/api/v2/users/endpoint.py b/web-server/opendc/api/v2/users/endpoint.py index c6041756..c597732f 100644 --- a/web-server/opendc/api/v2/users/endpoint.py +++ b/web-server/opendc/api/v2/users/endpoint.py @@ -1,6 +1,4 @@ from opendc.models.user import User -from opendc.util import exceptions -from opendc.util.database import DB from opendc.util.rest import Response @@ -13,7 +11,7 @@ def GET(request): user.check_exists() - return Response(200, f'Successfully retrieved user.', user.obj) + return Response(200, 'Successfully retrieved user.', user.obj) def POST(request): @@ -28,4 +26,4 @@ def POST(request): user.check_already_exists() user.insert() - return Response(200, f'Successfully created user.', user.obj) + return Response(200, 'Successfully created user.', user.obj) diff --git a/web-server/opendc/api/v2/users/userId/endpoint.py b/web-server/opendc/api/v2/users/userId/endpoint.py index e68a2bb3..660083b6 100644 --- a/web-server/opendc/api/v2/users/userId/endpoint.py +++ b/web-server/opendc/api/v2/users/userId/endpoint.py @@ -1,5 +1,4 @@ from opendc.models.user import User -from opendc.util import exceptions from opendc.util.rest import Response @@ -12,7 +11,7 @@ def GET(request): user.check_exists() - return Response(200, f'Successfully retrieved user.', user.obj) + return Response(200, 'Successfully retrieved user.', user.obj) def PUT(request): @@ -34,7 +33,7 @@ def PUT(request): user.update() - return Response(200, f'Successfully updated user.', user.obj) + return Response(200, 'Successfully updated user.', user.obj) def DELETE(request): @@ -49,4 +48,4 @@ def DELETE(request): user.delete() - return Response(200, f'Successfully deleted user.', user.obj) + return Response(200, 'Successfully deleted user.', user.obj) |
