回答編集履歴

1

追記

2016/11/04 00:58

投稿

sharow
sharow

スコア1149

test CHANGED
@@ -62,30 +62,86 @@
62
62
 
63
63
 
64
64
 
65
- ```
66
-
67
- $ python a.py
68
-
69
- hogehogehoge
70
-
71
- hogehogehoge hogehogehoge
65
+ この例では`input()`が`'hoge'`を返すだけの関数に置き換えられています。`return_value`だけでなく、`side_effect`で関数を指定することもできます。詳しくは[ドキュメント](http://docs.python.jp/3/library/unittest.mock.html)をご覧ください。
72
66
 
73
67
 
74
68
 
75
- $ python a.py test
69
+ ## 追記
76
-
77
- .
78
-
79
- ----------------------------------------------------------------------
80
-
81
- Ran 1 test in 0.000s
82
70
 
83
71
 
84
72
 
73
+ なるほどimport時に実行されるコードの副作用ですか。一応できなくはないみたいですが、なんかちょっと危なっかしい気もします。そういうことならsubprocessを使った方法もあながち悪くないかもしれませんね。
74
+
75
+
76
+
77
+
78
+
85
- OK
79
+ ```python
80
+
81
+ #wanko.py
82
+
83
+ name = input()
84
+
85
+ print(name,name)
86
86
 
87
87
  ```
88
88
 
89
89
 
90
90
 
91
+ ```python
92
+
93
+ import sys
94
+
95
+ import io
96
+
97
+ import unittest
98
+
99
+ import unittest.mock as mock
100
+
101
+
102
+
103
+ class TestWanko(unittest.TestCase):
104
+
105
+ def setUp(self):
106
+
107
+ self.orig_stdout = sys.stdout
108
+
109
+ sys.stdout = io.StringIO()
110
+
111
+
112
+
113
+ def tearDown(self):
114
+
115
+ sys.stdout = self.orig_stdout
116
+
117
+ if 'wanko' in sys.modules:
118
+
119
+ del sys.modules['wanko']
120
+
121
+
122
+
91
- この例では`input()`が`'hoge'`を返すだけの関数に置き換えられています。`return_value`だけでなく、`side_effect`で関数を指定することもできます。詳しくは[ドキュメント](http://docs.python.jp/3/library/unittest.mock.html)をご覧ください。
123
+ @mock.patch('builtins.input', return_value='hoge')
124
+
125
+ def test0(self, *args, **kwarg):
126
+
127
+ import wanko
128
+
129
+ self.assertEqual(sys.stdout.getvalue(), 'hoge hoge\n')
130
+
131
+
132
+
133
+ @mock.patch('builtins.input', return_value='wan')
134
+
135
+ def test1(self, *args, **kwarg):
136
+
137
+ import wanko
138
+
139
+ self.assertEqual(sys.stdout.getvalue(), 'wan wan\n')
140
+
141
+
142
+
143
+ unittest.main()
144
+
145
+ ```
146
+
147
+