with edit(layer) raises an error if the commit fails

This commit is contained in:
Matthias Kuhn 2015-08-12 14:55:36 +02:00
parent f64783493e
commit 8ab69e9386
2 changed files with 16 additions and 2 deletions

View File

@ -135,6 +135,13 @@ try:
except ImportError:
pass
class QgsEditError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
# Define a `with edit(layer)` statement
class edit:
@ -147,7 +154,8 @@ class edit:
def __exit__(self, ex_type, ex_value, traceback):
if ex_type is None:
assert self.layer.commitChanges()
if not self.layer.commitChanges():
raise QgsEditError(self.layer.commitErrors())
return True
else:
self.layer.rollBack()

View File

@ -21,7 +21,8 @@ from utilities import (unittest,
from qgis.core import (edit,
QgsFeature,
QgsGeometry,
QgsVectorLayer
QgsVectorLayer,
QgsEditError
)
getQgisTestApp()
@ -72,5 +73,10 @@ class TestSyntacticSugar(TestCase):
assert ml.dataProvider().getFeatures().next()['value']==10
# Check that we get a QgsEditError exception when the commit fails
with self.assertRaises(QgsEditError):
with edit(ml) as l:
l.rollBack()
if __name__ == "__main__":
unittest.main()