Beispiel #1
0
def read(fpath, encoding=None, decode=True):
    """Reads a document from file system.

    :param str fpath: Path to previously saved file.
    :param str encoding: Encoding to use during deserialization.
    :param bool decode: Flag indicating whether document will be decoded.

    :returns: A pyesdoc document instance.
    :rtype: object

    """
    # Validate file path.
    if not os.path.isfile(fpath):
        raise IOError("Document file path does not exist")

    # Optionally derive encoding from file extension.
    if encoding is None:
        encoding = os.path.splitext(fpath)[1][1:]

    # Set raw content.
    with open(fpath, "r") as fstream:
        fcontent = str_to_unicode(fstream.read())

    # Decode upon request.
    return pyesdoc.decode(fcontent, encoding) if decode else fcontent
Beispiel #2
0
def read(fpath, encoding=None, decode=True):
    """Reads a document from file system.

    :param str fpath: Path to previously saved file.
    :param str encoding: Encoding to use during deserialization.
    :param bool decode: Flag indicating whether document will be decoded.

    :returns: A pyesdoc document instance.
    :rtype: object

    """
    fpath = os.path.expanduser(fpath)

    # Validate file path.
    if not os.path.isfile(fpath):
        raise IOError("Document file path does not exist")

    # Optionally derive encoding from file extension.
    if encoding is None:
        encoding = os.path.splitext(fpath)[1][1:]

    # Set raw content.
    with open(fpath, 'r') as fstream:
        fcontent = str_to_unicode(fstream.read())

    # Decode upon request.
    return pyesdoc.decode(fcontent, encoding) if decode else fcontent
def _do_test(encoding):
    """Executes a serialization test."""
    for desc in (_get_description(t) for t in (str, unicode)):
        _MODEL.description = desc
        representation = pyesdoc.encode(_MODEL, encoding)
        tu.assert_object(representation, str)
        as_doc = pyesdoc.decode(representation, encoding)
        tu.assert_object(as_doc, cim.v1.ModelComponent)
def _do_test(encoding):
    """Executes a serialization test."""
    for desc in (_get_description(t) for t in (str, unicode)):
        _MODEL.description = desc
        representation = pyesdoc.encode(_MODEL, encoding)
        tu.assert_object(representation, str)
        as_doc = pyesdoc.decode(representation, encoding)
        tu.assert_object(as_doc, cim.v1.ModelComponent)
Beispiel #5
0
def decode(doc, encoding):
    """Decode a document representation."""
    # Decode.
    doc = pyesdoc.decode(doc, encoding)

    # Perform basic assertions.
    assert doc is not None
    assert isinstance(doc, object)

    return doc
Beispiel #6
0
def decode(doc, encoding):
    """Decode a document representation."""
    # Decode.
    doc = pyesdoc.decode(doc, encoding)

    # Perform basic assertions.
    assert doc is not None
    assert isinstance(doc, object)

    return doc
def _test_retrieve(encoding):
	"""Tests retrieving a specific document encoding."""
	params = _URL_GET_PARAMS.format(encoding, _DOC.meta.id, _DOC.meta.version)
	url = "{}{}".format(_URL_GET, params)
	response = requests.get(url)
	assert response.status_code == 200

	if encoding != 'html':
		doc = pyesdoc.decode(response.text, encoding)
		assert doc.meta.id == _DOC.meta.id
		assert doc.meta.version == _DOC.meta.version
		if pyesdoc.encode(_DOC, encoding) != response.text:
			pass
def test_republish():
	"""ES-DOC :: WS :: Test republishing a document.

	"""
	_DOC.rationale = "to restate the bleeding obvious"
	_DOC.meta.version += 1

	data = pyesdoc.encode(_DOC, 'json')
	headers = {'Content-Type': 'application/json'}
	url = _URL_PUT
	response = requests.put(url, data=data, headers=headers)
	assert response.status_code == 200

	params = _URL_GET_PARAMS.format('json', _DOC.meta.id, _DOC.meta.version)
	url = "{}{}".format(_URL_GET, params)
	response = requests.get(url)
	assert response.status_code == 200

	doc = pyesdoc.decode(response.text, 'json')
	assert doc.meta.id == _DOC.meta.id
	assert doc.meta.version == _DOC.meta.version
	assert doc.rationale == "to restate the bleeding obvious"
Beispiel #9
0
        def _validate_request_body():
            """Validates request body.

            """
            # Decode document.
            doc = pyesdoc.decode(self.request.body, 'json')
            if not doc:
                raise exceptions.DocumentDecodingException()

            # Minimally validate document.
            if not pyesdoc.is_valid(doc):
                raise exceptions.DocumentInvalidException()

            # Validate document version.
            if doc.meta.version <= 0:
                raise exceptions.DocumentInvalidException("Version must be > 0")

            # Validate document publishing state.
            if pyesdoc.archive.exists(doc.meta.id, doc.meta.version):
                raise exceptions.DocumentPublishedException()

            # Validation passed therefore cache decoded & extended payload.
            self.doc = pyesdoc.extend(doc)
Beispiel #10
0
    for index, input_dict in enumerate(inputs):
        # Return machine doc with applicable models and experiments:
        cim_out, apply_models_out, appl_exp_out = generate_outputs(
            input_dict,
            two_c_pools=two_c_pools[index],
            two_s_pools=two_s_pools[index],
            docs_given=has_docs[index])

        # Validate the CIM document - there should not be any errors
        if pyesdoc.is_valid(cim_out):
            print("Complete: machine CIM document generated and is valid.")
        else:
            print("Machine CIM document generated is not valid:")
            for err in pyesdoc.validate(cim_out):
                print(err)

        # Test serialisation of the machine doc...
        j = pyesdoc.encode(cim_out, pyesdoc.constants.ENCODING_JSON)
        assert json.loads(j)
        assert isinstance(pyesdoc.decode(j, pyesdoc.constants.ENCODING_JSON),
                          cim.Machine)

        x = pyesdoc.encode(cim_out, pyesdoc.constants.ENCODING_XML)
        assert isinstance(pyesdoc.decode(x, pyesdoc.constants.ENCODING_XML),
                          cim.Machine)

        # CIM document is valid and can be encoded correctly, so ready to
        # store it in the specified location as JSON:
        pyesdoc.write(cim_out, CIM_OUT_PATH, encoding=encoding)
        print("Machine CIM document successfully written to filesystem.")