Repository: SINTEF/dlite (language: python)

Issue:
Instance.to_bytes() segfaults if driver is not supported
Calling `Instance.to_bytes()` with a driver that doesn't support `memsave` results in segmation fault.



Discussion / hints:

Fix patch:
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;


Test patch:
diff --git a/bindings/python/tests/test_entity.py b/bindings/python/tests/test_entity.py
index a6d0322e6..8c5cb1853 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..103206659 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")