code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python '''Test that mouse cursor can be made visible and hidden. Expected behaviour: One window will be opened. Press 'v' to hide mouse cursor and 'V' to show mouse cursor. It should only affect the mouse when within the client area of the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_MOUSE_VISIBLE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.V: visible = (modifiers & key.MOD_SHIFT) self.w.set_mouse_visible(visible) print 'Mouse is now %s' % (visible and 'visible' or 'hidden') def on_mouse_motion(self, x, y, dx, dy): print 'on_mousemotion(x=%f, y=%f, dx=%f, dy=%f)' % (x, y, dx, dy) def test_set_visible(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ import unittest import time class BaseEventSequence(unittest.TestCase): next_sequence = 0 last_sequence = 0 finished = False timeout = 2 start_time = time.time() def check_sequence(self, sequence, name): if self.next_sequence == 0 and sequence != 0: return if sequence == 0: self.start_time = time.time() if not self.finished: if self.next_sequence != sequence: print 'ERROR: %s out of order' % name else: print 'OK: %s' % name self.next_sequence += 1 if self.next_sequence > self.last_sequence: self.finished = True def check_timeout(self): self.assertTrue(time.time() - self.start_time < self.timeout)
Python
#!/usr/bin/env python '''Test that window size can be set. Expected behaviour: One window will be opened. The window's dimensions will be printed to the terminal. - press "x" to increase the width - press "X" to decrease the width - press "y" to increase the height - press "Y" to decrease the height You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key import window_util class WINDOW_SET_SIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): delta = 20 if modifiers & key.MOD_SHIFT: delta = -delta if symbol == key.X: self.width += delta elif symbol == key.Y: self.height += delta self.w.set_size(self.width, self.height) print 'Window size set to %dx%d.' % (self.width, self.height) def test_set_size(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse cursor can be set to a platform-dependent image. Expected behaviour: One window will be opened. Press the left and right arrow keys to cycle through the system mouse cursors. The current cursor selected will be printed to the terminal. Note that not all cursors are unique on each platform; for example, if a platform doesn't define a cursor for a given name, a suitable replacement (e.g., a plain arrow) will be used instead. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_VISIBLE.py 703 2007-02-28 14:18:00Z Alex.Holkner $' import unittest from pyglet import window from pyglet.window import key from pyglet.gl import * class WINDOW_SET_MOUSE_PLATFORM_CURSOR(unittest.TestCase): i = 0 def on_key_press(self, symbol, modifiers): names = [ self.w.CURSOR_DEFAULT, self.w.CURSOR_CROSSHAIR, self.w.CURSOR_HAND, self.w.CURSOR_HELP, self.w.CURSOR_NO, self.w.CURSOR_SIZE, self.w.CURSOR_SIZE_UP, self.w.CURSOR_SIZE_UP_RIGHT, self.w.CURSOR_SIZE_RIGHT, self.w.CURSOR_SIZE_DOWN_RIGHT, self.w.CURSOR_SIZE_DOWN, self.w.CURSOR_SIZE_DOWN_LEFT, self.w.CURSOR_SIZE_LEFT, self.w.CURSOR_SIZE_UP_LEFT, self.w.CURSOR_SIZE_UP_DOWN, self.w.CURSOR_SIZE_LEFT_RIGHT, self.w.CURSOR_TEXT, self.w.CURSOR_WAIT, self.w.CURSOR_WAIT_ARROW, ] if symbol == key.ESCAPE: self.w.on_close() if symbol == key.RIGHT: self.i = (self.i + 1) % len(names) elif symbol == key.LEFT: self.i = (self.i - 1) % len(names) cursor = self.w.get_system_mouse_cursor(names[self.i]) self.w.set_mouse_cursor(cursor) print 'Set cursor to "%s"' % names[self.i] return True def test_set_visible(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse motion event works correctly. Expected behaviour: One window will be opened. Move the mouse in and out of this window and ensure the absolute and relative coordinates are correct. - Absolute coordinates should have (0,0) at bottom-left of client area of window with positive y-axis pointing up and positive x-axis right. - Relative coordinates should be positive when moving up and right. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOUSEMOTION(unittest.TestCase): def on_mouse_motion(self, x, y, dx, dy): print 'Mouse at (%f, %f); relative (%f, %f).' % \ (x, y, dx, dy) def test_motion(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse drag event works correctly. Expected behaviour: One window will be opened. Click and drag with the mouse and ensure that buttons, coordinates and modifiers are reported correctly. Events should be generated even when the drag leaves the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger class EVENT_MOUSE_DRAG(unittest.TestCase): def test_mouse_drag(self): w = window.Window(200, 200) w.push_handlers(WindowEventLogger()) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be minimized and maximized. Expected behaviour: One window will be opened. - press "x" to maximize the window. - press "n" to minimize the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_MINIMIZE_MAXIMIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.X: self.w.maximize() print 'Window maximized.' elif symbol == key.N: self.w.minimize() print 'Window minimized.' def test_minimize_maximize(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * import window_util class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_text(self, text): text = text[:1] i = ord(text) - ord('a') if 0 <= i < len(self.modes): print 'Switching to %s' % self.modes[i] self.w.screen.set_mode(self.modes[i]) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) window_util.draw_client_border(self.w) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) self.modes = w.screen.get_modes() print 'Press a letter to switch to the corresponding mode:' for i, mode in enumerate(self.modes): print '%s: %s' % (chr(i + ord('a')), mode) w.push_handlers(self) #w.push_handlers(WindowEventLogger()) self.on_expose() while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be resized. Expected behaviour: One window will be opened. It should be resizable by the user. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet.window import key import window_util class WINDOW_RESIZABLE(unittest.TestCase): def test_resizable(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) glClearColor(1, 1, 1, 1) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that multiple windows share objects by default. This test is non-interactive. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from ctypes import * from pyglet import window from pyglet.gl import * __noninteractive = True class CONTEXT_SHARE(unittest.TestCase): def create_context(self, share): display = window.get_platform().get_default_display() screen = display.get_default_screen() config = screen.get_best_config() return config.create_context(share) def test_context_share_list(self): w1 = window.Window(200, 200) try: w1.switch_to() glist = glGenLists(1) glNewList(glist, GL_COMPILE) glLoadIdentity() glEndList() self.assertTrue(glIsList(glist)) except: w1.close() raise w2 = window.Window(200, 200) try: w2.switch_to() self.assertTrue(glIsList(glist)) finally: w1.close() w2.close() def test_context_noshare_list(self): w1 = window.Window(200, 200) try: w1.switch_to() glist = glGenLists(1) glNewList(glist, GL_COMPILE) glLoadIdentity() glEndList() self.assertTrue(glIsList(glist)) except: w1.close() raise w2 = window.Window(200, 200, context=self.create_context(None)) try: w2.set_visible(True) w2.switch_to() self.assertTrue(not glIsList(glist)) finally: w1.close() w2.close() def test_context_share_texture(self): w1 = window.Window(200, 200) try: w1.switch_to() textures = c_uint() glGenTextures(1, byref(textures)) texture = textures.value glBindTexture(GL_TEXTURE_2D, texture) data = (c_ubyte * 4)() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data) self.assertTrue(glIsTexture(texture)) except: w1.close() raise w2 = window.Window(200, 200) try: w2.switch_to() self.assertTrue(glIsTexture(texture)) glDeleteTextures(1, byref(textures)) self.assertTrue(not glIsTexture(texture)) w1.switch_to() self.assertTrue(not glIsTexture(texture)) finally: w1.close() w2.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that exclusive mouse mode can be set. Expected behaviour: One window will be opened. Press 'e' to enable exclusive mode and 'E' to disable exclusive mode. In exclusive mode: - the mouse cursor should be invisible - moving the mouse should generate events with bogus x,y but correct dx and dy. - it should not be possible to switch applications with the mouse - if application loses focus (i.e., with keyboard), the mouse should operate normally again until focus is returned to the app, in which case it should hide again. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_EXCLUSIVE_MOUSE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.E: exclusive = not (modifiers & key.MOD_SHIFT) self.w.set_exclusive_mouse(exclusive) print 'Exclusive mouse is now %r' % exclusive def on_mouse_motion(self, x, y, dx, dy): print 'on_mousemotion(x=%f, y=%f, dx=%f, dy=%f)' % (x, y, dx, dy) def test_set_exclusive_mouse(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be set to and from various fullscreen sizes. Expected behaviour: One window will be opened. Press a number to switch to the corresponding fullscreen size; hold control and press a number to switch back to the corresponding window size: 0 - Default size 1 - 320x200 2 - 640x480 3 - 800x600 4 - 1024x768 5 - 1280x800 (widescreen) 6 - 1280x1024 In all cases the window bounds will be indicated by a green rectangle which should be completely visible. All events will be printed to the terminal. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * import window_util class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): fullscreen = not modifiers & key.MOD_CTRL doing = fullscreen and 'Setting' or 'Restoring from' if symbol == key._0: print '%s default size' % doing self.w.set_fullscreen(fullscreen) return elif symbol == key._1: width, height = 320, 200 elif symbol == key._2: width, height = 640, 480 elif symbol == key._3: width, height = 800, 600 elif symbol == key._4: width, height = 1024, 768 elif symbol == key._5: width, height = 1280, 800 # 16:10 elif symbol == key._6: width, height = 1280, 1024 else: return print '%s width=%d, height=%d' % (doing, width, height) self.w.set_fullscreen(fullscreen, width=width, height=height) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) window_util.draw_client_border(self.w) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) w.push_handlers(self) w.push_handlers(WindowEventLogger()) self.on_expose() try: while not w.has_exit: w.dispatch_events() w.close() except SystemExit: # Child process on linux calls sys.exit(0) when it's done. pass if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window expose event works correctly. Expected behaviour: One window will be opened. Uncovering the window from other windows or the edge of the screen should produce the expose event. Note that on OS X and other compositing window managers this event is equivalent to EVENT_SHOW. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_EXPOSE(unittest.TestCase): def on_expose(self): print 'Window exposed.' def test_expose(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be set fullscreen and back again. Expected behaviour: One window will be opened. - press "f" to enter fullscreen mode. - press "g" to leave fullscreen mode. All events will be printed to the terminal. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.F: print 'Setting fullscreen.' self.w.set_fullscreen(True) elif symbol == key.G: print 'Leaving fullscreen.' self.w.set_fullscreen(False) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) w.push_handlers(self) w.push_handlers(WindowEventLogger()) self.on_expose() while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that activate and deactivate events work correctly. Expected behaviour: One window will be opened. Clicking on the window should activate it, clicking on another window should deactivate it. Messages will be printed to the console for both events. On OS X you can also (de)activate a window with Command+Tab, or using Expose (F9) or the Dock. On Windows and most Linux window managers you can use Alt+Tab or the task bar. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_ACTIVATE_DEACTIVATE(unittest.TestCase): def on_activate(self): print 'Window activated.' def on_deactivate(self): print 'Window deactivated.' def test_activate_deactivate(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # $Id: $ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 3 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_show(self): self.check_sequence(2, 'on_show') def on_expose(self): self.check_sequence(3, 'on_expose') def test_method(self): win = window.Window(fullscreen=True) win.push_handlers(self) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a non-resizable window's size can be set. Expected behaviour: One window will be opened. The window's dimensions will be printed to the terminal. - press "x" to increase the width - press "X" to decrease the width - press "y" to increase the height - press "Y" to decrease the height You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key import window_util class WINDOW_FIXED_SET_SIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): delta = 20 if modifiers & key.MOD_SHIFT: delta = -delta if symbol == key.X: self.width += delta elif symbol == key.Y: self.height += delta self.w.set_size(self.width, self.height) print 'Window size set to %dx%d.' % (self.width, self.height) def test_set_size(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 3 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_show(self): self.check_sequence(2, 'on_show') def on_expose(self): self.check_sequence(3, 'on_expose') def test_method(self): win = window.Window(visible=False) win.dispatch_events() win.push_handlers(self) win.set_visible(True) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # $Id: $ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 3 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_show(self): self.check_sequence(2, 'on_show') def on_expose(self): self.check_sequence(3, 'on_expose') def test_method(self): win = window.Window() win.push_handlers(self) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse cursor can be made visible and hidden. Expected behaviour: One window will be opened. Press 'v' to hide mouse cursor and 'V' to show mouse cursor. It should only affect the mouse when within the client area of the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_MOUSE_VISIBLE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.V: visible = (modifiers & key.MOD_SHIFT) self.w.set_mouse_visible(visible) print 'Mouse is now %s' % (visible and 'visible' or 'hidden') def on_mouse_motion(self, x, y, dx, dy): print 'on_mousemotion(x=%f, y=%f, dx=%f, dy=%f)' % (x, y, dx, dy) def test_set_visible(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window icon can be set. Expected behaviour: One window will be opened. It will have an icon depicting a yellow "A". Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import image from pyglet import window from pyglet.window import key from os.path import join, dirname icon_file = join(dirname(__file__), 'icon1.png') class WINDOW_SET_ICON(unittest.TestCase): def test_set_icon(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.set_icon(image.load(icon_file)) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that show and hide events work correctly. Expected behaviour: One window will be opened. There should be one shown event printed initially. Minimizing and restoring the window should produce hidden and shown events, respectively. On OS X the events should also be fired when the window is hidden and shown (using Command+H or the dock context menu). Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_SHOW_HIDE(unittest.TestCase): def on_show(self): print 'Window shown.' def on_hide(self): print 'Window hidden.' def test_show_hide(self): w = window.Window(200, 200, visible=False) w.push_handlers(self) w.set_visible() while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that activate and deactivate events work correctly. Expected behaviour: One window will be opened. Clicking on the window should activate it, clicking on another window should deactivate it. Messages will be printed to the console for both events. On OS X you can also (de)activate a window with Command+Tab, or using Expose (F9) or the Dock. On Windows and most Linux window managers you can use Alt+Tab or the task bar. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_ACTIVATE_DEACTIVATE(unittest.TestCase): def on_activate(self): print 'Window activated.' def on_deactivate(self): print 'Window deactivated.' def test_activate_deactivate(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window style can be tool. Expected behaviour: One tool-styled window will be opened. Close the window to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window class TEST_WINDOW_STYLE_TOOL(unittest.TestCase): def test_style_tool(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, style=window.Window.WINDOW_STYLE_TOOL) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that key press and release events work correctly. Expected behaviour: One window will be opened. Type into this window and check the console output for key press and release events. Check that the correct key symbol and modifiers are reported. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class EVENT_KEYPRESS(unittest.TestCase): def on_key_press(self, symbol, modifiers): print 'Pressed %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) def on_key_release(self, symbol, modifiers): print 'Released %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) def test_keypress(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that image mouse cursor can be set. Expected behaviour: One window will be opened. The mouse cursor in the window will be a custom cursor. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet.gl import * from pyglet import image from pyglet import window from os.path import join, dirname cursor_file = join(dirname(__file__), 'cursor.png') class WINDOW_SET_MOUSE_CURSOR(unittest.TestCase): def on_mouse_motion(self, x, y, dx, dy): print 'on_mousemotion(x=%f, y=%f, dx=%f, dy=%f)' % (x, y, dx, dy) def test_set_mouse_cursor(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) img = image.load(cursor_file) w.set_mouse_cursor(window.ImageMouseCursor(img, 4, 28)) w.push_handlers(self) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that exclusive keyboard mode can be set. Expected behaviour: One window will be opened. Press 'e' to enable exclusive mode and 'E' to disable exclusive mode. In exclusive mode: - Pressing system keys, the Expose keys, etc., should have no effect besides displaying as keyboard events. - On OS X, the Power switch is not disabled (though this is possible if desired, see source). - On OS X, the menu bar and dock will disappear during keyboard exclusive mode. - On Windows, only Alt+Tab is disabled. A user can still switch away using Ctrl+Escape, Alt+Escape, the Windows key or Ctrl+Alt+Del. - Switching to another application (i.e., with the mouse) should make these keys work normally again until this application regains focus. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_SET_EXCLUSIVE_KEYBOARD(unittest.TestCase): def on_key_press(self, symbol, modifiers): print 'Pressed %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) if symbol == key.E: exclusive = not (modifiers & key.MOD_SHIFT) self.w.set_exclusive_keyboard(exclusive) print 'Exclusive keyboard is now %r' % exclusive def on_key_release(self, symbol, modifiers): print 'Released %s with modifiers %s' % \ (key.symbol_string(symbol), key.modifiers_string(modifiers)) def test_set_exclusive_keyboard(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a window can have multisample. A window will be opened containing two rotating squares. Initially, there will be no multisampling (the edges will look "jaggy"). Press: * M to toggle multisampling on/off * S to increase samples (2, 4, 6, 8, 10, ...) * Shift+S to decrease samples Each time sample_buffers or samples is modified, the window will be recreated. Watch the console for success and failure messages. If the multisample options are not supported, a "Failure" message will be printed and the window will be left as-is. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_OPEN.py 750 2007-03-17 01:16:12Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet import clock from pyglet.window import key class WINDOW_MULTISAMPLE(unittest.TestCase): win = None width = 640 height = 480 soft_multisample = True multisample = False samples = 2 def set_window(self): oldwindow = self.win try: if self.multisample: print 'Attempting samples=%d...' % self.samples, config = Config(sample_buffers=1, samples=self.samples, double_buffer=True) else: print 'Disabling multisample...', config = Config(double_buffer=True) self.win = window.Window(self.width, self.height, vsync=True, config=config) self.win.switch_to() self.win.push_handlers(self.on_key_press) if self.multisample: if self.soft_multisample: glEnable(GL_MULTISAMPLE_ARB) else: glDisable(GL_MULTISAMPLE_ARB) if oldwindow: oldwindow.close() print 'Success.' except window.NoSuchConfigException: print 'Failed.' def on_key_press(self, symbol, modifiers): mod = 1 if modifiers & key.MOD_SHIFT: mod = -1 if symbol == key.M: self.multisample = not self.multisample self.set_window() if symbol == key.S: self.samples += 2 * mod self.samples = max(2, self.samples) self.set_window() # Another test: try enabling/disabling GL_MULTISAMPLE_ARB... # seems to have no effect if samples > 4. if symbol == key.N: self.soft_multisample = not self.soft_multisample if self.soft_multisample: print 'Enabling GL_MULTISAMPLE_ARB' glEnable(GL_MULTISAMPLE_ARB) else: print 'Disabling GL_MULTISAMPLE_ARB' glDisable(GL_MULTISAMPLE_ARB) def render(self): self.win.switch_to() size = self.height / 4 glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glLoadIdentity() glTranslatef(self.width/2, self.height/2, 0) glRotatef(self.angle, 0, 0, 1) glColor3f(1, 0, 0) glBegin(GL_QUADS) glVertex2f(-size, -size) glVertex2f(size, -size) glVertex2f(size, size) glVertex2f(-size, size) glEnd() glRotatef(-self.angle * 2, 0, 0, 1) glColor4f(0, 1, 0, 0.5) glBegin(GL_QUADS) glVertex2f(-size, -size) glVertex2f(size, -size) glVertex2f(size, size) glVertex2f(-size, size) glEnd() def test_multisample(self): self.set_window() self.angle = 0 clock.set_fps_limit(30) while not self.win.has_exit: dt = clock.tick() self.angle += dt self.win.dispatch_events() self.render() self.win.flip() self.win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that vsync can be set. Expected behaviour: A window will alternate between red and green fill. - Press "v" to toggle vsync on/off. "Tearing" should only be visible when vsync is off (as indicated at the terminal). Not all video drivers support vsync. On Linux, check the output of `tools/info.py`: - If GLX_SGI_video_sync extension is present, should work as expected. - If GLX_MESA_swap_control extension is present, should work as expected. - If GLX_SGI_swap_control extension is present, vsync can be enabled, but once enabled, it cannot be switched off (there will be no error message). - If none of these extensions are present, vsync is not supported by your driver, but no error message or warning will be printed. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest from pyglet import window from pyglet.window import key from pyglet.gl import * class WINDOW_SET_VSYNC(unittest.TestCase): colors = [(1, 0, 0, 1), (0, 1, 0, 1)] color_index = 0 def open_window(self): return window.Window(200, 200, vsync=False) def on_key_press(self, symbol, modifiers): if symbol == key.V: vsync = not self.w1.vsync self.w1.set_vsync(vsync) print 'vsync is %r' % self.w1.vsync def draw_window(self, window, colour): window.switch_to() glClearColor(*colour) glClear(GL_COLOR_BUFFER_BIT) window.flip() def test_open_window(self): self.w1 = self.open_window() self.w1.push_handlers(self) print 'vsync is %r' % self.w1.vsync while not self.w1.has_exit: self.color_index = 1 - self.color_index self.draw_window(self.w1, self.colors[self.color_index]) self.w1.dispatch_events() self.w1.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be set to and from various fullscreen sizes. Expected behaviour: One window will be opened. Press a number to switch to the corresponding fullscreen size; hold control and press a number to switch back to the corresponding window size: 0 - Default size 1 - 320x200 2 - 640x480 3 - 800x600 4 - 1024x768 5 - 1280x800 (widescreen) 6 - 1280x1024 In all cases the window bounds will be indicated by a green rectangle which should be completely visible. All events will be printed to the terminal. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * import window_util class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): fullscreen = not modifiers & key.MOD_CTRL doing = fullscreen and 'Setting' or 'Restoring from' if symbol == key._0: print '%s default size' % doing self.w.set_fullscreen(fullscreen) return elif symbol == key._1: width, height = 320, 200 elif symbol == key._2: width, height = 640, 480 elif symbol == key._3: width, height = 800, 600 elif symbol == key._4: width, height = 1024, 768 elif symbol == key._5: width, height = 1280, 800 # 16:10 elif symbol == key._6: width, height = 1280, 1024 else: return print '%s width=%d, height=%d' % (doing, width, height) self.w.set_fullscreen(fullscreen, width=width, height=height) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) window_util.draw_client_border(self.w) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) w.push_handlers(self) w.push_handlers(WindowEventLogger()) self.on_expose() try: while not w.has_exit: w.dispatch_events() w.close() except SystemExit: # Child process on linux calls sys.exit(0) when it's done. pass if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window move event works correctly. Expected behaviour: One window will be opened. Move the window and ensure that the location printed to the terminal is correct. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOVE(unittest.TestCase): def on_move(self, x, y): print 'Window moved to %dx%d.' % (x, y) def test_move(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be minimized and maximized. Expected behaviour: One window will be opened. - press "x" to maximize the window. - press "n" to minimize the window. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class WINDOW_MINIMIZE_MAXIMIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.X: self.w.maximize() print 'Window maximized.' elif symbol == key.N: self.w.minimize() print 'Window minimized.' def test_minimize_maximize(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse motion event works correctly. Expected behaviour: One window will be opened. Move the mouse in and out of this window and ensure the absolute and relative coordinates are correct. - Absolute coordinates should have (0,0) at bottom-left of client area of window with positive y-axis pointing up and positive x-axis right. - Relative coordinates should be positive when moving up and right. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOUSEMOTION(unittest.TestCase): def on_mouse_motion(self, x, y, dx, dy): print 'Mouse at (%f, %f); relative (%f, %f).' % \ (x, y, dx, dy) def test_motion(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that multiple windows share objects by default. This test is non-interactive. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from ctypes import * from pyglet import window from pyglet.gl import * __noninteractive = True class CONTEXT_SHARE(unittest.TestCase): def create_context(self, share): display = window.get_platform().get_default_display() screen = display.get_default_screen() config = screen.get_best_config() return config.create_context(share) def test_context_share_list(self): w1 = window.Window(200, 200) try: w1.switch_to() glist = glGenLists(1) glNewList(glist, GL_COMPILE) glLoadIdentity() glEndList() self.assertTrue(glIsList(glist)) except: w1.close() raise w2 = window.Window(200, 200) try: w2.switch_to() self.assertTrue(glIsList(glist)) finally: w1.close() w2.close() def test_context_noshare_list(self): w1 = window.Window(200, 200) try: w1.switch_to() glist = glGenLists(1) glNewList(glist, GL_COMPILE) glLoadIdentity() glEndList() self.assertTrue(glIsList(glist)) except: w1.close() raise w2 = window.Window(200, 200, context=self.create_context(None)) try: w2.set_visible(True) w2.switch_to() self.assertTrue(not glIsList(glist)) finally: w1.close() w2.close() def test_context_share_texture(self): w1 = window.Window(200, 200) try: w1.switch_to() textures = c_uint() glGenTextures(1, byref(textures)) texture = textures.value glBindTexture(GL_TEXTURE_2D, texture) data = (c_ubyte * 4)() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data) self.assertTrue(glIsTexture(texture)) except: w1.close() raise w2 = window.Window(200, 200) try: w2.switch_to() self.assertTrue(glIsTexture(texture)) glDeleteTextures(1, byref(textures)) self.assertTrue(not glIsTexture(texture)) w1.switch_to() self.assertTrue(not glIsTexture(texture)) finally: w1.close() w2.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # $Id: $ import unittest from pyglet import window import base_event_sequence __noninteractive = True class TEST_CLASS(base_event_sequence.BaseEventSequence): last_sequence = 2 def on_resize(self, width, height): self.check_sequence(1, 'on_resize') def on_expose(self): self.check_sequence(2, 'on_expose') def test_method(self): win = window.Window(fullscreen=True) win.dispatch_events() win.push_handlers(self) win.set_fullscreen(False) self.check_sequence(0, 'begin') while not win.has_exit and not self.finished: win.dispatch_events() self.check_timeout() win.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that the window can be activated (focus set). Expected behaviour: One window will be opened. Every 5 seconds it will be activated; it should be come to the front and accept keyboard input (this will be shown on the terminal). On Windows XP, the taskbar icon may flash (indicating the application requires attention) rather than moving the window to the foreground. This is the correct behaviour. Press escape or close the window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window from pyglet.window.event import WindowEventLogger class WINDOW_ACTVATE(unittest.TestCase): def test_activate(self): w = window.Window(200, 200) w.push_handlers(WindowEventLogger()) last_time = time.time() while not w.has_exit: if time.time() - last_time > 5: w.activate() last_time = time.time() print 'Activated window.' w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that text events work correctly. Expected behaviour: One window will be opened. Type into this window and check the console output for text events. - Repeated when keys are held down - Motion events (e.g., arrow keys, HOME/END, etc) are reported - Select events (motion + SHIFT) are reported - Non-keyboard text entry is used (e.g., pen or international palette). - Combining characters do not generate events, but the modified character is sent. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class EVENT_KEYPRESS(unittest.TestCase): def on_text(self, text): print 'Typed %r' % text def on_text_motion(self, motion): print 'Motion %s' % key.motion_string(motion) def on_text_motion_select(self, motion): print 'Select %s' % key.motion_string(motion) def test_text(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that a non-resizable window's size can be set. Expected behaviour: One window will be opened. The window's dimensions will be printed to the terminal. - press "x" to increase the width - press "X" to decrease the width - press "y" to increase the height - press "Y" to decrease the height You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key import window_util class WINDOW_FIXED_SET_SIZE(unittest.TestCase): def on_key_press(self, symbol, modifiers): delta = 20 if modifiers & key.MOD_SHIFT: delta = -delta if symbol == key.X: self.width += delta elif symbol == key.Y: self.height += delta self.w.set_size(self.width, self.height) print 'Window size set to %dx%d.' % (self.width, self.height) def test_set_size(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse enter and leave events work correctly. Expected behaviour: One window will be opened. Move the mouse in and out of this window and ensure the events displayed are correct. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window class EVENT_MOUSE_ENTER_LEAVE(unittest.TestCase): def on_mouse_enter(self, x, y): print 'Entered at %f, %f' % (x, y) def on_mouse_leave(self, x, y): print 'Left at %f, %f' % (x, y) def test_motion(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-2, -2, window.width + 2, window.height + 2) glColor3f(0, 1, 0) rect(1, 1, window.width - 2, window.height - 2)
Python
#!/usr/bin/env python '''Test that a window can be opened fullscreen. Expected behaviour: A fullscreen window will be created, with a flat purple colour. - Press 'g' to leave fullscreen mode and create a window. - Press 'f' to re-enter fullscreen mode. - All events will be printed to the console. Ensure that mouse, keyboard and activation/deactivation events are all correct. Close either window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import pyglet.window from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * class WINDOW_INITIAL_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.F: print 'Setting fullscreen.' self.w.set_fullscreen(True) elif symbol == key.G: print 'Leaving fullscreen.' self.w.set_fullscreen(False) def on_expose(self): glClearColor(1, 0, 1, 1) glClear(GL_COLOR_BUFFER_BIT) self.w.flip() def test_initial_fullscreen(self): self.w = window.Window(fullscreen=True) self.w.push_handlers(self) self.w.push_handlers(WindowEventLogger()) self.on_expose() while not self.w.has_exit: self.w.dispatch_events() self.w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that resize event works correctly. Expected behaviour: One window will be opened. Resize the window and ensure that the dimensions printed to the terminal are correct. You should see a green border inside the window but no red. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window import window_util class EVENT_RESIZE(unittest.TestCase): def on_resize(self, width, height): print 'Window resized to %dx%d.' % (width, height) def test_resize(self): w = window.Window(200, 200, resizable=True) w.push_handlers(self) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be resized. Expected behaviour: One window will be opened. It should be resizable by the user. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet.window import key import window_util class WINDOW_RESIZABLE(unittest.TestCase): def test_resizable(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) glClearColor(1, 1, 1, 1) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that window can be resized. Expected behaviour: One window will be opened. It should be resizable by the user. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_CURSOR.py 717 2007-03-03 07:04:10Z Alex.Holkner $' import unittest from pyglet.gl import * from pyglet import window from pyglet.window import key import window_util class WINDOW_RESIZABLE(unittest.TestCase): def test_resizable(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height, resizable=True) glClearColor(1, 1, 1, 1) while not w.has_exit: w.dispatch_events() window_util.draw_client_border(w) w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that mouse cursor can be set to a platform-dependent image. Expected behaviour: One window will be opened. Press the left and right arrow keys to cycle through the system mouse cursors. The current cursor selected will be printed to the terminal. Note that not all cursors are unique on each platform; for example, if a platform doesn't define a cursor for a given name, a suitable replacement (e.g., a plain arrow) will be used instead. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: WINDOW_SET_MOUSE_VISIBLE.py 703 2007-02-28 14:18:00Z Alex.Holkner $' import unittest from pyglet import window from pyglet.window import key from pyglet.gl import * class WINDOW_SET_MOUSE_PLATFORM_CURSOR(unittest.TestCase): i = 0 def on_key_press(self, symbol, modifiers): names = [ self.w.CURSOR_DEFAULT, self.w.CURSOR_CROSSHAIR, self.w.CURSOR_HAND, self.w.CURSOR_HELP, self.w.CURSOR_NO, self.w.CURSOR_SIZE, self.w.CURSOR_SIZE_UP, self.w.CURSOR_SIZE_UP_RIGHT, self.w.CURSOR_SIZE_RIGHT, self.w.CURSOR_SIZE_DOWN_RIGHT, self.w.CURSOR_SIZE_DOWN, self.w.CURSOR_SIZE_DOWN_LEFT, self.w.CURSOR_SIZE_LEFT, self.w.CURSOR_SIZE_UP_LEFT, self.w.CURSOR_SIZE_UP_DOWN, self.w.CURSOR_SIZE_LEFT_RIGHT, self.w.CURSOR_TEXT, self.w.CURSOR_WAIT, self.w.CURSOR_WAIT_ARROW, ] if symbol == key.ESCAPE: self.w.on_close() if symbol == key.RIGHT: self.i = (self.i + 1) % len(names) elif symbol == key.LEFT: self.i = (self.i - 1) % len(names) cursor = self.w.get_system_mouse_cursor(names[self.i]) self.w.set_mouse_cursor(cursor) print 'Set cursor to "%s"' % names[self.i] return True def test_set_visible(self): self.width, self.height = 200, 200 self.w = w = window.Window(self.width, self.height) w.push_handlers(self) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.dispatch_events() w.flip() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that multiple windows can be opened. Expected behaviour: Two small windows will be opened, one coloured yellow and the other purple. Close either window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.gl import * class MULTIPLE_WINDOW_OPEN(unittest.TestCase): def open_window(self): return window.Window(200, 200) def draw_window(self, window, colour): window.switch_to() glClearColor(*colour) glClear(GL_COLOR_BUFFER_BIT) window.flip() def test_open_window(self): w1 = self.open_window() w2 = self.open_window() while not (w1.has_exit or w2.has_exit): self.draw_window(w1, (1, 0, 1, 1)) self.draw_window(w2, (1, 1, 0, 1)) w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ import unittest import time class BaseEventSequence(unittest.TestCase): next_sequence = 0 last_sequence = 0 finished = False timeout = 2 start_time = time.time() def check_sequence(self, sequence, name): if self.next_sequence == 0 and sequence != 0: return if sequence == 0: self.start_time = time.time() if not self.finished: if self.next_sequence != sequence: print 'ERROR: %s out of order' % name else: print 'OK: %s' % name self.next_sequence += 1 if self.next_sequence > self.last_sequence: self.finished = True def check_timeout(self): self.assertTrue(time.time() - self.start_time < self.timeout)
Python
#!/usr/bin/env python '''Test that window can be set fullscreen and back again. Expected behaviour: One window will be opened. - press "f" to enter fullscreen mode. - press "g" to leave fullscreen mode. All events will be printed to the terminal. Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window.event import WindowEventLogger from pyglet.window import key from pyglet.gl import * class WINDOW_SET_FULLSCREEN(unittest.TestCase): def on_key_press(self, symbol, modifiers): if symbol == key.F: print 'Setting fullscreen.' self.w.set_fullscreen(True) elif symbol == key.G: print 'Leaving fullscreen.' self.w.set_fullscreen(False) def on_expose(self): glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) self.w.flip() def test_set_fullscreen(self): self.w = w = window.Window(200, 200) w.push_handlers(self) w.push_handlers(WindowEventLogger()) self.on_expose() while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test framework for pyglet. Reads details of components and capabilities from a requirements document, runs the appropriate unit tests. How to Run the Tests -------------------- :: python tests/test.py top app graphics clock resource # these all run automatically python tests/test.py font media text python tests/test.py image python tests/test.py window Because the tests are interactive, they can take quite a while to complete. The 'window' section in particular takes a long time. It can be frustrating to get almost through the tests and then something gets messed up, so we suggest you run the tests in sections as listed above. If you are curious, the sections are defined in tests/plan.txt. Here are the different sections and how long they take. =========== =========== Section Time to Run =========== =========== top automatic app automatic graphics automatic clock automatic resource automatic font 1 minute media 1 minute text 1 minute image 5 minutes window 10 minutes =========== =========== Overview -------- First, some definitions: Test case: A single test, implemented by a Python module in the tests/ directory. Tests can be interactive (requiring the user to pass or fail them) or non-interactive (the test passes or fails itself). Section: A list of test cases to be run in a specified order. Sections can also contain other sections to an arbitrary level. Capability: A capability is a tag that can be applied to a test-case, which specifies a particular instance of the test. The tester can select which capabilities are present on their system; and only test cases matching those capabilities will be run. There are platform capabilities "WIN", "OSX" and "X11", which are automatically selected by default. The "DEVELOPER" capability is used to mark test cases which test a feature under active development. The "GENERIC" capability signifies that the test case is equivalent under all platforms, and is selected by default. Other capabilities can be specified and selected as needed. For example, we may wish to use an "NVIDIA" or "ATI" capability to specialise a test-case for a particular video card make. Some tests generate regression images if enabled, so you will only need to run through the interactive procedure once. During subsequent runs the image shown on screen will be compared with the regression images and passed automatically if they match. There are command line options for enabling this feature.Literal block By default regression images are saved in tests/regression/images/ Running tests ------------- The test procedure is interactive (this is necessary to facilitate the many GUI-related tests, which cannot be completely automated). With no command-line arguments, all test cases in all sections will be run:: python tests/test.py Before each test, a description of the test will be printed, including some information of what you should look for, and what interactivityLiteral block is provided (including how to stop the test). Press ENTER to begin the test. When the test is complete, assuming there were no detectable errors (for example, failed assertions or an exception), you will be asked to enter a [P]ass or [F]ail. You should Fail the test if the behaviour was not as described, and enter a short reason. Details of each test session are logged for future use. Command-line options: `--plan=` Specify the test plan file (defaults to tests/plan.txt) `--test-root=` Specify the top-level directory to look for unit tests in (defaults to test/) `--capabilities=` Specify the capabilities to select, comma separated. By default this only includes your operating system capability (X11, WIN or OSX) and GENERIC. `--log-level=` Specify the minimum log level to write (defaults to 10: info) `--log-file=` Specify log file to write to (defaults to "pyglet.%d.log") `--regression-capture` Save regression images to disk. Use this only if the tests have already been shown to pass. `--regression-check` Look for a regression image on disk instead of prompting the user for passage. If a regression image is found, it is compared with the test case using the tolerance specified below. Recommended only for developers. `--regression-tolerance=` Specify the tolerance when comparing a regression image. A value of 2, for example, means each sample component must be +/- 2 units of the regression image. Tolerance of 0 means images must be identical, tolerance of 256 means images will always match (if correct dimensions). Defaults to 2. `--regression-path=` Specify the directory to store and look for regression images. Defaults to tests/regression/images/ `--developer` Selects the DEVELOPER capability. `--no-interactive=` Don't write descriptions or prompt for confirmation; just run each test in succcession. After the command line options, you can specify a list of sections or test cases to run. Examples -------- python tests/test.py --capabilities=GENERIC,NVIDIA,WIN window Runs all tests in the window section with the given capabilities. Test just the FULLSCREEN_TOGGLE test case without prompting for input (useful for development). python tests/image/PIL_RGBA_SAVE.py Run a single test outside of the test harness. Handy for development; it is equivalent to specifying --no-interactive. Writing tests ------------- Add the test case to the appropriate section in the test plan (plan.txt). Create one unit test script per test case. For example, the test for window.FULLSCREEN_TOGGLE is located at:: tests/window/FULLSCREEN_TOGGLE.py The test file must contain: - A module docstring describing what the test does and what the user should look for. - One or more subclasses of unittest.TestCase. - No other module-level code, except perhaps an if __name__ == '__main__' condition for running tests stand-alone. - Optionally, the attribute "__noninteractive = True" to specify that the test is not interactive; doesn't require user intervention. During development, test cases should be marked with DEVELOPER. Once finished add the WIN, OSX and X11 capabilities, or GENERIC if it's platform independent. Writing regression tests ------------------------ Your test case should subclass tests.regression.ImageRegressionTestCase instead of unitttest.TestCase. At the point where the buffer (window image) should be checked/saved, call self.capture_regression_image(). If this method returns True, you can exit straight away (regression test passed), otherwise continue running interactively (regression image was captured, wait for user confirmation). You can call capture_regression_image() several times; only the final image will be used. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import array import logging import os import optparse import re import sys import time import unittest # So we can find tests.regression and ensure local pyglet copy is tested. sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import tests.regression import pyglet.image regressions_path = os.path.join(os.path.dirname(__file__), 'regression', 'images') class TestCase(object): def __init__(self, name): self.name = name self.short_name = name.split('.')[-1] self.capabilities = set() def get_module_filename(self, root=''): path = os.path.join(*self.name.split('.')) return '%s.py' % os.path.join(root, path) def get_module(self, root=''): name = 'tests.%s' % self.name module = __import__(name) for c in name.split('.')[1:]: module = getattr(module, c) return module def get_regression_image_filename(self): return os.path.join(regressions_path, '%s.png' % self.name) def test(self, options): if not options.capabilities.intersection(self.capabilities): return options.log.info('Testing %s.', self) if options.pretend: return module = None try: module = self.get_module(options.test_root) except IOError: options.log.warning('No test exists for %s', self) except Exception: options.log.exception('Cannot load test for %s', self) if not module: return module_interactive = options.interactive if hasattr(module, '__noninteractive') and \ getattr(module, '__noninteractive'): module_interactive = False if options.regression_check and \ os.path.exists(self.get_regression_image_filename()): result = RegressionCheckTestResult( self, options.regression_tolerance) module_interactive = False elif options.regression_capture: result = RegressionCaptureTestResult(self) else: result = StandardTestResult(self) print '-' * 78 options.completed_tests += 1 print ("Running Test: %s (%d/%d)\n" % (self, options.completed_tests, options.num_tests)) if module.__doc__: print ' ' + module.__doc__.replace('\n','\n ') if module_interactive: raw_input('Press return to begin test...') suite = unittest.TestLoader().loadTestsFromModule(module) options.log.info('Begin unit tests for %s', self) suite(result) for failure in result.failures: options.log.error('Failure in %s', self) options.log.error(failure[1]) for error in result.errors: options.log.error('Error in %s', self) options.log.error(error[1]) options.log.info('%d tests run', result.testsRun) num_failures = len(result.failures) num_errors = len(result.errors) if num_failures or num_errors: print '%d Failures and %d Errors detected.' % (num_failures, num_errors) if (module_interactive and len(result.failures) == 0 and len(result.errors) == 0): # print module.__doc__ user_result = raw_input('[P]assed test, [F]ailed test: ') if user_result and user_result.strip()[0] in ('F', 'f'): print 'Enter failure description: ' description = raw_input('> ') options.log.error('User marked fail for %s', self) options.log.error(description) else: options.log.info('User marked pass for %s', self) result.setUserPass() def __repr__(self): return 'TestCase(%s)' % self.name def __str__(self): return self.name def __cmp__(self, other): return cmp(str(self), str(other)) def num_tests(self): return 1 class TestSection(object): def __init__(self, name): self.name = name self.children = [] def add(self, child): # child can be TestSection or TestCase self.children.append(child) def test(self, options): for child in self.children: child.test(options) def __repr__(self): return 'TestSection(%s)' % self.name def num_tests(self): return sum([c.num_tests() for c in self.children]) class TestPlan(TestSection): def __init__(self): self.root = None self.names = {} @classmethod def from_file(cls, file): plan = TestPlan() plan.root = TestSection('{root}') plan.root.indent = None # Section stack sections = [plan.root] if not hasattr(file, 'read'): file = open(file, 'r') line_number = 0 for line in file: line_number += 1 # Skip empty lines if not line.strip(): continue # Skip comments if line[0] == '#': continue indent = len(line) - len(line.lstrip()) while (sections and sections[-1].indent and sections[-1].indent > indent): sections.pop() if sections[-1].indent is None: sections[-1].indent = indent if sections[-1].indent != indent: raise Exception('Indentation mismatch line %d' % line_number) if '.' in line: tokens = line.strip().split() test_case = TestCase(tokens[0]) test_case.capabilities = set(tokens[1:]) sections[-1].add(test_case) plan.names[test_case.name] = test_case plan.names[test_case.short_name] = test_case else: section = TestSection(line.strip()) section.indent = None sections[-1].add(section) sections.append(section) plan.names[section.name] = section return plan class StandardTestResult(unittest.TestResult): def __init__(self, component): super(StandardTestResult, self).__init__() def setUserPass(self): pass class RegressionCaptureTestResult(unittest.TestResult): def __init__(self, component): super(RegressionCaptureTestResult, self).__init__() self.component = component self.captured_image = None def startTest(self, test): super(RegressionCaptureTestResult, self).startTest(test) if isinstance(test, tests.regression.ImageRegressionTestCase): test._enable_regression_image = True def addSuccess(self, test): super(RegressionCaptureTestResult, self).addSuccess(test) assert self.captured_image is None if isinstance(test, tests.regression.ImageRegressionTestCase): self.captured_image = test._captured_image def setUserPass(self): if self.captured_image: filename = self.component.get_regression_image_filename() self.captured_image.save(filename) logging.getLogger().info('Wrote regression image %s' % filename) class Regression(Exception): pass def buffer_equal(a, b, tolerance=0): if tolerance == 0: return a == b if len(a) != len(b): return False a = array.array('B', a) b = array.array('B', b) for i in range(len(a)): if abs(a[i] - b[i]) > tolerance: return False return True class RegressionCheckTestResult(unittest.TestResult): def __init__(self, component, tolerance): super(RegressionCheckTestResult, self).__init__() self.filename = component.get_regression_image_filename() self.regression_image = pyglet.image.load(self.filename) self.tolerance = tolerance def startTest(self, test): super(RegressionCheckTestResult, self).startTest(test) if isinstance(test, tests.regression.ImageRegressionTestCase): test._enable_regression_image = True test._enable_interactive = False logging.getLogger().info('Using regression %s' % self.filename) def addSuccess(self, test): # Check image ref_image = self.regression_image.image_data this_image = test._captured_image.image_data this_image.format = ref_image.format this_image.pitch = ref_image.pitch if this_image.width != ref_image.width: self.addFailure(test, 'Buffer width does not match regression image') elif this_image.height != ref_image.height: self.addFailure(test, 'Buffer height does not match regression image') elif not buffer_equal(this_image.data, ref_image.data, self.tolerance): self.addFailure(test, 'Buffer does not match regression image') else: super(RegressionCheckTestResult, self).addSuccess(test) def addFailure(self, test, err): err = Regression(err) super(RegressionCheckTestResult, self).addFailure(test, (Regression, err, [])) def main(): capabilities = ['GENERIC'] platform_capabilities = { 'linux': 'X11', 'linux2': 'X11', 'linux3': 'X11', 'win32': 'WIN', 'cygwin': 'WIN', 'darwin': 'OSX' } if sys.platform in platform_capabilities: capabilities.append(platform_capabilities[sys.platform]) script_root = os.path.dirname(__file__) plan_filename = os.path.normpath(os.path.join(script_root, 'plan.txt')) test_root = script_root op = optparse.OptionParser() op.usage = 'test.py [options] [components]' op.add_option('--plan', help='test plan file', default=plan_filename) op.add_option('--test-root', default=script_root, help='directory containing test cases') op.add_option('--capabilities', help='selected test capabilities', default=','.join(capabilities)) op.add_option('--log-level', help='verbosity of logging', default=10, type='int') op.add_option('--log-file', help='log to FILE', metavar='FILE', default='pyglet.%d.log') op.add_option('--regression-path', metavar='DIR', default=regressions_path, help='locate regression images in DIR') op.add_option('--regression-tolerance', type='int', default=2, help='tolerance for comparing regression images') op.add_option('--regression-check', action='store_true', help='enable image regression checks') op.add_option('--regression-capture', action='store_true', help='enable image regression capture') op.add_option('--no-interactive', action='store_false', default=True, dest='interactive', help='disable interactive prompting') op.add_option('--developer', action='store_true', help='add DEVELOPER capability') op.add_option('--pretend', action='store_true', help='print selected test cases only') options, args = op.parse_args() options.capabilities = set(options.capabilities.split(',')) if options.developer: options.capabilities.add('DEVELOPER') if options.regression_capture: try: os.makedirs(regressions_path) except OSError: pass if '%d' in options.log_file: i = 1 while os.path.exists(options.log_file % i): i += 1 options.log_file = options.log_file % i print 'Test results are saved in log file:', options.log_file logging.basicConfig(filename=options.log_file, level=options.log_level, format='%(levelname)s %(message)s') options.log = logging.getLogger() options.log.info('Beginning test at %s', time.ctime()) options.log.info('Capabilities are: %s', ', '.join(options.capabilities)) options.log.info('sys.platform = %s', sys.platform) options.log.info('pyglet.version = %s', pyglet.version) options.log.info('Reading test plan from %s', options.plan) plan = TestPlan.from_file(options.plan) errors = False if args: components = [] for arg in args: try: component = plan.names[arg] components.append(component) except KeyError: options.log.error('Unknown test case or section "%s"', arg) errors = True else: components = [plan.root] if not errors: options.num_tests = sum([c.num_tests() for c in components]) options.completed_tests = 0 for component in components: component.test(options) print '-' * 78 print 'Test results are saved in log file:', options.log_file if __name__ == '__main__': main()
Python
#!/usr/bin/env python '''Test framework for pyglet. Reads details of components and capabilities from a requirements document, runs the appropriate unit tests. Overview -------- First, some definitions: Test case: A single test, implemented by a Python module in the tests/ directory. Tests can be interactive (requiring the user to pass or fail them) or non-interactive (the test passes or fails itself). Section: A list of test cases to be run in a specified order. Sections can also contain other sections to an arbitrary level. Capability: A capability is a tag that can be applied to a test-case, which specifies a particular instance of the test. The tester can select which capabilities are present on their system; and only test cases matching those capabilities will be run. There are platform capabilities "WIN", "OSX" and "X11", which are automatically selected by default. The "DEVELOPER" capability is used to mark test cases which test a feature under active development. The "GENERIC" capability signifies that the test case is equivalent under all platforms, and is selected by default. Other capabilities can be specified and selected as needed. For example, we may wish to use an "NVIDIA" or "ATI" capability to specialise a test-case for a particular video card make. Some tests generate regression images if enabled, so you will only need to run through the interactive procedure once. During subsequent runs the image shown on screen will be compared with the regression images and passed automatically if they match. There are command line options for enabling this feature. By default regression images are saved in tests/regression/images/ Running tests ------------- The test procedure is interactive (this is necessary to facilitate the many GUI-related tests, which cannot be completely automated). With no command-line arguments, all test cases in all sections will be run:: python tests/test.py Before each test, a description of the test will be printed, including some information of what you should look for, and what interactivity is provided (including how to stop the test). Press ENTER to begin the test. When the test is complete, assuming there were no detectable errors (for example, failed assertions or an exception), you will be asked to enter a [P]ass or [F]ail. You should Fail the test if the behaviour was not as described, and enter a short reason. Details of each test session are logged for future use. Command-line options: --plan= Specify the test plan file (defaults to tests/plan.txt) --test-root= Specify the top-level directory to look for unit tests in (defaults to test/) --capabilities= Specify the capabilities to select, comma separated. By default this only includes your operating system capability (X11, WIN or OSX) and GENERIC. --log-level= Specify the minimum log level to write (defaults to 10: info) --log-file= Specify log file to write to (defaults to "pyglet.%d.log") --regression-capture Save regression images to disk. Use this only if the tests have already been shown to pass. --regression-check Look for a regression image on disk instead of prompting the user for passage. If a regression image is found, it is compared with the test case using the tolerance specified below. Recommended only for developers. --regression-tolerance= Specify the tolerance when comparing a regression image. A value of 2, for example, means each sample component must be +/- 2 units of the regression image. Tolerance of 0 means images must be identical, tolerance of 256 means images will always match (if correct dimensions). Defaults to 2. --regression-path= Specify the directory to store and look for regression images. Defaults to tests/regression/images/ --developer Selects the DEVELOPER capability. --no-interactive= Don't write descriptions or prompt for confirmation; just run each test in succcession. After the command line options, you can specify a list of sections or test cases to run. Examples -------- python tests/test.py --capabilities=GENERIC,NVIDIA,WIN window Runs all tests in the window section with the given capabilities. python tests/test.py --no-interactive FULLSCREEN_TOGGLE Test just the FULLSCREEN_TOGGLE test case without prompting for input (useful for development). python tests/image/PIL_RGBA_SAVE.py Run a single test outside of the test harness. Handy for development; it is equivalent to specifying --no-interactive. Writing tests ------------- Add the test case to the appropriate section in the test plan (plan.txt). Create one unit test script per test case. For example, the test for window.FULLSCREEN_TOGGLE is located at:: tests/window/FULLSCREEN_TOGGLE.py The test file must contain: - A module docstring describing what the test does and what the user should look for. - One or more subclasses of unittest.TestCase. - No other module-level code, except perhaps an if __name__ == '__main__' condition for running tests stand-alone. - Optionally, the attribute "__noninteractive = True" to specify that the test is not interactive; doesn't require user intervention. During development, test cases should be marked with DEVELOPER. Once finished add the WIN, OSX and X11 capabilities, or GENERIC if it's platform independent. Writing regression tests ------------------------ Your test case should subclass tests.regression.ImageRegressionTestCase instead of unitttest.TestCase. At the point where the buffer (window image) should be checked/saved, call self.capture_regression_image(). If this method returns True, you can exit straight away (regression test passed), otherwise continue running interactively (regression image was captured, wait for user confirmation). You can call capture_regression_image() several times; only the final image will be used. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import array import logging import os import optparse import re import sys import time import unittest # So we can find tests.regression and ensure local pyglet copy is tested. sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import tests.regression import pyglet.image regressions_path = os.path.join(os.path.dirname(__file__), 'regression', 'images') class TestCase(object): def __init__(self, name): self.name = name self.short_name = name.split('.')[-1] self.capabilities = set() def get_module_filename(self, root=''): path = os.path.join(*self.name.split('.')) return '%s.py' % os.path.join(root, path) def get_module(self, root=''): name = 'tests.%s' % self.name module = __import__(name) for c in name.split('.')[1:]: module = getattr(module, c) return module def get_regression_image_filename(self): return os.path.join(regressions_path, '%s.png' % self.name) def test(self, options): if not options.capabilities.intersection(self.capabilities): return options.log.info('Testing %s.', self) if options.pretend: return module = None try: module = self.get_module(options.test_root) except IOError: options.log.warning('No test exists for %s', self) except Exception: options.log.exception('Cannot load test for %s', self) if not module: return module_interactive = options.interactive if hasattr(module, '__noninteractive') and \ getattr(module, '__noninteractive'): module_interactive = False if options.regression_check and \ os.path.exists(self.get_regression_image_filename()): result = RegressionCheckTestResult( self, options.regression_tolerance) module_interactive = False elif options.regression_capture: result = RegressionCaptureTestResult(self) else: result = StandardTestResult(self) print('-' * 78) options.completed_tests += 1 print("Running Test: %s (%d/%d)\n" % (self, options.completed_tests, options.num_tests)) if module.__doc__: print(' ' + module.__doc__.replace('\n','\n ')) if module_interactive: raw_input('Press return to begin test...') suite = unittest.TestLoader().loadTestsFromModule(module) options.log.info('Begin unit tests for %s', self) suite(result) for failure in result.failures: options.log.error('Failure in %s', self) options.log.error(failure[1]) for error in result.errors: options.log.error('Error in %s', self) options.log.error(error[1]) options.log.info('%d tests run', result.testsRun) num_failures = len(result.failures) num_errors = len(result.errors) if num_failures or num_errors: print('%d Failures and %d Errors detected.' % (num_failures, num_errors)) if (module_interactive and len(result.failures) == 0 and len(result.errors) == 0): # print(module.__doc__) user_result = raw_input('[P]assed test, [F]ailed test: ') if user_result and user_result.strip()[0] in ('F', 'f'): print('Enter failure description: ') description = raw_input('> ') options.log.error('User marked fail for %s', self) options.log.error(description) else: options.log.info('User marked pass for %s', self) result.setUserPass() def __repr__(self): return 'TestCase(%s)' % self.name def __str__(self): return self.name def __cmp__(self, other): return cmp(str(self), str(other)) def num_tests(self): return 1 class TestSection(object): def __init__(self, name): self.name = name self.children = [] def add(self, child): # child can be TestSection or TestCase self.children.append(child) def test(self, options): for child in self.children: child.test(options) def __repr__(self): return 'TestSection(%s)' % self.name def num_tests(self): return sum([c.num_tests() for c in self.children]) class TestPlan(TestSection): def __init__(self): self.root = None self.names = {} @classmethod def from_file(cls, file): plan = TestPlan() plan.root = TestSection('{root}') plan.root.indent = None # Section stack sections = [plan.root] if not hasattr(file, 'read'): file = open(file, 'r') line_number = 0 for line in file: line_number += 1 # Skip empty lines if not line.strip(): continue # Skip comments if line[0] == '#': continue indent = len(line) - len(line.lstrip()) while (sections and sections[-1].indent and sections[-1].indent > indent): sections.pop() if sections[-1].indent is None: sections[-1].indent = indent if sections[-1].indent != indent: raise Exception('Indentation mismatch line %d' % line_number) if '.' in line: tokens = line.strip().split() test_case = TestCase(tokens[0]) test_case.capabilities = set(tokens[1:]) sections[-1].add(test_case) plan.names[test_case.name] = test_case plan.names[test_case.short_name] = test_case else: section = TestSection(line.strip()) section.indent = None sections[-1].add(section) sections.append(section) plan.names[section.name] = section return plan class StandardTestResult(unittest.TestResult): def __init__(self, component): super(StandardTestResult, self).__init__() def setUserPass(self): pass class RegressionCaptureTestResult(unittest.TestResult): def __init__(self, component): super(RegressionCaptureTestResult, self).__init__() self.component = component self.captured_image = None def startTest(self, test): super(RegressionCaptureTestResult, self).startTest(test) if isinstance(test, tests.regression.ImageRegressionTestCase): test._enable_regression_image = True def addSuccess(self, test): super(RegressionCaptureTestResult, self).addSuccess(test) assert self.captured_image is None if isinstance(test, tests.regression.ImageRegressionTestCase): self.captured_image = test._captured_image def setUserPass(self): if self.captured_image: filename = self.component.get_regression_image_filename() self.captured_image.save(filename) logging.getLogger().info('Wrote regression image %s' % filename) class Regression(Exception): pass def buffer_equal(a, b, tolerance=0): if tolerance == 0: return a == b if len(a) != len(b): return False a = array.array('B', a) b = array.array('B', b) for i in range(len(a)): if abs(a[i] - b[i]) > tolerance: return False return True class RegressionCheckTestResult(unittest.TestResult): def __init__(self, component, tolerance): super(RegressionCheckTestResult, self).__init__() self.filename = component.get_regression_image_filename() self.regression_image = pyglet.image.load(self.filename) self.tolerance = tolerance def startTest(self, test): super(RegressionCheckTestResult, self).startTest(test) if isinstance(test, tests.regression.ImageRegressionTestCase): test._enable_regression_image = True test._enable_interactive = False logging.getLogger().info('Using regression %s' % self.filename) def addSuccess(self, test): # Check image ref_image = self.regression_image.image_data this_image = test._captured_image.image_data this_image.format = ref_image.format this_image.pitch = ref_image.pitch if this_image.width != ref_image.width: self.addFailure(test, 'Buffer width does not match regression image') elif this_image.height != ref_image.height: self.addFailure(test, 'Buffer height does not match regression image') elif not buffer_equal(this_image.data, ref_image.data, self.tolerance): self.addFailure(test, 'Buffer does not match regression image') else: super(RegressionCheckTestResult, self).addSuccess(test) def addFailure(self, test, err): err = Regression(err) super(RegressionCheckTestResult, self).addFailure(test, (Regression, err, [])) def main(): capabilities = ['GENERIC'] platform_capabilities = { 'linux': 'X11', 'linux2': 'X11', 'linux3': 'X11', 'win32': 'WIN', 'cygwin': 'WIN', 'darwin': 'OSX' } if sys.platform in platform_capabilities: capabilities.append(platform_capabilities[sys.platform]) script_root = os.path.dirname(__file__) plan_filename = os.path.normpath(os.path.join(script_root, 'plan.txt')) test_root = script_root op = optparse.OptionParser() op.usage = 'test.py [options] [components]' op.add_option('--plan', help='test plan file', default=plan_filename) op.add_option('--test-root', default=script_root, help='directory containing test cases') op.add_option('--capabilities', help='selected test capabilities', default=','.join(capabilities)) op.add_option('--log-level', help='verbosity of logging', default=10, type='int') op.add_option('--log-file', help='log to FILE', metavar='FILE', default='pyglet.%d.log') op.add_option('--regression-path', metavar='DIR', default=regressions_path, help='locate regression images in DIR') op.add_option('--regression-tolerance', type='int', default=2, help='tolerance for comparing regression images') op.add_option('--regression-check', action='store_true', help='enable image regression checks') op.add_option('--regression-capture', action='store_true', help='enable image regression capture') op.add_option('--no-interactive', action='store_false', default=True, dest='interactive', help='disable interactive prompting') op.add_option('--developer', action='store_true', help='add DEVELOPER capability') op.add_option('--pretend', action='store_true', help='print selected test cases only') options, args = op.parse_args() options.capabilities = set(options.capabilities.split(',')) if options.developer: options.capabilities.add('DEVELOPER') if options.regression_capture: try: os.makedirs(regressions_path) except OSError: pass if '%d' in options.log_file: i = 1 while os.path.exists(options.log_file % i): i += 1 options.log_file = options.log_file % i print('Test results are saved in log file:', options.log_file) logging.basicConfig(filename=options.log_file, level=options.log_level, format='%(levelname)s %(message)s') options.log = logging.getLogger() options.log.info('Beginning test at %s', time.ctime()) options.log.info('Capabilities are: %s', ', '.join(options.capabilities)) options.log.info('sys.platform = %s', sys.platform) options.log.info('pyglet.version = %s', pyglet.version) options.log.info('Reading test plan from %s', options.plan) plan = TestPlan.from_file(options.plan) errors = False if args: components = [] for arg in args: try: component = plan.names[arg] components.append(component) except KeyError: options.log.error('Unknown test case or section "%s"', arg) errors = True else: components = [plan.root] if not errors: options.num_tests = sum([c.num_tests() for c in components]) options.completed_tests = 0 for component in components: component.test(options) print('-' * 78) print('Test results are saved in log file:', options.log_file) if __name__ == '__main__': main()
Python
#!/usr/bin/env python '''Test that all public modules are accessible after importing just 'pyglet'. This _must_ be the first test run. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $' import unittest import pyglet __noninteractive = True modules = [ 'app', 'clock', 'event', 'font', 'font.base', 'gl', 'gl.gl_info', 'gl.glu_info', 'graphics', 'graphics.allocation', 'graphics.vertexattribute', 'graphics.vertexbuffer', 'graphics.vertexdomain', 'image', 'image.atlas', 'media', 'resource', 'sprite', 'text', 'text.caret', 'text.document', 'text.layout', 'text.runlist', 'window', 'window.event', 'window.key', 'window.mouse', ] def add_module_tests(name, bases, dict): for module in modules: components = module.split('.') def create_test(components): def test_module(self): top = pyglet for component in components: self.assertTrue(hasattr(top, component), 'Cannot access "%s" in "%s"' % (component, top.__name__)) top = getattr(top, component) return test_module test_module = create_test(components) test_name = 'test_%s' % module.replace('.', '_') test_module.__name__ = test_name dict[test_name] = test_module return type.__new__(type, name, bases, dict) class TEST_CASE(unittest.TestCase): __metaclass__ = add_module_tests if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that all public modules are accessible after importing just 'pyglet'. This _must_ be the first test run. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: TICK.py 310 2006-12-23 15:56:35Z Alex.Holkner $' import unittest import pyglet __noninteractive = True modules = [ 'app', 'clock', 'event', 'font', 'font.base', 'gl', 'gl.gl_info', 'gl.glu_info', 'graphics', 'graphics.allocation', 'graphics.vertexattribute', 'graphics.vertexbuffer', 'graphics.vertexdomain', 'image', 'image.atlas', 'media', 'resource', 'sprite', 'text', 'text.caret', 'text.document', 'text.layout', 'text.runlist', 'window', 'window.event', 'window.key', 'window.mouse', ] def add_module_tests(name, bases, dict): for module in modules: components = module.split('.') def create_test(components): def test_module(self): top = pyglet for component in components: self.assertTrue(hasattr(top, component), 'Cannot access "%s" in "%s"' % (component, top.__name__)) top = getattr(top, component) return test_module test_module = create_test(components) test_name = 'test_%s' % module.replace('.', '_') test_module.__name__ = test_name dict[test_name] = test_module return type.__new__(type, name, bases, dict) class TEST_CASE(unittest.TestCase): __metaclass__ = add_module_tests if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgb_24bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgb_24bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test DXT1 compressed RGBA load from a DDS file. You should see the rgba_dxt1.dds image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.dds import DDSImageDecoder class TEST_DDS_RGBA_DXT1(base_load.TestLoad): texture_file = 'rgba_dxt1.dds' decoder = DDSImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGBA save using PyPNG. You should see rgba.png reference image on the left, and saved (and reloaded) image on the right. The saved image may have larger dimensions due to texture size restrictions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_save from pyglet.image.codecs.png import PNGImageEncoder class TEST_PNG_RGBA_SAVE(base_save.TestSave): texture_file = 'rgba.png' encoder = PNGImageEncoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test LA load using PyPNG. You should see the la.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.png import PNGImageDecoder class TEST_PNG_LA_LOAD(base_load.TestLoad): texture_file = 'la.png' decoder = PNGImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test LA load using PIL. You should see the la.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.pil import * class TEST_PNG_LA(base_load.TestLoad): texture_file = 'la.png' decoder = PILImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test rearrangement of color components using the OpenGL color matrix. The test will be skipped if the GL_ARB_imaging extension is not present. You should see the RGBA test image correctly rendered. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load import sys from pyglet.gl import gl_info class TEST_MATRIX_RGBA(base_load.TestLoad): texture_file = 'rgba.png' def load_image(self): if not gl_info.have_extension('GL_ARB_imaging'): print 'GL_ARB_imaging is not present, skipping test.' self.has_exit = True else: # Load image as usual then rearrange components super(TEST_MATRIX_RGBA, self).load_image() pixels = self.image.get_data('GBAR', self.image.width * 4) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test LA load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk). You should see the la.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load import sys if sys.platform.startswith('linux'): from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass elif sys.platform in ('win32', 'cygwin'): from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass elif sys.platform == 'darwin': from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass else: from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass class TEST_PLATFORM_LA_LOAD(base_load.TestLoad): texture_file = 'la.png' decoder = dclass() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGB load using PyPNG. You should see the rgb.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load from pyglet.image.codecs.png import PNGImageDecoder class TEST_PNG_RGB_LOAD(base_load.TestLoad): texture_file = 'rgb.png' decoder = PNGImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test DXT3 compressed RGBA load from a DDS file. You should see the rgba_dxt3.dds image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.dds import DDSImageDecoder class TEST_DDS_RGBA_DXT3(base_load.TestLoad): texture_file = 'rgba_dxt3.dds' decoder = DDSImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test rearrangement of color components using the OpenGL color matrix. The test will be skipped if the GL_ARB_imaging extension is not present. You should see the RGB test image correctly rendered. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load import sys from pyglet.gl import gl_info class TEST_MATRIX_RGB(base_load.TestLoad): texture_file = 'rgb.png' def load_image(self): if not gl_info.have_extension('GL_ARB_imaging'): print 'GL_ARB_imaging is not present, skipping test.' self.has_exit = True else: # Load image as usual then rearrange components super(TEST_MATRIX_RGB, self).load_image() self.image.format = 'GRB' pixels = self.image.data # forces conversion if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgb_32bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgb_32bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # $Id:$ import unittest from pyglet.image import atlas __noninteractive = True class Rect(object): def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def __repr__(self): return 'Rect(%d, %d to %d, %d)' % ( self.x1, self.y1, self.x2, self.y2) def intersects(self, other): return self.x2 > other.x1 and self.x1 < other.x2 and \ self.y2 > other.y1 and self.y1 < other.y2 class AllocatorEnvironment(object): def __init__(self, test_case, width, height): self.test_case = test_case self.rectes = [] self.allocator = atlas.Allocator(width, height) def check(self, test_case): for i, rect in enumerate(self.rectes): test_case.assertTrue(0 <= rect.x1 < self.allocator.width) test_case.assertTrue(0 <= rect.x2 <= self.allocator.width) test_case.assertTrue(0 <= rect.y1 < self.allocator.height) test_case.assertTrue(0 <= rect.y2 <= self.allocator.height) for other in self.rectes[i + 1:]: test_case.assertFalse(rect.intersects(other)) def add(self, width, height): x, y = self.allocator.alloc(width, height) self.rectes.append(Rect(x, y, x + width, y + height)) self.check(self.test_case) def add_fail(self, width, height): self.test_case.assertRaises(atlas.AllocatorException, self.allocator.alloc, width, height) class TestPack(unittest.TestCase): def test_over_x(self): env = AllocatorEnvironment(self, 3, 3) env.add_fail(3, 4) def test_over_y(self): env = AllocatorEnvironment(self, 3, 3) env.add_fail(4, 3) def test_1(self): env = AllocatorEnvironment(self, 4, 4) for i in range(16): env.add(1, 1) env.add_fail(1, 1) def test_2(self): env = AllocatorEnvironment(self, 3, 3) env.add(2, 2) for i in range(4): env.add(1, 1) def test_3(self): env = AllocatorEnvironment(self, 3, 3) env.add(3, 3) env.add_fail(1, 1) def test_4(self): env = AllocatorEnvironment(self, 5, 4) for i in range(4): env.add(2, 2) env.add_fail(2, 1) env.add(1, 2) env.add(1, 2) env.add_fail(1, 1) def test_5(self): env = AllocatorEnvironment(self, 4, 4) env.add(3, 2) env.add(4, 2) env.add(1, 2) env.add_fail(1, 1) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGB load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk). You should see the rgb.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load import sys if sys.platform.startswith('linux'): from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass elif sys.platform in ('win32', 'cygwin'): from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass elif sys.platform == 'darwin': from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass else: from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass class TEST_PLATFORM_RGB_LOAD(base_load.TestLoad): texture_file = 'rgb.png' decoder = dclass() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgba_32bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgba_32bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test L load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk). You should see the l.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load import sys if sys.platform.startswith('linux'): from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass elif sys.platform in ('win32', 'cygwin'): from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass elif sys.platform == 'darwin': from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass else: from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass class TEST_PLATFORM_L_LOAD(base_load.TestLoad): texture_file = 'l.png' decoder = dclass() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGB load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk). You should see the rgb.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load import sys if sys.platform.startswith('linux'): from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass elif sys.platform in ('win32', 'cygwin'): from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass elif sys.platform == 'darwin': from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass else: from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass class TEST_PLATFORM_RGB_LOAD(base_load.TestLoad): texture_file = 'rgb.png' decoder = dclass() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet.gl import * from pyglet.image import * from pyglet.window import * __noninteractive = True class TestTexture3D(unittest.TestCase): def create_image(self, width, height, color): data = ('%c' % color) * (width * height) return ImageData(width, height, 'L', data) def check_image(self, image, width, height, color): self.assertTrue(image.width == width) self.assertTrue(image.height == height) color = '%c' % (color) image = image.image_data data = image.get_data('L', image.width) self.assertTrue(data == color * len(data)) def set_grid_image(self, itemwidth, itemheight, rows, cols, rowpad, colpad): data = '' color = 1 width = itemwidth * cols + colpad * (cols - 1) height = itemheight * rows + rowpad * (rows - 1) for row in range(rows): rowdata = '' for col in range(cols): rowdata += ('%c' % color) * itemwidth if col < cols - 1: rowdata += '\0' * colpad color += 1 data += rowdata * itemheight if row < rows - 1: data += (width * '\0') * rowpad assert len(data) == width * height self.image = ImageData(width, height, 'L', data) grid = ImageGrid(self.image, rows, cols, itemwidth, itemheight, rowpad, colpad) self.grid = Texture3D.create_for_image_grid(grid) def check_cell(self, cellimage, cellindex): self.assertTrue(cellimage.width == self.grid.item_width) self.assertTrue(cellimage.height == self.grid.item_height) color = '%c' % (cellindex + 1) cellimage = cellimage.image_data data = cellimage.get_data('L', cellimage.width) self.assertTrue(data == color * len(data)) def setUp(self): self.w = Window(visible=False) def test2(self): # Test 2 images of 32x32 images = [self.create_image(32, 32, i+1) for i in range(2)] texture = Texture3D.create_for_images(images) self.assertTrue(len(texture) == 2) for i in range(2): self.check_image(texture[i], 32, 32, i+1) def test5(self): # test 5 images of 31x94 (power2 issues) images = [self.create_image(31, 94, i+1) for i in range(5)] texture = Texture3D.create_for_images(images) self.assertTrue(len(texture) == 5) for i in range(5): self.check_image(texture[i], 31, 94, i+1) def testSet(self): # test replacing an image images = [self.create_image(32, 32, i+1) for i in range(3)] texture = Texture3D.create_for_images(images) self.assertTrue(len(texture) == 3) for i in range(3): self.check_image(texture[i], 32, 32, i+1) texture[1] = self.create_image(32, 32, 87) self.check_image(texture[0], 32, 32, 1) self.check_image(texture[1], 32, 32, 87) self.check_image(texture[2], 32, 32, 3) def testSquare(self): # Test a 3x3 grid with no padding and 4x4 images rows = cols = 3 self.set_grid_image(4, 4, rows, cols, 0, 0) for i in range(rows * cols): self.check_cell(self.grid[i], i) def testRect(self): # Test a 2x5 grid with no padding and 3x8 images rows, cols = 2, 5 self.set_grid_image(3, 8, rows, cols, 0, 0) for i in range(rows * cols): self.check_cell(self.grid[i], i) def testPad(self): # Test a 5x3 grid with rowpad=3 and colpad=7 and 10x9 images rows, cols = 5, 3 self.set_grid_image(10, 9, rows, cols, 3, 7) for i in range(rows * cols): self.check_cell(self.grid[i], i) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test L load using PIL. You should see the la.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.pil import * class TEST_PIL_L(base_load.TestLoad): texture_file = 'l.png' decoder = PILImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGBA save using PyPNG. You should see rgba.png reference image on the left, and saved (and reloaded) image on the right. The saved image may have larger dimensions due to texture size restrictions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_save from pyglet.image.codecs.png import PNGImageEncoder class TEST_PNG_RGBA_SAVE(base_save.TestSave): texture_file = 'rgba.png' encoder = PNGImageEncoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test L load using PyPNG. You should see the l.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.png import PNGImageDecoder class TEST_PNG_L_LOAD(base_load.TestLoad): texture_file = 'l.png' decoder = PNGImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test rearrangement of color components using the OpenGL color matrix. The test will be skipped if the GL_ARB_imaging extension is not present. You should see the RGBA test image correctly rendered. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load import sys from pyglet.gl import gl_info class TEST_MATRIX_RGBA(base_load.TestLoad): texture_file = 'rgba.png' def load_image(self): if not gl_info.have_extension('GL_ARB_imaging'): print 'GL_ARB_imaging is not present, skipping test.' self.has_exit = True else: # Load image as usual then rearrange components super(TEST_MATRIX_RGBA, self).load_image() pixels = self.image.get_data('GBAR', self.image.width * 4) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Base class for image tests. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from StringIO import StringIO from os.path import dirname, join from pyglet.gl import * from pyglet import image from pyglet.image import codecs from pyglet.window import * from pyglet.window.event import * from tests.regression import ImageRegressionTestCase class TestSave(ImageRegressionTestCase): texture_file = None original_texture = None saved_texture = None show_checkerboard = True alpha = True has_exit = False def on_expose(self): self.draw() self.window.flip() if self.capture_regression_image(): self.has_exit = True def draw(self): glClearColor(1, 1, 1, 1) glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() if self.show_checkerboard: glPushMatrix() glScalef(self.window.width/float(self.checkerboard.width), self.window.height/float(self.checkerboard.height), 1.) glMatrixMode(GL_TEXTURE) glPushMatrix() glScalef(self.window.width/float(self.checkerboard.width), self.window.height/float(self.checkerboard.height), 1.) glMatrixMode(GL_MODELVIEW) self.checkerboard.blit(0, 0, 0) glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() self.draw_original() self.draw_saved() def draw_original(self): if self.original_texture: self.original_texture.blit( self.window.width / 4 - self.original_texture.width / 2, (self.window.height - self.original_texture.height) / 2, 0) def draw_saved(self): if self.saved_texture: self.saved_texture.blit( self.window.width * 3 / 4 - self.saved_texture.width / 2, (self.window.height - self.saved_texture.height) / 2, 0) def load_texture(self): if self.texture_file: self.texture_file = join(dirname(__file__), self.texture_file) self.original_texture = image.load(self.texture_file).texture file = StringIO() self.original_texture.save(self.texture_file, file, encoder=self.encoder) file.seek(0) self.saved_texture = image.load(self.texture_file, file).texture def create_window(self): width, height = 800, 600 return Window(width, height, visible=False) def test_save(self): self.window = w = self.create_window() w.push_handlers(self) self.screen = image.get_buffer_manager().get_color_buffer() self.checkerboard = image.create(32, 32, image.CheckerImagePattern()) self.load_texture() if self.alpha: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) w.set_visible() while not (w.has_exit or self.has_exit): w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test L save using PIL. You should see l.png reference image on the left, and saved (and reloaded) image on the right. The saved image may have larger dimensions due to texture size restrictions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_save from pyglet.image.codecs.pil import PILImageEncoder class TEST_PIL_L_SAVE(base_save.TestSave): texture_file = 'l.png' encoder = PILImageEncoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test LA load using PIL. You should see the la.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.pil import * class TEST_PNG_LA(base_load.TestLoad): texture_file = 'la.png' decoder = PILImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgb_32bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgb_32bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGBA load using PIL. You should see the rgba.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load from pyglet.image.codecs.pil import * class TEST_PIL_RGBA_LOAD(base_load.TestLoad): texture_file = 'rgba.png' decoder = PILImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test DXT3 compressed RGBA load from a DDS file. You should see the rgba_dxt3.dds image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.dds import DDSImageDecoder class TEST_DDS_RGBA_DXT3(base_load.TestLoad): texture_file = 'rgba_dxt3.dds' decoder = DDSImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test LA save using PyPNG. You should see la.png reference image on the left, and saved (and reloaded) image on the right. The saved image may have larger dimensions due to texture size restrictions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_save from pyglet.image.codecs.png import PNGImageEncoder class TEST_PNG_LA_SAVE(base_save.TestSave): texture_file = 'la.png' encoder = PNGImageEncoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGB save using PyPNG. You should see rgb.png reference image on the left, and saved (and reloaded) image on the right. The saved image may have larger dimensions due to texture size restrictions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_save from pyglet.image.codecs.png import PNGImageEncoder class TEST_PNG_RGB_SAVE(base_save.TestSave): texture_file = 'rgb.png' encoder = PNGImageEncoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test LA save using PIL. You should see la.png reference image on the left, and saved (and reloaded) image on the right. The saved image may have larger dimensions due to texture size restrictions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_save from pyglet.image.codecs.pil import PILImageEncoder class TEST_PIL_LA_SAVE(base_save.TestSave): texture_file = 'la.png' encoder = PILImageEncoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgb_16bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgb_16bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test DXT1 compressed RGBA load from a DDS file. You should see the rgba_dxt1.dds image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.dds import DDSImageDecoder class TEST_DDS_RGBA_DXT1(base_load.TestLoad): texture_file = 'rgba_dxt1.dds' decoder = DDSImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test depth buffer save. A scene consisting of a single coloured triangle will be rendered. The depth buffer will then be saved to a stream and loaded as a texture. You will see the original scene first for up to several seconds before the depth buffer image appears (because retrieving and saving the image is a slow operation). Messages will be printed to stdout indicating what stage is occuring. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from StringIO import StringIO import unittest import base_save from pyglet.gl import * from pyglet import image class TEST_DEPTH_SAVE(base_save.TestSave): alpha = False def draw_original(self): glClear(GL_DEPTH_BUFFER_BIT) glEnable(GL_DEPTH_TEST) glBegin(GL_TRIANGLES) glColor4f(1, 0, 0, 1) glVertex3f(0, 0, -1) glColor4f(0, 1, 0, 1) glVertex3f(200, 0, 0) glColor4f(0, 0, 1, 1) glVertex3f(0, 200, 1) glEnd() glDisable(GL_DEPTH_TEST) glColor4f(1, 1, 1, 1) def load_texture(self): print 'Drawing scene...' self.window.set_visible() self.window.dispatch_events() self.draw() print 'Saving depth image...' img = image.get_buffer_manager().get_depth_buffer() file = StringIO() img.save('buffer.png', file) print 'Loading depth image as texture...' file.seek(0) self.saved_texture = image.load('buffer.png', file) print 'Done.' self.window.set_visible(False) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgb_4bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgb_4bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test LA load using PyPNG. You should see the la.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.png import PNGImageDecoder class TEST_PNG_LA_LOAD(base_load.TestLoad): texture_file = 'la.png' decoder = PNGImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGB load using PyPNG. You should see the rgb.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load from pyglet.image.codecs.png import PNGImageDecoder class TEST_PNG_RGB_LOAD(base_load.TestLoad): texture_file = 'rgb.png' decoder = PNGImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Base class for image tests. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from os.path import dirname, join from pyglet.gl import * from pyglet import image from pyglet.image import codecs from pyglet.window import * from pyglet.window.event import * from tests.regression import ImageRegressionTestCase class TestLoad(ImageRegressionTestCase): texture_file = None image = None texture = None show_checkerboard = True alpha = True has_exit = False decoder = None def on_expose(self): glClearColor(1, 1, 1, 1) glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() if self.show_checkerboard: glPushMatrix() glScalef(self.window.width/float(self.checkerboard.width), self.window.height/float(self.checkerboard.height), 1.) glMatrixMode(GL_TEXTURE) glPushMatrix() glScalef(self.window.width/float(self.checkerboard.width), self.window.height/float(self.checkerboard.height), 1.) glMatrixMode(GL_MODELVIEW) self.checkerboard.blit(0, 0, 0) glMatrixMode(GL_TEXTURE) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() if self.texture: glPushMatrix() glTranslatef((self.window.width - self.texture.width) / 2, (self.window.height - self.texture.height) / 2, 0) self.texture.blit(0, 0, 0) glPopMatrix() self.window.flip() if self.capture_regression_image(): self.has_exit = True def load_image(self): if self.texture_file: self.texture_file = join(dirname(__file__), self.texture_file) self.image = image.load(self.texture_file, decoder=self.decoder) def test_load(self): width, height = 800, 600 self.window = w = Window(width, height, visible=False) w.push_handlers(self) self.screen = image.get_buffer_manager().get_color_buffer() self.checkerboard = image.create(32, 32, image.CheckerImagePattern()) self.load_image() if self.image: self.texture = self.image.texture if self.alpha: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) w.set_visible() while not (w.has_exit or self.has_exit): w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test colour buffer copy to texture. A scene consisting of a single coloured triangle will be rendered. The colour buffer will then be saved to a stream and loaded as a texture. You will see the original scene first for up to several seconds before the buffer image appears (because retrieving and saving the image is a slow operation). Messages will be printed to stdout indicating what stage is occuring. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from StringIO import StringIO import unittest import base_save from pyglet.gl import * from pyglet import image class TEST_BUFFER_COPY(base_save.TestSave): alpha = False def draw_original(self): glBegin(GL_TRIANGLES) glColor4f(1, 0, 0, 1) glVertex3f(0, 0, -1) glColor4f(0, 1, 0, 1) glVertex3f(200, 0, 0) glColor4f(0, 0, 1, 1) glVertex3f(0, 200, 1) glEnd() glColor4f(1, 1, 1, 1) def load_texture(self): print 'Drawing scene...' self.window.set_visible() self.window.dispatch_events() self.draw() print 'Copying colour image...' self.saved_texture = \ image.get_buffer_manager().get_color_buffer().texture print 'Done.' self.window.set_visible(False) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgba_32bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgba_32bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test that the checkerboard pattern looks correct. One window will open, it should show one instance of the checkerboard pattern in two levels of grey. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet.gl import * from pyglet import image from pyglet.window import * from pyglet.window.event import * from tests.regression import ImageRegressionTestCase class TEST_CHECKERBOARD(ImageRegressionTestCase): has_exit = False def on_expose(self): glClearColor(1, 1, 1, 1) glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() self.texture.blit(0, 0, 0) self.window.flip() if self.capture_regression_image(): self.has_exit = True def test_main(self): width, height = 200, 200 self.window = w = Window(width, height, visible=False) w.push_handlers(self) self.texture = image.create(32, 32, image.CheckerImagePattern()).texture w.set_visible() while not (w.has_exit or self.has_exit): w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test L save using PyPNG. You should see l.png reference image on the left, and saved (and reloaded) image on the right. The saved image may have larger dimensions due to texture size restrictions. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_save from pyglet.image.codecs.png import PNGImageEncoder class TEST_PNG_L_SAVE(base_save.TestSave): texture_file = 'l.png' encoder = PNGImageEncoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGBA load using PyPNG. You should see the rgba.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load from pyglet.image.codecs.png import PNGImageDecoder class TEST_PNG_RGBA_LOAD(base_load.TestLoad): texture_file = 'rgba.png' decoder = PNGImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test DXT5 compressed RGBA load from a DDS file. You should see the rgba_dxt5.dds image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.dds import DDSImageDecoder class TEST_DDS_RGBA_DXT5(base_load.TestLoad): texture_file = 'rgba_dxt5.dds' decoder = DDSImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGB load using PIL. You should see the rgb.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load from pyglet.image.codecs.pil import * class TEST_PIL_RGB_LOAD(base_load.TestLoad): texture_file = 'rgb.png' decoder = PILImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test DXT1 compressed RGB load from a DDS file. You should see the rgb_dxt1.dds image. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.dds import DDSImageDecoder class TEST_DDS_RGB_DXT1(base_load.TestLoad): texture_file = 'rgb_dxt1.dds' decoder = DDSImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test load using the Python BMP loader. You should see the rgb_24bpp.bmp image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import unittest import base_load from pyglet.image.codecs.bmp import BMPImageDecoder class TEST_SUITE(base_load.TestLoad): texture_file = 'rgb_24bpp.bmp' decoder = BMPImageDecoder() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python '''Test RGBA load using the platform decoder (QuickTime, Quartz, GDI+ or Gdk). You should see the rgba.png image on a checkboard background. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest import base_load import sys if sys.platform.startswith('linux'): from pyglet.image.codecs.gdkpixbuf2 import GdkPixbuf2ImageDecoder as dclass elif sys.platform in ('win32', 'cygwin'): from pyglet.image.codecs.gdiplus import GDIPlusDecoder as dclass elif sys.platform == 'darwin': from pyglet import options as pyglet_options if pyglet_options['darwin_cocoa']: from pyglet.image.codecs.quartz import QuartzImageDecoder as dclass else: from pyglet.image.codecs.quicktime import QuickTimeImageDecoder as dclass class TEST_PLATFORM_RGBA_LOAD(base_load.TestLoad): texture_file = 'rgba.png' decoder = dclass() if __name__ == '__main__': unittest.main()
Python