Skip to content

Commit af3e13c

Browse files
author
y-p
committed
Add testing helpers for mocking and encoding tests.
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.
1 parent 8b16ff6 commit af3e13c

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

pandas/util/testing.py

+49-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import string
88
import sys
99

10+
from contextlib import contextmanager # contextlib is available since 2.5
11+
1012
from distutils.version import LooseVersion
1113

1214
from numpy.random import randn
@@ -23,7 +25,6 @@
2325
from pandas.tseries.period import PeriodIndex
2426
from pandas.tseries.interval import IntervalIndex
2527

26-
2728
Index = index.Index
2829
Series = series.Series
2930
DataFrame = frame.DataFrame
@@ -378,3 +379,50 @@ def test_network(self):
378379

379380
t.network = True
380381
return t
382+
383+
384+
class SimpleMock(object):
385+
"""
386+
Poor man's mocking object
387+
388+
Note: only works for new-style classes, assumes __getattribute__ exists.
389+
390+
>>> a = type("Duck",(),{})
391+
>>> a.attr1,a.attr2 ="fizz","buzz"
392+
>>> b = SimpleMock(a,"attr1","bar")
393+
>>> b.attr1 == "bar" and b.attr2 == "buzz"
394+
True
395+
>>> a.attr1 == "fizz" and a.attr2 == "buzz"
396+
True
397+
"""
398+
def __init__(self, obj, *args, **kwds):
399+
assert(len(args) % 2 == 0)
400+
attrs = kwds.get("attrs", {})
401+
attrs.update({k:v for k, v in zip(args[::2], args[1::2])})
402+
self.attrs = attrs
403+
self.obj = obj
404+
405+
def __getattribute__(self,name):
406+
attrs = object.__getattribute__(self, "attrs")
407+
obj = object.__getattribute__(self, "obj")
408+
return attrs.get(name, type(obj).__getattribute__(obj,name))
409+
410+
@contextmanager
411+
def stdin_encoding(encoding=None):
412+
"""
413+
Context manager for running bits of code while emulating an arbitrary
414+
stdin encoding.
415+
416+
>>> import sys
417+
>>> _encoding = sys.stdin.encoding
418+
>>> with stdin_encoding('AES'): sys.stdin.encoding
419+
'AES'
420+
>>> sys.stdin.encoding==_encoding
421+
True
422+
423+
"""
424+
import sys
425+
_stdin = sys.stdin
426+
sys.stdin = SimpleMock(sys.stdin, "encoding", encoding)
427+
yield
428+
sys.stdin = _stdin

0 commit comments

Comments
 (0)