| 1 |
import unittest |
|---|
| 2 |
from StringIO import StringIO |
|---|
| 3 |
|
|---|
| 4 |
|
|---|
| 5 |
# Appropriated from Trac, all credit to the Trac developers. |
|---|
| 6 |
def Mock(bases=(), *initargs, **kw): |
|---|
| 7 |
""" |
|---|
| 8 |
Simple factory for dummy classes that can be used as replacement for the |
|---|
| 9 |
real implementation in tests. |
|---|
| 10 |
|
|---|
| 11 |
Base classes for the mock can be specified using the first parameter, which |
|---|
| 12 |
must be either a tuple of class objects or a single class object. If the |
|---|
| 13 |
bases parameter is omitted, the base class of the mock will be object. |
|---|
| 14 |
|
|---|
| 15 |
So to create a mock that is derived from the builtin dict type, you can do: |
|---|
| 16 |
|
|---|
| 17 |
>>> mock = Mock(dict) |
|---|
| 18 |
>>> mock['foo'] = 'bar' |
|---|
| 19 |
>>> mock['foo'] |
|---|
| 20 |
'bar' |
|---|
| 21 |
|
|---|
| 22 |
Attributes of the class are provided by any additional keyword parameters. |
|---|
| 23 |
|
|---|
| 24 |
>>> mock = Mock(foo='bar') |
|---|
| 25 |
>>> mock.foo |
|---|
| 26 |
'bar' |
|---|
| 27 |
|
|---|
| 28 |
Objects produces by this function have the special feature of not requiring |
|---|
| 29 |
the 'self' parameter on methods, because you should keep data at the scope |
|---|
| 30 |
of the test function. So you can just do: |
|---|
| 31 |
|
|---|
| 32 |
>>> mock = Mock(add=lambda x,y: x+y) |
|---|
| 33 |
>>> mock.add(1, 1) |
|---|
| 34 |
2 |
|---|
| 35 |
|
|---|
| 36 |
To access attributes from the mock object from inside a lambda function, |
|---|
| 37 |
just access the mock itself: |
|---|
| 38 |
|
|---|
| 39 |
>>> mock = Mock(dict, do=lambda x: 'going to the %s' % mock[x]) |
|---|
| 40 |
>>> mock['foo'] = 'bar' |
|---|
| 41 |
>>> mock.do('foo') |
|---|
| 42 |
'going to the bar' |
|---|
| 43 |
|
|---|
| 44 |
Because assignments or other types of statements don't work in lambda |
|---|
| 45 |
functions, assigning to a local variable from a mock function requires some |
|---|
| 46 |
extra work: |
|---|
| 47 |
|
|---|
| 48 |
>>> myvar = [None] |
|---|
| 49 |
>>> mock = Mock(set=lambda x: myvar.__setitem__(0, x)) |
|---|
| 50 |
>>> mock.set(1) |
|---|
| 51 |
>>> myvar[0] |
|---|
| 52 |
1 |
|---|
| 53 |
""" |
|---|
| 54 |
if not isinstance(bases, tuple): |
|---|
| 55 |
bases = (bases,) |
|---|
| 56 |
cls = type('Mock', bases, {}) |
|---|
| 57 |
mock = cls(*initargs) |
|---|
| 58 |
for k,v in kw.items(): |
|---|
| 59 |
setattr(mock, k, v) |
|---|
| 60 |
return mock |
|---|
| 61 |
|
|---|
| 62 |
|
|---|
| 63 |
def suite(): |
|---|
| 64 |
import pyndexter.tests |
|---|
| 65 |
import pyndexter.indexers.tests |
|---|
| 66 |
|
|---|
| 67 |
suite = unittest.TestSuite() |
|---|
| 68 |
suite.addTest(pyndexter.tests.suite()) |
|---|
| 69 |
suite.addTest(pyndexter.indexers.tests.suite()) |
|---|
| 70 |
return suite |
|---|
| 71 |
|
|---|
| 72 |
if __name__ == '__main__': |
|---|
| 73 |
unittest.main(defaultTest='suite') |
|---|