[pygobject/wip/jfelder/template-hierarchy-fix: 9/9] gtktemplate: Do not crash on multiple init_template calls



commit 715ead536e4b680db72cd2a6e5cc974380f21afa
Author: Jean Felder <jfelder src gnome org>
Date:   Thu Apr 16 23:54:18 2020 +0200

    gtktemplate: Do not crash on multiple init_template calls
    
    init_template method is automatically called when a widget is
    created and it is not supposed to be called multiple times. That is
    why this method is turned into a no-op after its first call via a
    lambda function.
    
    init_template can still be called after a widget creation (and it is
    supposed to do nothing). However, a second call will result in a crash
    because the lambda function has a parameter while init_template is not
    supposed to have any parameter.
    
    This issue is fixed by removing the parameter of the lambda function.
    
    A new test is also added to assert that a second init_template call
    does nothing.

 gi/_gtktemplate.py         |  2 +-
 tests/test_gtk_template.py | 30 ++++++++++++++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)
---
diff --git a/gi/_gtktemplate.py b/gi/_gtktemplate.py
index efaca339..4b80106c 100644
--- a/gi/_gtktemplate.py
+++ b/gi/_gtktemplate.py
@@ -99,7 +99,7 @@ def register_template(cls):
 
 
 def init_template(self, cls, base_init_template):
-    self.init_template = lambda s: None
+    self.init_template = lambda: None
 
     if self.__class__ is not cls:
         raise TypeError(
diff --git a/tests/test_gtk_template.py b/tests/test_gtk_template.py
index c28c293f..b43975b9 100644
--- a/tests/test_gtk_template.py
+++ b/tests/test_gtk_template.py
@@ -656,3 +656,33 @@ def test_template_hierarchy():
 
     win = MyWindow()
     assert isinstance(win, MyWindow)
+
+
+def test_multiple_init_template_calls():
+    testbox = """
+    <interface>
+      <template class="TestBox" parent="GtkBox">
+        <child>
+          <object class="GtkLabel" id="_label"/>
+        </child>
+       </template>
+     </interface>
+    """
+    @Gtk.Template(string=testbox)
+    class TestBox(Gtk.Box):
+
+        __gtype_name__ = "TestBox"
+
+        _label = Gtk.Template.Child()
+
+        def __init__(self):
+            super().__init__()
+            self._label.props.label = "TestLabel"
+
+    test_box = TestBox()
+    assert isinstance(test_box, TestBox)
+    assert len(testbox.get_children()) == 1
+
+    test_box.init_template()
+    assert isinstance(test_box, TestBox)
+    assert len(testbox.get_children()) == 1


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]