summaryrefslogtreecommitdiff
path: root/web-server/opendc/api/v2/simulations/simulationId
diff options
context:
space:
mode:
authorjc0b <j@jc0b.computer>2020-06-30 14:12:07 +0200
committerFabian Mastenbroek <mail.fabianm@gmail.com>2020-08-24 19:43:10 +0200
commit66b2d85385d05abb590535da60341876ecdbab71 (patch)
tree0656f64a4179d419adac86e488e21def7a7fa2b8 /web-server/opendc/api/v2/simulations/simulationId
parent88d8a9cbeae3466230db6bd13120bd4438abbc66 (diff)
parentc99ef7504a1374170f88b89faeb7e6dec6a55253 (diff)
Merge changes with upstream
Diffstat (limited to 'web-server/opendc/api/v2/simulations/simulationId')
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py34
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/authorizations/test_endpoint.py40
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/__init__.py0
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py178
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/endpoint.py7
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/experiments/endpoint.py106
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/experiments/test_endpoint.py78
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/test_endpoint.py3
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/topologies/endpoint.py3
-rw-r--r--web-server/opendc/api/v2/simulations/simulationId/topologies/test_endpoint.py14
10 files changed, 167 insertions, 296 deletions
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