From 2f10455db2b00c86594fdea6e63817651b744972 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 16 Jul 2024 08:21:45 +1000 Subject: [PATCH] Fix __geo_interface__ should use None for NULL values Fixes #58084 --- python/core/additions/qgsfeature.py | 4 ++-- tests/src/python/test_qgsfeature.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/python/core/additions/qgsfeature.py b/python/core/additions/qgsfeature.py index c94d18806e22..bf0100ab01dc 100644 --- a/python/core/additions/qgsfeature.py +++ b/python/core/additions/qgsfeature.py @@ -16,12 +16,12 @@ * * *************************************************************************** """ +from PyQt5.QtCore import QVariant def mapping_feature(feature): geom = feature.geometry() - fields = [field.name() for field in feature.fields()] - properties = dict(list(zip(fields, feature.attributes()))) + properties = {k: None if (v is None or isinstance(v, QVariant) and v.isNull()) else v for k, v in feature.attributeMap().items()} return {'type': 'Feature', 'properties': properties, 'geometry': geom.__geo_interface__} diff --git a/tests/src/python/test_qgsfeature.py b/tests/src/python/test_qgsfeature.py index 7106c283dad7..a7afbd5c74a8 100644 --- a/tests/src/python/test_qgsfeature.py +++ b/tests/src/python/test_qgsfeature.py @@ -392,6 +392,29 @@ def testUnsetFeature(self): self.assertTrue(f.isUnsetValue(3)) self.assertTrue(f.isUnsetValue(4)) + def test_geo_interface(self): + fields = QgsFields() + field1 = QgsField('my_field', QVariant.String) + fields.append(field1) + field2 = QgsField('my_field2', QVariant.String) + fields.append(field2) + field3 = QgsField('my_field3', QVariant.Int) + fields.append(field3) + + feat = QgsFeature(fields) + feat.setAttributes(['abc', 'def', 123]) + feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(123, 456))) + self.assertEqual(feat.__geo_interface__, {'geometry': {'coordinates': [123.0, 456.0], 'type': 'Point'}, + 'properties': {'my_field': 'abc', 'my_field2': 'def', 'my_field3': 123}, + 'type': 'Feature'}) + + feat.setAttributes([NULL, None, NULL]) + self.assertEqual(feat.__geo_interface__, { + 'geometry': {'coordinates': [123.0, 456.0], 'type': 'Point'}, + 'properties': {'my_field': None, 'my_field2': None, + 'my_field3': None}, + 'type': 'Feature'}) + if __name__ == '__main__': unittest.main()