From 9036d65eb16fa9a68b577bd5cff8d7042525598c Mon Sep 17 00:00:00 2001 From: Jesper Friis Date: Sat, 12 Aug 2023 21:42:06 +0200 Subject: [PATCH] Fix segfault when calling Instance.to_bytes() for drivers not supporting memsave --- bindings/python/dlite-entity.i | 6 +++++- bindings/python/tests/test_entity.py | 2 +- bindings/python/tests/test_storage.py | 16 +++++++++++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/bindings/python/dlite-entity.i b/bindings/python/dlite-entity.i index f53ee8c0a..7d69573a8 100644 --- a/bindings/python/dlite-entity.i +++ b/bindings/python/dlite-entity.i @@ -410,7 +410,11 @@ Call signatures: void to_bytes(const char *driver, unsigned char **ARGOUT_BYTES, size_t *LEN) { unsigned char *buf=NULL; int m, n = dlite_instance_memsave(driver, buf, 0, $self); - if (n < 0) return; + if (n < 0) { + *ARGOUT_BYTES = NULL; + *LEN = 0; + return; + } if (!(buf = malloc(n))) { dlite_err(dliteMemoryError, "allocation failure"); return; diff --git a/bindings/python/tests/test_entity.py b/bindings/python/tests/test_entity.py index 4ed493f6c..8bcfda91e 100755 --- a/bindings/python/tests/test_entity.py +++ b/bindings/python/tests/test_entity.py @@ -11,7 +11,7 @@ try: import pytest HAVE_PYTEST = True -except ImportError: +except ModuleNotFoundError: HAVE_PYTEST = False diff --git a/bindings/python/tests/test_storage.py b/bindings/python/tests/test_storage.py index 97244df29..fb5cf499a 100755 --- a/bindings/python/tests/test_storage.py +++ b/bindings/python/tests/test_storage.py @@ -4,6 +4,13 @@ import dlite +try: + import pytest + HAVE_PYTEST = True +except ModuleNotFoundError: + HAVE_PYTEST = False + + thisdir = os.path.abspath(os.path.dirname(__file__)) url = 'json://' + thisdir + '/MyEntity.json' @@ -37,7 +44,6 @@ inst = dlite.Instance.from_url(f'json://{thisdir}/inst.json#my-data') - # Test yaml try: import yaml @@ -95,3 +101,11 @@ #del inst # FIXME: read from inst.ttl not db.xml inst3 = dlite.Instance.from_url('rdf://db.xml#my-data') + + +# Tests for issue #587 +bytearr = inst.to_bytes("yaml") +print(bytes(bytearr).decode()) +if HAVE_PYTEST: + with pytest.raises(dlite.DLiteError): + inst.to_bytes("json")