|
7 | 7 | import string
|
8 | 8 | import sys
|
9 | 9 |
|
| 10 | +from contextlib import contextmanager # contextlib is available since 2.5 |
| 11 | + |
10 | 12 | from distutils.version import LooseVersion
|
11 | 13 |
|
12 | 14 | from numpy.random import randn
|
|
23 | 25 | from pandas.tseries.period import PeriodIndex
|
24 | 26 | from pandas.tseries.interval import IntervalIndex
|
25 | 27 |
|
26 |
| - |
27 | 28 | Index = index.Index
|
28 | 29 | Series = series.Series
|
29 | 30 | DataFrame = frame.DataFrame
|
@@ -378,3 +379,50 @@ def test_network(self):
|
378 | 379 |
|
379 | 380 | t.network = True
|
380 | 381 | 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