Rename GP_Context -> GP_Pixmap
[gfxprim.git] / tests / pylib / testutils.py
blob7c7f740b48498657ad708ee00ef73d98ede2e31e
1 ### Helper imports and decorators
3 from random import Random
5 from gfxprim import core
7 __all__ = ["alltypes", "for_each_case",
8 "RandomizePixmap", "PixmapRand"]
11 def alltypes(_filter=None):
12 """
13 Creates one test for each PixelType (except INVALID).
14 The pixeltype is given to the test function and the name
15 is appended to its name and is mentioned in the new docstring.
16 """
17 if _filter is None:
18 _filter = lambda x: True
19 cases = dict([(t.name, t) for t in core.PixelTypes[1:] if _filter(t)])
20 return for_each_case(cases, givename=False)
23 def for_each_case(cases, givename=True):
24 """
25 Creates one test for each of `cases`.
27 Cases is either list of strings or or string dict (with any values).
28 The test is then given (name) for list or (name, value) for dict,
29 or just (value) if givename=False.
30 """
31 def decorate(f):
32 for n in cases:
33 assert isinstance(n, str)
34 if isinstance(cases, dict):
35 if givename:
36 nf = (lambda nn, nv: (lambda: f(nn, nv)))(n, cases[n])
37 else:
38 nf = (lambda nv: (lambda: f(nv)))(cases[n])
39 else: # assume a list or a tuple
40 nf = (lambda nn: (lambda: f(nn)))(n)
41 nf.__name__ = f.__name__ + "_" + n
42 nf.__module__ = f.__module__
43 nf.__doc__ = "%s<%s:%s>"% (
44 f.__doc__ + " " if f.__doc__ else "",
45 nf.__module__, nf.__name__)
46 f.__globals__[nf.__name__] = nf
47 return None
48 return decorate
51 ### core.Pixmap helpers
53 def PixmapRand(w, h, t, seed=None):
54 "Return new Pixmap(w, h, t) filled with RandomizePixmap(c, seed)"
55 c = core.Pixmap(w, h, t)
56 RandomizePixmap(c, seed)
57 return c
60 def RandomizePixmap(c, seed=None):
61 """Fill Pixmap with pseudorandom data.
63 The default seed is computed from size and type number.
64 """
66 if seed is None:
67 seed = c.w + (1 << c.h) * c.pixel_type
68 r = Random(seed)
69 for x in range(c.w):
70 for y in range(c.h):
71 p = r.randint(0, (1 << c.bpp) - 1)
72 c.PutPixel(x, y, p)
73 assert c.GetPixel(x, y) == p