Пример #1
0
    def dumps(self, obj, **kwargs):
        """
        Serialize a gemd object, or container of them, into a json-formatting string.

        Parameters
        ----------
        obj: DictSerializable or List[DictSerializable]
            The object(s) to serialize to a string.
        **kwargs: keyword args, optional
            Optional keyword arguments to pass to `json.dumps()`.

        Returns
        -------
        str
            A string version of the serialized objects.

        """
        # create a top level list of [flattened_objects, link-i-fied return value]
        res = {"object": obj}
        additional = flatten(res)
        res = substitute_links(res)
        res["context"] = additional
        return json_builtin.dumps(res,
                                  cls=GEMDEncoder,
                                  sort_keys=True,
                                  **kwargs)
Пример #2
0
def test_pure_subsitutions():
    """Make sure substitute methods don't mutate inputs."""
    json_str = '''
          [
            [
              {
                "uids": {
                  "id": "9118c2d3-1c38-47fe-a650-c2b92fdb6777"
                },
                "type": "material_run",
                "name": "flour"
              }
            ],
            {
              "type": "ingredient_run",
              "uids": {
                "id": "8858805f-ec02-49e4-ba3b-d784e2aea3f8"
              },
              "material": {
                "type": "link_by_uid",
                "scope": "ID",
                "id": "9118c2d3-1c38-47fe-a650-c2b92fdb6777"
              },
              "process": {
                "type": "link_by_uid",
                "scope": "ID",
                "id": "9148c2d3-2c38-47fe-b650-c2b92fdb6777"
              }
            }
          ]
       '''
    index = {}
    original = json.loads(
        json_str, object_hook=lambda x: GEMDJson()._load_and_index(x, index))
    frozen = deepcopy(original)
    loaded = substitute_objects(original, index)
    assert original == frozen
    frozen_loaded = deepcopy(loaded)
    substitute_links(loaded)
    assert loaded == frozen_loaded
    for o in loaded:
        substitute_links(o)
    assert loaded == frozen_loaded
Пример #3
0
    def thin_dumps(self, obj, **kwargs):
        """
        Serialize a "thin" version of an object in which pointers are replaced by links.

        Parameters
        ----------
        obj:
            Object to dump
        **kwargs: keyword args, optional
            Optional keyword arguments to pass to `json.dumps()`.

        Returns
        -------
        str
            A serialized string of `obj`, with link_by_uid in place of pointers to other objects.

        """
        set_uuids(obj)
        res = substitute_links(obj)
        return json_builtin.dumps(res,
                                  cls=GEMDEncoder,
                                  sort_keys=True,
                                  **kwargs)