def test_context_taking(): """ Test GLContext ownership and taking """ def get_canvas(c): return c.backend_canvas cb = DummyCanvasBackend() c = GLContext() # Context is not taken and cannot get backend_canvas assert not c.istaken assert_raises(RuntimeError, get_canvas, c) assert_in('no backend', repr(c)) # Take it c.take('test-foo', cb) assert c.backend_canvas is cb assert_in('test-foo backend', repr(c)) # Now we cannot take it again assert_raises(RuntimeError, c.take, 'test', cb) # Canvas backend can delete (we use a weak ref) cb = DummyCanvasBackend() # overwrite old object gc.collect() # Still cannot take it, but backend is invalid assert_raises(RuntimeError, c.take, 'test', cb) assert_raises(RuntimeError, get_canvas, c)
def test_context_taking(): """ Test GLContext ownership and taking """ def get_canvas(c): return c.shared.ref cb = DummyCanvasBackend() c = GLContext() # Context is not taken and cannot get backend_canvas assert c.shared.name is None assert_raises(RuntimeError, get_canvas, c) assert_in('None backend', repr(c.shared)) # Take it c.shared.add_ref('test-foo', cb) assert c.shared.ref is cb assert_in('test-foo backend', repr(c.shared)) # Now we can take it again c.shared.add_ref('test-foo', cb) assert len(c.shared._refs) == 2 #assert_raises(RuntimeError, c.take, 'test', cb) # Canvas backend can delete (we use a weak ref) cb = DummyCanvasBackend() # overwrite old object gc.collect() # No more refs assert_raises(RuntimeError, get_canvas, c)
def test_Variable(): # Test init fail assert_raises(TypeError, Variable) # no args assert_raises(TypeError, Variable, 3) # wrong type assert_raises(TypeError, Variable, "name", "str") # wrong type assert_raises(ValueError, Variable, 'bla bla') # need correct vtype assert_raises(ValueError, Variable, 'uniform b l a') # too many # Test init success var = Variable('uniform float bla') # Finally assert_equal(var.name, 'bla') assert_equal(var.dtype, 'float') assert_equal(var.vtype, 'uniform') assert var.value is None # test assign new value var.value = 10. assert_equal(var.dtype, 'float') # type is locked; won't change # test name-only init var = Variable('bla') # Finally assert_equal(var.name, 'bla') assert_equal(var.dtype, None) assert_equal(var.vtype, None) assert var.value is None # test assign new value var.value = 10 assert_equal(var.dtype, 'int') assert_equal(var.vtype, 'uniform') assert_equal(var.value, 10) # test init with value var = Variable('bla', (1, 2, 3)) # Also valid assert_equal(var.name, 'bla') assert_equal(var.dtype, 'vec3') assert_equal(var.vtype, 'uniform') assert_equal(var.value, (1, 2, 3)) # Test value #var = Variable('uniform float bla', data) # Also valid #assert_equal(var.value, data) #var.value = 3 #assert_equal(var.value, 3) # Test repr var = Variable('uniform float bla') assert_in('uniform float bla', var.compile()) # Test injection, definition, dependencies assert_equal(var.expression({var: 'xxx'}), 'xxx') assert_equal(var.definition({var: 'xxx'}), 'uniform float xxx;') assert_in(var, var.dependencies()) # Renaming var = Variable('uniform float bla') assert_equal(var.name, 'bla') var.name = 'foo' assert_equal(var.name, 'foo')
def test_context_taking(): """Test GLContext ownership and taking""" def get_canvas(c): return c.shared.ref cb = DummyCanvasBackend() c = GLContext() # Context is not taken and cannot get backend_canvas assert c.shared.name is None assert_raises(RuntimeError, get_canvas, c) assert_in('None backend', repr(c.shared)) # Take it c.shared.add_ref('test-foo', cb) assert c.shared.ref is cb assert_in('test-foo backend', repr(c.shared)) # Now we can take it again c.shared.add_ref('test-foo', cb) assert len(c.shared._refs) == 2 # assert_raises(RuntimeError, c.take, 'test', cb) # Canvas backend can delete (we use a weak ref) cb = DummyCanvasBackend() # overwrite old object gc.collect() # No more refs assert_raises(RuntimeError, get_canvas, c)
def test_event_order(): """Test event order""" x = list() class MyCanvas(Canvas): def on_initialize(self, event): x.append('init') def on_draw(self, event): sz = True if self.size is not None else False x.append('draw size=%s show=%s' % (sz, show)) def on_close(self, event): x.append('close') for show in (False, True): # clear our storage variable while x: x.pop() with MyCanvas(show=show) as c: c.update() c.app.process_events() print(x) assert_true(len(x) >= 3) assert_equal(x[0], 'init') assert_in('draw size=True', x[1]) assert_in('draw size=True', x[-2]) assert_equal(x[-1], 'close')
def test_testing(): """Test testing ports""" assert_raises(AssertionError, assert_in, 'foo', 'bar') assert_in('foo', 'foobar') assert_raises(AssertionError, assert_not_in, 'foo', 'foobar') assert_not_in('foo', 'bar') assert_raises(AssertionError, assert_is, None, 0) assert_is(None, None)
def test_testing(): """Test testing ports""" assert_raises(AssertionError, assert_in, "foo", "bar") assert_in("foo", "foobar") assert_raises(AssertionError, assert_not_in, "foo", "foobar") assert_not_in("foo", "bar") assert_raises(AssertionError, assert_is, None, 0) assert_is(None, None)
def test_sys_info(): """Test printing of system information""" fname = op.join(temp_dir, 'info.txt') sys_info(fname) assert_raises(IOError, sys_info, fname) # no overwrite with open(fname, 'r') as fid: out = ''.join(fid.readlines()) # Note: 'GL version' only for non-GLUT keys = ['Python', 'Backend', 'pyglet', 'Platform:'] for key in keys: assert_in(key, out)
def test_sys_info(): """Test printing of system information""" fname = op.join(temp_dir, 'info.txt') sys_info(fname) assert_raises(IOError, sys_info, fname) # no overwrite with open(fname, 'r') as fid: out = ''.join(fid.readlines()) keys = ['GL version', 'Python', 'Backend', 'pyglet', 'Platform:'] for key in keys: assert_in(key, out) print(out) assert_true('Info-gathering error' not in out)
def test_sys_info(): """Test printing of system information""" fname = op.join(temp_dir, "info.txt") sys_info(fname) assert_raises(IOError, sys_info, fname) # no overwrite with open(fname, "r") as fid: out = "".join(fid.readlines()) keys = ["GL version", "Python", "Backend", "pyglet", "Platform:"] for key in keys: assert_in(key, out) print(out) assert_true("Info-gathering error" not in out)
def test_error(self): vert = ''' void main() { vec2 xy; error on this line vec2 ab; } ''' frag = 'void main() { glFragColor = vec4(1, 1, 1, 1); }' with app.Canvas() as c: program = Program(vert, frag) try: program._glir.flush(c.context.shared.parser) except Exception as err: assert_in('error on this line', str(err)) else: raise Exception("Compile program should have failed.")
def test_debug_logging(): """Test advanced debugging logging""" with use_log_level('debug', 'Selected', True, False) as l: logger.debug('Selected foo') assert_equal(len(l), 1) assert_in('test_logging', l[0]) # can't really parse this location with use_log_level('debug', record=True, print_msg=False) as l: logger.debug('foo') assert_equal(len(l), 1) assert_in('test_logging', l[0]) with use_log_level('debug', 'foo', True, False) as l: logger.debug('bar') assert_equal(len(l), 0) with use_log_level('info', record=True, print_msg=False) as l: logger.debug('foo') logger.info('bar') assert_equal(len(l), 1) assert_not_in('unknown', l[0])
def test_ignore_comments(self): shader = VertexShader(""" attribute vec4 color; attribute float x; // attribute float y; attribute float z; //attribute float w; """) names = [attr[0] for attr in shader.attributes] assert_in("color", names) assert_in("x", names) assert_in("z", names) assert_not_in("y", names) assert_not_in("w", names)
def test_application(): """Test application running""" app = use_app() print(app) # __repr__ without app app.create() wrong = 'glfw' if app.backend_name.lower() != 'glfw' else 'pyqt4' assert_raises(RuntimeError, use_app, wrong) app.process_events() print(app) # test __repr__ assert_raises(ValueError, Canvas, keys='foo') assert_raises(TypeError, Canvas, keys=dict(escape=1)) assert_raises(ValueError, Canvas, keys=dict(escape='foo')) # not an attr pos = [0, 0] if app.backend_module.capability['position'] else None size = (100, 100) # Use "with" statement so failures don't leave open window # (and test context manager behavior) title = 'default' with Canvas(title=title, size=size, app=app, show=True, position=pos) as canvas: context = canvas.context assert_true(canvas.create_native() is None) # should be done already assert_is(canvas.app, app) assert_true(canvas.native) assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1]) canvas.measure_fps(0.001) sleep(0.002) canvas.update() app.process_events() assert_true(canvas.fps > 0) # Other methods print(canvas) # __repr__ assert_equal(canvas.title, title) canvas.title = 'you' with use_log_level('warning', record=True, print_msg=False) as l: if app.backend_module.capability['position']: # todo: disable more tests based on capability canvas.position = pos canvas.size = size if 'ipynb_vnc' in canvas.app.backend_name.lower(): assert_true(len(l) >= 1) else: assert_true(len(l) == 0) canvas.connect(on_mouse_move) assert_raises(ValueError, canvas.connect, _on_mouse_move) if sys.platform != 'darwin': # XXX knownfail, prob. needs warmup canvas.show(False) canvas.show() app.process_events() assert_raises(ValueError, canvas.connect, on_nonexist) # deprecation of "paint" with use_log_level('info', record=True, print_msg=False) as log: olderr = sys.stderr try: fid = StringIO() sys.stderr = fid @canvas.events.paint.connect def fake(event): pass finally: sys.stderr = olderr assert_equal(len(log), 1) assert_in('deprecated', log[0]) # screenshots gl.glViewport(0, 0, *size) ss = _screenshot() assert_array_equal(ss.shape, size + (4,)) assert_equal(len(canvas._backend._vispy_get_geometry()), 4) if sys.platform != 'win32': # XXX knownfail for windows assert_array_equal(canvas.size, size) assert_equal(len(canvas.position), 2) # XXX knawnfail, doesn't "take" # GLOO: should have an OpenGL context already, so these should work vert = "void main (void) {gl_Position = pos;}" frag = "void main (void) {gl_FragColor = pos;}" program = Program(vert, frag) assert_raises(RuntimeError, program.glir.flush, context.shared.parser) vert = "uniform vec4 pos;\nvoid main (void) {gl_Position = pos;}" frag = "uniform vec4 pos;\nvoid main (void) {gl_FragColor = pos;}" program = Program(vert, frag) #uniform = program.uniforms[0] program['pos'] = [1, 2, 3, 4] vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}" frag = "void main (void) {}" program = Program(vert, frag) #attribute = program.attributes[0] program["pos"] = [1, 2, 3, 4] # use a real program program._glir.clear() vert = ("uniform mat4 u_model;" "attribute vec2 a_position; attribute vec4 a_color;" "varying vec4 v_color;" "void main (void) {v_color = a_color;" "gl_Position = u_model * vec4(a_position, 0.0, 1.0);" "v_color = a_color;}") frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}" n, p = 250, 50 T = np.random.uniform(0, 2 * np.pi, n) position = np.zeros((n, 2), dtype=np.float32) position[:, 0] = np.cos(T) position[:, 1] = np.sin(T) color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1) data = np.zeros(n * p, [('a_position', np.float32, 2), ('a_color', np.float32, 4)]) data['a_position'] = np.repeat(position, p, axis=0) data['a_color'] = np.repeat(color, p, axis=0) program = Program(vert, frag) program.bind(VertexBuffer(data)) program['u_model'] = np.eye(4, dtype=np.float32) # different codepath if no call to activate() program.draw(gl.GL_POINTS) subset = IndexBuffer(np.arange(10, dtype=np.uint32)) program.draw(gl.GL_POINTS, subset) # bad programs frag_bad = ("varying vec4 v_colors") # no semicolon program = Program(vert, frag_bad) assert_raises(RuntimeError, program.glir.flush, context.shared.parser) frag_bad = None # no fragment code. no main is not always enough assert_raises(ValueError, Program, vert, frag_bad) # Timer timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2, start=True, app=app) timer.start() timer.interval = 0.002 assert_equal(timer.interval, 0.002) assert_true(timer.running) sleep(.003) assert_true(timer.elapsed >= 0.002) timer.stop() assert_true(not timer.running) assert_true(timer.native) timer.disconnect() # test that callbacks take reasonable inputs _test_callbacks(canvas) # cleanup canvas.swap_buffers() canvas.update() app.process_events() # put this in even though __exit__ will call it to make sure we don't # have problems calling it multiple times canvas.close() # done by context
def _test_module_properties(_module=None): """Test application module""" if _module is None: app = use_app() _module = app.backend_module # Test that the keymap contains all keys supported by vispy. module_fname = _module.__name__.split(".")[-1] if module_fname != "_egl": # skip keys for EGL keymap = _module.KEYMAP vispy_keys = keymap.values() for keyname in dir(keys): if keyname.upper() != keyname: continue key = getattr(keys, keyname) assert_in(key, vispy_keys) # For Qt backend, we have a common implementation alt_modname = "" if module_fname in ("_pyside", "_pyqt4"): alt_modname = _module.__name__.rsplit(".", 1)[0] + "._qt" # Test that all _vispy_x methods are there. exceptions = ( "_vispy_init", "_vispy_get_native_canvas", "_vispy_get_native_timer", "_vispy_get_native_app", "_vispy_mouse_move", "_vispy_mouse_press", "_vispy_mouse_release", "_vispy_get_geometry", "_process_backend_kwargs", ) # defined in base class Klass = _module.CanvasBackend KlassRef = vispy.app.base.BaseCanvasBackend base = KlassRef(None, None) for key in dir(KlassRef): if not key.startswith("__"): method = getattr(Klass, key) if key not in exceptions: print(key) args = [None] * (len(getargspec(method).args) - 1) assert_raises(NotImplementedError, getattr(base, key), *args) if hasattr(method, "__module__"): mod_str = method.__module__ # Py3k else: mod_str = method.im_func.__module__ assert_in( mod_str, (_module.__name__, alt_modname), "Method %s.%s not defined in %s" % (Klass, key, _module.__name__), ) Klass = _module.TimerBackend KlassRef = vispy.app.timer.TimerBackend for key in dir(KlassRef): if not key.startswith("__"): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, "__module__"): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t Klass = _module.ApplicationBackend KlassRef = vispy.app.application.ApplicationBackend for key in dir(KlassRef): if not key.startswith("__"): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, "__module__"): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t # Test that all events seem to be emitted. # Get text fname = _module.__file__.rstrip("c") # "strip" will break windows! with open(fname, "rb") as fid: text = fid.read().decode("utf-8") canvas = vispy.app.Canvas(create_native=False, app=DummyApplication()) # Stylus and touch are ignored because they are not yet implemented. # Mouse events are emitted from the CanvasBackend base class. ignore = set(["stylus", "touch", "mouse_press", "paint", "mouse_move", "mouse_release", "close"]) if module_fname == "_egl": ignore += ["key_release", "key_press"] eventNames = set(canvas.events._emitters.keys()) - ignore if not alt_modname: # Only check for non-proxy modules for name in eventNames: assert_in("events.%s" % name, text, "events.%s does not appear in %s" % (name, fname))
def test_application(): """Test application running""" app = use_app() print(app) # __repr__ without app app.create() wrong = 'glut' if app.backend_name.lower() != 'glut' else 'pyglet' assert_raises(RuntimeError, use_app, wrong) app.process_events() print(app) # test __repr__ assert_raises(ValueError, Canvas, keys='foo') assert_raises(TypeError, Canvas, keys=dict(escape=1)) assert_raises(ValueError, Canvas, keys=dict(escape='foo')) # not an attr pos = [0, 0] if app.backend_module.capability['position'] else None size = (100, 100) # Use "with" statement so failures don't leave open window # (and test context manager behavior) title = 'default' with Canvas(title=title, size=size, app=app, show=True, position=pos) as canvas: assert_true(canvas.create_native() is None) # should be done already assert_is(canvas.app, app) assert_true(canvas.native) assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1]) canvas.measure_fps(0.001) sleep(0.002) canvas.update() app.process_events() assert_true(canvas.fps > 0) # Other methods print(canvas) # __repr__ assert_equal(canvas.title, title) canvas.title = 'you' with use_log_level('warning', record=True, print_msg=False) as l: if app.backend_module.capability['position']: # todo: disable more tests based on capability canvas.position = pos canvas.size = size if 'ipynb_vnc' in canvas.app.backend_name.lower(): assert_true(len(l) >= 1) else: assert_true(len(l) == 0) canvas.connect(on_mouse_move) assert_raises(ValueError, canvas.connect, _on_mouse_move) if sys.platform != 'darwin': # XXX knownfail, prob. needs warmup canvas.show(False) canvas.show() app.process_events() assert_raises(ValueError, canvas.connect, on_nonexist) # deprecation of "paint" with use_log_level('info', record=True, print_msg=False) as log: olderr = sys.stderr try: with open(os.devnull, 'w') as fid: sys.stderr = fid @canvas.events.paint.connect def fake(event): pass finally: sys.stderr = olderr assert_equal(len(log), 1) assert_in('deprecated', log[0]) # screenshots gl.glViewport(0, 0, *size) ss = _screenshot() assert_array_equal(ss.shape, size + (4,)) assert_equal(len(canvas._backend._vispy_get_geometry()), 4) if (app.backend_name.lower() != 'glut' and # XXX knownfail for Almar sys.platform != 'win32'): # XXX knownfail for windows assert_array_equal(canvas.size, size) assert_equal(len(canvas.position), 2) # XXX knawnfail, doesn't "take" # GLOO: should have an OpenGL context already, so these should work vert = VertexShader("void main (void) {gl_Position = pos;}") frag = FragmentShader("void main (void) {gl_FragColor = pos;}") program = Program(vert, frag) assert_raises(RuntimeError, program.activate) vert = VertexShader("uniform vec4 pos;" "void main (void) {gl_Position = pos;}") frag = FragmentShader("uniform vec4 pos;" "void main (void) {gl_FragColor = pos;}") program = Program(vert, frag) #uniform = program.uniforms[0] program['pos'] = [1, 2, 3, 4] program.activate() # should print #uniform.upload(program) program.detach(vert) program.detach(frag) assert_raises(RuntimeError, program.detach, vert) assert_raises(RuntimeError, program.detach, frag) vert = VertexShader("attribute vec4 pos;" "void main (void) {gl_Position = pos;}") frag = FragmentShader("void main (void) {}") program = Program(vert, frag) #attribute = program.attributes[0] program["pos"] = [1, 2, 3, 4] program.activate() #attribute.upload(program) # cannot get element count #assert_raises(RuntimeError, program.draw, 'POINTS') # use a real program vert = ("uniform mat4 u_model;" "attribute vec2 a_position; attribute vec4 a_color;" "varying vec4 v_color;" "void main (void) {v_color = a_color;" "gl_Position = u_model * vec4(a_position, 0.0, 1.0);" "v_color = a_color;}") frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}" n, p = 250, 50 T = np.random.uniform(0, 2 * np.pi, n) position = np.zeros((n, 2), dtype=np.float32) position[:, 0] = np.cos(T) position[:, 1] = np.sin(T) color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1) data = np.zeros(n * p, [('a_position', np.float32, 2), ('a_color', np.float32, 4)]) data['a_position'] = np.repeat(position, p, axis=0) data['a_color'] = np.repeat(color, p, axis=0) program = Program(vert, frag) program.bind(VertexBuffer(data)) program['u_model'] = np.eye(4, dtype=np.float32) # different codepath if no call to activate() program.draw(gl.GL_POINTS) subset = IndexBuffer(np.arange(10, dtype=np.uint32)) program.draw(gl.GL_POINTS, subset) # bad programs frag_bad = ("varying vec4 v_colors") # no semicolon program = Program(vert, frag_bad) assert_raises(RuntimeError, program.activate) frag_bad = None # no fragment code. no main is not always enough program = Program(vert, frag_bad) assert_raises(ValueError, program.activate) # Timer timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2, start=True, app=app) timer.start() timer.interval = 0.002 assert_equal(timer.interval, 0.002) assert_true(timer.running) sleep(.003) assert_true(timer.elapsed >= 0.002) timer.stop() assert_true(not timer.running) assert_true(timer.native) timer.disconnect() # test that callbacks take reasonable inputs _test_callbacks(canvas) # cleanup canvas.swap_buffers() canvas.update() app.process_events() # put this in even though __exit__ will call it to make sure we don't # have problems calling it multiple times canvas.close() # done by context
def test_FunctionChain(): f1 = Function("void f1(){}") f2 = Function("void f2(){}") f3 = Function("float f3(vec3 x){}") f4 = Function("vec3 f4(vec3 y){}") f5 = Function("vec3 f5(vec4 z){}") ch = FunctionChain('chain', [f1, f2]) assert ch.name == 'chain' assert ch.args == [] assert ch.rtype == 'void' assert_in('f1', ch.compile()) assert_in('f2', ch.compile()) ch.remove(f2) assert_not_in('f2', ch.compile()) ch.append(f2) assert_in('f2', ch.compile()) ch = FunctionChain(funcs=[f5, f4, f3]) assert_equal('float', ch.rtype) assert_equal([('vec4', 'z')], ch.args) assert_in('f3', ch.compile()) assert_in('f4', ch.compile()) assert_in('f5', ch.compile()) assert_in(f3, ch.dependencies()) assert_in(f4, ch.dependencies()) assert_in(f5, ch.dependencies())
def test_function_basics(): # Test init fail assert_raises(TypeError, Function) # no args assert_raises(ValueError, Function, 3) # need string # Test init success 1 fun = Function('void main(){}') assert_equal(fun.name, 'main') assert len(fun.template_vars) == 0 # Test init success with template vars fun = Function('void main(){$foo; $bar;}') assert_equal(fun.name, 'main') assert len(fun.template_vars) == 2 assert_in('foo', fun.template_vars) assert_in('bar', fun.template_vars) # Test setting verbatim expressions assert_raises(KeyError, fun.__setitem__, 'bla', '33') # no such template fun['foo'] = '33' fun['bar'] = 'bla bla' assert_is(type(fun['foo']), TextExpression) assert_equal(fun['foo'].expression(None), '33') assert_is(type(fun['bar']), TextExpression) assert_equal(fun['bar'].expression(None), 'bla bla') # Test setting call expressions fun = Function('void main(){\n$foo;\n$bar;\n$spam(XX);\n$eggs(YY);\n}') trans = Function('float transform_scale(float x) {return x+1.0;}') assert_raises(TypeError, trans) # requires 1 arg assert_raises(TypeError, trans, '1', '2') fun['foo'] = trans('2') fun['bar'] = trans('3') fun['spam'] = trans fun['eggs'] = trans # for name in ['foo', 'bar']: assert_is(type(fun[name]), FunctionCall) assert_equal(fun[name].function, trans) assert_in(trans, fun.dependencies()) for name in ['spam', 'eggs']: assert_equal(fun[name], trans) # text = fun.compile() assert_in('\ntransform_scale(2);\n', text) assert_in('\ntransform_scale(3);\n', text) assert_in('\ntransform_scale(XX);\n', text) assert_in('\ntransform_scale(YY);\n', text) # Test variable expressions fun = Function('void main(){$foo; $bar;}') fun['foo'] = Variable('uniform float bla') fun['bar'] = Variable('attribute float bla') assert_is(type(fun['foo']), Variable) assert_is(type(fun['bar']), Variable) assert_in(fun['foo'], fun.dependencies()) assert_in(fun['bar'], fun.dependencies()) # Test special variables fun = Function('void main(){$foo; $bar;}') variable = Variable('attribute vec3 v_pos') varying = Variable('varying vec3 color') # These do not work due to index assert_raises(TypeError, fun.__setitem__, 3, 3) # not a string assert_raises(KeyError, fun.__setitem__, 'xxx', 3) # unknown template var assert_raises(TypeError, fun.__setitem__, variable, 3) # only varyings # These work fun['gl_PointSize'] = '3.0' fun[varying] = variable # And getting works assert_equal(fun['gl_PointSize'].text, '3.0') assert_equal(fun[varying], variable)
def test_import_vispy_pyopengl(): """ Importing vispy.gloo.gl.pyopengl should import PyOpenGL. """ allmodnames = loaded_vispy_modules('vispy.gloo.gl.pyopengl', 2, True) assert_in('OpenGL', allmodnames)
def test_FunctionCall(): fun = Function(transformScale) fun['scale'] = '1.0' fun2 = Function(transformZOffset) # No args assert_raises(TypeError, fun) # need 1 arg assert_raises(TypeError, fun, 1, 2) # need 1 arg call = fun('x') # Test repr exp = call.expression({fun: 'y'}) assert_equal(exp, 'y(x)') # Test sig assert len(call._args) == 1 # Test dependencies assert_in(fun, call.dependencies()) assert_in(call._args[0], call.dependencies()) # More args call = fun(fun2('foo')) # Test repr exp = call.expression({fun: 'y', fun2: 'z'}) assert_in('y(z(', exp) # Test sig assert len(call._args) == 1 call2 = call._args[0] assert len(call2._args) == 1 # Test dependencies assert_in(fun, call.dependencies()) assert_in(call._args[0], call.dependencies()) assert_in(fun2, call.dependencies()) assert_in(call2._args[0], call.dependencies())
def _test_module_properties(_module=None): """Test application module""" if _module is None: app = use_app() _module = app.backend_module # Test that the keymap contains all keys supported by vispy. module_fname = _module.__name__.split('.')[-1] if module_fname != '_egl': # skip keys for EGL keymap = _module.KEYMAP vispy_keys = keymap.values() for keyname in dir(keys): if keyname.upper() != keyname: continue key = getattr(keys, keyname) assert_in(key, vispy_keys) # For Qt backend, we have a common implementation alt_modname = '' if module_fname in ('_pyside', '_pyqt4', '_pyqt5'): alt_modname = _module.__name__.rsplit('.', 1)[0] + '._qt' # Test that all _vispy_x methods are there. exceptions = ('_vispy_get_native_canvas', '_vispy_get_native_timer', '_vispy_get_native_app', '_vispy_reuse', '_vispy_mouse_move', '_vispy_mouse_press', '_vispy_mouse_release', '_vispy_get_geometry', '_process_backend_kwargs' ) # defined in base class class KlassRef(vispy.app.base.BaseCanvasBackend): def __init__(self, *args, **kwargs): pass # Do not call the base class, since it will check for Canvas Klass = _module.CanvasBackend base = KlassRef() for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: print(key) args = [None] * (len(getargspec(method).args) - 1) assert_raises(NotImplementedError, getattr(base, key), *args) if hasattr(method, '__module__'): mod_str = method.__module__ # Py3k else: mod_str = method.im_func.__module__ assert_in( mod_str, (_module.__name__, alt_modname), "Method %s.%s not defined in %s" % (Klass, key, _module.__name__)) Klass = _module.TimerBackend KlassRef = vispy.app.timer.TimerBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t Klass = _module.ApplicationBackend KlassRef = vispy.app.application.ApplicationBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t # Test that all events seem to be emitted. # Get text fname = _module.__file__.rstrip('c') # "strip" will break windows! with open(fname, 'rb') as fid: text = fid.read().decode('utf-8') canvas = vispy.app.Canvas(create_native=False, app=DummyApplication()) # Stylus and touch are ignored because they are not yet implemented. # Mouse events are emitted from the CanvasBackend base class. ignore = set([ 'stylus', 'touch', 'mouse_press', 'paint', 'mouse_move', 'mouse_release', 'close' ]) if module_fname == '_egl': ignore += ['key_release', 'key_press'] eventNames = set(canvas.events._emitters.keys()) - ignore if not alt_modname: # Only check for non-proxy modules for name in eventNames: assert_in('events.%s' % name, text, 'events.%s does not appear in %s' % (name, fname))
def test_function_basics(): # Test init fail assert_raises(TypeError, Function) # no args assert_raises(ValueError, Function, 3) # need string # Test init success 1 fun = Function('void main(){}') assert_equal(fun.name, 'main') assert len(fun.template_vars) == 0 # Test init success with template vars fun = Function('void main(){$foo; $bar;}') assert_equal(fun.name, 'main') assert len(fun.template_vars) == 2 assert_in('foo', fun.template_vars) assert_in('bar', fun.template_vars) # Test setting verbatim expressions assert_raises(KeyError, fun.__setitem__, 'bla', '33') # no such template fun['foo'] = '33' fun['bar'] = 'bla bla' assert_is(type(fun['foo']), TextExpression) assert_equal(fun['foo'].expression(None), '33') assert_is(type(fun['bar']), TextExpression) assert_equal(fun['bar'].expression(None), 'bla bla') # Test setting call expressions fun = Function('void main(){\n$foo;\n$bar;\n$spam(XX);\n$eggs(YY);\n}') trans = Function('float transform_scale(float x) {return x+1.0;}') assert_raises(TypeError, trans) # requires 1 arg assert_raises(TypeError, trans, '1', '2') fun['foo'] = trans('2') fun['bar'] = trans('3') fun['spam'] = trans fun['eggs'] = trans # for name in ['foo', 'bar']: assert_is(type(fun[name]), FunctionCall) assert_equal(fun[name].function, trans) assert_in(trans, fun.dependencies()) for name in ['spam', 'eggs']: assert_equal(fun[name], trans) # text = fun.compile() assert_in('\ntransform_scale(2);\n', text) assert_in('\ntransform_scale(3);\n', text) assert_in('\ntransform_scale(XX);\n', text) assert_in('\ntransform_scale(YY);\n', text) # test pre/post assignments fun = Function('void main() {some stuff;}') fun['pre'] = '__pre__' fun['post'] = '__post__' text = fun.compile() assert text == 'void main() {\n __pre__\nsome stuff;\n __post__\n}\n' # Test variable expressions fun = Function('void main(){$foo; $bar;}') fun['foo'] = Variable('uniform float bla') fun['bar'] = Variable('attribute float bla') assert_is(type(fun['foo']), Variable) assert_is(type(fun['bar']), Variable) assert_in(fun['foo'], fun.dependencies()) assert_in(fun['bar'], fun.dependencies()) # Test special variables fun = Function('void main(){$foo; $bar;}') variable = Variable('attribute vec3 v_pos') varying = Variable('varying vec3 color') # These do not work due to index assert_raises(TypeError, fun.__setitem__, 3, 3) # not a string assert_raises(KeyError, fun.__setitem__, 'xxx', 3) # unknown template var assert_raises(TypeError, fun.__setitem__, variable, 3) # only varyings # These work fun['gl_PointSize'] = '3.0' fun[varying] = variable # And getting works assert_equal(fun['gl_PointSize'].text, '3.0') assert_equal(fun[varying], variable)
def test_font_list(): """Test font listing""" f = list_fonts() assert_true(len(f) > 0) for font in _vispy_fonts: assert_in(font, f)
def _test_module_properties(_module=None): """Test application module""" if _module is None: app = use_app() _module = app.backend_module # Test that the keymap contains all keys supported by vispy. module_fname = _module.__name__.split('.')[-1] if module_fname != '_egl': # skip keys for EGL keymap = _module.KEYMAP vispy_keys = keymap.values() for keyname in dir(keys): if keyname.upper() != keyname: continue key = getattr(keys, keyname) assert_in(key, vispy_keys) # For Qt backend, we have a common implementation alt_modname = '' if module_fname in ('_pyside', '_pyqt4', '_pyqt5'): alt_modname = _module.__name__.rsplit('.', 1)[0] + '._qt' # Test that all _vispy_x methods are there. exceptions = ( '_vispy_get_native_canvas', '_vispy_get_native_timer', '_vispy_get_native_app', '_vispy_reuse', '_vispy_mouse_move', '_vispy_mouse_press', '_vispy_mouse_release', '_vispy_mouse_double_click', '_vispy_detect_double_click', '_vispy_get_geometry', '_vispy_get_physical_size', '_process_backend_kwargs') # defined in base class class KlassRef(vispy.app.base.BaseCanvasBackend): def __init__(self, *args, **kwargs): pass # Do not call the base class, since it will check for Canvas Klass = _module.CanvasBackend base = KlassRef() for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: print(key) args = [None] * (len(getargspec(method).args) - 1) assert_raises(NotImplementedError, getattr(base, key), *args) if hasattr(method, '__module__'): mod_str = method.__module__ # Py3k else: mod_str = method.im_func.__module__ assert_in(mod_str, (_module.__name__, alt_modname), "Method %s.%s not defined in %s" % (Klass, key, _module.__name__)) Klass = _module.TimerBackend KlassRef = vispy.app.timer.TimerBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t Klass = _module.ApplicationBackend KlassRef = vispy.app.application.ApplicationBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t # Test that all events seem to be emitted. # Get text fname = _module.__file__.rstrip('c') # "strip" will break windows! with open(fname, 'rb') as fid: text = fid.read().decode('utf-8') canvas = vispy.app.Canvas(create_native=False, app=DummyApplication()) # Stylus and touch are ignored because they are not yet implemented. # Mouse events are emitted from the CanvasBackend base class. ignore = set(['stylus', 'touch', 'mouse_press', 'paint', 'mouse_move', 'mouse_release', 'mouse_double_click', 'detect_double_click', 'close']) if module_fname == '_egl': ignore += ['key_release', 'key_press'] eventNames = set(canvas.events._emitters.keys()) - ignore if not alt_modname: # Only check for non-proxy modules for name in eventNames: assert_in('events.%s' % name, text, 'events.%s does not appear in %s' % (name, fname))
def test_import_vispy_pyopengl(): """ Importing vispy.gloo.gl.pyopengl2 should import PyOpenGL. """ allmodnames = loaded_vispy_modules('vispy.gloo.gl.pyopengl2', 2, True) assert_in('OpenGL', allmodnames)
def test_import_vispy_pyopengl(): """ Importing vispy.gloo.gl.pyopengl2 should import PyOpenGL. """ allmodnames = loaded_vispy_modules("vispy.gloo.gl.pyopengl2", 2, True) assert_in("OpenGL", allmodnames)