File: helpers.py

package info (click to toggle)
python-asdf 2.14.3-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,280 kB
  • sloc: python: 16,612; makefile: 124
file content (65 lines) | stat: -rw-r--r-- 1,555 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
Helpers for writing unit tests of ASDF support.
"""

from io import BytesIO

import asdf


def roundtrip_object(obj, version=None):
    """
    Add the specified object to an AsdfFile's tree, write the file to
    a buffer, then read it back in and return the deserialized object.

    Parameters
    ----------
    obj : object
        Object to serialize.
    version : str or None.
        ASDF Standard version.  If None, use the library's default version.

    Returns
    -------
    object
        The deserialized object.
    """
    buff = BytesIO()
    with asdf.AsdfFile(version=version) as af:
        af["obj"] = obj
        af.write_to(buff)

    buff.seek(0)
    with asdf.open(buff, lazy_load=False, copy_arrays=True) as af:
        return af["obj"]


def yaml_to_asdf(yaml_content, version=None):
    """
    Given a string of YAML content, adds the extra pre-
    and post-amble to make it an ASDF file.

    Parameters
    ----------
    yaml_content : string or bytes
        YAML content.
    version : str or None.
        ASDF Standard version.  If None, use the library's default version.

    Returns
    -------
    io.BytesIO
        A file-like object containing the ASDF file.
    """
    if isinstance(yaml_content, str):
        yaml_content = yaml_content.encode("utf-8")

    buff = BytesIO()
    with asdf.AsdfFile(version=version) as af:
        af["$REPLACE"] = "ME"
        af.write_to(buff)

    buff.seek(0)
    asdf_content = buff.read().replace(b"$REPLACE: ME", yaml_content)

    return BytesIO(asdf_content)