Imported Upstream version 2.28.6
[platform/upstream/pygobject2.git] / tests / test_overrides.py
1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # vim: tabstop=4 shiftwidth=4 expandtab
3
4 import unittest
5
6 import sys
7 import os
8 sys.path.insert(0, "../")
9
10 from compathelper import _long, _unicode, _bytes
11
12 from gi.repository import GLib
13 from gi.repository import GObject
14 from gi.repository import Gdk
15 from gi.repository import Gtk
16 from gi.repository import Gio
17 from gi.repository import Pango
18 from gi.repository import GdkPixbuf
19 import gi.overrides as overrides
20 import gi.types
21
22 class TestGLib(unittest.TestCase):
23
24     def test_gvariant_create(self):
25         # simple values
26
27         variant = GLib.Variant('i', 42)
28         self.assertTrue(isinstance(variant, GLib.Variant))
29         self.assertEquals(variant.get_int32(), 42)
30
31         variant = GLib.Variant('s', '')
32         self.assertTrue(isinstance(variant, GLib.Variant))
33         self.assertEquals(variant.get_string(), '')
34
35         variant = GLib.Variant('s', 'hello')
36         self.assertTrue(isinstance(variant, GLib.Variant))
37         self.assertEquals(variant.get_string(), 'hello')
38
39         # boxed variant
40         variant = GLib.Variant('v', GLib.Variant('i', 42))
41         self.assertTrue(isinstance(variant, GLib.Variant))
42         self.assertTrue(isinstance(variant.get_variant(), GLib.Variant))
43         self.assertEqual(variant.get_type_string(), 'v')
44         self.assertEqual(variant.get_variant().get_type_string(), 'i')
45         self.assertEquals(variant.get_variant().get_int32(), 42)
46
47         variant = GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42)))
48         self.assertEqual(variant.get_type_string(), 'v')
49         self.assertEqual(variant.get_variant().get_type_string(), 'v')
50         self.assertEqual(variant.get_variant().get_variant().get_type_string(), 'i')
51         self.assertEquals(variant.get_variant().get_variant().get_int32(), 42)
52
53         # tuples
54
55         variant = GLib.Variant('()', ())
56         self.assertEqual(variant.get_type_string(), '()')
57         self.assertEquals(variant.n_children(), 0)
58
59         variant = GLib.Variant('(i)', (3,))
60         self.assertEqual(variant.get_type_string(), '(i)')
61         self.assertTrue(isinstance(variant, GLib.Variant))
62         self.assertEquals(variant.n_children(), 1)
63         self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
64         self.assertEquals(variant.get_child_value(0).get_int32(), 3)
65
66         variant = GLib.Variant('(ss)', ('mec', 'mac'))
67         self.assertEqual(variant.get_type_string(), '(ss)')
68         self.assertTrue(isinstance(variant, GLib.Variant))
69         self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
70         self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
71         self.assertEquals(variant.get_child_value(0).get_string(), 'mec')
72         self.assertEquals(variant.get_child_value(1).get_string(), 'mac')
73
74         # nested tuples
75         variant = GLib.Variant('((si)(ub))', (('hello', -1), (42, True)))
76         self.assertEqual(variant.get_type_string(), '((si)(ub))')
77         self.assertEqual(variant.unpack(), (('hello', -1), (_long(42), True)))
78
79         # dictionaries
80
81         variant = GLib.Variant('a{si}', {})
82         self.assertTrue(isinstance(variant, GLib.Variant))
83         self.assertEqual(variant.get_type_string(), 'a{si}')
84         self.assertEquals(variant.n_children(), 0)
85
86         variant = GLib.Variant('a{si}', {'': 1, 'key1': 2, 'key2': 3})
87         self.assertEqual(variant.get_type_string(), 'a{si}')
88         self.assertTrue(isinstance(variant, GLib.Variant))
89         self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
90         self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
91         self.assertTrue(isinstance(variant.get_child_value(2), GLib.Variant))
92         self.assertEqual(variant.unpack(), {'': 1, 'key1': 2, 'key2': 3})
93
94         # nested dictionaries
95         variant = GLib.Variant('a{sa{si}}', {})
96         self.assertTrue(isinstance(variant, GLib.Variant))
97         self.assertEqual(variant.get_type_string(), 'a{sa{si}}')
98         self.assertEquals(variant.n_children(), 0)
99
100         d = {'':     {'': 1, 'keyn1': 2},
101              'key1': {'key11': 11, 'key12': 12}}
102         variant = GLib.Variant('a{sa{si}}', d)
103         self.assertEqual(variant.get_type_string(), 'a{sa{si}}')
104         self.assertTrue(isinstance(variant, GLib.Variant))
105         self.assertEqual(variant.unpack(), d)
106
107         # arrays
108
109         variant = GLib.Variant('ai', [])
110         self.assertEqual(variant.get_type_string(), 'ai')
111         self.assertEquals(variant.n_children(), 0)
112
113         variant = GLib.Variant('ai', [1, 2])
114         self.assertEqual(variant.get_type_string(), 'ai')
115         self.assertTrue(isinstance(variant, GLib.Variant))
116         self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
117         self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
118         self.assertEquals(variant.get_child_value(0).get_int32(), 1)
119         self.assertEquals(variant.get_child_value(1).get_int32(), 2)
120
121         variant = GLib.Variant('as', [])
122         self.assertEqual(variant.get_type_string(), 'as')
123         self.assertEquals(variant.n_children(), 0)
124
125         variant = GLib.Variant('as', [''])
126         self.assertEqual(variant.get_type_string(), 'as')
127         self.assertTrue(isinstance(variant, GLib.Variant))
128         self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
129         self.assertEquals(variant.get_child_value(0).get_string(), '')
130
131         variant = GLib.Variant('as', ['hello', 'world'])
132         self.assertEqual(variant.get_type_string(), 'as')
133         self.assertTrue(isinstance(variant, GLib.Variant))
134         self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
135         self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
136         self.assertEquals(variant.get_child_value(0).get_string(), 'hello')
137         self.assertEquals(variant.get_child_value(1).get_string(), 'world')
138
139         # nested arrays
140         variant = GLib.Variant('aai', [])
141         self.assertEqual(variant.get_type_string(), 'aai')
142         self.assertEquals(variant.n_children(), 0)
143
144         variant = GLib.Variant('aai', [[]])
145         self.assertEqual(variant.get_type_string(), 'aai')
146         self.assertEquals(variant.n_children(), 1)
147         self.assertEquals(variant.get_child_value(0).n_children(), 0)
148
149         variant = GLib.Variant('aai', [[1, 2], [3, 4, 5]])
150         self.assertEqual(variant.get_type_string(), 'aai')
151         self.assertEquals(variant.unpack(), [[1, 2], [3, 4, 5]])
152
153         #
154         # complex types
155         #
156
157         variant = GLib.Variant('(as)', ([],))
158         self.assertEqual(variant.get_type_string(), '(as)')
159         self.assertEquals(variant.n_children(), 1)
160         self.assertEquals(variant.get_child_value(0).n_children(), 0)
161
162         variant = GLib.Variant('(as)', ([''],))
163         self.assertEqual(variant.get_type_string(), '(as)')
164         self.assertEquals(variant.n_children(), 1)
165         self.assertEquals(variant.get_child_value(0).n_children(), 1)
166         self.assertEquals(variant.get_child_value(0).get_child_value(0).get_string(), '')
167
168         variant = GLib.Variant('(as)', (['hello'],))
169         self.assertEqual(variant.get_type_string(), '(as)')
170         self.assertEquals(variant.n_children(), 1)
171         self.assertEquals(variant.get_child_value(0).n_children(), 1)
172         self.assertEquals(variant.get_child_value(0).get_child_value(0).get_string(), 'hello')
173
174         obj = {'a1': (1, True), 'a2': (2, False)}
175         variant = GLib.Variant('a{s(ib)}', obj)
176         self.assertEqual(variant.get_type_string(), 'a{s(ib)}')
177         self.assertEqual(variant.unpack(), obj)
178
179         obj = {'a1': (1, GLib.Variant('b', True)), 'a2': (2, GLib.Variant('y', 255))}
180         variant = GLib.Variant('a{s(iv)}', obj)
181         self.assertEqual(variant.get_type_string(), 'a{s(iv)}')
182         self.assertEqual(variant.unpack(), {'a1': (1, True), 'a2': (2, 255)})
183
184         obj = (1, {'a': {'a1': True, 'a2': False},
185                    'b': {'b1': False},
186                    'c': {}
187                   },
188                'foo')
189         variant = GLib.Variant('(ia{sa{sb}}s)', obj)
190         self.assertEqual(variant.get_type_string(), '(ia{sa{sb}}s)')
191         self.assertEqual(variant.unpack(), obj)
192
193         obj = {"frequency": GLib.Variant('t', 738000000),
194             "hierarchy": GLib.Variant('i', 0),
195             "bandwidth": GLib.Variant('x', 8),
196             "code-rate-hp": GLib.Variant('d', 2.0/3.0),
197             "constellation": GLib.Variant('s', "QAM16"),
198             "guard-interval": GLib.Variant('u', 4),}
199         variant = GLib.Variant('a{sv}', obj)
200         self.assertEqual(variant.get_type_string(), 'a{sv}')
201         self.assertEqual(variant.unpack(), {"frequency": 738000000,
202             "hierarchy": 0,
203             "bandwidth": 8,
204             "code-rate-hp": 2.0/3.0,
205             "constellation": "QAM16",
206             "guard-interval": 4})
207
208     def test_gvariant_create_errors(self):
209         # excess arguments
210         self.assertRaises(TypeError, GLib.Variant, 'i', 42, 3)
211         self.assertRaises(TypeError, GLib.Variant, '(i)', (42, 3))
212
213         # not enough arguments
214         self.assertRaises(TypeError, GLib.Variant, '(ii)', (42,))
215
216         # data type mismatch
217         self.assertRaises(TypeError, GLib.Variant, 'i', 'hello')
218         self.assertRaises(TypeError, GLib.Variant, 's', 42)
219         self.assertRaises(TypeError, GLib.Variant, '(ss)', 'mec', 'mac')
220
221         # unimplemented data type
222         self.assertRaises(NotImplementedError, GLib.Variant, 'Q', 1)
223
224     def test_gvariant_unpack(self):
225         # simple values
226         res = GLib.Variant.new_int32(-42).unpack()
227         self.assertEqual(res, -42)
228
229         res = GLib.Variant.new_uint64(34359738368).unpack()
230         self.assertEqual(res, 34359738368)
231
232         res = GLib.Variant.new_boolean(True).unpack()
233         self.assertEqual(res, True)
234
235         res = GLib.Variant.new_object_path('/foo/Bar').unpack()
236         self.assertEqual(res, '/foo/Bar')
237
238         # variant
239         res = GLib.Variant('v', GLib.Variant.new_int32(-42)).unpack()
240         self.assertEqual(res, -42)
241
242         variant = GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42)))
243         self.assertEqual(res, -42)
244
245         # tuple
246         res = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1),
247                 GLib.Variant.new_string('hello')).unpack()
248         self.assertEqual(res, (-1, 'hello'))
249
250         # array
251         vb = GLib.VariantBuilder()
252         vb.init(gi._gi.variant_type_from_string('ai'))
253         vb.add_value(GLib.Variant.new_int32(-1))
254         vb.add_value(GLib.Variant.new_int32(3))
255         res = vb.end().unpack()
256         self.assertEqual(res, [-1, 3])
257
258         # dictionary
259         res = GLib.Variant('a{si}', {'key1': 1, 'key2': 2}).unpack()
260         self.assertEqual(res, {'key1': 1, 'key2': 2})
261
262     def test_gvariant_iteration(self):
263         # array index access
264         vb = GLib.VariantBuilder()
265         vb.init(gi._gi.variant_type_from_string('ai'))
266         vb.add_value(GLib.Variant.new_int32(-1))
267         vb.add_value(GLib.Variant.new_int32(3))
268         v = vb.end()
269
270         self.assertEqual(len(v), 2)
271         self.assertEqual(v[0], -1)
272         self.assertEqual(v[1], 3)
273         self.assertEqual(v[-1], 3)
274         self.assertEqual(v[-2], -1)
275         self.assertRaises(IndexError, v.__getitem__, 2)
276         self.assertRaises(IndexError, v.__getitem__, -3)
277         self.assertRaises(ValueError, v.__getitem__, 'a')
278
279         # array iteration
280         self.assertEqual([x for x in v], [-1, 3])
281         self.assertEqual(list(v), [-1, 3])
282
283         # tuple index access
284         v = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1),
285                 GLib.Variant.new_string('hello'))
286         self.assertEqual(len(v), 2)
287         self.assertEqual(v[0], -1)
288         self.assertEqual(v[1], 'hello')
289         self.assertEqual(v[-1], 'hello')
290         self.assertEqual(v[-2], -1)
291         self.assertRaises(IndexError, v.__getitem__, 2)
292         self.assertRaises(IndexError, v.__getitem__, -3)
293         self.assertRaises(ValueError, v.__getitem__, 'a')
294
295         # tuple iteration
296         self.assertEqual([x for x in v], [-1, 'hello'])
297         self.assertEqual(tuple(v), (-1, 'hello'))
298
299         # dictionary index access
300         vsi = GLib.Variant('a{si}', {'key1': 1, 'key2': 2})
301         vis = GLib.Variant('a{is}', {1: 'val1', 5: 'val2'})
302
303         self.assertEqual(len(vsi), 2)
304         self.assertEqual(vsi['key1'], 1)
305         self.assertEqual(vsi['key2'], 2)
306         self.assertRaises(KeyError, vsi.__getitem__, 'unknown')
307
308         self.assertEqual(len(vis), 2)
309         self.assertEqual(vis[1], 'val1')
310         self.assertEqual(vis[5], 'val2')
311         self.assertRaises(KeyError, vsi.__getitem__, 3)
312
313         # dictionary iteration
314         self.assertEqual(set(vsi.keys()), set(['key1', 'key2']))
315         self.assertEqual(set(vis.keys()), set([1, 5]))
316
317         # string index access
318         v = GLib.Variant('s', 'hello')
319         self.assertEqual(len(v), 5)
320         self.assertEqual(v[0], 'h')
321         self.assertEqual(v[4], 'o')
322         self.assertEqual(v[-1], 'o')
323         self.assertEqual(v[-5], 'h')
324         self.assertRaises(IndexError, v.__getitem__, 5)
325         self.assertRaises(IndexError, v.__getitem__, -6)
326
327         # string iteration
328         self.assertEqual([x for x in v], ['h', 'e', 'l', 'l', 'o'])
329
330 class TestPango(unittest.TestCase):
331
332     def test_default_font_description(self):
333         desc = Pango.FontDescription()
334         self.assertEquals(desc.get_variant(), Pango.Variant.NORMAL)
335
336     def test_font_description(self):
337         desc = Pango.FontDescription('monospace')
338         self.assertEquals(desc.get_family(), 'monospace')
339         self.assertEquals(desc.get_variant(), Pango.Variant.NORMAL)
340
341     def test_layout(self):
342         self.assertRaises(TypeError, Pango.Layout)
343         context = Pango.Context()
344         layout = Pango.Layout(context)
345         self.assertEquals(layout.get_context(), context)
346
347 class TestGdk(unittest.TestCase):
348
349     def test_constructor(self):
350         attribute = Gdk.WindowAttr()
351         attribute.window_type = Gdk.WindowType.CHILD
352         attributes_mask = Gdk.WindowAttributesType.X | \
353             Gdk.WindowAttributesType.Y
354         window = Gdk.Window(None, attribute, attributes_mask)
355         self.assertEquals(window.get_window_type(), Gdk.WindowType.CHILD)
356
357     def test_color(self):
358         color = Gdk.Color(100, 200, 300)
359         self.assertEquals(color.red, 100)
360         self.assertEquals(color.green, 200)
361         self.assertEquals(color.blue, 300)
362         self.assertEquals(color, Gdk.Color(100, 200, 300))
363         self.assertNotEquals(color, Gdk.Color(1, 2, 3))
364
365     def test_rgba(self):
366         self.assertEquals(Gdk.RGBA, overrides.Gdk.RGBA)
367         rgba = Gdk.RGBA(0.1, 0.2, 0.3, 0.4)
368         self.assertEquals(rgba, Gdk.RGBA(0.1, 0.2, 0.3, 0.4))
369         self.assertNotEquals(rgba, Gdk.RGBA(0.0, 0.2, 0.3, 0.4))
370         self.assertEquals(rgba.red, 0.1)
371         self.assertEquals(rgba.green, 0.2)
372         self.assertEquals(rgba.blue, 0.3)
373         self.assertEquals(rgba.alpha, 0.4)
374         rgba.green = 0.9
375         self.assertEquals(rgba.green, 0.9)
376
377     def test_event(self):
378         event = Gdk.Event.new(Gdk.EventType.CONFIGURE)
379         self.assertEquals(event.type, Gdk.EventType.CONFIGURE)
380         self.assertEquals(event.send_event, 0)
381
382         event = Gdk.Event.new(Gdk.EventType.DRAG_MOTION)
383         event.x_root, event.y_root = 0, 5
384         self.assertEquals(event.x_root, 0)
385         self.assertEquals(event.y_root, 5)
386
387         event = Gdk.Event()
388         event.type = Gdk.EventType.SCROLL
389         self.assertRaises(AttributeError, lambda: getattr(event, 'foo_bar'))
390
391     def test_event_structures(self):
392         def button_press_cb(button, event):
393             self.assertTrue(isinstance(event, Gdk.EventButton))
394             self.assertTrue(event.type == Gdk.EventType.BUTTON_PRESS)
395             self.assertEquals(event.send_event, 0)
396             self.assertEquals(event.get_state(), Gdk.ModifierType.CONTROL_MASK)
397             self.assertEquals(event.get_root_coords(), (2, 5))
398
399             event.time = 12345
400             self.assertEquals(event.get_time(), 12345)
401
402         w = Gtk.Window()
403         b = Gtk.Button()
404         b.connect('button-press-event', button_press_cb)
405         w.add(b)
406         w.show_all()
407         Gdk.test_simulate_button(b.get_window(),
408                                  2, 5,
409                                  0,
410                                  Gdk.ModifierType.CONTROL_MASK,
411                                  Gdk.EventType.BUTTON_PRESS)
412
413     def test_cursor(self):
414         self.assertEquals(Gdk.Cursor, overrides.Gdk.Cursor)
415         c = Gdk.Cursor(Gdk.CursorType.WATCH)
416         self.assertNotEqual(c, None)
417         c = Gdk.Cursor(cursor_type = Gdk.CursorType.WATCH)
418         self.assertNotEqual(c, None)
419
420         display_manager = Gdk.DisplayManager.get()
421         display = display_manager.get_default_display()
422
423         test_pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB,
424                                            False,
425                                            8,
426                                            5,
427                                            10)
428
429         c = Gdk.Cursor(display,
430                        test_pixbuf,
431                        y=0, x=0)
432
433         self.assertNotEqual(c, None)
434         self.assertRaises(ValueError, Gdk.Cursor, 1, 2, 3)
435
436 class TestGtk(unittest.TestCase):
437
438     def test_container(self):
439         box = Gtk.Box()
440         self.assertTrue(box)
441         label = Gtk.Label()
442         label2 = Gtk.Label()
443         box.add(label)
444         box.add(label2)
445         self.assertTrue(label in box)
446         self.assertTrue(label2 in box)
447         self.assertEqual(len(box), 2)
448         self.assertTrue(box)
449         l = [x for x in box]
450         self.assertEqual(l, [label, label2])
451
452     def test_actions(self):
453         self.assertEquals(Gtk.Action, overrides.Gtk.Action)
454         self.assertRaises(TypeError, Gtk.Action)
455         action = Gtk.Action("test", "Test", "Test Action", Gtk.STOCK_COPY)
456         self.assertEquals(action.get_name(), "test")
457         self.assertEquals(action.get_label(), "Test")
458         self.assertEquals(action.get_tooltip(), "Test Action")
459         self.assertEquals(action.get_stock_id(), Gtk.STOCK_COPY)
460
461         self.assertEquals(Gtk.RadioAction, overrides.Gtk.RadioAction)
462         self.assertRaises(TypeError, Gtk.RadioAction)
463         action = Gtk.RadioAction("test", "Test", "Test Action", Gtk.STOCK_COPY, 1)
464         self.assertEquals(action.get_name(), "test")
465         self.assertEquals(action.get_label(), "Test")
466         self.assertEquals(action.get_tooltip(), "Test Action")
467         self.assertEquals(action.get_stock_id(), Gtk.STOCK_COPY)
468         self.assertEquals(action.get_current_value(), 1)
469
470     def test_actiongroup(self):
471         self.assertEquals(Gtk.ActionGroup, overrides.Gtk.ActionGroup)
472         self.assertRaises(TypeError, Gtk.ActionGroup)
473
474         action_group = Gtk.ActionGroup (name = 'TestActionGroup')
475         callback_data = "callback data"
476
477         def test_action_callback_data(action, user_data):
478             self.assertEquals(user_data, callback_data);
479
480         def test_radio_action_callback_data(action, current, user_data):
481             self.assertEquals(user_data, callback_data);
482
483         action_group.add_actions ([
484             ('test-action1', None, 'Test Action 1',
485              None, None, test_action_callback_data),
486             ('test-action2', Gtk.STOCK_COPY, 'Test Action 2',
487               None, None, test_action_callback_data)], callback_data)
488         action_group.add_toggle_actions([
489             ('test-toggle-action1', None, 'Test Toggle Action 1',
490              None, None, test_action_callback_data, False),
491             ('test-toggle-action2', Gtk.STOCK_COPY, 'Test Toggle Action 2',
492               None, None, test_action_callback_data, True)], callback_data)
493         action_group.add_radio_actions([
494             ('test-radio-action1', None, 'Test Radio Action 1'),
495             ('test-radio-action2', Gtk.STOCK_COPY, 'Test Radio Action 2')], 1,
496             test_radio_action_callback_data,
497             callback_data)
498
499         expected_results = [('test-action1', Gtk.Action),
500                             ('test-action2', Gtk.Action),
501                             ('test-toggle-action1', Gtk.ToggleAction),
502                             ('test-toggle-action2', Gtk.ToggleAction),
503                             ('test-radio-action1', Gtk.RadioAction),
504                             ('test-radio-action2', Gtk.RadioAction)]
505
506         for action in action_group.list_actions():
507             a = (action.get_name(), type(action))
508             self.assertTrue(a in expected_results)
509             expected_results.remove(a)
510             action.activate()
511
512     def test_uimanager(self):
513         self.assertEquals(Gtk.UIManager, overrides.Gtk.UIManager)
514         ui = Gtk.UIManager()
515         ui.add_ui_from_string(
516 """
517 <ui>
518     <menubar name="menubar1"></menubar>
519 </ui>
520 """
521 )
522         menubar = ui.get_widget("/menubar1")
523         self.assertEquals(type(menubar), Gtk.MenuBar)
524
525         ag = Gtk.ActionGroup (name="ag1")
526         ui.insert_action_group(ag)
527         ag2 = Gtk.ActionGroup (name="ag2")
528         ui.insert_action_group(ag2)
529         groups = ui.get_action_groups()
530         self.assertEquals(ag, groups[-2])
531         self.assertEquals(ag2, groups[-1])
532
533     def test_builder(self):
534         self.assertEquals(Gtk.Builder, overrides.Gtk.Builder)
535
536         class SignalTest(GObject.GObject):
537             __gtype_name__ = "GIOverrideSignalTest"
538             __gsignals__ = {
539                 "test-signal": (GObject.SIGNAL_RUN_FIRST,
540                                 GObject.TYPE_NONE,
541                                 []),
542             }
543
544
545         class SignalCheck:
546             def __init__(self):
547                 self.sentinel = 0
548
549             def on_signal_1(self, *args):
550                 self.sentinel += 1
551
552             def on_signal_3(self, *args):
553                 self.sentinel += 3
554
555         signal_checker = SignalCheck()
556         builder = Gtk.Builder()
557
558         # add object1 to the builder
559         builder.add_from_string(
560 """
561 <interface>
562   <object class="GIOverrideSignalTest" id="object1">
563       <signal name="test-signal" handler="on_signal_1" />
564   </object>
565 </interface>
566 """)
567
568         # only add object3 to the builder
569         builder.add_objects_from_string(
570 """
571 <interface>
572   <object class="GIOverrideSignalTest" id="object2">
573       <signal name="test-signal" handler="on_signal_2" />
574   </object>
575   <object class="GIOverrideSignalTest" id="object3">
576       <signal name="test-signal" handler="on_signal_3" />
577   </object>
578   <object class="GIOverrideSignalTest" id="object4">
579       <signal name="test-signal" handler="on_signal_4" />
580   </object>
581 </interface>
582
583 """,
584             ['object3'])
585
586         # hook up signals
587         builder.connect_signals(signal_checker)
588
589         # call their notify signals and check sentinel
590         objects = builder.get_objects()
591         self.assertEquals(len(objects), 2)
592         for obj in objects:
593             obj.emit('test-signal')
594
595         self.assertEquals(signal_checker.sentinel, 4)
596
597     def test_dialogs(self):
598         self.assertEquals(Gtk.Dialog, overrides.Gtk.Dialog)
599         self.assertEquals(Gtk.AboutDialog, overrides.Gtk.AboutDialog)
600         self.assertEquals(Gtk.MessageDialog, overrides.Gtk.MessageDialog)
601         self.assertEquals(Gtk.ColorSelectionDialog, overrides.Gtk.ColorSelectionDialog)
602         self.assertEquals(Gtk.FileChooserDialog, overrides.Gtk.FileChooserDialog)
603         self.assertEquals(Gtk.FontSelectionDialog, overrides.Gtk.FontSelectionDialog)
604         self.assertEquals(Gtk.RecentChooserDialog, overrides.Gtk.RecentChooserDialog)
605
606         # Gtk.Dialog
607         dialog = Gtk.Dialog (title='Foo',
608                              flags=Gtk.DialogFlags.MODAL,
609                              buttons=('test-button1', 1))
610
611         dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
612
613         self.assertEquals('Foo', dialog.get_title())
614         self.assertTrue(dialog.get_modal())
615         button = dialog.get_widget_for_response (1)
616         self.assertEquals('test-button1', button.get_label())
617         button = dialog.get_widget_for_response (2)
618         self.assertEquals('test-button2', button.get_label())
619         button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
620         self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
621
622         # Gtk.AboutDialog
623         dialog = Gtk.AboutDialog()
624
625         # Gtk.MessageDialog
626         dialog = Gtk.MessageDialog (title='message dialog test',
627                                     flags=Gtk.DialogFlags.MODAL,
628                                     buttons=Gtk.ButtonsType.OK,
629                                     message_format='dude!')
630
631         self.assertEquals('message dialog test', dialog.get_title())
632         self.assertTrue(dialog.get_modal())
633         text = dialog.get_property('text')
634         self.assertEquals('dude!', text)
635
636         dialog.format_secondary_text('2nd text')
637         self.assertEqual(dialog.get_property('secondary-text'), '2nd text')
638         self.assertFalse(dialog.get_property('secondary-use-markup'))
639
640         dialog.format_secondary_markup('2nd markup')
641         self.assertEqual(dialog.get_property('secondary-text'), '2nd markup')
642         self.assertTrue(dialog.get_property('secondary-use-markup'))
643
644         # Gtk.ColorSelectionDialog
645         dialog = Gtk.ColorSelectionDialog("color selection dialog test")
646         self.assertEquals('color selection dialog test', dialog.get_title())
647
648         # Gtk.FileChooserDialog
649         dialog = Gtk.FileChooserDialog (title='file chooser dialog test',
650                                         buttons=('test-button1', 1),
651                                         action=Gtk.FileChooserAction.SAVE)
652
653         dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
654         self.assertEquals('file chooser dialog test', dialog.get_title())
655         button = dialog.get_widget_for_response (1)
656         self.assertEquals('test-button1', button.get_label())
657         button = dialog.get_widget_for_response (2)
658         self.assertEquals('test-button2', button.get_label())
659         button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
660         self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
661         action = dialog.get_property('action')
662         self.assertEquals(Gtk.FileChooserAction.SAVE, action)
663
664
665         # Gtk.FontSelectionDialog
666         dialog = Gtk.ColorSelectionDialog("font selection dialog test")
667         self.assertEquals('font selection dialog test', dialog.get_title())
668
669         # Gtk.RecentChooserDialog
670         test_manager = Gtk.RecentManager()
671         dialog = Gtk.RecentChooserDialog (title='recent chooser dialog test',
672                                           buttons=('test-button1', 1),
673                                           manager=test_manager)
674
675         dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
676         self.assertEquals('recent chooser dialog test', dialog.get_title())
677         button = dialog.get_widget_for_response (1)
678         self.assertEquals('test-button1', button.get_label())
679         button = dialog.get_widget_for_response (2)
680         self.assertEquals('test-button2', button.get_label())
681         button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
682         self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
683
684     class TestClass(GObject.GObject):
685         __gtype_name__ = "GIOverrideTreeAPITest"
686
687         def __init__(self, tester, int_value, string_value):
688             super(TestGtk.TestClass, self).__init__()
689             self.tester = tester
690             self.int_value = int_value
691             self.string_value = string_value
692
693         def check(self, int_value, string_value):
694             self.tester.assertEquals(int_value, self.int_value)
695             self.tester.assertEquals(string_value, self.string_value)
696
697     def test_tree_store(self):
698         self.assertEquals(Gtk.TreeStore, overrides.Gtk.TreeStore)
699         self.assertEquals(Gtk.ListStore, overrides.Gtk.ListStore)
700         self.assertEquals(Gtk.TreeModel, overrides.Gtk.TreeModel)
701         self.assertEquals(Gtk.TreeViewColumn, overrides.Gtk.TreeViewColumn)
702
703         class TestPyObject(object):
704             pass
705
706         test_pyobj = TestPyObject()
707         test_pydict = {1:1, "2":2, "3":"3"}
708         test_pylist = [1,"2", "3"]
709         tree_store = Gtk.TreeStore(int,
710                                    'gchararray',
711                                    TestGtk.TestClass,
712                                    object,
713                                    object,
714                                    object,
715                                    bool,
716                                    bool,
717                                    GObject.TYPE_UINT,
718                                    GObject.TYPE_ULONG,
719                                    GObject.TYPE_INT64,
720                                    GObject.TYPE_UINT64,
721                                    GObject.TYPE_UCHAR,
722                                    GObject.TYPE_CHAR)
723
724         parent = None
725         for i in range(100):
726             label = 'this is child #%d' % i
727             testobj = TestGtk.TestClass(self, i, label)
728             parent = tree_store.append(parent, (i,
729                                                 label,
730                                                 testobj,
731                                                 test_pyobj,
732                                                 test_pydict,
733                                                 test_pylist,
734                                                 i % 2,
735                                                 bool(i % 2),
736                                                 i,
737                                                 9223372036854775808,
738                                                 -9223372036854775808,
739                                                 0xffffffffffffffff,
740                                                 254,
741                                                 _bytes('a')
742                                                 ))
743
744         # len gets the number of children in the root node
745         # since we kept appending to the previous node
746         # there should only be one child of the root
747         self.assertEquals(len(tree_store), 1)
748
749         # walk the tree to see if the values were stored correctly
750         parent = None
751         i = 0
752
753         treeiter = tree_store.iter_children(parent)
754         while treeiter:
755            i = tree_store.get_value(treeiter, 0)
756            s = tree_store.get_value(treeiter, 1)
757            obj = tree_store.get_value(treeiter, 2)
758            obj.check(i, s)
759
760            pyobj = tree_store.get_value(treeiter, 3)
761            self.assertEquals(pyobj, test_pyobj)
762            pydict = tree_store.get_value(treeiter, 4)
763            self.assertEquals(pydict, test_pydict)
764            pylist = tree_store.get_value(treeiter, 5)
765            self.assertEquals(pylist, test_pylist)
766
767            bool_1 = tree_store.get_value(treeiter, 6)
768            bool_2 = tree_store.get_value(treeiter, 7)
769            self.assertEquals(bool_1, bool_2)
770            self.assertTrue(isinstance(bool_1, bool))
771            self.assertTrue(isinstance(bool_2, bool))
772
773            uint_ = tree_store.get_value(treeiter, 8)
774            self.assertEquals(uint_, i)
775            ulong_ = tree_store.get_value(treeiter, 9)
776            self.assertEquals(ulong_, 9223372036854775808)
777            int64_ = tree_store.get_value(treeiter, 10)
778            self.assertEquals(int64_, -9223372036854775808)
779            uint64_ = tree_store.get_value(treeiter, 11)
780            self.assertEquals(uint64_, 0xffffffffffffffff)
781            uchar_ = tree_store.get_value(treeiter, 12)
782            self.assertEquals(ord(uchar_), 254)
783            char_ = tree_store.get_value(treeiter, 13)
784            self.assertEquals(char_, 'a')
785
786            parent = treeiter
787            treeiter = tree_store.iter_children(parent)
788
789         self.assertEquals(i, 99)
790
791     def test_list_store(self):
792         class TestPyObject(object):
793             pass
794
795         class TestPyGObject(GObject.Object):
796             __gtype_name__ = 'TestPyGObject'
797             def __init__(self, i):
798                 GObject.Object.__init__(self)
799                 self.sentinal = i + 5
800
801         test_pyobj = TestPyObject()
802         test_pydict = {1:1, "2":2, "3":"3"}
803         test_pylist = [1,"2", "3"]
804
805         list_store = Gtk.ListStore(int, str, 'GIOverrideTreeAPITest', object, object, object, bool, bool, object)
806         for i in range(93):
807             label = 'this is row #%d' % i
808             testobj = TestGtk.TestClass(self, i, label)
809             testpygobj = TestPyGObject(i)
810             parent = list_store.append((i,
811                                         label,
812                                         testobj,
813                                         test_pyobj,
814                                         test_pydict,
815                                         test_pylist,
816                                         i % 2,
817                                         bool(i % 2),
818                                         testpygobj))
819
820         i = 93
821         label = _unicode('this is row #93')
822         treeiter = list_store.append()
823         list_store.set_value(treeiter, 0, i)
824         list_store.set_value(treeiter, 1, label)
825         list_store.set_value(treeiter, 2, TestGtk.TestClass(self, i, label))
826         list_store.set_value(treeiter, 3, test_pyobj)
827         list_store.set_value(treeiter, 4, test_pydict)
828         list_store.set_value(treeiter, 5, test_pylist)
829         list_store.set_value(treeiter, 6, 1)
830         list_store.set_value(treeiter, 7, True)
831         list_store.set_value(treeiter, 8, TestPyGObject(i))
832
833         # test automatic unicode->str conversion
834         i = 94
835         label = _unicode('this is row #94')
836         treeiter = list_store.append((i,
837                                       label,
838                                       TestGtk.TestClass(self, i, label),
839                                       test_pyobj,
840                                       test_pydict,
841                                       test_pylist,
842                                       0,
843                                       False,
844                                       TestPyGObject(i)))
845
846         # add sorted items out of order to test insert* apis
847         # also test sending in None to not set a column
848         i = 97
849         label = 'this is row #97'
850         treeiter = list_store.append((None,
851                                       None,
852                                       None,
853                                       test_pyobj,
854                                       None,
855                                       test_pylist,
856                                       1,
857                                       None,
858                                       TestPyGObject(i)))
859
860         list_store.set_value(treeiter, 0, i)
861         list_store.set_value(treeiter, 1, label)
862         list_store.set_value(treeiter, 2, TestGtk.TestClass(self, i, label))
863         list_store.set_value(treeiter, 4, test_pydict)
864         list_store.set_value(treeiter, 7, True)
865  
866         # this should append
867         i = 99
868         label = 'this is row #99'
869         list_store.insert(9999, (i,
870                                  label,
871                                  TestGtk.TestClass(self, i, label),
872                                  test_pyobj,
873                                  test_pydict,
874                                  test_pylist,
875                                  1,
876                                  True,
877                                  TestPyGObject(i)))
878
879         i = 96
880         label = 'this is row #96'
881         list_store.insert_before(treeiter, (i,
882                                             label,
883                                             TestGtk.TestClass(self, i, label),
884                                             test_pyobj,
885                                             test_pydict,
886                                             test_pylist,
887                                             0,
888                                             False,
889                                             TestPyGObject(i)))
890
891         i = 98
892         label = 'this is row #98'
893         list_store.insert_after(treeiter, (i,
894                                            label,
895                                            TestGtk.TestClass(self, i, label),
896                                            test_pyobj,
897                                            test_pydict,
898                                            test_pylist,
899                                            0,
900                                            False,
901                                            TestPyGObject(i)))
902
903
904         i = 95
905         label = 'this is row #95'
906         list_store.insert(95, (i,
907                                label,
908                                TestGtk.TestClass(self, i, label),
909                                test_pyobj,
910                                test_pydict,
911                                test_pylist,
912                                1,
913                                True,
914                                TestPyGObject(i)))
915
916         self.assertEquals(len(list_store), 100)
917
918         # walk the list to see if the values were stored correctly
919         i = 0
920         treeiter = list_store.get_iter_first()
921
922         counter = 0
923         while treeiter:
924             i = list_store.get_value(treeiter, 0)
925             self.assertEquals(i, counter)
926             s = list_store.get_value(treeiter, 1)
927             obj = list_store.get_value(treeiter, 2)
928             obj.check(i, s)
929
930             pyobj = list_store.get_value(treeiter, 3)
931             self.assertEquals(pyobj, test_pyobj)
932             pydict = list_store.get_value(treeiter, 4)
933             self.assertEquals(pydict, test_pydict)
934             pylist = list_store.get_value(treeiter, 5)
935             self.assertEquals(pylist, test_pylist)
936
937             bool_1 = list_store.get_value(treeiter, 6)
938             bool_2 = list_store.get_value(treeiter, 7)
939             self.assertEquals(bool_1, bool_2)
940             self.assertTrue(isinstance(bool_1, bool))
941             self.assertTrue(isinstance(bool_2, bool))
942
943             pygobj = list_store.get_value(treeiter, 8)
944             self.assertEquals(pygobj.sentinal, i + 5)
945
946             treeiter = list_store.iter_next(treeiter)
947
948             counter += 1
949
950         self.assertEquals(i, 99)
951
952     def test_tree_path(self):
953         p1 = Gtk.TreePath()
954         p2 = Gtk.TreePath.new_first()
955         self.assertEqual(p1, p2)
956         self.assertEqual(str(p1), '0')
957         p1 = Gtk.TreePath(2)
958         p2 = Gtk.TreePath.new_from_string('2')
959         self.assertEqual(p1, p2)
960         self.assertEqual(str(p1), '2')
961         p1 = Gtk.TreePath('1:2:3')
962         p2 = Gtk.TreePath.new_from_string('1:2:3')
963         self.assertEqual(p1, p2)
964         self.assertEqual(str(p1), '1:2:3')
965         p1 = Gtk.TreePath((1,2,3))
966         p2 = Gtk.TreePath.new_from_string('1:2:3')
967         self.assertEqual(p1, p2)
968         self.assertEqual(str(p1), '1:2:3')
969         self.assertTrue(p1 != None)
970         self.assertFalse(p1 == None)
971         self.assertTrue(p1 > None)
972         self.assertTrue(p1 >= None)
973         self.assertFalse(p1 < None)
974         self.assertFalse(p1 <= None)
975
976     def test_tree_model(self):
977         tree_store = Gtk.TreeStore(int, str)
978
979         self.assertTrue(tree_store)
980         self.assertEqual(len(tree_store), 0)
981         self.assertEqual(tree_store.get_iter_first(), None)
982
983         def get_by_index(row, col=None):
984             if col:
985                 return tree_store[row][col]
986             else:
987                 return tree_store[row]
988
989         self.assertRaises(TypeError, get_by_index, None)
990         self.assertRaises(TypeError, get_by_index, "")
991         self.assertRaises(TypeError, get_by_index, ())
992
993         self.assertRaises(IndexError, get_by_index, "0")
994         self.assertRaises(IndexError, get_by_index, 0)
995         self.assertRaises(IndexError, get_by_index, (0,))
996
997         self.assertRaises(ValueError, tree_store.get_iter, "0")
998         self.assertRaises(ValueError, tree_store.get_iter, 0)
999         self.assertRaises(ValueError, tree_store.get_iter, (0,))
1000
1001         self.assertRaises(ValueError, tree_store.get_iter_from_string, "0")
1002
1003         for row in tree_store:
1004             self.fail("Should not be reached")
1005
1006         class DerivedIntType(int):
1007             pass
1008
1009         class DerivedStrType(str):
1010             pass
1011
1012         for i in range(100):
1013             label = 'this is row #%d' % i
1014             parent = tree_store.append(None, (DerivedIntType(i), DerivedStrType(label),))
1015             self.assertNotEquals(parent, None)
1016             for j in range(20):
1017                 label = 'this is child #%d of node #%d' % (j, i)
1018                 child = tree_store.append(parent, (j, label,))
1019                 self.assertNotEqual(child, None)
1020
1021         self.assertTrue(tree_store)
1022         self.assertEqual(len(tree_store), 100)
1023
1024         for i,row in enumerate(tree_store):
1025             self.assertEqual(row.model, tree_store)
1026             self.assertEqual(row.parent, None)
1027
1028             self.assertEqual(tree_store[i].path, row.path)
1029             self.assertEqual(tree_store[str(i)].path, row.path)
1030             self.assertEqual(tree_store[(i,)].path, row.path)
1031
1032             self.assertEqual(tree_store[i][0], i)
1033             self.assertEqual(tree_store[i][1], "this is row #%d" % i)
1034
1035             aiter = tree_store.get_iter(i)
1036             self.assertEqual(tree_store.get_path(aiter), row.path)
1037
1038             aiter = tree_store.get_iter(str(i))
1039             self.assertEqual(tree_store.get_path(aiter), row.path)
1040
1041             aiter = tree_store.get_iter((i,))
1042             self.assertEqual(tree_store.get_path(aiter), row.path)
1043
1044             self.assertEqual(tree_store.iter_parent(aiter), row.parent)
1045
1046             next = tree_store.iter_next(aiter)
1047             if i < len(tree_store) - 1:
1048                 self.assertEqual(tree_store.get_path(next), row.next.path)
1049             else:
1050                 self.assertEqual(next, None)
1051
1052             self.assertEqual(tree_store.iter_n_children(row.iter), 20)
1053
1054             child = tree_store.iter_children(row.iter)
1055             for j,childrow in enumerate(row.iterchildren()):
1056                 child_path = tree_store.get_path(child)
1057                 self.assertEqual(childrow.path, child_path)
1058                 self.assertEqual(childrow.parent.path, row.path)
1059                 self.assertEqual(childrow.path, tree_store[child].path)
1060                 self.assertEqual(childrow.path, tree_store[child_path].path)
1061
1062                 self.assertEqual(childrow[0], tree_store[child][0])
1063                 self.assertEqual(childrow[0], j)
1064                 self.assertEqual(childrow[1], tree_store[child][1])
1065                 self.assertEqual(childrow[1], 'this is child #%d of node #%d' % (j, i))
1066
1067                 self.assertRaises(IndexError, get_by_index, child, 2)
1068
1069                 tree_store[child][1] = 'this was child #%d of node #%d' % (j, i)
1070                 self.assertEqual(childrow[1], 'this was child #%d of node #%d' % (j, i))
1071
1072                 nth_child = tree_store.iter_nth_child(row.iter, j)
1073                 self.assertEqual(childrow.path, tree_store.get_path(nth_child))
1074
1075                 childrow2 = tree_store["%d:%d" % (i, j)]
1076                 self.assertEqual(childrow.path, childrow2.path)
1077
1078                 childrow2 = tree_store[(i, j,)]
1079                 self.assertEqual(childrow.path, childrow2.path)
1080
1081                 child = tree_store.iter_next(child)
1082                 if j < 19:
1083                     self.assertEqual(childrow.next.path, tree_store.get_path(child))
1084                 else:
1085                     self.assertEqual(child, childrow.next)
1086                     self.assertEqual(child, None)
1087
1088             self.assertEqual(j, 19)
1089
1090         self.assertEqual(i, 99)
1091
1092         # negative indices
1093         for i in range(-1,-100,-1):
1094             i_real = i + 100
1095             self.assertEqual(tree_store[i][0], i_real)
1096
1097             row = tree_store[i]
1098             for j in range(-1, -20, -1):
1099                 j_real = j + 20
1100                 path = (i_real, j_real,)
1101
1102                 self.assertEqual(tree_store[path][-2], j_real)
1103
1104                 label = 'this was child #%d of node #%d' % (j_real, i_real)
1105                 self.assertEqual(tree_store[path][-1], label)
1106
1107                 new_label = 'this still is child #%d of node #%d' % (j_real, i_real)
1108                 tree_store[path][-1] = new_label
1109                 self.assertEqual(tree_store[path][-1], new_label)
1110
1111                 self.assertRaises(IndexError, get_by_index, path, -3)
1112
1113         self.assertRaises(IndexError, get_by_index, -101)
1114
1115         last_row = tree_store[99]
1116         self.assertNotEqual(last_row, None)
1117
1118         for i,childrow in enumerate(last_row.iterchildren()):
1119             if i < 19:
1120                 self.assertTrue(tree_store.remove(childrow.iter))
1121             else:
1122                 self.assertFalse(tree_store.remove(childrow.iter))
1123
1124         self.assertEqual(i, 19)
1125
1126         self.assertEqual(tree_store.iter_n_children(last_row.iter), 0)
1127         for childrow in last_row.iterchildren():
1128             self.fail("Should not be reached")
1129
1130         aiter = tree_store.get_iter(10)
1131         self.assertRaises(TypeError, tree_store.get, aiter, 1, 'a')
1132         self.assertRaises(ValueError, tree_store.get, aiter, 1, -1)
1133         self.assertRaises(ValueError, tree_store.get, aiter, 1, 100)
1134         self.assertEqual(tree_store.get(aiter, 0, 1), (10, 'this is row #10'))
1135
1136     def test_tree_view_column(self):
1137         cell = Gtk.CellRendererText()
1138         column = Gtk.TreeViewColumn(title='This is just a test',
1139                                     cell_renderer=cell,
1140                                     text=0,
1141                                     style=2)
1142
1143     def test_tree_selection(self):
1144         store = Gtk.ListStore(int, str)
1145         for i in range(10):
1146             store.append((i, "foo"))
1147         view = Gtk.TreeView()
1148         view.set_model(store)
1149         firstpath = store.get_path(store.get_iter_first())
1150         sel = view.get_selection()
1151
1152         sel.select_path(firstpath)
1153         (m, s) = sel.get_selected()
1154         self.assertEqual(m, store)
1155         self.assertEqual(store.get_path(s), firstpath)
1156
1157         sel.select_path(0)
1158         (m, s) = sel.get_selected()
1159         self.assertEqual(m, store)
1160         self.assertEqual(store.get_path(s), firstpath)
1161
1162         sel.select_path("0:0")
1163         (m, s) = sel.get_selected()
1164         self.assertEqual(m, store)
1165         self.assertEqual(store.get_path(s), firstpath)
1166
1167         sel.select_path((0,0))
1168         (m, s) = sel.get_selected()
1169         self.assertEqual(m, store)
1170         self.assertEqual(store.get_path(s), firstpath)
1171
1172     def test_text_buffer(self):
1173         self.assertEquals(Gtk.TextBuffer, overrides.Gtk.TextBuffer)
1174         buffer = Gtk.TextBuffer()
1175         tag = buffer.create_tag ('title', font = 'Sans 18')
1176
1177         self.assertEquals(tag.props.name, 'title')
1178         self.assertEquals(tag.props.font, 'Sans 18')
1179
1180         (start, end) = buffer.get_bounds()
1181
1182         mark = buffer.create_mark(None, start)
1183         self.assertFalse(mark.get_left_gravity())
1184
1185         buffer.set_text('Hello Jane Hello Bob')
1186         (start, end) = buffer.get_bounds()
1187         text = buffer.get_text(start, end, False)
1188         self.assertEquals(text, 'Hello Jane Hello Bob')
1189
1190         buffer.set_text('')
1191         (start, end) = buffer.get_bounds()
1192         text = buffer.get_text(start, end, False)
1193         self.assertEquals(text, '')
1194
1195         buffer.insert(end, 'HelloHello')
1196         buffer.insert(end, ' Bob')
1197
1198         cursor_iter = end.copy()
1199         cursor_iter.backward_chars(9)
1200         buffer.place_cursor(cursor_iter)
1201         buffer.insert_at_cursor(' Jane ')
1202
1203         (start, end) = buffer.get_bounds()
1204         text = buffer.get_text(start, end, False)
1205         self.assertEquals(text, 'Hello Jane Hello Bob')
1206
1207         sel = buffer.get_selection_bounds()
1208         self.assertEquals(sel, ())
1209         buffer.select_range(start, end)
1210         sel = buffer.get_selection_bounds()
1211         self.assertTrue(sel[0].equal(start))
1212         self.assertTrue(sel[1].equal(end))
1213
1214         buffer.set_text('')
1215         buffer.insert_with_tags(buffer.get_start_iter(), 'HelloHello', tag)
1216         (start, end) = buffer.get_bounds()
1217         self.assertTrue(start.begins_tag(tag))
1218         self.assertTrue(start.has_tag(tag))
1219
1220         buffer.set_text('')
1221         buffer.insert_with_tags_by_name(buffer.get_start_iter(), 'HelloHello', 'title')
1222         (start, end) = buffer.get_bounds()
1223         self.assertTrue(start.begins_tag(tag))
1224         self.assertTrue(start.has_tag(tag))
1225
1226         self.assertRaises(ValueError, buffer.insert_with_tags_by_name,
1227                 buffer.get_start_iter(), 'HelloHello', 'unknowntag')
1228
1229     def test_text_iter(self):
1230         self.assertEquals(Gtk.TextIter, overrides.Gtk.TextIter)
1231         buffer = Gtk.TextBuffer()
1232         buffer.set_text('Hello Jane Hello Bob')
1233         tag = buffer.create_tag ('title', font = 'Sans 18')
1234         (start, end) = buffer.get_bounds()
1235         start.forward_chars(10)
1236         buffer.apply_tag(tag, start, end)
1237         self.assertTrue(start.begins_tag())
1238         self.assertTrue(end.ends_tag())
1239         self.assertTrue(start.toggles_tag())
1240         self.assertTrue(end.toggles_tag())
1241         start.backward_chars(1)
1242         self.assertFalse(start.begins_tag())
1243         self.assertFalse(start.ends_tag())
1244         self.assertFalse(start.toggles_tag())
1245
1246     def test_buttons(self):
1247         self.assertEquals(Gtk.Button, overrides.Gtk.Button)
1248
1249         # test Gtk.Button
1250         button = Gtk.Button()
1251         button = Gtk.Button(stock=Gtk.STOCK_CLOSE)
1252         self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
1253         self.assertTrue(button.get_use_stock())
1254         self.assertTrue(button.get_use_underline())
1255
1256         # test Gtk.LinkButton
1257         self.assertRaises(TypeError, Gtk.LinkButton)
1258         button = Gtk.LinkButton('http://www.gtk.org', 'Gtk')
1259         self.assertEquals('http://www.gtk.org', button.get_uri())
1260         self.assertEquals('Gtk', button.get_label())
1261
1262     def test_inheritance(self):
1263         for name in overrides.Gtk.__all__:
1264             over = getattr(overrides.Gtk, name)
1265             for element in dir(Gtk):
1266                 try:
1267                     klass = getattr(Gtk, element)
1268                     info = klass.__info__
1269                 except (NotImplementedError, AttributeError):
1270                     continue
1271
1272                 # Get all parent classes and interfaces klass inherits from
1273                 if isinstance(info, gi.types.ObjectInfo):
1274                     classes = list(info.get_interfaces())
1275                     parent = info.get_parent()
1276                     while parent.get_name() != "Object":
1277                         classes.append(parent)
1278                         parent = parent.get_parent()
1279                     classes = [kl for kl in classes if kl.get_namespace() == "Gtk"]
1280                 else:
1281                     continue
1282
1283                 for kl in classes:
1284                     if kl.get_name() == name:
1285                         self.assertTrue(issubclass(klass, over,),
1286                             "%r does not inherit from override %r" % (klass, over,))
1287
1288     def test_editable(self):
1289         self.assertEquals(Gtk.Editable, overrides.Gtk.Editable)
1290
1291         # need to use Gtk.Entry because Editable is an interface
1292         entry=Gtk.Entry()
1293         pos = entry.insert_text('HeWorld', 0)
1294         self.assertEquals(pos, 7)
1295         pos = entry.insert_text('llo ', 2)
1296         self.assertEquals(pos, 6)
1297         text = entry.get_chars(0, 11)
1298         self.assertEquals('Hello World', text)
1299
1300     def test_label(self):
1301         label = Gtk.Label('Hello')
1302         self.assertEquals(label.get_text(), 'Hello')
1303
1304     def adjustment_check(self, adjustment, value=0.0, lower=0.0, upper=0.0,
1305                          step_increment=0.0, page_increment=0.0, page_size=0.0):
1306         self.assertEquals(adjustment.get_value(), value)
1307         self.assertEquals(adjustment.get_lower(), lower)
1308         self.assertEquals(adjustment.get_upper(), upper)
1309         self.assertEquals(adjustment.get_step_increment(), step_increment)
1310         self.assertEquals(adjustment.get_page_increment(), page_increment)
1311         self.assertEquals(adjustment.get_page_size(), page_size)
1312
1313     def test_adjustment(self):
1314         adjustment =       Gtk.Adjustment(1, 0, 6, 4, 5, 3)
1315         self.adjustment_check(adjustment, 1, 0, 6, 4, 5, 3)
1316
1317         adjustment =       Gtk.Adjustment(1, 0, 6, 4, 5)
1318         self.adjustment_check(adjustment, 1, 0, 6, 4, 5)
1319
1320         adjustment =       Gtk.Adjustment(1, 0, 6, 4)
1321         self.adjustment_check(adjustment, 1, 0, 6, 4)
1322
1323         adjustment =       Gtk.Adjustment(1, 0, 6)
1324         self.adjustment_check(adjustment, 1, 0, 6)
1325
1326         adjustment = Gtk.Adjustment()
1327         self.adjustment_check(adjustment)
1328
1329         adjustment = Gtk.Adjustment(value=1, lower=0, upper=6,
1330                                     step_increment=4, page_increment=5, page_size=3)
1331         self.adjustment_check(adjustment, 1, 0, 6, 4, 5, 3)
1332
1333     def test_table(self):
1334         table = Gtk.Table()
1335         self.assertEquals(table.get_size(), (1,1))
1336         self.assertEquals(table.get_homogeneous(), False)
1337         table = Gtk.Table(2, 3)
1338         self.assertEquals(table.get_size(), (2,3))
1339         self.assertEquals(table.get_homogeneous(), False)
1340         table = Gtk.Table(2, 3, True)
1341         self.assertEquals(table.get_size(), (2,3))
1342         self.assertEquals(table.get_homogeneous(), True)
1343
1344         # Test PyGTK interface
1345         table = Gtk.Table(rows=3, columns=2)
1346         self.assertEquals(table.get_size(), (3,2))
1347         # Test using the actual property names
1348         table = Gtk.Table(n_rows=2, n_columns=3, homogeneous=True)
1349         self.assertEquals(table.get_size(), (2,3))
1350         self.assertEquals(table.get_homogeneous(), True)
1351
1352         label = Gtk.Label('Hello')
1353         table.attach(label, 0, 1, 0, 1)
1354         self.assertEquals(label, table.get_children()[0])
1355
1356     def test_scrolledwindow(self):
1357         sw = Gtk.ScrolledWindow()
1358         sb = sw.get_hscrollbar()
1359         self.assertEquals(sw.get_hadjustment(), sb.get_adjustment())
1360         sb = sw.get_vscrollbar()
1361         self.assertEquals(sw.get_vadjustment(), sb.get_adjustment())
1362
1363     def test_widget_drag_methods(self):
1364         widget = Gtk.Button()
1365
1366         # here we are not checking functionality, only that the methods exist
1367         # and except the right number of arguments
1368
1369         widget.drag_check_threshold(0, 0, 0, 0)
1370
1371         # drag_dest_ methods
1372         widget.drag_dest_set(Gtk.DestDefaults.DROP, None, Gdk.DragAction.COPY)
1373         widget.drag_dest_add_image_targets()
1374         widget.drag_dest_add_text_targets()
1375         widget.drag_dest_add_uri_targets()
1376         widget.drag_dest_get_track_motion()
1377         widget.drag_dest_set_track_motion(True)
1378         widget.drag_dest_get_target_list()
1379         widget.drag_dest_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry()]))
1380         widget.drag_dest_unset()
1381
1382         widget.drag_highlight()
1383         widget.drag_unhighlight()
1384
1385         # drag_source_ methods
1386         widget.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, None, Gdk.DragAction.MOVE)
1387         widget.drag_source_add_image_targets()
1388         widget.drag_source_add_text_targets()
1389         widget.drag_source_add_uri_targets()
1390         widget.drag_source_set_icon_name("")
1391         widget.drag_source_set_icon_pixbuf(GdkPixbuf.Pixbuf())
1392         widget.drag_source_set_icon_stock("")
1393         widget.drag_source_get_target_list()
1394         widget.drag_source_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry()]))
1395         widget.drag_source_unset()
1396
1397         # these methods cannot be called because they require a valid drag on
1398         # a real GdkWindow. So we only check that they exist and are callable.
1399         self.assertTrue(hasattr(widget.drag_dest_set_proxy, '__call__'))
1400         self.assertTrue(hasattr(widget.drag_get_data, '__call__'))
1401
1402 class TestGio(unittest.TestCase):
1403     def setUp(self):
1404         os.environ['GSETTINGS_BACKEND'] = 'memory'
1405         # support a separate build tree, so look in build dir first
1406         os.environ['GSETTINGS_SCHEMA_DIR'] = os.environ.get('TESTS_BUILDDIR', 
1407                 os.path.dirname(__file__))
1408         self.settings = Gio.Settings('org.gnome.test')
1409         # we change the values in the tests, so set them to predictable start
1410         # value
1411         self.settings.reset('test-string')
1412         self.settings.reset('test-array')
1413
1414     def test_file_enumerator(self):
1415         self.assertEquals(Gio.FileEnumerator, overrides.Gio.FileEnumerator)
1416         f = Gio.file_new_for_path("./")
1417
1418         iter_info = []
1419         for info in f.enumerate_children("standard::*", 0, None):
1420             iter_info.append(info.get_name())
1421
1422         next_info = []
1423         enumerator = f.enumerate_children("standard::*", 0, None)
1424         while True:
1425             info = enumerator.next_file(None)
1426             if info is None:
1427                 break
1428             next_info.append(info.get_name())
1429
1430         self.assertEquals(iter_info, next_info)
1431
1432     def test_gsettings_native(self):
1433         self.assertTrue('test-array' in self.settings.list_keys())
1434
1435         # get various types
1436         v = self.settings.get_value('test-boolean')
1437         self.assertEqual(v.get_boolean(), True)
1438         self.assertEqual(self.settings.get_boolean('test-boolean'), True)
1439
1440         v = self.settings.get_value('test-string')
1441         self.assertEqual(v.get_string(), 'Hello')
1442         self.assertEqual(self.settings.get_string('test-string'), 'Hello')
1443
1444         v = self.settings.get_value('test-array')
1445         self.assertEqual(v.unpack(), [1, 2])
1446
1447         v = self.settings.get_value('test-tuple')
1448         self.assertEqual(v.unpack(), (1, 2))
1449
1450         # set a value
1451         self.settings.set_string('test-string', 'World')
1452         self.assertEqual(self.settings.get_string('test-string'), 'World')
1453
1454         self.settings.set_value('test-string', GLib.Variant('s', 'Goodbye'))
1455         self.assertEqual(self.settings.get_string('test-string'), 'Goodbye')
1456
1457     def test_gsettings_constructor(self):
1458         # default constructor uses path from schema
1459         self.assertEqual(self.settings.get_property('path'), '/tests/')
1460
1461         # optional constructor arguments
1462         with_path = Gio.Settings('org.gnome.nopathtest', path='/mypath/')
1463         self.assertEqual(with_path.get_property('path'), '/mypath/')
1464         self.assertEqual(with_path['np-int'], 42)
1465
1466     def test_gsettings_override(self):
1467         # dictionary interface
1468         self.assertEqual(len(self.settings), 4)
1469         self.assertTrue('test-array' in self.settings)
1470         self.assertTrue('test-array' in self.settings.keys())
1471         self.failIf('nonexisting' in self.settings)
1472         self.failIf(4 in self.settings)
1473         self.assertEqual(bool(self.settings), True)
1474
1475         # get various types
1476         self.assertEqual(self.settings['test-boolean'], True)
1477         self.assertEqual(self.settings['test-string'], 'Hello')
1478         self.assertEqual(self.settings['test-array'], [1, 2])
1479         self.assertEqual(self.settings['test-tuple'], (1, 2))
1480
1481         self.assertRaises(KeyError, self.settings.__getitem__, 'unknown')
1482         self.assertRaises(KeyError, self.settings.__getitem__, 2)
1483
1484         # set a value
1485         self.settings['test-string'] = 'Goodbye'
1486         self.assertEqual(self.settings['test-string'], 'Goodbye')
1487         self.settings['test-array'] = [3, 4, 5]
1488         self.assertEqual(self.settings['test-array'], [3, 4, 5])
1489
1490         self.assertRaises(TypeError, self.settings.__setitem__, 'test-string', 1)
1491         self.assertRaises(KeyError, self.settings.__setitem__, 'unknown', 'moo')
1492
1493     def test_gsettings_empty(self):
1494         empty = Gio.Settings('org.gnome.empty', path='/tests/')
1495         self.assertEqual(len(empty), 0)
1496         self.assertEqual(bool(empty), True)
1497         self.assertEqual(empty.keys(), [])
1498
1499     def test_closures(self):
1500         # make sure this doesn't crash
1501         def fake_cb(*args):
1502             pass
1503
1504         ag = Gtk.AccelGroup()
1505         ag.connect(Gdk.KEY_l, Gdk.ModifierType.CONTROL_MASK, 0, fake_cb)