Exemplo n.º 1
0
 def test__parse_path(self):
     manager = KBaseWSManager()
     cases = [
         ("123", NarrativeRef({
             "wsid": "123",
             "objid": None,
             "ver": None
         })),
         ("ws.123", NarrativeRef({
             "wsid": "123",
             "objid": None,
             "ver": None
         })),
         (
             "ws.123.obj.456",
             NarrativeRef({
                 "wsid": "123",
                 "objid": "456",
                 "ver": None
             }),
         ),
         (
             "ws.123.obj.456.ver.7",
             NarrativeRef({
                 "wsid": "123",
                 "objid": "456",
                 "ver": "7"
             }),
         ),
     ]
     for c in cases:
         self.assertEqual(c[1], manager._parse_path(c[0]))
Exemplo n.º 2
0
    def test_ref_init_fail(self):
        with self.assertRaises(ValueError) as e:
            NarrativeRef({"wsid": "x", "objid": None, "ver": None})
        self.assertIn("A numerical Workspace id is required for a Narrative ref, not x", str(e.exception))

        with self.assertRaises(ValueError) as e:
            NarrativeRef({"wsid": 678, "objid": "x", "ver": None})
        self.assertIn("objid must be numerical, not x", str(e.exception))

        with self.assertRaises(ValueError) as e:
            NarrativeRef({"wsid": 678, "objid": 1, "ver": "x"})
        self.assertIn("If ver is present in the ref, it must be numerical, not x", str(e.exception))
Exemplo n.º 3
0
def str_to_ref(s):
    """ Takes a ref string, returns a NarrativeRef object """
    vals = s.split("/")
    ref = {"wsid": vals[0], "objid": vals[1]}
    if len(vals) == 3:
        ref["ver"] = vals[2]
    return NarrativeRef(ref)
Exemplo n.º 4
0
def upload_narrative(nar_file, auth_token, user_id, url=ci_ws, set_public=False):
    """
    Uploads a Narrative from a downloaded object file.
    This file needs to be in JSON format, and it expects all
    data and info that is usually returned by the Workspace.get_objects
    method.

    Returns a dict of three elements:
        ws: the id of the workspace that was created
        obj: the id of the narrative object
        ref: the above two joined together into an object ref (for convenience)
    """

    # read the file
    f = open(nar_file, "r")
    nar = json.loads(f.read())
    f.close()

    # do some setup.
    current_nar_metadata = ws_metadata
    current_nar_metadata["narrative_nice_name"] = nar["data"]["metadata"]["name"]
    ws_client = Workspace(url=url, token=auth_token)

    # create the new workspace for the narrative
    ws_info = ws_client.create_workspace(
        {
            "workspace": "{}:{}".format(user_id, str(time.time()).replace(".", "")),
            "meta": current_nar_metadata,
            "globalread": "r" if set_public else "n",
        }
    )
    ws_id = ws_info[0]

    # setup and save the narrative object
    nar["info"][10]
    ws_save_obj = {
        "type": "KBaseNarrative.Narrative",
        "data": nar["data"],
        "name": nar["info"][1],
        "meta": nar["info"][10],
        "provenance": [
            {
                "script": "upload_narrative_test.py",
                "description": "Temporary Narrative uploaded for automated testing",
            }
        ],
    }
    obj_info = ws_client.save_objects({"id": ws_id, "objects": [ws_save_obj]})

    # tweak the workspace's metadata to properly present its narrative
    ws_client.alter_workspace_metadata(
        {"wsi": {"id": ws_id}, "new": {"narrative": obj_info[0][0]}}
    )
    return {
        "ws": ws_info[0],
        "obj": obj_info[0][0],
        "refstr": "{}/{}".format(ws_info[0], obj_info[0][0]),
        "ref": NarrativeRef({"wsid": ws_info[0], "objid": obj_info[0][0]}),
    }
Exemplo n.º 5
0
def upload_narrative(nar_file, auth_token, user_id, url=ci_ws, set_public=False):
    """
    Uploads a Narrative from a downloaded object file.
    This file needs to be in JSON format, and it expects all
    data and info that is usually returned by the Workspace.get_objects
    method.

    Returns a dict of three elements:
        ws: the id of the workspace that was created
        obj: the id of the narrative object
        ref: the above two joined together into an object ref (for convenience)
    """

    # read the file
    f = open(nar_file, 'r')
    nar = json.loads(f.read())
    f.close()

    # do some setup.
    current_nar_metadata = ws_metadata
    current_nar_metadata['narrative_nice_name'] = nar['data']['metadata']['name']
    ws_client = Workspace(url=url, token=auth_token)

    # create the new workspace for the narrative
    ws_info = ws_client.create_workspace({
        'workspace': '{}:{}'.format(user_id, str(time.time()).replace('.', '')),
        'meta': current_nar_metadata,
        'globalread': 'r' if set_public else 'n'
    })
    ws_id = ws_info[0]

    # setup and save the narrative object
    metadata = nar['info'][10]
    ws_save_obj = {
        'type': 'KBaseNarrative.Narrative',
        'data': nar['data'],
        'name': nar['info'][1],
        'meta': nar['info'][10],
        'provenance': [{
            'script': 'upload_narrative_test.py',
            'description': 'Temporary Narrative uploaded for automated testing'
        }]
    }
    obj_info = ws_client.save_objects({'id': ws_id,
                                       'objects': [ws_save_obj]})

    # tweak the workspace's metadata to properly present its narrative
    ws_client.alter_workspace_metadata({'wsi': {'id': ws_id}, 'new': {'narrative': obj_info[0][0]}})
    return {
        'ws': ws_info[0],
        'obj': obj_info[0][0],
        'refstr': '{}/{}'.format(ws_info[0], obj_info[0][0]),
        'ref': NarrativeRef({'wsid': ws_info[0], 'objid': obj_info[0][0]})
    }
Exemplo n.º 6
0
    def _parse_path(self, path):
        """
        From the URL path for a Narrative, returns a NarrativeRef

        if the path isn't parseable, this raises a 404 with the invalid path.
        """
        path = path.strip("/")
        m = self.path_regex.match(path)
        if m is None:
            raise HTTPError(404, "Invalid Narrative path {}".format(path))
        try:
            return NarrativeRef(
                dict(wsid=m.group("wsid"), objid=m.group("objid"), ver=m.group("ver"))
            )
        except RuntimeError as e:
            raise HTTPError(500, str(e))
        except WorkspaceError as e:
            raise HTTPError(e.http_code, e.message)
Exemplo n.º 7
0
 def test_no_ws_perm(self):
     with self.assertRaises(WorkspaceError) as e:
         NarrativeRef({"wsid": 789, "objid": None, "ver": None})
     self.assertEqual(403, e.exception.http_code)
     self.assertIn("You do not have access to this workspace", e.exception.message)
Exemplo n.º 8
0
 def test_no_objid_fail(self):
     with self.assertRaises(RuntimeError) as e:
         NarrativeRef({"wsid": 678, "objid": None, "ver": None})
     self.assertIn("Couldn't find Narrative object id in Workspace metadata", str(e.exception))
Exemplo n.º 9
0
 def test_ok(self):
     ref = NarrativeRef({"wsid": 123, "objid": 456, "ver": 7})
     self.assertEqual(ref.wsid, 123)
     self.assertEqual(ref.objid, 456)
     self.assertEqual(ref.ver, 7)
Exemplo n.º 10
0
 def test_no_objid_ok(self):
     ref = NarrativeRef({"wsid": 123, "objid": None, "ver": None})
     self.assertEqual(ref.wsid, 123)
     self.assertEqual(ref.objid, 1)
     self.assertIsNone(ref.ver)