Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add context test
  • Loading branch information
YoannQDQ committed Apr 29, 2023
1 parent 01265af commit 7094bba
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions tests/src/python/test_qgsexpression.py
Expand Up @@ -15,10 +15,12 @@
NULL,
QgsExpression,
QgsExpressionContext,
QgsExpressionContextUtils,
QgsFeatureRequest,
QgsFields,
QgsFeature,
QgsField,
QgsVectorLayer,
)
from qgis.testing import unittest
from qgis.utils import qgsfunction
Expand Down Expand Up @@ -101,6 +103,10 @@ def func_params_no_list(values):
def func_feature(*args, feature):
return (feature["a"] + sum(args)) * feature["b"]

@qgsfunction(group='testing', register=False)
def func_layer_name_operation(operation="upper", context=None):
return getattr(context.variable("layer_name"), operation)()

def tearDown(self):
QgsExpression.unregisterFunction('testfun')

Expand Down Expand Up @@ -424,6 +430,21 @@ def testFeature(self):
e.setExpression("func_feature(3)")
self.assertEqual(e.evaluate(context), "_____")

def testContext(self):
QgsExpression.registerFunction(self.func_layer_name_operation)
context = QgsExpressionContext()

layer = QgsVectorLayer("Point?field=a:int&field=b:string", "test context", "memory")
context.appendScope(QgsExpressionContextUtils.layerScope(layer))

e = QgsExpression()
e.setExpression("func_layer_name_operation()")
self.assertEqual(e.evaluate(context), "TEST CONTEXT")
e.setExpression("func_layer_name_operation('title')")
self.assertEqual(e.evaluate(context), "Test Context")
e.setExpression("func_layer_name_operation('split')")
self.assertEqual(e.evaluate(context), ["test", "context"])


if __name__ == "__main__":
unittest.main()

0 comments on commit 7094bba

Please sign in to comment.