diff --git a/src/aiida/orm/nodes/data/singlefile.py b/src/aiida/orm/nodes/data/singlefile.py index 8faefc8cb4..d4cc4b7095 100644 --- a/src/aiida/orm/nodes/data/singlefile.py +++ b/src/aiida/orm/nodes/data/singlefile.py @@ -39,6 +39,17 @@ def from_string(cls, content: str, filename: str | pathlib.Path | None = None, * """ return cls(io.StringIO(content), filename, **kwargs) + @classmethod + def from_bytes( + cls, content: bytes, filename: str | pathlib.Path | None = None, **kwargs: t.Any + ) -> 'SinglefileData': + """Construct a new instance and set ``content`` as its contents. + + :param content: The content as bytes. + :param filename: Specify filename to use (defaults to ``file.txt``). + """ + return cls(io.BytesIO(content), filename, **kwargs) + def __init__( self, file: str | pathlib.Path | t.IO, filename: str | pathlib.Path | None = None, **kwargs: t.Any ) -> None: diff --git a/tests/orm/nodes/data/test_singlefile.py b/tests/orm/nodes/data/test_singlefile.py index 304050648a..1d1930d83b 100644 --- a/tests/orm/nodes/data/test_singlefile.py +++ b/tests/orm/nodes/data/test_singlefile.py @@ -189,18 +189,40 @@ def test_from_string(): content = 'some\ncontent' node = SinglefileData.from_string(content).store() assert node.get_content() == content + assert node.get_content('rb') == content.encode() assert node.filename == SinglefileData.DEFAULT_FILENAME content = 'some\ncontent' filename = 'custom_filename.dat' node = SinglefileData.from_string(content, filename).store() assert node.get_content() == content + assert node.get_content('rb') == content.encode() + assert node.filename == filename + + +def test_from_bytes(): + """Test the :meth:`aiida.orm.nodes.data.singlefile.SinglefileData.from_bytes` classmethod.""" + content = b'some\ncontent' + node = SinglefileData.from_bytes(content).store() + assert node.get_content(mode='rb') == content + assert node.get_content(mode='r') == content.decode('utf-8') + assert node.filename == SinglefileData.DEFAULT_FILENAME + + content = b'some\ncontent' + filename = 'custom_filename.dat' + node = SinglefileData.from_bytes(content, filename).store() + assert node.get_content(mode='rb') == content + assert node.get_content(mode='r') == content.decode('utf-8') assert node.filename == filename def test_get_content(): """Test the :meth:`aiida.orm.nodes.data.singlefile.SinglefileData.get_content` method.""" + content = 'some\ncontent' + node = SinglefileData.from_string(content).store() + assert node.get_content() == content + assert node.get_content('rb') == content.encode() content = b'some\ncontent' - node = SinglefileData.from_string(content.decode('utf-8')).store() + node = SinglefileData.from_bytes(content).store() assert node.get_content() == content.decode('utf-8') assert node.get_content('rb') == content