Kaynağa Gözat

Many updates to wrapper

Yentl Van Tendeloo 8 yıl önce
ebeveyn
işleme
04595ebdee
2 değiştirilmiş dosya ile 239 ekleme ve 169 silme
  1. 238 168
      wrappers/modelverse.py
  2. 1 1
      wrappers/test_modelverse.py

+ 238 - 168
wrappers/modelverse.py

@@ -42,7 +42,7 @@ def _compile_AL(code):
         f.write(code)
         f.flush()
 
-    _input(do_compile("__constraint.alc", "../interface/HUTN/grammars/actionlanguage.g", "CS"))
+    return do_compile("__constraint.alc", "../interface/HUTN/grammars/actionlanguage.g", "CS")
 
 def _compile_model(code):
     # Compile a model and send the compiled graph
@@ -59,15 +59,17 @@ def _compile_model(code):
         f.write(code)
         f.flush()
 
-    _input(do_compile("__model.mvc", "../interface/HUTN/grammars/modelling.g", "M") + ["exit"])
+    return do_compile("__model.mvc", "../interface/HUTN/grammars/modelling.g", "M") + ["exit"]
 
-def _output():
+def _output(expected=None):
     try:
         global last_output
         last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read())
-        return last_output
     except:
         raise UnknownError()
+    if expected is not None and last_output != expected:
+        raise InterfaceMismatch(last_output)
+    return last_output
 
 def _last_output():
     return last_output
@@ -116,6 +118,9 @@ class PermissionDenied(ModelverseException):
 class InvalidMode(ModelverseException):
     pass
 
+class InterfaceMismatch(ModelverseException):
+    pass
+
 # Main MvC operations
 def init(address_param="http://localhost:8001"):
     """Starts up the connection to the Modelverse."""
@@ -135,31 +140,41 @@ def init(address_param="http://localhost:8001"):
         raise ConnectionError(e.reason)
 
 def login(username, password):
-    """Log in an existing user."""
+    """Log in a user, if user doesn't exist, it is created."""
     # return None
     # raises UnknownError
     # raises PermissionDenied
+    # raises InterfaceMismatch
     global mode
     if mode != 1:
         raise InvalidMode()
+    _output("Log on as which user?")
     _input(username)
-    _input(password)
-    _consume_to_end()
-    mode = 2
-
-def register(username, password):
-    """Register a new user."""
-    # return None
-    # raises UnknownError
-    # raises UserExists
-    global mode
-    if mode != 1:
-        raise InvalidMode()
-    _input(username)
-    _input(password)
-    _input(password)
-    _consume_to_end()
-    mode = 2
+    if _output() == "User password?":
+        _input(password)
+        if _output() == "Welcome to the Model Management Interface v2.0!":
+            _output("Use the 'help' command for a list of possible commands")
+            _output("Ready for command...")
+            mode = 2
+        elif _last_output() == "Wrong password!":
+            raise PermissionDenied()
+        else:
+            raise InterfaceMismatch(_last_output())
+    elif _output() == "This is a new user: please give password!":
+        _input(password)
+        _output("Please repeat the password")
+        _input(password)
+        if _output() == "Welcome to the Model Management Interface v2.0!":
+            _output("Use the 'help' command for a list of possible commands")
+            _output("Ready for command...")
+            mode = 2
+        elif _last_output() == "Not the same password!":
+            # We just sent the same password, so it should be identical, unless the interface changed
+            raise InterfaceMismatch(_last_output())
+        else:
+            raise InterfaceMismatch(_last_output())
+    else:
+        raise InterfaceMismatch(_last_output())
 
 def model_add(model_name, metamodel_name, model_code=None):
     """Instantiate a new model."""
@@ -171,29 +186,35 @@ def model_add(model_name, metamodel_name, model_code=None):
     # raises CompilationError
     if mode != 2:
         raise InvalidMode()
+    # Do this before creating the model, as otherwise compilation errors would make us inconsistent
+    if model_code is not None:
+        try:
+            compiled = _compile_model(model_code)
+        except:
+            raise CompilationError()
+    else:
+        compiled = ["exit"]
+
     _input("model_add")
-    _output()
-    _output()
+    _output("Creating new model!")
+    _output("Model type?")
     _input(metamodel_name)
     if _output() == "Model name?":
         _input(model_name)
         if _output() == "Waiting for model constructors...":
-            try:
-                if model_code == None:
-                    _input("exit")
-                else:
-                    _compile_model(model_code)
-            except Exception:
-                raise CompilationError()
-            _consume_to_end()
-        else:
-            _consume_to_end()
+            _input(compiled)
+            _output("Model upload success!")
+            _output("Ready for command...")
+        elif _last_output() == "Model with that name already exists!":
+            _output("Ready for command...")
             raise ModelExists()
-    elif _last_output() == "Could not find type model!":
-        _consume_to_end()
+        else:
+            raise InterfaceMismatch(_last_output())
+    elif _last_output().startswith("Could not find type model"):
+        _output("Ready for command...")
         raise UnknownModel()
     elif _last_output() == "Permission denied":
-        _consume_to_end()
+        _output("Ready for command...")
         raise PermissionDenied()
 
 def model_modify(model_name):
@@ -207,13 +228,13 @@ def model_modify(model_name):
         raise InvalidMode()
 
     _input("model_modify")
-    _output()
+    _output("Which model do you want to modify?")
     _input(model_name)
     if _output() == "Permission denied":
-        _consume_to_end()
+        _output("Ready for command...")
         raise PermissionDenied()
     elif _last_output() == "Could not find model!":
-        _consume_to_end()
+        _output("Ready for command...")
         raise UnknownModel()
     elif _last_output() == "Model loaded, ready for commands!":
         mode = 3
@@ -221,11 +242,11 @@ def model_modify(model_name):
             write = True
         else:
             write = False
-        _consume_to_end()
+        _output("Use 'help' command for a list of possible commands")
+        _output("Please give your command.")
         return write
     else:
-        _consume_to_end()
-        raise UnknownException()
+        raise InterfaceMismatch()
 
 def model_list():
     """List all models."""
@@ -260,7 +281,7 @@ def model_list_full():
         lst.append((m, mm, own, grp, perm))
     return lst
 
-def model_overwrite(model_name, new_model):
+def model_overwrite(model_name, new_model=None):
     """Upload a new model and overwrite an existing model."""
     # return None
     # raises UnknownModel
@@ -269,29 +290,136 @@ def model_overwrite(model_name, new_model):
     # raises UnknownError
     if mode != 2:
         raise InvalidMode()
+
+    if new_model is not None:
+        try:
+            compiled = _compile_model(new_model)
+        except Exception as e:
+            raise CompilationError(e)
+    else:
+        compiled = ["exit"]
+
     _input("model_overwrite")
+    _output("Which model to overwrite?")
     _input(model_name)
-    _compile_model(new_model)
+    if _output() == "Permission denied":
+        _output("Ready for command...")
+        raise PermissionDenied()
+    elif _last_output() == "No such model":
+        _output("Ready for command...")
+        raise UnknownModel()
+    elif _last_output() == "Waiting for model constructors...":
+        _input(compiled)
+        _output("Model overwrite success")
+        _output("Ready for command...")
 
 def user_logout():
-    """Log out the current user. A new login will be required afterwards."""
+    """Log out the current user and break the connection."""
     # return None
     # raises UnknownException
     global mode
     if mode != 2:
         raise InvalidMode()
     _input("exit")
-    mode = 1
+    mode = 0
 
 def user_delete():
-    """Removes the current user. A new login will be required afterwards."""
+    """Removes the current user and break the connection."""
     # return None
     # raises UnknownException
     global mode
     if mode != 2:
         raise InvalidMode()
     _input("self-destruct")
-    mode = 1
+    mode = 0
+
+def transformation_add_MT_language():
+    """Create a new Model Transformation language out of a set of metamodels."""
+    raise NotImplementedError()
+
+def transformation_add_MT():
+    """Create a new model transformation."""
+    raise NotImplementedError()
+
+def transformation_add_AL():
+    """Create a new action language fragment."""
+    raise NotImplementedError()
+
+def transformation_add_MANUAL():
+    """Create a new manual model operation."""
+    raise NotImplementedError()
+
+def transformation_execute():
+    """Execute an existing model operation."""
+    raise NotImplementedError()
+
+def transformation_list():
+    """List existing model operations."""
+    raise NotImplementedError()
+
+def transformation_list_full():
+    """List detailed information on model operations."""
+    raise NotImplementedError()
+
+def transformation_detail():
+    """List full details of a a model operation."""
+    raise NotImplementedError()
+
+def transformation_RAMify():
+    """Ramify an existing metamodel."""
+    raise NotImplementedError()
+
+def process_execute():
+    """Execute a process model."""
+    raise NotImplementedError()
+
+def permission_modify():
+    """Modify permissions of a model."""
+    raise NotImplementedError()
+
+def permission_owner():
+    """Modify the owning user of a model."""
+    raise NotImplementedError()
+
+def permission_group():
+    """Modify the owning group of a model."""
+    raise NotImplementedError()
+
+def group_create():
+    """Create a new group."""
+    raise NotImplementedError()
+
+def group_delete():
+    """Delete a group of which you are an owner."""
+    raise NotImplementedError()
+
+def group_owner_add():
+    """Add a new owning user to a group you own."""
+    raise NotImplementedError()
+
+def group_owner_delete():
+    """Delete an owning user to a group you own."""
+    raise NotImplementedError()
+
+def group_join():
+    """Add a new user to a group you own."""
+    raise NotImplementedError()
+
+def group_kick():
+    """Delete a user from a group you own."""
+    raise NotImplementedError()
+
+def group_list():
+    """List existing groups."""
+    raise NotImplementedError()
+
+def admin_promote():
+    """Promote a user to admin status."""
+    raise NotImplementedError()
+
+def admin_demote():
+    """Demote a user from admin status."""
+    raise NotImplementedError()
 
 # Actual operations on the model
 def element_list():
@@ -302,7 +430,7 @@ def element_list():
         raise InvalidMode()
     _input("list")
     lst = []
-    _output()
+    _output("List of all elements:")
     while (_output() != "Please give your command."):
         v = _last_output()
         m, mm = v.split(":")
@@ -318,7 +446,7 @@ def types():
     if mode != 3:
         raise InvalidMode()
     _input("types")
-    _output()
+    _output("List of all types:")
     lst = []
     while (_output() != "Please give your command."):
         v = _last_output()
@@ -335,11 +463,11 @@ def read(ID):
     if mode != 3:
         raise InvalidMode()
     _input("read")
-    _output()
+    _output("Element to read?")
     _input(ID)
-    _output()
+    _output("ID: " + str(ID))
     if _last_output() == "Unknown element; aborting":
-        _consume_to_end()
+        _output("Please give your command.")
         raise UnknownIdentifier()
     else:
         t = _output().split(":")[1].strip()
@@ -361,14 +489,15 @@ def read_attrs(ID):
     if mode != 3:
         raise InvalidMode()
     _input("read")
-    _output()
+    _output("Element to read?")
     _input(ID)
-    _output()
+    _output("ID: " + str(ID))
     if _last_output() == "Unknown element; aborting":
-        _consume_to_end()
+        _output("Please give your command.")
         raise UnknownIdentifier()
     else:
         rval = {}
+        # Skip until attributes
         while (_output() != "Attributes:"):
             pass
         while (_output() != "Please give your command."):
@@ -392,49 +521,65 @@ def instantiate(typename, edge=None, ID=""):
         raise InvalidMode()
     _input("instantiate")
     if (_output() == "Permission denied"):
-        _consume_to_end()
+        _output("Please give your command.")
         raise PermissionDenied()
     else:
         _input(typename)
         if (_output() == "Name of new element?"):
             _input(ID)
             if (_output() == "Element already exists; aborting"):
-                _consume_to_end()
+                _output("Please give your command.")
                 raise ElementExists()
 
-            if (edge is not None):
-                if (_last_output() == "Source name?"):
-                    _input(edge[0])
-                    if (_output() != "Destination name?"):
-                        _consume_to_end()
-                        raise UnknownIdentifier()
+            if (edge is not None) and (_last_output() == "Source name?"):
+                # Is an edge and we have data
+                _input(edge[0])
+                if _output() == "Destination name?":
                     _input(edge[1])
-                    ID = _output()
-                    if (ID == "Unknown destination; aborting"):
-                        _consume_to_end()
+                    if _output() == "Instantiation successful!":
+                        ID = _output()
+                        _output("Please give your command.")
+                        return ID
+                    elif _last_output() == "Unknown destination; aborting":
+                        _output("Please give your command.")
                         raise UnknownIdentifier()
                     else:
-                        _consume_to_end()
-                        return ID
+                        raise InterfaceMismatch(_last_output())
+                elif _last_output() == "Unknown source; aborting":
+                    _output("Please give your command.")
+                    raise UnknownIdentifier()
                 else:
-                    _consume_to_end()
-                    raise NotAnEdge()
-            else:
+                    raise InterfaceMismatch(_last_output())
+            elif (edge is None) and (_last_output() != "Source name?"):
+                # Is no edge and we don't have data
                 ID = _last_output()
-                _consume_to_end()
+                _output("Please give your command.")
                 return ID
+            elif (edge is not None) and (_last_output() != "Source name?"):
+                # Is no edge, but we have edge data to input: ERROR
+                # Delete the element again
+                ID = _last_output()
+                _output("Please give your command.")
+                delete_element(ID)
+                raise NotAnEdge()
+            elif (edge is None) and (_last_output() == "Source name?"):
+                # Is an edge, but we have no edge data to input: ERROR
+                # Add an empty source, which is guaranteed not to be there
+                _input("")
+                _output("Unknown source; aborting")
+                _output("Please give your command.")
+                raise NotAnEdge()
 
         elif (_last_output() == "Permission denied"):
-            _consume_to_end()
+            _output("Please give your command.")
             raise PermissionDenied()
         elif (_last_output() == "Unknown type specified; aborting"):
-            _consume_to_end()
+            _output("Please give your command.")
             raise UnknownType()
         else:
-            print(9)
-            print(_last_output())
+            raise InterfaceMismatch(_last_output())
 
-def delete(ID):
+def delete_element(ID):
     """Delete the element with the given ID"""
     # return None
     # raises UnknownError
@@ -442,7 +587,20 @@ def delete(ID):
     if mode != 3:
         raise InvalidMode()
     _input("delete")
-    _input(ID)
+    if _output() == "What is the name of the element you want to delete?":
+        _input(ID)
+        if _output() == "Deleted!":
+            _output("Please give your command.")
+        elif _last_output() == "No such element; aborting":
+            _output("Please give your command.")
+            raise UnknownIdentifier()
+        else:
+            raise InterfaceMismatch(_last_output())
+    elif _output() == "Permission denied":
+        _output("Please give your command.")
+        raise PermissionDenied()
+    else:
+        raise InterfaceMismatch(_last_output())
 
 def attr_assign(ID, attr, value):
     """Assign a value to an attribute"""
@@ -541,91 +699,3 @@ def model_exit():
     _input("exit")
     _consume_to_end()
     mode = 2
-
-def transformation_add_MT_language():
-    """Create a new Model Transformation language out of a set of metamodels."""
-    raise NotImplementedError()
-
-def transformation_add_MT():
-    """Create a new model transformation."""
-    raise NotImplementedError()
-
-def transformation_add_AL():
-    """Create a new action language fragment."""
-    raise NotImplementedError()
-
-def transformation_add_MANUAL():
-    """Create a new manual model operation."""
-    raise NotImplementedError()
-
-def transformation_execute():
-    """Execute an existing model operation."""
-    raise NotImplementedError()
-
-def transformation_list():
-    """List existing model operations."""
-    raise NotImplementedError()
-
-def transformation_list_full():
-    """List detailed information on model operations."""
-    raise NotImplementedError()
-
-def transformation_detail():
-    """List full details of a a model operation."""
-    raise NotImplementedError()
-
-def transformation_RAMify():
-    """Ramify an existing metamodel."""
-    raise NotImplementedError()
-
-def process_execute():
-    """Execute a process model."""
-    raise NotImplementedError()
-
-def permission_modify():
-    """Modify permissions of a model."""
-    raise NotImplementedError()
-
-def permission_owner():
-    """Modify the owning user of a model."""
-    raise NotImplementedError()
-
-def permission_group():
-    """Modify the owning group of a model."""
-    raise NotImplementedError()
-
-def group_create():
-    """Create a new group."""
-    raise NotImplementedError()
-
-def group_delete():
-    """Delete a group of which you are an owner."""
-    raise NotImplementedError()
-
-def group_owner_add():
-    """Add a new owning user to a group you own."""
-    raise NotImplementedError()
-
-def group_owner_delete():
-    """Delete an owning user to a group you own."""
-    raise NotImplementedError()
-
-def group_join():
-    """Add a new user to a group you own."""
-    raise NotImplementedError()
-
-def group_kick():
-    """Delete a user from a group you own."""
-    raise NotImplementedError()
-
-def group_list():
-    """List existing groups."""
-    raise NotImplementedError()
-
-def admin_promote():
-    """Promote a user to admin status."""
-    raise NotImplementedError()
-
-def admin_demote():
-    """Demote a user from admin status."""
-    raise NotImplementedError()

+ 1 - 1
wrappers/test_modelverse.py

@@ -7,7 +7,7 @@ model_name = str(random())
 model_name2 = str(random())
 
 init()
-register(username, password)
+login(username, password)
 
 model_add(model_name, "SimpleClassDiagrams", open("../models/petrinet_ports.mvc", "r").read())
 model_modify("SimpleClassDiagrams")