本文整理汇总了Python中vispy.testing.assert_raises函数的典型用法代码示例。如果您正苦于以下问题:Python assert_raises函数的具体用法?Python assert_raises怎么用?Python assert_raises使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了assert_raises函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_check_enum
def test_check_enum():
from vispy.gloo import gl
# Test enums
assert util.check_enum(gl.GL_RGB) == 'rgb'
assert util.check_enum(gl.GL_TRIANGLE_STRIP) == 'triangle_strip'
# Test strings
assert util.check_enum('RGB') == 'rgb'
assert util.check_enum('Triangle_STRIp') == 'triangle_strip'
# Test wrong input
assert_raises(ValueError, util.check_enum, int(gl.GL_RGB))
assert_raises(ValueError, util.check_enum, int(gl.GL_TRIANGLE_STRIP))
assert_raises(ValueError, util.check_enum, [])
# Test with test
util.check_enum('RGB', 'test', ('rgb', 'alpha')) == 'rgb'
util.check_enum(gl.GL_ALPHA, 'test', ('rgb', 'alpha')) == 'alpha'
#
assert_raises(ValueError, util.check_enum, 'RGB', 'test', ('a', 'b'))
assert_raises(ValueError, util.check_enum, gl.GL_ALPHA, 'test', ('a', 'b'))
# Test PyOpenGL enums
try:
from OpenGL import GL
except ImportError:
return # we cannot test PyOpenGL
#
assert util.check_enum(GL.GL_RGB) == 'rgb'
assert util.check_enum(GL.GL_TRIANGLE_STRIP) == 'triangle_strip'
示例2: test_config
def test_config():
"""Test vispy config methods and file downloading"""
assert_raises(TypeError, config.update, data_path=dict())
assert_raises(KeyError, config.update, foo="bar") # bad key
data_dir = op.join(temp_dir, "data")
assert_raises(IOError, set_data_dir, data_dir) # didn't say to create
orig_val = os.environ.get("_VISPY_CONFIG_TESTING", None)
os.environ["_VISPY_CONFIG_TESTING"] = "true"
try:
assert_raises(IOError, set_data_dir, data_dir) # doesn't exist yet
set_data_dir(data_dir, create=True, save=True)
assert_equal(config["data_path"], data_dir)
config["data_path"] = data_dir
print(config) # __repr__
load_data_file("CONTRIBUTING.txt")
fid = open(op.join(data_dir, "test-faked.txt"), "w")
fid.close()
load_data_file("test-faked.txt") # this one shouldn't download
assert_raises(RuntimeError, load_data_file, "foo-nonexist.txt")
save_config()
finally:
if orig_val is not None:
os.environ["_VISPY_CONFIG_TESTING"] = orig_val
else:
del os.environ["_VISPY_CONFIG_TESTING"]
示例3: test_context_config
def test_context_config():
""" Test GLContext handling of config dict
"""
default_config = get_default_config()
# Pass default config unchanged
c = GLContext(default_config)
assert_equal(c.config, default_config)
# Must be deep copy
c.config['double_buffer'] = False
assert_not_equal(c.config, default_config)
# Passing nothing should yield default config
c = GLContext()
assert_equal(c.config, default_config)
# Must be deep copy
c.config['double_buffer'] = False
assert_not_equal(c.config, default_config)
# This should work
c = GLContext({'red_size': 4, 'double_buffer': False})
assert_equal(c.config.keys(), default_config.keys())
# Passing crap should raise
assert_raises(KeyError, GLContext, {'foo': 3})
assert_raises(TypeError, GLContext, {'double_buffer': 'not_bool'})
示例4: test_FunctionCall
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())
示例5: test_use
def test_use():
# Set default app to None, so we can test the use function
vispy.app.use_app()
default_app = vispy.app._default_app.default_app
vispy.app._default_app.default_app = None
app_name = default_app.backend_name.split(' ')[0]
try:
# With no arguments, should do nothing
assert_raises(TypeError, vispy.use)
assert_equal(vispy.app._default_app.default_app, None)
# With only gl args, should do nothing to app
vispy.use(gl='gl2')
assert_equal(vispy.app._default_app.default_app, None)
# Specify app (one we know works)
vispy.use(app_name)
assert_not_equal(vispy.app._default_app.default_app, None)
# Again, but now wrong app
wrong_name = 'glfw' if app_name.lower() != 'glfw' else 'pyqt4'
assert_raises(RuntimeError, vispy.use, wrong_name)
# And both
vispy.use(app_name, 'gl2')
finally:
# Restore
vispy.app._default_app.default_app = default_app
示例6: test_Variable
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')
示例7: _test_texture_internalformats
def _test_texture_internalformats(Texture, baseshape):
# Test format for concrete Texture class and baseshape + (numchannels,)
# Test internalformats valid with desktop OpenGL
formats = [
(1, 'red', ['red', 'r8', 'r16', 'r16f', 'r32f']),
(2, 'rg', ['rg', 'rg8', 'rg16', 'rg16f', 'rg32f']),
(3, 'rgb', ['rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f']),
(4, 'rgba', ['rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'])
]
for channels in range(1, 5):
for fmt, ifmts in [(f, iL) for n, f, iL in formats if n == channels]:
shape = baseshape + (channels,)
data = np.zeros(shape, dtype=np.uint8)
for ifmt in ifmts:
T = Texture(shape=shape, format=fmt, internalformat=ifmt)
assert 'Texture' in repr(T)
assert T._shape == shape
T = Texture(data=data, format=fmt, internalformat=ifmt)
assert 'Texture' in repr(T)
assert T._shape == shape
for channels in range(1, 5):
for fmt, ifmts in [(f, iL) for n, f, iL in formats if n != channels]:
shape = baseshape + (channels,)
data = np.zeros(shape, dtype=np.uint8)
for ifmt in ifmts:
assert_raises(ValueError, Texture, shape=shape, format=fmt,
internalformat=ifmt)
assert_raises(ValueError, Texture, data=data, format=fmt,
internalformat=ifmt)
示例8: test_linear_region_vertical_horizontal
def test_linear_region_vertical_horizontal():
"""Test vertical and horizontal LinearRegionVisual with a single color"""
# Definition of the region
pos = np.array([5, 15, 24, 36, 40, 42], dtype=np.float32)
# Expected internal pos buffer for vertical region
expected_pos_v = np.array([[5.0, -1.],
[5.0, 1.],
[15.0, -1.],
[15.0, 1.],
[24.0, -1.],
[24.0, 1.],
[36.0, -1.],
[36.0, 1.],
[40.0, -1.],
[40.0, 1.],
[42.0, -1.],
[42.0, 1.]], dtype=np.float32)
# Expected internal pos buffer for horizontal region
expected_pos_h = np.array([expected_pos_v[:, 1] * -1,
expected_pos_v[:, 0]], dtype=np.float32).T
# Test both horizontal and vertical region
for is_vertical, reference_image in [(True, 'linear_region1.png'),
(False, 'linear_region1_h.png')]:
expected_pos = expected_pos_v if is_vertical else expected_pos_h
with TestingCanvas() as c:
# Check set_data is working correctly within visual constructor
region = visuals.LinearRegion(pos=pos,
color=[0.0, 1.0, 0.0, 0.5],
vertical=is_vertical,
parent=c.scene)
assert np.all(region._pos == expected_pos)
assert np.all(region.pos == pos)
assert region.is_vertical == is_vertical
# Check set_data is working as expected when passing a list as
# pos argument
region.set_data(pos=list(pos))
assert np.all(region._pos == expected_pos)
assert np.all(region.pos == pos)
# Check set_data is working as expected when passing a tuple as
# pos argument
region.set_data(pos=tuple(pos))
assert np.all(region._pos == expected_pos)
assert np.all(region.pos == pos)
# Test with different dtypes that must be converted to float32
for t in [np.int64, np.float64, np.int32]:
region.set_data(pos=pos.astype(t))
assert np.all(region._pos == expected_pos)
assert np.all(region.pos == pos)
assert_image_approved(c.render(), 'visuals/%s' % reference_image)
# Check ValueError is raised when pos is not 1D
assert_raises(ValueError, region.set_data, pos=[[1, 2], [3, 4]])
示例9: test_context_sharing
def test_context_sharing():
"""Test context sharing"""
with Canvas() as c1:
vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
frag = "void main (void) {gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);}"
program = Program(vert, frag)
program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)]
program.draw('points')
def check():
# Do something to program and see if it worked
program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)] # Do command
program.draw('points')
check_error()
# Check while c1 is active
check()
# Check while c2 is active (with different context)
with Canvas() as c2:
# pyglet always shares
if 'pyglet' not in c2.app.backend_name.lower():
assert_raises(Exception, check)
# Check while c2 is active (with *same* context)
with Canvas(shared=c1.context) as c2:
assert c1.context.shared is c2.context.shared # same object
check()
示例10: test_color_array
def test_color_array():
"""Basic tests for ColorArray class"""
x = ColorArray(['r', 'g', 'b'])
assert_array_equal(x.rgb, np.eye(3))
# Test ColorArray.__getitem__.
assert isinstance(x[0], ColorArray)
assert isinstance(x[:], ColorArray)
assert_array_equal(x.rgba[:], x[:].rgba)
assert_array_equal(x.rgba[0], x[0].rgba.squeeze())
assert_array_equal(x.rgba[1:3], x[1:3].rgba)
assert_raises(ValueError, x.__getitem__, (0, 1))
# Test ColorArray.__setitem__.
x[0] = 0
assert_array_equal(x.rgba[0, :], np.zeros(4))
assert_array_equal(x.rgba, x[:].rgba)
x[1] = 1
assert_array_equal(x[1].rgba, np.ones((1, 4)))
x[:] = .5
assert_array_equal(x.rgba, .5 * np.ones((3, 4)))
assert_raises(ValueError, x.__setitem__, (0, 1), 0)
# test hsv color space colors
x = ColorArray(color_space="hsv", color=[(0, 0, 1),
(0, 0, 0.5), (0, 0, 0)])
assert_array_equal(x.rgba[0], [1, 1, 1, 1])
assert_array_equal(x.rgba[1], [0.5, 0.5, 0.5, 1])
assert_array_equal(x.rgba[2], [0, 0, 0, 1])
x = ColorArray(color_space="hsv")
assert_array_equal(x.rgba[0], [0, 0, 0, 1])
示例11: test_context_taking
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)
示例12: test_figure_creation
def test_figure_creation():
"""Test creating a figure"""
with vp.Fig(show=False) as fig:
fig[0, 0:2]
fig[1:3, 0:2]
ax_right = fig[1:3, 2]
assert fig[1:3, 2] is ax_right
# collision
assert_raises(ValueError, fig.__getitem__, (slice(1, 3), 1))
示例13: test_wrappers
def test_wrappers():
"""Test gloo wrappers"""
with Canvas():
gl.use_gl('gl2 debug')
gloo.clear('#112233') # make it so that there's something non-zero
# check presets
assert_raises(ValueError, gloo.set_state, preset='foo')
for state in gloo.get_state_presets().keys():
gloo.set_state(state)
assert_raises(ValueError, gloo.set_blend_color, (0., 0.)) # bad color
assert_raises(TypeError, gloo.set_hint, 1, 2) # need strs
# this doesn't exist in ES 2.0 namespace
assert_cmd_raises(ValueError, gloo.set_hint, 'fog_hint', 'nicest')
# test bad enum
assert_raises(RuntimeError, gloo.set_line_width, -1)
# check read_pixels
x = gloo.read_pixels()
assert_true(isinstance(x, np.ndarray))
assert_true(isinstance(gloo.read_pixels((0, 0, 1, 1)), np.ndarray))
assert_raises(ValueError, gloo.read_pixels, (0, 0, 1)) # bad port
y = gloo.read_pixels(alpha=False, out_type=np.ubyte)
assert_equal(y.shape, x.shape[:2] + (3,))
assert_array_equal(x[..., :3], y)
y = gloo.read_pixels(out_type='float')
assert_allclose(x/255., y)
# now let's (indirectly) check our set_* functions
viewport = (0, 0, 1, 1)
blend_color = (0., 0., 0.)
_funs = dict(viewport=viewport, # checked
hint=('generate_mipmap_hint', 'nicest'),
depth_range=(1., 2.),
front_face='cw', # checked
cull_face='front',
line_width=1.,
polygon_offset=(1., 1.),
blend_func=('zero', 'one'),
blend_color=blend_color,
blend_equation='func_add',
scissor=(0, 0, 1, 1),
stencil_func=('never', 1, 2, 'back'),
stencil_mask=4,
stencil_op=('zero', 'zero', 'zero', 'back'),
depth_func='greater',
depth_mask=True,
color_mask=(True, True, True, True),
sample_coverage=(0.5, True))
gloo.set_state(**_funs)
gloo.clear((1., 1., 1., 1.), 0.5, 1)
gloo.flush()
gloo.finish()
# check some results
assert_array_equal(gl.glGetParameter(gl.GL_VIEWPORT), viewport)
assert_equal(gl.glGetParameter(gl.GL_FRONT_FACE), gl.GL_CW)
assert_equal(gl.glGetParameter(gl.GL_BLEND_COLOR), blend_color + (1,))
示例14: test_use_uniforms
def test_use_uniforms():
"""Test using uniform arrays"""
VERT_SHADER = """
attribute vec2 a_pos;
varying vec2 v_pos;
void main (void)
{
v_pos = a_pos;
gl_Position = vec4(a_pos, 0., 1.);
}
"""
FRAG_SHADER = """
varying vec2 v_pos;
uniform vec3 u_color[2];
void main()
{
gl_FragColor = vec4((u_color[0] + u_color[1]) / 2., 1.);
}
"""
shape = (500, 500)
with Canvas(size=shape) as c:
c.set_current()
c.context.glir.set_verbose(True)
assert_equal(c.size, shape[::-1])
shape = (3, 3)
set_viewport((0, 0) + shape)
program = Program(VERT_SHADER, FRAG_SHADER)
program['a_pos'] = [[-1., -1.], [1., -1.], [-1., 1.], [1., 1.]]
program['u_color'] = np.ones((2, 3))
c.context.clear('k')
c.set_current()
program.draw('triangle_strip')
out = _screenshot()
assert_allclose(out[:, :, 0] / 255., np.ones(shape), atol=1. / 255.)
# now set one element
program['u_color[1]'] = np.zeros(3, np.float32)
c.context.clear('k')
program.draw('triangle_strip')
out = _screenshot()
assert_allclose(out[:, :, 0] / 255., 127.5 / 255. * np.ones(shape),
atol=1. / 255.)
# and the other
assert_raises(ValueError, program.__setitem__, 'u_color',
np.zeros(3, np.float32))
program['u_color'] = np.zeros((2, 3), np.float32)
program['u_color[0]'] = np.ones(3, np.float32)
c.context.clear((0.33,) * 3)
program.draw('triangle_strip')
out = _screenshot()
assert_allclose(out[:, :, 0] / 255., 127.5 / 255. * np.ones(shape),
atol=1. / 255.)
示例15: test_key
def test_key():
"""Test basic key functionality"""
def bad():
return (ENTER == dict())
assert_raises(ValueError, bad)
assert_true(not (ENTER == None)) # noqa
assert_equal('Return', ENTER)
print(ENTER.name)
print(ENTER) # __repr__
assert_equal(Key('1'), 49) # ASCII code