blob: ae8099f4f130e719e40c50e38a6a91d380f22b0f [file] [log] [blame]
Xixuan Wu865fa282017-09-05 15:23:19 -07001# Copyright 2017 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Module for utils unittests."""
6
7import unittest
8
9import utils
10
11
Xixuan Wu008ee832017-10-12 16:59:34 -070012# Global variable for mocking functions.
Xixuan Wu865fa282017-09-05 15:23:19 -070013SUCCESS_COUNT = 0
14
15
16def successful_func():
17 """Mock a successful function with clear returns."""
18 return 1
19
20
21def failed_func():
22 """Mock a failed function which raises error."""
23 raise ValueError('')
24
25
26def half_func():
27 """Mock a function first raises error, then succeeds."""
28 global SUCCESS_COUNT
29 SUCCESS_COUNT += 1
30
31 if SUCCESS_COUNT >= 10:
32 return successful_func()
33 else:
34 failed_func()
35
36
37class UtilsTestCase(unittest.TestCase):
38
39 def setUp(self):
40 """Reset global variable SUCCESS_COUNT."""
41 global SUCCESS_COUNT
42 SUCCESS_COUNT = 0
43
44 def testWaitForValueWithExpectedValueSuccess(self):
45 """Test wait_for_value with right expected_value."""
46 self.assertEqual(
47 utils.wait_for_value(successful_func, expected_value=1), 1)
48
49 def testWaitForValueWithExpectedValueFailure(self):
50 """Test wait_for_value with wrong expected_value."""
51 self.assertEqual(
52 utils.wait_for_value(successful_func, expected_value=2, timeout_sec=1),
53 1)
54
55 def testWaitForValueWithoutExpectedValueSuccess(self):
56 """Test wait_for_value with empty expected_value."""
57 self.assertEqual(utils.wait_for_value(successful_func), 1)
58
59 def testWaitForValueWithEmptyException(self):
60 """Test wait_for_value with empty exception_to_raise."""
61 self.assertRaises(ValueError, utils.wait_for_value, failed_func)
62
63 def testWaitForValueWithRightException(self):
64 """Test wait_for_value with right exception_to_raise."""
65 self.assertEqual(
66 utils.wait_for_value(half_func, exception_to_raise=ValueError), 1)
67
68 def testWaitForValueWithMultipleException(self):
69 """Test wait_for_value with multiple exception_to_raise."""
70 self.assertEqual(
71 utils.wait_for_value(half_func,
72 exception_to_raise=(ValueError, KeyError)), 1)
73
74 def testWaitForValueWithWrongException(self):
75 """Test wait_for_value with wrong exception_to_raise."""
76 self.assertRaises(ValueError, utils.wait_for_value,
77 half_func, exception_to_raise=KeyError)