OILS / mycpp / examples / test_ctx_pattern.py View on Github | oilshell.org

65 lines, 31 significant
1#!/usr/bin/env python2
2"""
3test_scoped_resource.py
4"""
5from __future__ import print_function
6
7import os
8import sys
9
10from mycpp import mylib
11from mycpp.mylib import log
12from typing import List, Dict, Optional, Any
13
14
15class ctx_Eval(object):
16 """
17 Based on bug #1986
18 """
19
20 def __init__(self, vars):
21 # type: (Optional[Dict[str, str]]) -> None
22 self.vars = vars
23 if vars is not None:
24 self.restore = [] # type: List[str]
25 self.restore.append('x')
26
27 # Collection must be here to trigger bug
28 mylib.MaybeCollect()
29
30 def __enter__(self):
31 # type: () -> None
32 pass
33
34 def __exit__(self, type, value, traceback):
35 # type: (Any, Any, Any) -> None
36 if self.vars is not None:
37 self.restore.pop()
38
39
40def run_tests():
41 # type: () -> None
42
43 d = {'x': 'y'} # type: Dict[str, str]
44 for i in xrange(0, 1000):
45 #with ctx_Eval(d):
46 # print('d %d' % i)
47
48 with ctx_Eval(None):
49 print('none %d' % i)
50
51 # Not enough to trigger bug
52 # mylib.MaybeCollect()
53
54
55def run_benchmarks():
56 # type: () -> None
57 pass
58
59
60if __name__ == '__main__':
61 if os.getenv('BENCHMARK'):
62 log('Benchmarking...')
63 run_benchmarks()
64 else:
65 run_tests()