Ejemplo n.º 1
0
def test_debug_logging():
    """Test advanced debugging logging"""
    with use_log_level('debug', 'Selected', True) as l:
        a = app.Application()
        a.use()
        a.quit()
    assert_equal(len(l), 1)
    assert_true('vispy.app.application' in l[0])

    with use_log_level('debug', record=True) as l:
        a = app.Application()
        a.use()
        a.quit()
    assert_equal(len(l), 1)
    assert_true('vispy.app.application' in l[0])

    with use_log_level('debug', 'foo', True) as l:
        a = app.Application()
        a.use()
        a.quit()
    assert_equal(len(l), 0)

    with use_log_level('info', record=True) as l:
        a = app.Application()
        a.use()
        a.quit()
    assert_equal(len(l), 1)
    assert_true('vispy.app.application' not in l[0])
Ejemplo n.º 2
0
def test_logging():
    """Test logging context manager"""
    ll = logger.level
    with use_log_level('warning', print_msg=False):
        assert_equal(logger.level, logging.WARN)
    assert_equal(logger.level, ll)
    with use_log_level('debug', print_msg=False):
        assert_equal(logger.level, logging.DEBUG)
    assert_equal(logger.level, ll)
Ejemplo n.º 3
0
def test_logging():
    """Test logging context manager"""
    ll = logger.level
    with use_log_level('warning', print_msg=False):
        assert_equal(logger.level, logging.WARN)
    assert_equal(logger.level, ll)
    with use_log_level('debug', print_msg=False):
        assert_equal(logger.level, logging.DEBUG)
    assert_equal(logger.level, ll)
Ejemplo n.º 4
0
 def test_group_ignore(self):
     """EmitterGroup.block_all"""
     grp = EmitterGroup(em1=Event)
     grp.em1.connect(self.error_event)
     with use_log_level('warning', record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
     grp.ignore_callback_errors = False
     assert_raises(RuntimeError, grp.em1)
     grp.ignore_callback_errors = True
     with use_log_level('warning', record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
Ejemplo n.º 5
0
 def test_group_ignore(self):
     """EmitterGroup.block_all"""
     grp = EmitterGroup(em1=Event)
     grp.em1.connect(self.error_event)
     with use_log_level("warning", record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
     grp.ignore_callback_errors = False
     assert_raises(RuntimeError, grp.em1)
     grp.ignore_callback_errors = True
     with use_log_level("warning", record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
Ejemplo n.º 6
0
    def test_setitem(self):
        vert = VertexShader("")
        frag = FragmentShader("")

        program = Program(vert, frag)
        #with self.assertRaises(ValueError):
        #    program["A"] = 1
        with use_log_level('error', record=True, print_msg=False):
            self.assertRaises(KeyError, program.__setitem__, "A", 1)
Ejemplo n.º 7
0
    def test_setitem(self):
        vert = VertexShader("")
        frag = FragmentShader("")

        program = Program(vert, frag)
        #with self.assertRaises(ValueError):
        #    program["A"] = 1
        with use_log_level('error', record=True, print_msg=False):
            self.assertRaises(KeyError, program.__setitem__, "A", 1)
Ejemplo n.º 8
0
def test_fs():
    """Test fullscreen support"""
    a = use_app()
    if not a.backend_module.capability['fullscreen']:
        return
    assert_raises(TypeError, Canvas, fullscreen='foo')
    if (a.backend_name.lower() == 'glfw' or
            (a.backend_name.lower() == 'sdl2' and sys.platform == 'darwin')):
        raise SkipTest('Backend takes over screen')
    with use_log_level('warning', record=True, print_msg=False) as l:
        with Canvas(fullscreen=False) as c:
            assert_equal(c.fullscreen, False)
            c.fullscreen = True
            assert_equal(c.fullscreen, True)
    assert_equal(len(l), 0)
    with use_log_level('warning', record=True, print_msg=False):
        # some backends print a warning b/c fullscreen can't be specified
        with Canvas(fullscreen=0) as c:
            assert_equal(c.fullscreen, True)
Ejemplo n.º 9
0
def test_fs():
    """Test fullscreen support"""
    a = use_app()
    if not a.backend_module.capability['fullscreen']:
        return
    assert_raises(TypeError, Canvas, fullscreen='foo')
    if (a.backend_name.lower() == 'glfw' or
            (a.backend_name.lower() == 'sdl2' and sys.platform == 'darwin')):
        raise SkipTest('Backend takes over screen')
    with use_log_level('warning', record=True, print_msg=False) as l:
        with Canvas(fullscreen=False) as c:
            assert_equal(c.fullscreen, False)
            c.fullscreen = True
            assert_equal(c.fullscreen, True)
    assert_equal(len(l), 0)
    with use_log_level('warning', record=True, print_msg=False):
        # some backends print a warning b/c fullscreen can't be specified
        with Canvas(fullscreen=0) as c:
            assert_equal(c.fullscreen, True)
Ejemplo n.º 10
0
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])
Ejemplo n.º 11
0
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])
Ejemplo n.º 12
0
def _test_basics(backend):
    """Create app and canvas so we have a context. Then run tests."""
    # use the backend
    with use_log_level('error', print_msg=False):
        gl.use_gl(backend)  # pyopengl throws warning on injection

    with Canvas():
        _test_setting_parameters()
        _test_enabling_disabling()
        _test_setting_stuff()
        _test_object_creation_and_deletion()
        _test_fbo()
        gl.glFinish()
Ejemplo n.º 13
0
def _test_setting_stuff():
    # Set stuff to touch functions

    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    #
    gl.glBlendColor(1.0, 1.0, 1.0, 1.0)
    gl.glBlendEquation(gl.GL_FUNC_ADD)
    gl.glBlendEquationSeparate(gl.GL_FUNC_ADD, gl.GL_FUNC_ADD)
    gl.glBlendFunc(gl.GL_ONE, gl.GL_ZERO)
    gl.glBlendFuncSeparate(gl.GL_ONE, gl.GL_ZERO, gl.GL_ONE, gl.GL_ZERO)
    #
    gl.glClearColor(0.0, 0.0, 0.0, 1.0)
    gl.glClearDepth(1)
    gl.glClearStencil(0)
    #
    gl.glColorMask(True, True, True, True)
    gl.glDepthMask(False)
    gl.glStencilMask(255)
    gl.glStencilMaskSeparate(gl.GL_FRONT, 128)
    #
    gl.glStencilFunc(gl.GL_ALWAYS, 0, 255)
    gl.glStencilFuncSeparate(gl.GL_FRONT, gl.GL_ALWAYS, 0, 255)
    gl.glStencilOp(gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    gl.glStencilOpSeparate(gl.GL_FRONT, gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    #
    gl.glFrontFace(gl.GL_CW)
    gl.glHint(gl.GL_GENERATE_MIPMAP_HINT, gl.GL_FASTEST)
    gl.glLineWidth(2.0)
    gl.glPolygonOffset(0.0, 0.0)
    gl.glSampleCoverage(1.0, False)

    # And getting stuff
    try:
        with use_log_level('error', print_msg=False):
            r, p = gl.glGetShaderPrecisionFormat(gl.GL_FRAGMENT_SHADER,
                                                 gl.GL_HIGH_FLOAT)
            gl.check_error()  # Sometimes the func is there but OpenGL errs
    except Exception:
        pass  # accept if the function is not there ...
        # We should catch RuntimeError and GL.error.NullFunctionError,
        # but PyOpenGL may not be available.
        # On Travis this function was not there on one machine according
        # to PyOpenGL, but our desktop backend worked fine ...

    #
    v = gl.glGetParameter(gl.GL_VERSION)
    assert_true(isinstance(v, string_types))
    assert_true(len(v) > 0)

    gl.check_error()
Ejemplo n.º 14
0
def _test_setting_stuff():
    # Set stuff to touch functions
    
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    #
    gl.glBlendColor(1.0, 1.0, 1.0, 1.0)
    gl.glBlendEquation(gl.GL_FUNC_ADD)
    gl.glBlendEquationSeparate(gl.GL_FUNC_ADD, gl.GL_FUNC_ADD)
    gl.glBlendFunc(gl.GL_ONE, gl.GL_ZERO)
    gl.glBlendFuncSeparate(gl.GL_ONE, gl.GL_ZERO, gl.GL_ONE, gl.GL_ZERO)
    #
    gl.glClearColor(0.0, 0.0, 0.0, 1.0)
    gl.glClearDepth(1)
    gl.glClearStencil(0)
    #
    gl.glColorMask(True, True, True, True)
    gl.glDepthMask(False)
    gl.glStencilMask(255)
    gl.glStencilMaskSeparate(gl.GL_FRONT, 128)
    #
    gl.glStencilFunc(gl.GL_ALWAYS, 0, 255)
    gl.glStencilFuncSeparate(gl.GL_FRONT, gl.GL_ALWAYS, 0, 255)
    gl.glStencilOp(gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    gl.glStencilOpSeparate(gl.GL_FRONT, gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    #
    gl.glFrontFace(gl.GL_CW)
    gl.glHint(gl.GL_GENERATE_MIPMAP_HINT, gl.GL_FASTEST)
    gl.glLineWidth(2.0)
    gl.glPolygonOffset(0.0, 0.0)
    gl.glSampleCoverage(1.0, False)
    
    # And getting stuff
    try:
        with use_log_level('error', print_msg=False):
            r, p = gl.glGetShaderPrecisionFormat(gl.GL_FRAGMENT_SHADER,
                                                 gl.GL_HIGH_FLOAT)
            gl.check_error()  # Sometimes the func is there but OpenGL errs
    except Exception:
        pass  # accept if the function is not there ...
        # We should catch RuntimeError and GL.error.NullFunctionError,
        # but PyOpenGL may not be available.
        # On Travis this function was not there on one machine according
        # to PyOpenGL, but our desktop backend worked fine ...
        
    #
    v = gl.glGetParameter(gl.GL_VERSION)
    assert_true(isinstance(v, string_types))
    assert_true(len(v) > 0)
    
    gl.check_error()
Ejemplo n.º 15
0
 def test_init_non_contiguous_data(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     with use_log_level('warning', record=True, print_msg=False) as l:
         T = Texture(data=data[::2, ::2])
     assert len(l) == 1
     assert T._shape == (5, 5, 1)
     assert T._dtype == np.uint8
     assert T._offset == (0, 0, 0)
     assert T._store is True
     assert T._copy is True
     assert T._need_resize is True
     assert T._pending_data
     assert T._data is not data
     assert len(T._pending_data) == 1
Ejemplo n.º 16
0
 def test_init_non_contiguous_data(self):
     data = np.zeros((10, 10), dtype=np.uint8)
     with use_log_level('warning', record=True, print_msg=False) as l:
         T = Texture(data=data[::2, ::2])
     assert len(l) == 1
     assert T._shape == (5, 5, 1)
     assert T._dtype == np.uint8
     assert T._offset == (0, 0, 0)
     assert T._store is True
     assert T._copy is True
     assert T._need_resize is True
     assert T._pending_data
     assert T._data is not data
     assert len(T._pending_data) == 1
Ejemplo n.º 17
0
def _test_basics(backend):
    """ Create app and canvas so we have a context. Then run tests.
    """

    # use the backend
    with use_log_level('error', print_msg=False):
        gl.use_gl(backend)  # pyopengl throws warning on injection

    with Canvas():
        _test_setting_parameters()
        _test_enabling_disabling()
        _test_setting_stuff()
        _test_object_creation_and_deletion()
        _test_fbo()
        gl.glFinish()
Ejemplo n.º 18
0
 def test_non_contiguous_storage(self):
     # Ask to have CPU storage and to use data as storage
     # Not possible since data[::2] is not contiguous
     data = np.ones(100, np.float32)
     data_given = data[::2]
     
     with use_log_level('warning', record=True, print_msg=False) as l:
         B = DataBuffer(data_given, store=True)
     assert len(l) == 1
     assert B._data is not data_given
     assert B.stride == 4
     
     B = DataBuffer(data_given, store=False)
     assert B._data is not data_given
     assert B.stride == 4*2
Ejemplo n.º 19
0
def has_backend(backend, has=(), capable=(), out=()):
    from ..app.backends import BACKENDMAP
    using = os.getenv('_VISPY_TESTING_APP', None)
    if using is not None and using != backend:
        # e.g., we are on  a 'pyglet' run but the test requires PyQt4
        ret = (False,) if len(out) > 0 else False
        for o in out:
            ret += (None,)
        return ret

    # let's follow the standard code path
    module_name = BACKENDMAP[backend.lower()][1]
    with use_log_level('warning', print_msg=False):
        mod = __import__('app.backends.%s' % module_name, globals(), level=2)
    mod = getattr(mod.backends, module_name)
    good = mod.testable
    for h in has:
        good = (good and getattr(mod, 'has_%s' % h))
    for cap in capable:
        good = (good and mod.capability[cap])
    ret = (good,) if len(out) > 0 else good
    for o in out:
        ret += (getattr(mod, o),)
    return ret
Ejemplo n.º 20
0
def test_color_interpretation():
    """Test basic color interpretation API"""
    # test useful ways of single color init
    r = ColorArray('r')
    print(r)  # test repr
    r2 = ColorArray(r)
    assert_equal(r, r2)
    r2.rgb = 0, 0, 0
    assert_equal(r2, ColorArray('black'))
    assert_equal(r, ColorArray('r'))  # modifying new one preserves old
    assert_equal(r, r.copy())
    assert_equal(r, ColorArray('#ff0000'))
    assert_equal(r, ColorArray('#FF0000FF'))
    assert_equal(r, ColorArray('red'))
    assert_equal(r, ColorArray('red', alpha=1.0))
    assert_equal(ColorArray((1, 0, 0, 0.1)), ColorArray('red', alpha=0.1))
    assert_array_equal(r.rgb.ravel(), (1., 0., 0.))
    assert_array_equal(r.rgba.ravel(), (1., 0., 0., 1.))
    assert_array_equal(r.RGBA.ravel(), (255, 0, 0, 255))

    # handling multiple colors
    rgb = ColorArray(list('rgb'))
    print(rgb)  # multi repr
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    # complex/annoying case
    rgb = ColorArray(['r', (0, 1, 0), '#0000ffff'])
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    assert_raises(RuntimeError, ColorArray, ['r', np.eye(3)])  # can't nest

    # getting/setting properties
    r = ColorArray('#ffff')
    assert_equal(r, ColorArray('white'))
    r = ColorArray('#ff000000')
    assert_true('turquoise' in get_color_names())  # make sure our JSON loaded
    assert_equal(r.alpha, 0)
    r.alpha = 1.0
    assert_equal(r, ColorArray('r'))
    r.alpha = 0
    r.rgb = (1, 0, 0)
    assert_equal(r.alpha, 0)
    assert_equal(r.hex, ['#ff0000'])
    r.alpha = 1
    r.hex = '00ff00'
    assert_equal(r, ColorArray('g'))
    assert_array_equal(r.rgb.ravel(), (0., 1., 0.))
    r.RGB = 255, 0, 0
    assert_equal(r, ColorArray('r'))
    assert_array_equal(r.RGB.ravel(), (255, 0, 0))
    r.RGBA = 255, 0, 0, 0
    assert_equal(r, ColorArray('r', alpha=0))
    w = ColorArray()
    w.rgb = ColorArray('r').rgb + ColorArray('g').rgb + ColorArray('b').rgb
    assert_equal(w, ColorArray('white'))
    w = ColorArray('white')
    assert_equal(w, w.darker().lighter())
    assert_equal(w, w.darker(0.1).darker(-0.1))
    w2 = w.darker()
    assert_true(w != w2)
    w.darker(copy=False)
    assert_equal(w, w2)
    with use_log_level('warning', record=True, print_msg=False) as w:
        w = ColorArray('white')
        w.value = 2
        assert_equal(len(w), 1)
    assert_equal(w, ColorArray('white'))

    # warnings and errors
    assert_raises(ValueError, ColorArray, '#ffii00')  # non-hex
    assert_raises(ValueError, ColorArray, '#ff000')  # too short
    assert_raises(ValueError, ColorArray, [0, 0])  # not enough vals
    assert_raises(ValueError, ColorArray, [2, 0, 0])  # val > 1
    assert_raises(ValueError, ColorArray, [-1, 0, 0])  # val < 0
    c = ColorArray([2., 0., 0.], clip=True)  # val > 1
    assert_true(np.all(c.rgb <= 1))
    c = ColorArray([-1., 0., 0.], clip=True)  # val < 0
    assert_true(np.all(c.rgb >= 0))

    # make sure our color dict works
    for key in get_color_names():
        assert_true(ColorArray(key))
    assert_raises(ValueError, ColorArray, 'foo')  # unknown color error

    _color_dict = get_color_dict()
    assert isinstance(_color_dict, dict)
    assert set(_color_dict.keys()) == set(get_color_names())
Ejemplo n.º 21
0
def test_color_interpretation():
    """Test basic color interpretation API"""
    # test useful ways of single color init
    r = ColorArray('r')
    print(r)  # test repr
    r2 = ColorArray(r)
    assert_equal(r, r2)
    r2.rgb = 0, 0, 0
    assert_equal(r2, ColorArray('black'))
    assert_equal(r, ColorArray('r'))  # modifying new one preserves old
    assert_equal(r, r.copy())
    assert_equal(r, ColorArray('#ff0000'))
    assert_equal(r, ColorArray('#FF0000FF'))
    assert_equal(r, ColorArray('red'))
    assert_equal(r, ColorArray('red', alpha=1.0))
    assert_equal(ColorArray((1, 0, 0, 0.1)), ColorArray('red', alpha=0.1))
    assert_array_equal(r.rgb.ravel(), (1., 0., 0.))
    assert_array_equal(r.rgba.ravel(), (1., 0., 0., 1.))
    assert_array_equal(r.RGBA.ravel(), (255, 0, 0, 255))

    # handling multiple colors
    rgb = ColorArray(list('rgb'))
    print(rgb)  # multi repr
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    # complex/annoying case
    rgb = ColorArray(['r', (0, 1, 0), '#0000ffff'])
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    assert_raises(RuntimeError, ColorArray, ['r', np.eye(3)])  # can't nest

    # getting/setting properties
    r = ColorArray('#ffff')
    assert_equal(r, ColorArray('white'))
    r = ColorArray('#ff000000')
    assert_true('turquoise' in get_color_names())  # make sure our JSON loaded
    assert_equal(r.alpha, 0)
    r.alpha = 1.0
    assert_equal(r, ColorArray('r'))
    r.alpha = 0
    r.rgb = (1, 0, 0)
    assert_equal(r.alpha, 0)
    assert_equal(r.hex, ['#ff0000'])
    r.alpha = 1
    r.hex = '00ff00'
    assert_equal(r, ColorArray('g'))
    assert_array_equal(r.rgb.ravel(), (0., 1., 0.))
    r.RGB = 255, 0, 0
    assert_equal(r, ColorArray('r'))
    assert_array_equal(r.RGB.ravel(), (255, 0, 0))
    r.RGBA = 255, 0, 0, 0
    assert_equal(r, ColorArray('r', alpha=0))
    w = ColorArray()
    w.rgb = ColorArray('r').rgb + ColorArray('g').rgb + ColorArray('b').rgb
    assert_equal(w, ColorArray('white'))
    w = ColorArray('white')
    assert_equal(w, w.darker().lighter())
    assert_equal(w, w.darker(0.1).darker(-0.1))
    w2 = w.darker()
    assert_true(w != w2)
    w.darker(copy=False)
    assert_equal(w, w2)
    with use_log_level('warning', record=True, print_msg=False) as w:
        w = ColorArray('white')
        w.value = 2
        assert_equal(len(w), 1)
    assert_equal(w, ColorArray('white'))

    # warnings and errors
    assert_raises(ValueError, ColorArray, '#ffii00')  # non-hex
    assert_raises(ValueError, ColorArray, '#ff000')  # too short
    assert_raises(ValueError, ColorArray, [0, 0])  # not enough vals
    assert_raises(ValueError, ColorArray, [2, 0, 0])  # val > 1
    assert_raises(ValueError, ColorArray, [-1, 0, 0])  # val < 0
    c = ColorArray([2., 0., 0.], clip=True)  # val > 1
    assert_true(np.all(c.rgb <= 1))
    c = ColorArray([-1., 0., 0.], clip=True)  # val < 0
    assert_true(np.all(c.rgb >= 0))
    
    # make sure our color dict works
    for key in get_color_names():
        assert_true(ColorArray(key))
    assert_raises(ValueError, ColorArray, 'foo')  # unknown color error
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
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