1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # vim: tabstop=4 shiftwidth=4 expandtab
8 sys.path.insert(0, "../")
10 from compathelper import _long, _unicode, _bytes
12 os.environ['GSETTINGS_BACKEND'] = 'memory'
13 # support a separate build tree, so look in build dir first
14 os.environ['GSETTINGS_SCHEMA_DIR'] = os.environ.get('TESTS_BUILDDIR',
15 os.path.dirname(__file__))
17 from gi.repository import GLib
18 from gi.repository import GObject
19 from gi.repository import Gdk
20 from gi.repository import Gtk
21 from gi.repository import Gio
22 from gi.repository import Pango
23 from gi.repository import GdkPixbuf
24 import gi.overrides as overrides
27 # in general we don't want tests to raise warnings, except when explicitly
28 # testing with bad values; in those cases it will temporarily be set back to
30 GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_WARNING)
32 class TestGLib(unittest.TestCase):
34 def test_gvariant_create(self):
37 variant = GLib.Variant('i', 42)
38 self.assertTrue(isinstance(variant, GLib.Variant))
39 self.assertEquals(variant.get_int32(), 42)
41 variant = GLib.Variant('s', '')
42 self.assertTrue(isinstance(variant, GLib.Variant))
43 self.assertEquals(variant.get_string(), '')
45 variant = GLib.Variant('s', 'hello')
46 self.assertTrue(isinstance(variant, GLib.Variant))
47 self.assertEquals(variant.get_string(), 'hello')
50 variant = GLib.Variant('v', GLib.Variant('i', 42))
51 self.assertTrue(isinstance(variant, GLib.Variant))
52 self.assertTrue(isinstance(variant.get_variant(), GLib.Variant))
53 self.assertEqual(variant.get_type_string(), 'v')
54 self.assertEqual(variant.get_variant().get_type_string(), 'i')
55 self.assertEquals(variant.get_variant().get_int32(), 42)
57 variant = GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42)))
58 self.assertEqual(variant.get_type_string(), 'v')
59 self.assertEqual(variant.get_variant().get_type_string(), 'v')
60 self.assertEqual(variant.get_variant().get_variant().get_type_string(), 'i')
61 self.assertEquals(variant.get_variant().get_variant().get_int32(), 42)
65 variant = GLib.Variant('()', ())
66 self.assertEqual(variant.get_type_string(), '()')
67 self.assertEquals(variant.n_children(), 0)
69 variant = GLib.Variant('(i)', (3,))
70 self.assertEqual(variant.get_type_string(), '(i)')
71 self.assertTrue(isinstance(variant, GLib.Variant))
72 self.assertEquals(variant.n_children(), 1)
73 self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
74 self.assertEquals(variant.get_child_value(0).get_int32(), 3)
76 variant = GLib.Variant('(ss)', ('mec', 'mac'))
77 self.assertEqual(variant.get_type_string(), '(ss)')
78 self.assertTrue(isinstance(variant, GLib.Variant))
79 self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
80 self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
81 self.assertEquals(variant.get_child_value(0).get_string(), 'mec')
82 self.assertEquals(variant.get_child_value(1).get_string(), 'mac')
85 variant = GLib.Variant('((si)(ub))', (('hello', -1), (42, True)))
86 self.assertEqual(variant.get_type_string(), '((si)(ub))')
87 self.assertEqual(variant.unpack(), (('hello', -1), (_long(42), True)))
91 variant = GLib.Variant('a{si}', {})
92 self.assertTrue(isinstance(variant, GLib.Variant))
93 self.assertEqual(variant.get_type_string(), 'a{si}')
94 self.assertEquals(variant.n_children(), 0)
96 variant = GLib.Variant('a{si}', {'': 1, 'key1': 2, 'key2': 3})
97 self.assertEqual(variant.get_type_string(), 'a{si}')
98 self.assertTrue(isinstance(variant, GLib.Variant))
99 self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
100 self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
101 self.assertTrue(isinstance(variant.get_child_value(2), GLib.Variant))
102 self.assertEqual(variant.unpack(), {'': 1, 'key1': 2, 'key2': 3})
104 # nested dictionaries
105 variant = GLib.Variant('a{sa{si}}', {})
106 self.assertTrue(isinstance(variant, GLib.Variant))
107 self.assertEqual(variant.get_type_string(), 'a{sa{si}}')
108 self.assertEquals(variant.n_children(), 0)
110 d = {'': {'': 1, 'keyn1': 2},
111 'key1': {'key11': 11, 'key12': 12}}
112 variant = GLib.Variant('a{sa{si}}', d)
113 self.assertEqual(variant.get_type_string(), 'a{sa{si}}')
114 self.assertTrue(isinstance(variant, GLib.Variant))
115 self.assertEqual(variant.unpack(), d)
119 variant = GLib.Variant('ai', [])
120 self.assertEqual(variant.get_type_string(), 'ai')
121 self.assertEquals(variant.n_children(), 0)
123 variant = GLib.Variant('ai', [1, 2])
124 self.assertEqual(variant.get_type_string(), 'ai')
125 self.assertTrue(isinstance(variant, GLib.Variant))
126 self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
127 self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
128 self.assertEquals(variant.get_child_value(0).get_int32(), 1)
129 self.assertEquals(variant.get_child_value(1).get_int32(), 2)
131 variant = GLib.Variant('as', [])
132 self.assertEqual(variant.get_type_string(), 'as')
133 self.assertEquals(variant.n_children(), 0)
135 variant = GLib.Variant('as', [''])
136 self.assertEqual(variant.get_type_string(), 'as')
137 self.assertTrue(isinstance(variant, GLib.Variant))
138 self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
139 self.assertEquals(variant.get_child_value(0).get_string(), '')
141 variant = GLib.Variant('as', ['hello', 'world'])
142 self.assertEqual(variant.get_type_string(), 'as')
143 self.assertTrue(isinstance(variant, GLib.Variant))
144 self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant))
145 self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant))
146 self.assertEquals(variant.get_child_value(0).get_string(), 'hello')
147 self.assertEquals(variant.get_child_value(1).get_string(), 'world')
150 variant = GLib.Variant('aai', [])
151 self.assertEqual(variant.get_type_string(), 'aai')
152 self.assertEquals(variant.n_children(), 0)
154 variant = GLib.Variant('aai', [[]])
155 self.assertEqual(variant.get_type_string(), 'aai')
156 self.assertEquals(variant.n_children(), 1)
157 self.assertEquals(variant.get_child_value(0).n_children(), 0)
159 variant = GLib.Variant('aai', [[1, 2], [3, 4, 5]])
160 self.assertEqual(variant.get_type_string(), 'aai')
161 self.assertEquals(variant.unpack(), [[1, 2], [3, 4, 5]])
167 variant = GLib.Variant('(as)', ([],))
168 self.assertEqual(variant.get_type_string(), '(as)')
169 self.assertEquals(variant.n_children(), 1)
170 self.assertEquals(variant.get_child_value(0).n_children(), 0)
172 variant = GLib.Variant('(as)', ([''],))
173 self.assertEqual(variant.get_type_string(), '(as)')
174 self.assertEquals(variant.n_children(), 1)
175 self.assertEquals(variant.get_child_value(0).n_children(), 1)
176 self.assertEquals(variant.get_child_value(0).get_child_value(0).get_string(), '')
178 variant = GLib.Variant('(as)', (['hello'],))
179 self.assertEqual(variant.get_type_string(), '(as)')
180 self.assertEquals(variant.n_children(), 1)
181 self.assertEquals(variant.get_child_value(0).n_children(), 1)
182 self.assertEquals(variant.get_child_value(0).get_child_value(0).get_string(), 'hello')
184 obj = {'a1': (1, True), 'a2': (2, False)}
185 variant = GLib.Variant('a{s(ib)}', obj)
186 self.assertEqual(variant.get_type_string(), 'a{s(ib)}')
187 self.assertEqual(variant.unpack(), obj)
189 obj = {'a1': (1, GLib.Variant('b', True)), 'a2': (2, GLib.Variant('y', 255))}
190 variant = GLib.Variant('a{s(iv)}', obj)
191 self.assertEqual(variant.get_type_string(), 'a{s(iv)}')
192 self.assertEqual(variant.unpack(), {'a1': (1, True), 'a2': (2, 255)})
194 obj = (1, {'a': {'a1': True, 'a2': False},
199 variant = GLib.Variant('(ia{sa{sb}}s)', obj)
200 self.assertEqual(variant.get_type_string(), '(ia{sa{sb}}s)')
201 self.assertEqual(variant.unpack(), obj)
203 obj = {"frequency": GLib.Variant('t', 738000000),
204 "hierarchy": GLib.Variant('i', 0),
205 "bandwidth": GLib.Variant('x', 8),
206 "code-rate-hp": GLib.Variant('d', 2.0/3.0),
207 "constellation": GLib.Variant('s', "QAM16"),
208 "guard-interval": GLib.Variant('u', 4),}
209 variant = GLib.Variant('a{sv}', obj)
210 self.assertEqual(variant.get_type_string(), 'a{sv}')
211 self.assertEqual(variant.unpack(), {"frequency": 738000000,
214 "code-rate-hp": 2.0/3.0,
215 "constellation": "QAM16",
216 "guard-interval": 4})
218 def test_gvariant_create_errors(self):
220 self.assertRaises(TypeError, GLib.Variant, 'i', 42, 3)
221 self.assertRaises(TypeError, GLib.Variant, '(i)', (42, 3))
223 # not enough arguments
224 self.assertRaises(TypeError, GLib.Variant, '(ii)', (42,))
227 self.assertRaises(TypeError, GLib.Variant, 'i', 'hello')
228 self.assertRaises(TypeError, GLib.Variant, 's', 42)
229 self.assertRaises(TypeError, GLib.Variant, '(ss)', 'mec', 'mac')
231 # unimplemented data type
232 self.assertRaises(NotImplementedError, GLib.Variant, 'Q', 1)
234 def test_gvariant_unpack(self):
236 res = GLib.Variant.new_int32(-42).unpack()
237 self.assertEqual(res, -42)
239 res = GLib.Variant.new_uint64(34359738368).unpack()
240 self.assertEqual(res, 34359738368)
242 res = GLib.Variant.new_boolean(True).unpack()
243 self.assertEqual(res, True)
245 res = GLib.Variant.new_object_path('/foo/Bar').unpack()
246 self.assertEqual(res, '/foo/Bar')
249 res = GLib.Variant('v', GLib.Variant.new_int32(-42)).unpack()
250 self.assertEqual(res, -42)
252 variant = GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42)))
253 self.assertEqual(res, -42)
256 res = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1),
257 GLib.Variant.new_string('hello')).unpack()
258 self.assertEqual(res, (-1, 'hello'))
261 vb = GLib.VariantBuilder.new(gi._gi.variant_type_from_string('ai'))
262 vb.add_value(GLib.Variant.new_int32(-1))
263 vb.add_value(GLib.Variant.new_int32(3))
264 res = vb.end().unpack()
265 self.assertEqual(res, [-1, 3])
268 res = GLib.Variant('a{si}', {'key1': 1, 'key2': 2}).unpack()
269 self.assertEqual(res, {'key1': 1, 'key2': 2})
271 def test_gvariant_iteration(self):
273 vb = GLib.VariantBuilder.new(gi._gi.variant_type_from_string('ai'))
274 vb.add_value(GLib.Variant.new_int32(-1))
275 vb.add_value(GLib.Variant.new_int32(3))
278 self.assertEqual(len(v), 2)
279 self.assertEqual(v[0], -1)
280 self.assertEqual(v[1], 3)
281 self.assertEqual(v[-1], 3)
282 self.assertEqual(v[-2], -1)
283 self.assertRaises(IndexError, v.__getitem__, 2)
284 self.assertRaises(IndexError, v.__getitem__, -3)
285 self.assertRaises(ValueError, v.__getitem__, 'a')
288 self.assertEqual([x for x in v], [-1, 3])
289 self.assertEqual(list(v), [-1, 3])
292 v = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1),
293 GLib.Variant.new_string('hello'))
294 self.assertEqual(len(v), 2)
295 self.assertEqual(v[0], -1)
296 self.assertEqual(v[1], 'hello')
297 self.assertEqual(v[-1], 'hello')
298 self.assertEqual(v[-2], -1)
299 self.assertRaises(IndexError, v.__getitem__, 2)
300 self.assertRaises(IndexError, v.__getitem__, -3)
301 self.assertRaises(ValueError, v.__getitem__, 'a')
304 self.assertEqual([x for x in v], [-1, 'hello'])
305 self.assertEqual(tuple(v), (-1, 'hello'))
307 # dictionary index access
308 vsi = GLib.Variant('a{si}', {'key1': 1, 'key2': 2})
309 vis = GLib.Variant('a{is}', {1: 'val1', 5: 'val2'})
311 self.assertEqual(len(vsi), 2)
312 self.assertEqual(vsi['key1'], 1)
313 self.assertEqual(vsi['key2'], 2)
314 self.assertRaises(KeyError, vsi.__getitem__, 'unknown')
316 self.assertEqual(len(vis), 2)
317 self.assertEqual(vis[1], 'val1')
318 self.assertEqual(vis[5], 'val2')
319 self.assertRaises(KeyError, vsi.__getitem__, 3)
321 # dictionary iteration
322 self.assertEqual(set(vsi.keys()), set(['key1', 'key2']))
323 self.assertEqual(set(vis.keys()), set([1, 5]))
325 # string index access
326 v = GLib.Variant('s', 'hello')
327 self.assertEqual(len(v), 5)
328 self.assertEqual(v[0], 'h')
329 self.assertEqual(v[4], 'o')
330 self.assertEqual(v[-1], 'o')
331 self.assertEqual(v[-5], 'h')
332 self.assertRaises(IndexError, v.__getitem__, 5)
333 self.assertRaises(IndexError, v.__getitem__, -6)
336 self.assertEqual([x for x in v], ['h', 'e', 'l', 'l', 'o'])
338 def test_variant_split_signature(self):
339 self.assertEqual(GLib.Variant.split_signature('()'), [])
341 self.assertEqual(GLib.Variant.split_signature('s'), ['s'])
343 self.assertEqual(GLib.Variant.split_signature('as'), ['as'])
345 self.assertEqual(GLib.Variant.split_signature('(s)'), ['s'])
347 self.assertEqual(GLib.Variant.split_signature('(iso)'), ['i', 's', 'o'])
349 self.assertEqual(GLib.Variant.split_signature('(s(ss)i(ii))'),
350 ['s', '(ss)', 'i', '(ii)'])
352 self.assertEqual(GLib.Variant.split_signature('(as)'), ['as'])
354 self.assertEqual(GLib.Variant.split_signature('(s(ss)iaiaasa(ii))'),
355 ['s', '(ss)', 'i', 'ai', 'aas', 'a(ii)'])
357 self.assertEqual(GLib.Variant.split_signature('(a{iv}(ii)((ss)a{s(ss)}))'),
358 ['a{iv}', '(ii)', '((ss)a{s(ss)})'])
360 def test_variant_hash(self):
361 v1 = GLib.Variant('s', 'somestring')
362 v2 = GLib.Variant('s', 'somestring')
363 v3 = GLib.Variant('s', 'somestring2')
365 self.assertTrue(v2 in set([v1, v3]))
366 self.assertTrue(v2 in frozenset([v1, v3]))
367 self.assertTrue(v2 in {v1: '1', v3:'2' })
369 def test_variant_compare(self):
370 # Check if identical GVariant are equal
372 def assert_equal(vtype, value):
373 self.assertEqual(GLib.Variant(vtype, value), GLib.Variant(vtype, value))
375 def assert_not_equal(vtype1, value1, vtype2, value2):
376 self.assertNotEqual(GLib.Variant(vtype1, value1), GLib.Variant(vtype2, value2))
378 numbers = ['y', 'n', 'q', 'i', 'u', 'x', 't', 'h', 'd']
380 assert_equal(num, 42)
381 assert_not_equal(num, 42, num, 41)
382 assert_not_equal(num, 42, 's', '42')
384 assert_equal('s', 'something')
385 assert_not_equal('s', 'something', 's', 'somethingelse')
386 assert_not_equal('s', 'something', 'i', 1234)
388 assert_equal('g', 'dustybinqhogx')
389 assert_not_equal('g', 'dustybinqhogx', 'g', 'dustybin')
390 assert_not_equal('g', 'dustybinqhogx', 'i', 1234)
392 assert_equal('o', '/dev/null')
393 assert_not_equal('o', '/dev/null', 'o', '/dev/zero')
394 assert_not_equal('o', '/dev/null', 'i', 1234)
396 assert_equal('(s)', ('strtuple',))
397 assert_not_equal('(s)', ('strtuple',), '(s)', ('strtuple2',))
399 assert_equal('a{si}', {'str': 42})
400 assert_not_equal('a{si}', {'str': 42}, 'a{si}', {'str': 43})
402 assert_equal('v', GLib.Variant('i', 42))
403 assert_not_equal('v', GLib.Variant('i', 42), 'v', GLib.Variant('i', 43))
405 def test_variant_bool(self):
406 # Check if the GVariant bool matches the unpacked Pythonic bool
408 def assert_equals_bool(vtype, value):
409 self.assertEqual(bool(GLib.Variant(vtype, value)), bool(value))
412 assert_equals_bool('b', True)
413 assert_equals_bool('b', False)
415 numbers = ['y', 'n', 'q', 'i', 'u', 'x', 't', 'h', 'd']
416 for number in numbers:
417 assert_equals_bool(number, 0)
418 assert_equals_bool(number, 1)
420 assert_equals_bool('s', '')
421 assert_equals_bool('g', '')
422 assert_equals_bool('s', 'something')
423 assert_equals_bool('o', '/dev/null')
424 assert_equals_bool('g', 'dustybinqhogx')
427 assert_equals_bool('ab', [True])
428 assert_equals_bool('ab', [False])
429 for number in numbers:
430 assert_equals_bool('a'+number, [])
431 assert_equals_bool('a'+number, [0])
432 assert_equals_bool('as', [])
433 assert_equals_bool('as', [''])
434 assert_equals_bool('ao', [])
435 assert_equals_bool('ao', ['/'])
436 assert_equals_bool('ag', [])
437 assert_equals_bool('ag', [''])
438 assert_equals_bool('aai', [[]])
441 assert_equals_bool('()', ())
442 for number in numbers:
443 assert_equals_bool('('+number+')', (0,))
444 assert_equals_bool('(s)', ('',))
445 assert_equals_bool('(o)', ('/',))
446 assert_equals_bool('(g)', ('',))
447 assert_equals_bool('(())', ((),))
450 assert_equals_bool('a{si}', {})
451 assert_equals_bool('a{si}', {'': 0})
453 # complex types, always True
454 assert_equals_bool('(as)', ([],))
455 assert_equals_bool('a{s(i)}', {'': (0,)})
457 # variant types, recursive unpacking
458 assert_equals_bool('v', GLib.Variant('i', 0))
459 assert_equals_bool('v', GLib.Variant('i', 1))
461 class TestPango(unittest.TestCase):
463 def test_default_font_description(self):
464 desc = Pango.FontDescription()
465 self.assertEquals(desc.get_variant(), Pango.Variant.NORMAL)
467 def test_font_description(self):
468 desc = Pango.FontDescription('monospace')
469 self.assertEquals(desc.get_family(), 'monospace')
470 self.assertEquals(desc.get_variant(), Pango.Variant.NORMAL)
472 def test_layout(self):
473 self.assertRaises(TypeError, Pango.Layout)
474 context = Pango.Context()
475 layout = Pango.Layout(context)
476 self.assertEquals(layout.get_context(), context)
478 layout.set_markup("Foobar")
479 self.assertEquals(layout.get_text(), "Foobar")
482 class TestGdk(unittest.TestCase):
484 def test_constructor(self):
485 attribute = Gdk.WindowAttr()
486 attribute.window_type = Gdk.WindowType.CHILD
487 attributes_mask = Gdk.WindowAttributesType.X | \
488 Gdk.WindowAttributesType.Y
489 window = Gdk.Window(None, attribute, attributes_mask)
490 self.assertEquals(window.get_window_type(), Gdk.WindowType.CHILD)
492 def test_color(self):
493 color = Gdk.Color(100, 200, 300)
494 self.assertEquals(color.red, 100)
495 self.assertEquals(color.green, 200)
496 self.assertEquals(color.blue, 300)
497 self.assertEquals(color, Gdk.Color(100, 200, 300))
498 self.assertNotEquals(color, Gdk.Color(1, 2, 3))
501 self.assertEquals(Gdk.RGBA, overrides.Gdk.RGBA)
502 rgba = Gdk.RGBA(0.1, 0.2, 0.3, 0.4)
503 self.assertEquals(rgba, Gdk.RGBA(0.1, 0.2, 0.3, 0.4))
504 self.assertNotEquals(rgba, Gdk.RGBA(0.0, 0.2, 0.3, 0.4))
505 self.assertEquals(rgba.red, 0.1)
506 self.assertEquals(rgba.green, 0.2)
507 self.assertEquals(rgba.blue, 0.3)
508 self.assertEquals(rgba.alpha, 0.4)
510 self.assertEquals(rgba.green, 0.9)
512 def test_event(self):
513 event = Gdk.Event.new(Gdk.EventType.CONFIGURE)
514 self.assertEquals(event.type, Gdk.EventType.CONFIGURE)
515 self.assertEquals(event.send_event, 0)
517 event = Gdk.Event.new(Gdk.EventType.DRAG_MOTION)
518 event.x_root, event.y_root = 0, 5
519 self.assertEquals(event.x_root, 0)
520 self.assertEquals(event.y_root, 5)
523 event.type = Gdk.EventType.SCROLL
524 self.assertRaises(AttributeError, lambda: getattr(event, 'foo_bar'))
526 def test_event_structures(self):
527 def button_press_cb(button, event):
528 self.assertTrue(isinstance(event, Gdk.EventButton))
529 self.assertTrue(event.type == Gdk.EventType.BUTTON_PRESS)
530 self.assertEquals(event.send_event, 0)
531 self.assertEquals(event.get_state(), Gdk.ModifierType.CONTROL_MASK)
532 self.assertEquals(event.get_root_coords(), (2, 5))
535 self.assertEquals(event.get_time(), 12345)
539 b.connect('button-press-event', button_press_cb)
542 Gdk.test_simulate_button(b.get_window(),
545 Gdk.ModifierType.CONTROL_MASK,
546 Gdk.EventType.BUTTON_PRESS)
548 def test_cursor(self):
549 self.assertEquals(Gdk.Cursor, overrides.Gdk.Cursor)
550 c = Gdk.Cursor(Gdk.CursorType.WATCH)
551 self.assertNotEqual(c, None)
552 c = Gdk.Cursor(cursor_type = Gdk.CursorType.WATCH)
553 self.assertNotEqual(c, None)
555 display_manager = Gdk.DisplayManager.get()
556 display = display_manager.get_default_display()
558 test_pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB,
564 c = Gdk.Cursor(display,
568 self.assertNotEqual(c, None)
569 self.assertRaises(ValueError, Gdk.Cursor, 1, 2, 3)
571 class TestGtk(unittest.TestCase):
573 def test_container(self):
575 self.failUnless(isinstance(box, Gtk.Box))
576 self.failUnless(isinstance(box, Gtk.Container))
577 self.failUnless(isinstance(box, Gtk.Widget))
583 self.assertTrue(label in box)
584 self.assertTrue(label2 in box)
585 self.assertEqual(len(box), 2)
588 self.assertEqual(l, [label, label2])
590 def test_actions(self):
591 self.assertEquals(Gtk.Action, overrides.Gtk.Action)
592 self.assertRaises(TypeError, Gtk.Action)
593 action = Gtk.Action("test", "Test", "Test Action", Gtk.STOCK_COPY)
594 self.assertEquals(action.get_name(), "test")
595 self.assertEquals(action.get_label(), "Test")
596 self.assertEquals(action.get_tooltip(), "Test Action")
597 self.assertEquals(action.get_stock_id(), Gtk.STOCK_COPY)
599 self.assertEquals(Gtk.RadioAction, overrides.Gtk.RadioAction)
600 self.assertRaises(TypeError, Gtk.RadioAction)
601 action = Gtk.RadioAction("test", "Test", "Test Action", Gtk.STOCK_COPY, 1)
602 self.assertEquals(action.get_name(), "test")
603 self.assertEquals(action.get_label(), "Test")
604 self.assertEquals(action.get_tooltip(), "Test Action")
605 self.assertEquals(action.get_stock_id(), Gtk.STOCK_COPY)
606 self.assertEquals(action.get_current_value(), 1)
608 def test_actiongroup(self):
609 self.assertEquals(Gtk.ActionGroup, overrides.Gtk.ActionGroup)
610 self.assertRaises(TypeError, Gtk.ActionGroup)
612 action_group = Gtk.ActionGroup (name = 'TestActionGroup')
613 callback_data = "callback data"
615 def test_action_callback_data(action, user_data):
616 self.assertEquals(user_data, callback_data);
618 def test_radio_action_callback_data(action, current, user_data):
619 self.assertEquals(user_data, callback_data);
621 action_group.add_actions ([
622 ('test-action1', None, 'Test Action 1',
623 None, None, test_action_callback_data),
624 ('test-action2', Gtk.STOCK_COPY, 'Test Action 2',
625 None, None, test_action_callback_data)], callback_data)
626 action_group.add_toggle_actions([
627 ('test-toggle-action1', None, 'Test Toggle Action 1',
628 None, None, test_action_callback_data, False),
629 ('test-toggle-action2', Gtk.STOCK_COPY, 'Test Toggle Action 2',
630 None, None, test_action_callback_data, True)], callback_data)
631 action_group.add_radio_actions([
632 ('test-radio-action1', None, 'Test Radio Action 1'),
633 ('test-radio-action2', Gtk.STOCK_COPY, 'Test Radio Action 2')], 1,
634 test_radio_action_callback_data,
637 expected_results = [('test-action1', Gtk.Action),
638 ('test-action2', Gtk.Action),
639 ('test-toggle-action1', Gtk.ToggleAction),
640 ('test-toggle-action2', Gtk.ToggleAction),
641 ('test-radio-action1', Gtk.RadioAction),
642 ('test-radio-action2', Gtk.RadioAction)]
644 for action in action_group.list_actions():
645 a = (action.get_name(), type(action))
646 self.assertTrue(a in expected_results)
647 expected_results.remove(a)
650 def test_uimanager(self):
651 self.assertEquals(Gtk.UIManager, overrides.Gtk.UIManager)
653 ui.add_ui_from_string(
656 <menubar name="menubar1"></menubar>
660 menubar = ui.get_widget("/menubar1")
661 self.assertEquals(type(menubar), Gtk.MenuBar)
663 ag = Gtk.ActionGroup (name="ag1")
664 ui.insert_action_group(ag)
665 ag2 = Gtk.ActionGroup (name="ag2")
666 ui.insert_action_group(ag2)
667 groups = ui.get_action_groups()
668 self.assertEquals(ag, groups[-2])
669 self.assertEquals(ag2, groups[-1])
671 def test_builder(self):
672 self.assertEquals(Gtk.Builder, overrides.Gtk.Builder)
674 class SignalTest(GObject.GObject):
675 __gtype_name__ = "GIOverrideSignalTest"
677 "test-signal": (GObject.SignalFlags.RUN_FIRST,
686 self.after_sentinel = 0;
688 def on_signal_1(self, *args):
690 self.after_sentinel += 1
692 def on_signal_3(self, *args):
695 def on_signal_after(self, *args):
696 if self.after_sentinel == 1:
697 self.after_sentinel += 1
699 signal_checker = SignalCheck()
700 builder = Gtk.Builder()
702 # add object1 to the builder
703 builder.add_from_string(
706 <object class="GIOverrideSignalTest" id="object1">
707 <signal name="test-signal" after="yes" handler="on_signal_after" />
708 <signal name="test-signal" handler="on_signal_1" />
713 # only add object3 to the builder
714 builder.add_objects_from_string(
717 <object class="GIOverrideSignalTest" id="object2">
718 <signal name="test-signal" handler="on_signal_2" />
720 <object class="GIOverrideSignalTest" id="object3">
721 <signal name="test-signal" handler="on_signal_3" />
723 <object class="GIOverrideSignalTest" id="object4">
724 <signal name="test-signal" handler="on_signal_4" />
732 builder.connect_signals(signal_checker)
734 # call their notify signals and check sentinel
735 objects = builder.get_objects()
736 self.assertEquals(len(objects), 2)
738 obj.emit('test-signal')
740 self.assertEquals(signal_checker.sentinel, 4)
741 self.assertEquals(signal_checker.after_sentinel, 2)
743 def test_dialogs(self):
744 self.assertEquals(Gtk.Dialog, overrides.Gtk.Dialog)
745 self.assertEquals(Gtk.AboutDialog, overrides.Gtk.AboutDialog)
746 self.assertEquals(Gtk.MessageDialog, overrides.Gtk.MessageDialog)
747 self.assertEquals(Gtk.ColorSelectionDialog, overrides.Gtk.ColorSelectionDialog)
748 self.assertEquals(Gtk.FileChooserDialog, overrides.Gtk.FileChooserDialog)
749 self.assertEquals(Gtk.FontSelectionDialog, overrides.Gtk.FontSelectionDialog)
750 self.assertEquals(Gtk.RecentChooserDialog, overrides.Gtk.RecentChooserDialog)
753 dialog = Gtk.Dialog (title='Foo',
754 flags=Gtk.DialogFlags.MODAL,
755 buttons=('test-button1', 1))
756 self.failUnless(isinstance(dialog, Gtk.Dialog))
757 self.failUnless(isinstance(dialog, Gtk.Window))
759 dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
761 self.assertEquals('Foo', dialog.get_title())
762 self.assertTrue(dialog.get_modal())
763 button = dialog.get_widget_for_response (1)
764 self.assertEquals('test-button1', button.get_label())
765 button = dialog.get_widget_for_response (2)
766 self.assertEquals('test-button2', button.get_label())
767 button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
768 self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
771 dialog = Gtk.AboutDialog()
772 self.failUnless(isinstance(dialog, Gtk.Dialog))
773 self.failUnless(isinstance(dialog, Gtk.Window))
776 dialog = Gtk.MessageDialog (title='message dialog test',
777 flags=Gtk.DialogFlags.MODAL,
778 buttons=Gtk.ButtonsType.OK,
779 message_format='dude!')
780 self.failUnless(isinstance(dialog, Gtk.Dialog))
781 self.failUnless(isinstance(dialog, Gtk.Window))
783 self.assertEquals('message dialog test', dialog.get_title())
784 self.assertTrue(dialog.get_modal())
785 text = dialog.get_property('text')
786 self.assertEquals('dude!', text)
788 dialog.format_secondary_text('2nd text')
789 self.assertEqual(dialog.get_property('secondary-text'), '2nd text')
790 self.assertFalse(dialog.get_property('secondary-use-markup'))
792 dialog.format_secondary_markup('2nd markup')
793 self.assertEqual(dialog.get_property('secondary-text'), '2nd markup')
794 self.assertTrue(dialog.get_property('secondary-use-markup'))
796 # Gtk.ColorSelectionDialog
797 dialog = Gtk.ColorSelectionDialog("color selection dialog test")
798 self.failUnless(isinstance(dialog, Gtk.Dialog))
799 self.failUnless(isinstance(dialog, Gtk.Window))
800 self.assertEquals('color selection dialog test', dialog.get_title())
802 # Gtk.FileChooserDialog
803 dialog = Gtk.FileChooserDialog (title='file chooser dialog test',
804 buttons=('test-button1', 1),
805 action=Gtk.FileChooserAction.SAVE)
806 self.failUnless(isinstance(dialog, Gtk.Dialog))
807 self.failUnless(isinstance(dialog, Gtk.Window))
809 dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
810 self.assertEquals('file chooser dialog test', dialog.get_title())
811 button = dialog.get_widget_for_response (1)
812 self.assertEquals('test-button1', button.get_label())
813 button = dialog.get_widget_for_response (2)
814 self.assertEquals('test-button2', button.get_label())
815 button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
816 self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
817 action = dialog.get_property('action')
818 self.assertEquals(Gtk.FileChooserAction.SAVE, action)
821 # Gtk.FontSelectionDialog
822 dialog = Gtk.ColorSelectionDialog("font selection dialog test")
823 self.failUnless(isinstance(dialog, Gtk.Dialog))
824 self.failUnless(isinstance(dialog, Gtk.Window))
825 self.assertEquals('font selection dialog test', dialog.get_title())
827 # Gtk.RecentChooserDialog
828 test_manager = Gtk.RecentManager()
829 dialog = Gtk.RecentChooserDialog (title='recent chooser dialog test',
830 buttons=('test-button1', 1),
831 manager=test_manager)
832 self.failUnless(isinstance(dialog, Gtk.Dialog))
833 self.failUnless(isinstance(dialog, Gtk.Window))
835 dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
836 self.assertEquals('recent chooser dialog test', dialog.get_title())
837 button = dialog.get_widget_for_response (1)
838 self.assertEquals('test-button1', button.get_label())
839 button = dialog.get_widget_for_response (2)
840 self.assertEquals('test-button2', button.get_label())
841 button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
842 self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
844 class TestClass(GObject.GObject):
845 __gtype_name__ = "GIOverrideTreeAPITest"
847 def __init__(self, tester, int_value, string_value):
848 super(TestGtk.TestClass, self).__init__()
850 self.int_value = int_value
851 self.string_value = string_value
853 def check(self, int_value, string_value):
854 self.tester.assertEquals(int_value, self.int_value)
855 self.tester.assertEquals(string_value, self.string_value)
857 def test_tree_store(self):
858 self.assertEquals(Gtk.TreeStore, overrides.Gtk.TreeStore)
859 self.assertEquals(Gtk.ListStore, overrides.Gtk.ListStore)
860 self.assertEquals(Gtk.TreeModel, overrides.Gtk.TreeModel)
861 self.assertEquals(Gtk.TreeViewColumn, overrides.Gtk.TreeViewColumn)
863 class TestPyObject(object):
866 test_pyobj = TestPyObject()
867 test_pydict = {1:1, "2":2, "3":"3"}
868 test_pylist = [1,"2", "3"]
869 tree_store = Gtk.TreeStore(int,
872 GObject.TYPE_PYOBJECT,
887 label = 'this is child #%d' % i
888 testobj = TestGtk.TestClass(self, i, label)
889 parent = tree_store.append(parent, (i,
906 parent = tree_store.append(parent)
908 label = 'this is child #%d' % i
909 testobj = TestGtk.TestClass(self, i, label)
910 tree_store.set(parent, 0, i,
920 10, GObject.G_MAXULONG,
921 11, GObject.G_MININT64,
922 12, 0xffffffffffffffff,
926 parent = tree_store.append(parent)
928 label = 'this is child #%d' % i
929 testobj = TestGtk.TestClass(self, i, label)
930 tree_store.set(parent, {0: i,
940 10: GObject.G_MAXULONG,
941 11: GObject.G_MININT64,
942 12: 0xffffffffffffffff,
946 parent = tree_store.append(parent)
948 label = 'this is child #%d' % i
949 testobj = TestGtk.TestClass(self, i, label)
950 tree_store.set(parent, (0, 2, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14),
967 # len gets the number of children in the root node
968 # since we kept appending to the previous node
969 # there should only be one child of the root
970 self.assertEquals(len(tree_store), 1)
972 # walk the tree to see if the values were stored correctly
976 treeiter = tree_store.iter_children(parent)
978 i = tree_store.get_value(treeiter, 0)
979 s = tree_store.get_value(treeiter, 1)
980 obj = tree_store.get_value(treeiter, 2)
982 obj2 = tree_store.get_value(treeiter, 3)
983 self.assertEquals(obj, obj2);
985 pyobj = tree_store.get_value(treeiter, 4)
986 self.assertEquals(pyobj, test_pyobj)
987 pydict = tree_store.get_value(treeiter, 5)
988 self.assertEquals(pydict, test_pydict)
989 pylist = tree_store.get_value(treeiter, 6)
990 self.assertEquals(pylist, test_pylist)
992 bool_1 = tree_store.get_value(treeiter, 7)
993 bool_2 = tree_store.get_value(treeiter, 8)
994 self.assertEquals(bool_1, bool_2)
995 self.assertTrue(isinstance(bool_1, bool))
996 self.assertTrue(isinstance(bool_2, bool))
998 uint_ = tree_store.get_value(treeiter, 9)
999 self.assertEquals(uint_, i)
1000 ulong_ = tree_store.get_value(treeiter, 10)
1001 self.assertEquals(ulong_, GObject.G_MAXULONG)
1002 int64_ = tree_store.get_value(treeiter, 11)
1003 self.assertEquals(int64_, GObject.G_MININT64)
1004 uint64_ = tree_store.get_value(treeiter, 12)
1005 self.assertEquals(uint64_, 0xffffffffffffffff)
1006 uchar_ = tree_store.get_value(treeiter, 13)
1007 self.assertEquals(ord(uchar_), 254)
1008 char_ = tree_store.get_value(treeiter, 14)
1009 self.assertEquals(char_, 'a')
1012 treeiter = tree_store.iter_children(parent)
1014 self.assertEquals(i, 99)
1016 def test_tree_store_signals(self):
1017 tree_store = Gtk.TreeStore(int, bool)
1019 def on_row_inserted(tree_store, tree_path, tree_iter, signal_list):
1020 signal_list.append('row-inserted')
1022 def on_row_changed(tree_store, tree_path, tree_iter, signal_list):
1023 signal_list.append('row-changed')
1026 tree_store.connect('row-inserted', on_row_inserted, signals)
1027 tree_store.connect('row-changed', on_row_changed, signals)
1029 # adding rows with and without data should only call one signal
1030 tree_store.append(None, (0, False))
1031 self.assertEqual(signals, ['row-inserted'])
1034 tree_store.append(None)
1035 self.assertEqual(signals, ['row-inserted'])
1038 tree_store.prepend(None, (0, False))
1039 self.assertEqual(signals, ['row-inserted'])
1042 tree_store.prepend(None)
1043 self.assertEqual(signals, ['row-inserted'])
1046 tree_store.insert(None, 1, (0, False))
1047 self.assertEqual(signals, ['row-inserted'])
1050 tree_store.insert(None, 1)
1051 self.assertEqual(signals, ['row-inserted'])
1053 def test_list_store(self):
1054 class TestPyObject(object):
1057 test_pyobj = TestPyObject()
1058 test_pydict = {1:1, "2":2, "3":"3"}
1059 test_pylist = [1,"2", "3"]
1061 list_store = Gtk.ListStore(int, str, 'GIOverrideTreeAPITest', object, object, object, bool, bool)
1062 for i in range(1, 93):
1063 label = 'this is row #%d' % i
1064 testobj = TestGtk.TestClass(self, i, label)
1065 parent = list_store.append((i,
1075 label = _unicode('this is row #93')
1076 treeiter = list_store.append()
1077 list_store.set_value(treeiter, 0, i)
1078 list_store.set_value(treeiter, 1, label)
1079 list_store.set_value(treeiter, 2, TestGtk.TestClass(self, i, label))
1080 list_store.set_value(treeiter, 3, test_pyobj)
1081 list_store.set_value(treeiter, 4, test_pydict)
1082 list_store.set_value(treeiter, 5, test_pylist)
1083 list_store.set_value(treeiter, 6, 1)
1084 list_store.set_value(treeiter, 7, True)
1087 label = 'this is row #0'
1088 list_store.prepend((0,
1090 TestGtk.TestClass(self, 0, label),
1097 # test automatic unicode->str conversion
1099 label = _unicode('this is row #94')
1100 treeiter = list_store.append((i,
1102 TestGtk.TestClass(self, i, label),
1109 # add sorted items out of order to test insert* apis
1110 # also test sending in None to not set a column
1112 label = 'this is row #97'
1113 treeiter = list_store.append((None,
1122 list_store.set_value(treeiter, 0, i)
1123 list_store.set_value(treeiter, 1, label)
1124 list_store.set_value(treeiter, 2, TestGtk.TestClass(self, i, label))
1125 list_store.set_value(treeiter, 4, test_pydict)
1126 list_store.set_value(treeiter, 7, True)
1128 # this should append
1130 label = 'this is row #99'
1131 list_store.insert(9999, (i,
1133 TestGtk.TestClass(self, i, label),
1141 label = 'this is row #96'
1142 list_store.insert_before(treeiter, (i,
1144 TestGtk.TestClass(self, i, label),
1152 label = 'this is row #98'
1153 list_store.insert_after(treeiter, (i,
1155 TestGtk.TestClass(self, i, label),
1164 label = 'this is row #95'
1165 list_store.insert(95, (i,
1167 TestGtk.TestClass(self, i, label),
1175 label = 'this is row #100'
1176 treeiter = list_store.append()
1177 list_store.set(treeiter, 1, label,
1179 2, TestGtk.TestClass(self, i, label),
1186 label = 'this is row #101'
1187 treeiter = list_store.append()
1188 list_store.set(treeiter, {1: label,
1190 2: TestGtk.TestClass(self, i, label),
1197 label = 'this is row #102'
1198 treeiter = list_store.append()
1199 list_store.set(treeiter, (1, 0, 2, 3, 4, 5, 6, 7),
1202 TestGtk.TestClass(self, i, label),
1209 self.assertEquals(len(list_store), 103)
1211 # walk the list to see if the values were stored correctly
1213 treeiter = list_store.get_iter_first()
1217 i = list_store.get_value(treeiter, 0)
1218 self.assertEquals(i, counter)
1219 s = list_store.get_value(treeiter, 1)
1220 obj = list_store.get_value(treeiter, 2)
1223 pyobj = list_store.get_value(treeiter, 3)
1224 self.assertEquals(pyobj, test_pyobj)
1225 pydict = list_store.get_value(treeiter, 4)
1226 self.assertEquals(pydict, test_pydict)
1227 pylist = list_store.get_value(treeiter, 5)
1228 self.assertEquals(pylist, test_pylist)
1230 bool_1 = list_store.get_value(treeiter, 6)
1231 bool_2 = list_store.get_value(treeiter, 7)
1232 self.assertEquals(bool_1, bool_2)
1233 self.assertTrue(isinstance(bool_1, bool))
1234 self.assertTrue(isinstance(bool_2, bool))
1236 treeiter = list_store.iter_next(treeiter)
1240 self.assertEquals(i, 102)
1242 def test_list_store_signals(self):
1243 list_store = Gtk.ListStore(int, bool)
1245 def on_row_inserted(list_store, tree_path, tree_iter, signal_list):
1246 signal_list.append('row-inserted')
1248 def on_row_changed(list_store, tree_path, tree_iter, signal_list):
1249 signal_list.append('row-changed')
1252 list_store.connect('row-inserted', on_row_inserted, signals)
1253 list_store.connect('row-changed', on_row_changed, signals)
1255 # adding rows with and without data should only call one signal
1256 list_store.append((0, False))
1257 self.assertEqual(signals, ['row-inserted'])
1261 self.assertEqual(signals, ['row-inserted'])
1264 list_store.prepend((0, False))
1265 self.assertEqual(signals, ['row-inserted'])
1268 list_store.prepend()
1269 self.assertEqual(signals, ['row-inserted'])
1272 list_store.insert(1, (0, False))
1273 self.assertEqual(signals, ['row-inserted'])
1276 list_store.insert(1)
1277 self.assertEqual(signals, ['row-inserted'])
1279 def test_tree_path(self):
1281 p2 = Gtk.TreePath.new_first()
1282 self.assertEqual(p1, p2)
1283 self.assertEqual(str(p1), '0')
1284 p1 = Gtk.TreePath(2)
1285 p2 = Gtk.TreePath.new_from_string('2')
1286 self.assertEqual(p1, p2)
1287 self.assertEqual(str(p1), '2')
1288 p1 = Gtk.TreePath('1:2:3')
1289 p2 = Gtk.TreePath.new_from_string('1:2:3')
1290 self.assertEqual(p1, p2)
1291 self.assertEqual(str(p1), '1:2:3')
1292 p1 = Gtk.TreePath((1,2,3))
1293 p2 = Gtk.TreePath.new_from_string('1:2:3')
1294 self.assertEqual(p1, p2)
1295 self.assertEqual(str(p1), '1:2:3')
1296 self.assertTrue(p1 != None)
1297 self.assertFalse(p1 == None)
1298 self.assertTrue(p1 > None)
1299 self.assertTrue(p1 >= None)
1300 self.assertFalse(p1 < None)
1301 self.assertFalse(p1 <= None)
1303 self.assertEquals(tuple(p1), (1, 2, 3))
1305 def test_tree_model(self):
1306 tree_store = Gtk.TreeStore(int, str)
1308 self.assertTrue(tree_store)
1309 self.assertEqual(len(tree_store), 0)
1310 self.assertEqual(tree_store.get_iter_first(), None)
1312 def get_by_index(row, col=None):
1314 return tree_store[row][col]
1316 return tree_store[row]
1318 self.assertRaises(TypeError, get_by_index, None)
1319 self.assertRaises(TypeError, get_by_index, "")
1320 self.assertRaises(TypeError, get_by_index, ())
1322 self.assertRaises(IndexError, get_by_index, "0")
1323 self.assertRaises(IndexError, get_by_index, 0)
1324 self.assertRaises(IndexError, get_by_index, (0,))
1326 self.assertRaises(ValueError, tree_store.get_iter, "0")
1327 self.assertRaises(ValueError, tree_store.get_iter, 0)
1328 self.assertRaises(ValueError, tree_store.get_iter, (0,))
1330 self.assertRaises(ValueError, tree_store.get_iter_from_string, "0")
1332 for row in tree_store:
1333 self.fail("Should not be reached")
1335 class DerivedIntType(int):
1338 class DerivedStrType(str):
1341 for i in range(100):
1342 label = 'this is row #%d' % i
1343 parent = tree_store.append(None, (DerivedIntType(i), DerivedStrType(label),))
1344 self.assertNotEquals(parent, None)
1346 label = 'this is child #%d of node #%d' % (j, i)
1347 child = tree_store.append(parent, (j, label,))
1348 self.assertNotEqual(child, None)
1350 self.assertTrue(tree_store)
1351 self.assertEqual(len(tree_store), 100)
1353 self.assertEqual(tree_store.iter_previous(tree_store.get_iter(0)), None)
1355 for i,row in enumerate(tree_store):
1356 self.assertEqual(row.model, tree_store)
1357 self.assertEqual(row.parent, None)
1359 self.assertEqual(tree_store[i].path, row.path)
1360 self.assertEqual(tree_store[str(i)].path, row.path)
1361 self.assertEqual(tree_store[(i,)].path, row.path)
1363 self.assertEqual(tree_store[i][0], i)
1364 self.assertEqual(tree_store[i][1], "this is row #%d" % i)
1366 aiter = tree_store.get_iter(i)
1367 self.assertEqual(tree_store.get_path(aiter), row.path)
1369 aiter = tree_store.get_iter(str(i))
1370 self.assertEqual(tree_store.get_path(aiter), row.path)
1372 aiter = tree_store.get_iter((i,))
1373 self.assertEqual(tree_store.get_path(aiter), row.path)
1375 self.assertEqual(tree_store.iter_parent(aiter), row.parent)
1377 next = tree_store.iter_next(aiter)
1378 if i < len(tree_store) - 1:
1379 self.assertEqual(tree_store.get_path(next), row.next.path)
1380 self.assertEqual(tree_store.get_path(tree_store.iter_previous(next)),
1381 tree_store.get_path(aiter))
1383 self.assertEqual(next, None)
1385 self.assertEqual(tree_store.iter_n_children(row.iter), 20)
1387 child = tree_store.iter_children(row.iter)
1388 for j,childrow in enumerate(row.iterchildren()):
1389 child_path = tree_store.get_path(child)
1390 self.assertEqual(childrow.path, child_path)
1391 self.assertEqual(childrow.parent.path, row.path)
1392 self.assertEqual(childrow.path, tree_store[child].path)
1393 self.assertEqual(childrow.path, tree_store[child_path].path)
1395 self.assertEqual(childrow[0], tree_store[child][0])
1396 self.assertEqual(childrow[0], j)
1397 self.assertEqual(childrow[1], tree_store[child][1])
1398 self.assertEqual(childrow[1], 'this is child #%d of node #%d' % (j, i))
1400 self.assertRaises(IndexError, get_by_index, child, 2)
1402 tree_store[child][1] = 'this was child #%d of node #%d' % (j, i)
1403 self.assertEqual(childrow[1], 'this was child #%d of node #%d' % (j, i))
1405 nth_child = tree_store.iter_nth_child(row.iter, j)
1406 self.assertEqual(childrow.path, tree_store.get_path(nth_child))
1408 childrow2 = tree_store["%d:%d" % (i, j)]
1409 self.assertEqual(childrow.path, childrow2.path)
1411 childrow2 = tree_store[(i, j,)]
1412 self.assertEqual(childrow.path, childrow2.path)
1414 child = tree_store.iter_next(child)
1416 self.assertEqual(childrow.next.path, tree_store.get_path(child))
1418 self.assertEqual(child, childrow.next)
1419 self.assertEqual(child, None)
1421 self.assertEqual(j, 19)
1423 self.assertEqual(i, 99)
1426 for i in range(-1,-100,-1):
1428 self.assertEqual(tree_store[i][0], i_real)
1431 for j in range(-1, -20, -1):
1433 path = (i_real, j_real,)
1435 self.assertEqual(tree_store[path][-2], j_real)
1437 label = 'this was child #%d of node #%d' % (j_real, i_real)
1438 self.assertEqual(tree_store[path][-1], label)
1440 new_label = 'this still is child #%d of node #%d' % (j_real, i_real)
1441 tree_store[path][-1] = new_label
1442 self.assertEqual(tree_store[path][-1], new_label)
1444 self.assertRaises(IndexError, get_by_index, path, -3)
1446 self.assertRaises(IndexError, get_by_index, -101)
1448 last_row = tree_store[99]
1449 self.assertNotEqual(last_row, None)
1451 for i,childrow in enumerate(last_row.iterchildren()):
1453 self.assertTrue(tree_store.remove(childrow.iter))
1455 self.assertFalse(tree_store.remove(childrow.iter))
1457 self.assertEqual(i, 19)
1459 self.assertEqual(tree_store.iter_n_children(last_row.iter), 0)
1460 for childrow in last_row.iterchildren():
1461 self.fail("Should not be reached")
1463 aiter = tree_store.get_iter(10)
1464 self.assertRaises(TypeError, tree_store.get, aiter, 1, 'a')
1465 self.assertRaises(ValueError, tree_store.get, aiter, 1, -1)
1466 self.assertRaises(ValueError, tree_store.get, aiter, 1, 100)
1467 self.assertEqual(tree_store.get(aiter, 0, 1), (10, 'this is row #10'))
1469 def test_tree_model_edit(self):
1470 model = Gtk.ListStore(int, str, float)
1471 model.append([1, "one", -0.1])
1472 model.append([2, "two", -0.2])
1477 self.assertRaises(TypeError, set_row, 3)
1478 self.assertRaises(TypeError, set_row, "three")
1479 self.assertRaises(ValueError, set_row, [])
1480 self.assertRaises(ValueError, set_row, [3, "three"])
1482 model[0] = (3, "three", -0.3)
1484 def test_tree_row_slice(self):
1485 model = Gtk.ListStore(int, str, float)
1486 model.append([1, "one", -0.1])
1488 self.assertEqual([1, "one", -0.1], model[0][:])
1489 self.assertEqual([1, "one"], model[0][:2])
1490 self.assertEqual(["one", -0.1], model[0][1:])
1491 self.assertEqual(["one"], model[0][1:-1])
1492 self.assertEqual([1], model[0][:-2])
1493 self.assertEqual([], model[0][5:])
1494 self.assertEqual([1, -0.1], model[0][0:3:2])
1496 model[0][:] = (2, "two", -0.2)
1497 self.assertEqual([2, "two", -0.2], model[0][:])
1499 model[0][:2] = (3, "three")
1500 self.assertEqual([3, "three", -0.2], model[0][:])
1502 model[0][1:] = ("four", -0.4)
1503 self.assertEqual([3, "four", -0.4], model[0][:])
1505 model[0][1:-1] = ("five",)
1506 self.assertEqual([3, "five", -0.4], model[0][:])
1508 model[0][0:3:2] = (6, -0.6)
1509 self.assertEqual([6, "five", -0.6], model[0][:])
1512 model[0][5:] = ("doesn't", "matter",)
1514 self.assertRaises(ValueError, set_row1)
1517 model[0][:1] = (0, "zero", 0)
1519 self.assertRaises(ValueError, set_row2)
1522 model[0][:2] = ("0", 0)
1524 self.assertRaises(ValueError, set_row3)
1526 def test_tree_view(self):
1527 store = Gtk.ListStore(int, str)
1528 store.append((0, "foo"))
1529 store.append((1, "bar"))
1530 view = Gtk.TreeView()
1531 # We can't easily call get_cursor() to make sure this works as
1532 # expected as we need to realize and focus the column
1533 view.set_cursor(store[1].path)
1534 view.set_cursor(str(store[1].path))
1536 view.get_cell_area(store[1].path)
1537 view.get_cell_area(str(store[1].path))
1539 def test_tree_view_column(self):
1540 cell = Gtk.CellRendererText()
1541 column = Gtk.TreeViewColumn(title='This is just a test',
1546 def test_tree_selection(self):
1547 store = Gtk.ListStore(int, str)
1549 store.append((i, "foo"))
1550 view = Gtk.TreeView()
1551 view.set_model(store)
1552 firstpath = store.get_path(store.get_iter_first())
1553 sel = view.get_selection()
1555 sel.select_path(firstpath)
1556 (m, s) = sel.get_selected()
1557 self.assertEqual(m, store)
1558 self.assertEqual(store.get_path(s), firstpath)
1561 (m, s) = sel.get_selected()
1562 self.assertEqual(m, store)
1563 self.assertEqual(store.get_path(s), firstpath)
1565 sel.select_path("0:0")
1566 (m, s) = sel.get_selected()
1567 self.assertEqual(m, store)
1568 self.assertEqual(store.get_path(s), firstpath)
1570 sel.select_path((0,0))
1571 (m, s) = sel.get_selected()
1572 self.assertEqual(m, store)
1573 self.assertEqual(store.get_path(s), firstpath)
1575 def test_text_buffer(self):
1576 self.assertEquals(Gtk.TextBuffer, overrides.Gtk.TextBuffer)
1577 buffer = Gtk.TextBuffer()
1578 tag = buffer.create_tag ('title', font = 'Sans 18')
1580 self.assertEquals(tag.props.name, 'title')
1581 self.assertEquals(tag.props.font, 'Sans 18')
1583 (start, end) = buffer.get_bounds()
1585 mark = buffer.create_mark(None, start)
1586 self.assertFalse(mark.get_left_gravity())
1588 buffer.set_text('Hello Jane Hello Bob')
1589 (start, end) = buffer.get_bounds()
1590 text = buffer.get_text(start, end, False)
1591 self.assertEquals(text, 'Hello Jane Hello Bob')
1594 (start, end) = buffer.get_bounds()
1595 text = buffer.get_text(start, end, False)
1596 self.assertEquals(text, '')
1598 buffer.insert(end, 'HelloHello')
1599 buffer.insert(end, ' Bob')
1601 cursor_iter = end.copy()
1602 cursor_iter.backward_chars(9)
1603 buffer.place_cursor(cursor_iter)
1604 buffer.insert_at_cursor(' Jane ')
1606 (start, end) = buffer.get_bounds()
1607 text = buffer.get_text(start, end, False)
1608 self.assertEquals(text, 'Hello Jane Hello Bob')
1610 sel = buffer.get_selection_bounds()
1611 self.assertEquals(sel, ())
1612 buffer.select_range(start, end)
1613 sel = buffer.get_selection_bounds()
1614 self.assertTrue(sel[0].equal(start))
1615 self.assertTrue(sel[1].equal(end))
1618 buffer.insert_with_tags(buffer.get_start_iter(), 'HelloHello', tag)
1619 (start, end) = buffer.get_bounds()
1620 self.assertTrue(start.begins_tag(tag))
1621 self.assertTrue(start.has_tag(tag))
1624 buffer.insert_with_tags_by_name(buffer.get_start_iter(), 'HelloHello', 'title')
1625 (start, end) = buffer.get_bounds()
1626 self.assertTrue(start.begins_tag(tag))
1627 self.assertTrue(start.has_tag(tag))
1629 self.assertRaises(ValueError, buffer.insert_with_tags_by_name,
1630 buffer.get_start_iter(), 'HelloHello', 'unknowntag')
1632 def test_text_iter(self):
1633 self.assertEquals(Gtk.TextIter, overrides.Gtk.TextIter)
1634 buffer = Gtk.TextBuffer()
1635 buffer.set_text('Hello Jane Hello Bob')
1636 tag = buffer.create_tag ('title', font = 'Sans 18')
1637 (start, end) = buffer.get_bounds()
1638 start.forward_chars(10)
1639 buffer.apply_tag(tag, start, end)
1640 self.assertTrue(start.begins_tag())
1641 self.assertTrue(end.ends_tag())
1642 self.assertTrue(start.toggles_tag())
1643 self.assertTrue(end.toggles_tag())
1644 start.backward_chars(1)
1645 self.assertFalse(start.begins_tag())
1646 self.assertFalse(start.ends_tag())
1647 self.assertFalse(start.toggles_tag())
1649 def test_buttons(self):
1650 self.assertEquals(Gtk.Button, overrides.Gtk.Button)
1653 button = Gtk.Button()
1654 self.failUnless(isinstance(button, Gtk.Button))
1655 self.failUnless(isinstance(button, Gtk.Container))
1656 self.failUnless(isinstance(button, Gtk.Widget))
1657 button = Gtk.Button(stock=Gtk.STOCK_CLOSE)
1658 self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
1659 self.assertTrue(button.get_use_stock())
1660 self.assertTrue(button.get_use_underline())
1662 # test Gtk.Button use_stock
1663 button = Gtk.Button(label=Gtk.STOCK_CLOSE, use_stock=True, use_underline=True)
1664 self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
1665 self.assertTrue(button.get_use_stock())
1666 self.assertTrue(button.get_use_underline())
1668 # test Gtk.LinkButton
1669 self.assertRaises(TypeError, Gtk.LinkButton)
1670 button = Gtk.LinkButton('http://www.Gtk.org', 'Gtk')
1671 self.failUnless(isinstance(button, Gtk.Button))
1672 self.failUnless(isinstance(button, Gtk.Container))
1673 self.failUnless(isinstance(button, Gtk.Widget))
1674 self.assertEquals('http://www.Gtk.org', button.get_uri())
1675 self.assertEquals('Gtk', button.get_label())
1677 def test_inheritance(self):
1678 for name in overrides.Gtk.__all__:
1679 over = getattr(overrides.Gtk, name)
1680 for element in dir(Gtk):
1682 klass = getattr(Gtk, element)
1683 info = klass.__info__
1684 except (NotImplementedError, AttributeError):
1687 # Get all parent classes and interfaces klass inherits from
1688 if isinstance(info, gi.types.ObjectInfo):
1689 classes = list(info.get_interfaces())
1690 parent = info.get_parent()
1691 while parent.get_name() != "Object":
1692 classes.append(parent)
1693 parent = parent.get_parent()
1694 classes = [kl for kl in classes if kl.get_namespace() == "Gtk"]
1699 if kl.get_name() == name:
1700 self.assertTrue(issubclass(klass, over,),
1701 "%r does not inherit from override %r" % (klass, over,))
1703 def test_editable(self):
1704 self.assertEquals(Gtk.Editable, overrides.Gtk.Editable)
1706 # need to use Gtk.Entry because Editable is an interface
1708 pos = entry.insert_text('HeWorld', 0)
1709 self.assertEquals(pos, 7)
1710 pos = entry.insert_text('llo ', 2)
1711 self.assertEquals(pos, 6)
1712 text = entry.get_chars(0, 11)
1713 self.assertEquals('Hello World', text)
1715 def test_label(self):
1716 label = Gtk.Label(label='Hello')
1717 self.failUnless(isinstance(label, Gtk.Widget))
1718 self.assertEquals(label.get_text(), 'Hello')
1720 def adjustment_check(self, adjustment, value=0.0, lower=0.0, upper=0.0,
1721 step_increment=0.0, page_increment=0.0, page_size=0.0):
1722 self.assertEquals(adjustment.get_value(), value)
1723 self.assertEquals(adjustment.get_lower(), lower)
1724 self.assertEquals(adjustment.get_upper(), upper)
1725 self.assertEquals(adjustment.get_step_increment(), step_increment)
1726 self.assertEquals(adjustment.get_page_increment(), page_increment)
1727 self.assertEquals(adjustment.get_page_size(), page_size)
1729 def test_adjustment(self):
1730 adjustment = Gtk.Adjustment(1, 0, 6, 4, 5, 3)
1731 self.adjustment_check(adjustment, 1, 0, 6, 4, 5, 3)
1733 adjustment = Gtk.Adjustment(1, 0, 6, 4, 5)
1734 self.adjustment_check(adjustment, 1, 0, 6, 4, 5)
1736 adjustment = Gtk.Adjustment(1, 0, 6, 4)
1737 self.adjustment_check(adjustment, 1, 0, 6, 4)
1739 adjustment = Gtk.Adjustment(1, 0, 6)
1740 self.adjustment_check(adjustment, 1, 0, 6)
1742 adjustment = Gtk.Adjustment()
1743 self.adjustment_check(adjustment)
1745 adjustment = Gtk.Adjustment(value=1, lower=0, upper=6,
1746 step_increment=4, page_increment=5, page_size=3)
1747 self.adjustment_check(adjustment, 1, 0, 6, 4, 5, 3)
1749 def test_table(self):
1751 self.failUnless(isinstance(table, Gtk.Table))
1752 self.failUnless(isinstance(table, Gtk.Container))
1753 self.failUnless(isinstance(table, Gtk.Widget))
1754 self.assertEquals(table.get_size(), (1,1))
1755 self.assertEquals(table.get_homogeneous(), False)
1756 table = Gtk.Table(2, 3)
1757 self.assertEquals(table.get_size(), (2,3))
1758 self.assertEquals(table.get_homogeneous(), False)
1759 table = Gtk.Table(2, 3, True)
1760 self.assertEquals(table.get_size(), (2,3))
1761 self.assertEquals(table.get_homogeneous(), True)
1763 # Test PyGTK interface
1764 table = Gtk.Table(rows=3, columns=2)
1765 self.assertEquals(table.get_size(), (3,2))
1766 # Test using the actual property names
1767 table = Gtk.Table(n_rows=2, n_columns=3, homogeneous=True)
1768 self.assertEquals(table.get_size(), (2,3))
1769 self.assertEquals(table.get_homogeneous(), True)
1771 label = Gtk.Label(label='Hello')
1772 self.failUnless(isinstance(label, Gtk.Widget))
1773 table.attach(label, 0, 1, 0, 1)
1774 self.assertEquals(label, table.get_children()[0])
1776 def test_scrolledwindow(self):
1777 sw = Gtk.ScrolledWindow()
1778 self.failUnless(isinstance(sw, Gtk.ScrolledWindow))
1779 self.failUnless(isinstance(sw, Gtk.Container))
1780 self.failUnless(isinstance(sw, Gtk.Widget))
1781 sb = sw.get_hscrollbar()
1782 self.assertEquals(sw.get_hadjustment(), sb.get_adjustment())
1783 sb = sw.get_vscrollbar()
1784 self.assertEquals(sw.get_vadjustment(), sb.get_adjustment())
1786 def test_widget_drag_methods(self):
1787 widget = Gtk.Button()
1789 # here we are not checking functionality, only that the methods exist
1790 # and except the right number of arguments
1792 widget.drag_check_threshold(0, 0, 0, 0)
1794 # drag_dest_ methods
1795 widget.drag_dest_set(Gtk.DestDefaults.DROP, None, Gdk.DragAction.COPY)
1796 widget.drag_dest_add_image_targets()
1797 widget.drag_dest_add_text_targets()
1798 widget.drag_dest_add_uri_targets()
1799 widget.drag_dest_get_track_motion()
1800 widget.drag_dest_set_track_motion(True)
1801 widget.drag_dest_get_target_list()
1802 widget.drag_dest_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test',0, 0)]))
1803 widget.drag_dest_unset()
1805 widget.drag_highlight()
1806 widget.drag_unhighlight()
1808 # drag_source_ methods
1809 widget.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, None, Gdk.DragAction.MOVE)
1810 widget.drag_source_add_image_targets()
1811 widget.drag_source_add_text_targets()
1812 widget.drag_source_add_uri_targets()
1813 widget.drag_source_set_icon_name("")
1814 widget.drag_source_set_icon_pixbuf(GdkPixbuf.Pixbuf())
1815 widget.drag_source_set_icon_stock("")
1816 widget.drag_source_get_target_list()
1817 widget.drag_source_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)]))
1818 widget.drag_source_unset()
1820 # these methods cannot be called because they require a valid drag on
1821 # a real GdkWindow. So we only check that they exist and are callable.
1822 self.assertTrue(hasattr(widget.drag_dest_set_proxy, '__call__'))
1823 self.assertTrue(hasattr(widget.drag_get_data, '__call__'))
1825 def test_scrollbar(self):
1827 adjustment = Gtk.Adjustment()
1829 hscrollbar = Gtk.HScrollbar()
1830 vscrollbar = Gtk.VScrollbar()
1831 self.assertNotEquals(hscrollbar.props.adjustment, adjustment)
1832 self.assertNotEquals(vscrollbar.props.adjustment, adjustment)
1834 hscrollbar = Gtk.HScrollbar(adjustment)
1835 vscrollbar = Gtk.VScrollbar(adjustment)
1836 self.assertEquals(hscrollbar.props.adjustment, adjustment)
1837 self.assertEquals(vscrollbar.props.adjustment, adjustment)
1839 def test_iconview(self):
1841 iconview = Gtk.IconView()
1842 self.assertEquals(iconview.props.model, None)
1844 model = Gtk.ListStore(str)
1845 iconview = Gtk.IconView(model)
1846 self.assertEquals(iconview.props.model, model)
1848 def test_toolbutton(self):
1850 button = Gtk.ToolButton()
1851 self.assertEquals(button.props.stock_id, None)
1853 button = Gtk.ToolButton('gtk-new')
1854 self.assertEquals(button.props.stock_id, 'gtk-new')
1856 icon = Gtk.Image.new_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.SMALL_TOOLBAR)
1858 button = Gtk.ToolButton(label='mylabel', icon_widget=icon)
1859 self.assertEqual(button.props.label, 'mylabel')
1860 self.assertEqual(button.props.icon_widget, icon)
1862 def test_iconset(self):
1864 iconset = Gtk.IconSet()
1865 pixbuf = GdkPixbuf.Pixbuf()
1866 iconset = Gtk.IconSet(pixbuf)
1868 def test_viewport(self):
1870 vadjustment = Gtk.Adjustment()
1871 hadjustment = Gtk.Adjustment()
1873 viewport = Gtk.Viewport(hadjustment=hadjustment,
1874 vadjustment=vadjustment)
1876 self.assertEquals(viewport.props.vadjustment, vadjustment)
1877 self.assertEquals(viewport.props.hadjustment, hadjustment)
1880 class TestGio(unittest.TestCase):
1882 self.settings = Gio.Settings('org.gnome.test')
1883 # we change the values in the tests, so set them to predictable start
1885 self.settings.reset('test-string')
1886 self.settings.reset('test-array')
1888 def test_file_enumerator(self):
1889 self.assertEquals(Gio.FileEnumerator, overrides.Gio.FileEnumerator)
1890 f = Gio.file_new_for_path("./")
1893 for info in f.enumerate_children("standard::*", 0, None):
1894 iter_info.append(info.get_name())
1897 enumerator = f.enumerate_children("standard::*", 0, None)
1899 info = enumerator.next_file(None)
1902 next_info.append(info.get_name())
1904 self.assertEquals(iter_info, next_info)
1906 def test_gsettings_native(self):
1907 self.assertTrue('test-array' in self.settings.list_keys())
1910 v = self.settings.get_value('test-boolean')
1911 self.assertEqual(v.get_boolean(), True)
1912 self.assertEqual(self.settings.get_boolean('test-boolean'), True)
1914 v = self.settings.get_value('test-string')
1915 self.assertEqual(v.get_string(), 'Hello')
1916 self.assertEqual(self.settings.get_string('test-string'), 'Hello')
1918 v = self.settings.get_value('test-array')
1919 self.assertEqual(v.unpack(), [1, 2])
1921 v = self.settings.get_value('test-tuple')
1922 self.assertEqual(v.unpack(), (1, 2))
1925 self.settings.set_string('test-string', 'World')
1926 self.assertEqual(self.settings.get_string('test-string'), 'World')
1928 self.settings.set_value('test-string', GLib.Variant('s', 'Goodbye'))
1929 self.assertEqual(self.settings.get_string('test-string'), 'Goodbye')
1931 def test_gsettings_constructor(self):
1932 # default constructor uses path from schema
1933 self.assertEqual(self.settings.get_property('path'), '/tests/')
1935 # optional constructor arguments
1936 with_path = Gio.Settings('org.gnome.nopathtest', path='/mypath/')
1937 self.assertEqual(with_path.get_property('path'), '/mypath/')
1938 self.assertEqual(with_path['np-int'], 42)
1940 def test_gsettings_override(self):
1941 # dictionary interface
1942 self.assertEqual(len(self.settings), 4)
1943 self.assertTrue('test-array' in self.settings)
1944 self.assertTrue('test-array' in self.settings.keys())
1945 self.failIf('nonexisting' in self.settings)
1946 self.failIf(4 in self.settings)
1947 self.assertEqual(bool(self.settings), True)
1950 self.assertEqual(self.settings['test-boolean'], True)
1951 self.assertEqual(self.settings['test-string'], 'Hello')
1952 self.assertEqual(self.settings['test-array'], [1, 2])
1953 self.assertEqual(self.settings['test-tuple'], (1, 2))
1955 self.assertRaises(KeyError, self.settings.__getitem__, 'unknown')
1956 self.assertRaises(KeyError, self.settings.__getitem__, 2)
1959 self.settings['test-string'] = 'Goodbye'
1960 self.assertEqual(self.settings['test-string'], 'Goodbye')
1961 self.settings['test-array'] = [3, 4, 5]
1962 self.assertEqual(self.settings['test-array'], [3, 4, 5])
1964 self.assertRaises(TypeError, self.settings.__setitem__, 'test-string', 1)
1965 self.assertRaises(KeyError, self.settings.__setitem__, 'unknown', 'moo')
1967 def test_gsettings_empty(self):
1968 empty = Gio.Settings('org.gnome.empty', path='/tests/')
1969 self.assertEqual(len(empty), 0)
1970 self.assertEqual(bool(empty), True)
1971 self.assertEqual(empty.keys(), [])