1# Copyright 2017 The Abseil Authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15import random 16 17from absl import flags 18from absl.testing import absltest 19 20 21FLAGS = flags.FLAGS 22flags.DEFINE_boolean('set_up_module_error', False, 23 'Cause setupModule to error.') 24flags.DEFINE_boolean('tear_down_module_error', False, 25 'Cause tearDownModule to error.') 26 27flags.DEFINE_boolean('set_up_class_error', False, 'Cause setUpClass to error.') 28flags.DEFINE_boolean('tear_down_class_error', False, 29 'Cause tearDownClass to error.') 30 31flags.DEFINE_boolean('set_up_error', False, 'Cause setUp to error.') 32flags.DEFINE_boolean('tear_down_error', False, 'Cause tearDown to error.') 33flags.DEFINE_boolean('test_error', False, 'Cause the test to error.') 34 35flags.DEFINE_boolean('set_up_fail', False, 'Cause setUp to fail.') 36flags.DEFINE_boolean('tear_down_fail', False, 'Cause tearDown to fail.') 37flags.DEFINE_boolean('test_fail', False, 'Cause the test to fail.') 38 39flags.DEFINE_float('random_error', 0.0, 40 '0 - 1.0: fraction of a random failure at any step', 41 lower_bound=0.0, upper_bound=1.0) 42 43 44def _random_error(): 45 return random.random() < FLAGS.random_error 46 47 48def setUpModule(): 49 if FLAGS.set_up_module_error or _random_error(): 50 raise Exception('setUpModule Errored!') 51 52 53def tearDownModule(): 54 if FLAGS.tear_down_module_error or _random_error(): 55 raise Exception('tearDownModule Errored!') 56 57 58class FailableTest(absltest.TestCase): 59 60 @classmethod 61 def setUpClass(cls): 62 if FLAGS.set_up_class_error or _random_error(): 63 raise Exception('setUpClass Errored!') 64 65 @classmethod 66 def tearDownClass(cls): 67 if FLAGS.tear_down_class_error or _random_error(): 68 raise Exception('tearDownClass Errored!') 69 70 def setUp(self): 71 if FLAGS.set_up_error or _random_error(): 72 raise Exception('setUp Errored!') 73 74 if FLAGS.set_up_fail: 75 self.fail('setUp Failed!') 76 77 def tearDown(self): 78 if FLAGS.tear_down_error or _random_error(): 79 raise Exception('tearDown Errored!') 80 81 if FLAGS.tear_down_fail: 82 self.fail('tearDown Failed!') 83 84 def test(self): 85 if FLAGS.test_error or _random_error(): 86 raise Exception('test Errored!') 87 88 if FLAGS.test_fail: 89 self.fail('test Failed!') 90 91 92if __name__ == '__main__': 93 absltest.main() 94