Pending: A Mixin class for testing

  • Thread starter Scott David Daniels
  • Start date
S

Scott David Daniels

Here is a Mix-in class I just built for testing.
It is quite simple, but illustrates how Mixins
can be used.

class Pending(object):
_pending = iter(())
def __new__(class_, *args, **kwargs):
try:
return class_._pending.next()
except StopIteration:
return super(Pending, class_).__new__(class_,
*args, **kwargs)

Now for the use:

class Float(Pending, float): pass

Float._pending = iter(range(4,7))

print [Float(x*(x+1)//2) for x in range(6)]

Possibly by using itertools functions such as chain as in:
Klass._pending = itertools.chain(generate_some(), Klass._pending)
you can inject fixed values to simplify testing.

Or something like this:

class SomeTrickyClass(...): # new-style only (derived from object)
...

class Hacked(Pending, SomeTrickyClass):
_pending = sample_value_generator()

TempHold, SomeTrickyClass = SomeTrickyClass, Hacked
try:
<do the test>
finally:
SomeTrickyClass = TempHold


--Scott David Daniels
(e-mail address removed)
 
P

Peter Otten

Scott said:
Here is a Mix-in class I just built for testing.
It is quite simple, but illustrates how Mixins
can be used.

class Pending(object):
_pending = iter(())
def __new__(class_, *args, **kwargs):
try:
return class_._pending.next()
except StopIteration:
return super(Pending, class_).__new__(class_,
*args, **kwargs)

Now for the use:

class Float(Pending, float): pass

Float._pending = iter(range(4,7))

print [Float(x*(x+1)//2) for x in range(6)]

Possibly by using itertools functions such as chain as in:
Klass._pending = itertools.chain(generate_some(), Klass._pending)
you can inject fixed values to simplify testing.

If you're willing to allow for issubclass() to fail you can do without a
mixin:

from itertools import chain, repeat

def preload(class_, iterable):
items = chain(
(lambda *args, **kw: item for item in iterable), repeat(class_))
return lambda *args, **kw: items.next()(*args, **kw)

float = preload(float, "ABC")
print [float(x) for x in range(6)]
issubclass(float, float) # TypeError

Argh :)

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top