@@ -171,6 +171,67 @@ def test_call_chain_is_maintained(self):
171
171
m .test1 ().test2 .test3 ().test4 ()
172
172
self .assertIn ("mock.test1().test2.test3().test4" , str (cm .exception ))
173
173
174
+ def test_seal_with_autospec (self ):
175
+ # https://bugs.python.org/issue45156
176
+ class Foo :
177
+ foo = 0
178
+ def bar1 (self ):
179
+ return 1
180
+ def bar2 (self ):
181
+ return 2
182
+
183
+ class Baz :
184
+ baz = 3
185
+ def ban (self ):
186
+ return 4
187
+
188
+ for spec_set in (True , False ):
189
+ with self .subTest (spec_set = spec_set ):
190
+ foo = mock .create_autospec (Foo , spec_set = spec_set )
191
+ foo .bar1 .return_value = 'a'
192
+ foo .Baz .ban .return_value = 'b'
193
+
194
+ mock .seal (foo )
195
+
196
+ self .assertIsInstance (foo .foo , mock .NonCallableMagicMock )
197
+ self .assertIsInstance (foo .bar1 , mock .MagicMock )
198
+ self .assertIsInstance (foo .bar2 , mock .MagicMock )
199
+ self .assertIsInstance (foo .Baz , mock .MagicMock )
200
+ self .assertIsInstance (foo .Baz .baz , mock .NonCallableMagicMock )
201
+ self .assertIsInstance (foo .Baz .ban , mock .MagicMock )
202
+
203
+ self .assertEqual (foo .bar1 (), 'a' )
204
+ foo .bar1 .return_value = 'new_a'
205
+ self .assertEqual (foo .bar1 (), 'new_a' )
206
+ self .assertEqual (foo .Baz .ban (), 'b' )
207
+ foo .Baz .ban .return_value = 'new_b'
208
+ self .assertEqual (foo .Baz .ban (), 'new_b' )
209
+
210
+ with self .assertRaises (TypeError ):
211
+ foo .foo ()
212
+ with self .assertRaises (AttributeError ):
213
+ foo .bar = 1
214
+ with self .assertRaises (AttributeError ):
215
+ foo .bar2 ()
216
+
217
+ foo .bar2 .return_value = 'bar2'
218
+ self .assertEqual (foo .bar2 (), 'bar2' )
219
+
220
+ with self .assertRaises (AttributeError ):
221
+ foo .missing_attr
222
+ with self .assertRaises (AttributeError ):
223
+ foo .missing_attr = 1
224
+ with self .assertRaises (AttributeError ):
225
+ foo .missing_method ()
226
+ with self .assertRaises (TypeError ):
227
+ foo .Baz .baz ()
228
+ with self .assertRaises (AttributeError ):
229
+ foo .Baz .missing_attr
230
+ with self .assertRaises (AttributeError ):
231
+ foo .Baz .missing_attr = 1
232
+ with self .assertRaises (AttributeError ):
233
+ foo .Baz .missing_method ()
234
+
174
235
175
236
if __name__ == "__main__" :
176
237
unittest .main ()
0 commit comments