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