Skip to content

Commit

Permalink
Add testing helpers for mocking and encoding tests.
Browse files Browse the repository at this point in the history
pandas.util.testing now has a SimpleMock class for mocking objects which
have read-only attributes.
Ths mocking support is used by the *stdin_encoding* context manager to
make it easy to test code with an arbitrary value for sys.stdin.encoding.
  • Loading branch information
y-p committed Sep 27, 2012
1 parent 8b16ff6 commit af3e13c
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion pandas/util/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import string
import sys

from contextlib import contextmanager # contextlib is available since 2.5

from distutils.version import LooseVersion

from numpy.random import randn
Expand All @@ -23,7 +25,6 @@
from pandas.tseries.period import PeriodIndex
from pandas.tseries.interval import IntervalIndex


Index = index.Index
Series = series.Series
DataFrame = frame.DataFrame
Expand Down Expand Up @@ -378,3 +379,50 @@ def test_network(self):

t.network = True
return t


class SimpleMock(object):
"""
Poor man's mocking object
Note: only works for new-style classes, assumes __getattribute__ exists.
>>> a = type("Duck",(),{})
>>> a.attr1,a.attr2 ="fizz","buzz"
>>> b = SimpleMock(a,"attr1","bar")
>>> b.attr1 == "bar" and b.attr2 == "buzz"
True
>>> a.attr1 == "fizz" and a.attr2 == "buzz"
True
"""
def __init__(self, obj, *args, **kwds):
assert(len(args) % 2 == 0)
attrs = kwds.get("attrs", {})
attrs.update({k:v for k, v in zip(args[::2], args[1::2])})
self.attrs = attrs
self.obj = obj

def __getattribute__(self,name):
attrs = object.__getattribute__(self, "attrs")
obj = object.__getattribute__(self, "obj")
return attrs.get(name, type(obj).__getattribute__(obj,name))

@contextmanager
def stdin_encoding(encoding=None):
"""
Context manager for running bits of code while emulating an arbitrary
stdin encoding.
>>> import sys
>>> _encoding = sys.stdin.encoding
>>> with stdin_encoding('AES'): sys.stdin.encoding
'AES'
>>> sys.stdin.encoding==_encoding
True
"""
import sys
_stdin = sys.stdin
sys.stdin = SimpleMock(sys.stdin, "encoding", encoding)
yield
sys.stdin = _stdin

0 comments on commit af3e13c

Please sign in to comment.