Home | History | Annotate | Download | only in server2
      1 #!/usr/bin/env python
      2 # Copyright 2013 The Chromium Authors. All rights reserved.
      3 # Use of this source code is governed by a BSD-style license that can be
      4 # found in the LICENSE file.
      5 
      6 import traceback
      7 import unittest
      8 
      9 from future import Future
     10 
     11 class FutureTest(unittest.TestCase):
     12   def testNoValueOrDelegate(self):
     13     self.assertRaises(ValueError, Future)
     14 
     15   def testValue(self):
     16     future = Future(value=42)
     17     self.assertEqual(42, future.Get())
     18     self.assertEqual(42, future.Get())
     19 
     20   def testDelegateValue(self):
     21     assertFalse = self.assertFalse
     22     class delegate(object):
     23       def __init__(self):
     24         self._get_called = False
     25       def Get(self):
     26         assertFalse(self._get_called)
     27         self._get_called = True
     28         return 42
     29 
     30     future = Future(delegate=delegate())
     31     self.assertEqual(42, future.Get())
     32     self.assertEqual(42, future.Get())
     33 
     34   def testErrorThrowingDelegate(self):
     35     class FunkyException(Exception):
     36       pass
     37 
     38     # Set up a chain of functions to test the stack trace.
     39     def qux():
     40       raise FunkyException()
     41     def baz():
     42       return qux()
     43     def bar():
     44       return baz()
     45     def foo():
     46       return bar()
     47     chain = [foo, bar, baz, qux]
     48 
     49     assertFalse = self.assertFalse
     50     class delegate(object):
     51       def __init__(self):
     52         self._get_called = False
     53       def Get(self):
     54         assertFalse(self._get_called)
     55         self._get_called = True
     56         return foo()
     57 
     58     fail = self.fail
     59     assertTrue = self.assertTrue
     60     def assert_raises_full_stack(future, err):
     61       try:
     62         future.Get()
     63         fail('Did not raise %s' % err)
     64       except Exception as e:
     65         assertTrue(isinstance(e, err))
     66         stack = traceback.format_exc()
     67         assertTrue(all(stack.find(fn.__name__) != -1 for fn in chain))
     68 
     69     future = Future(delegate=delegate())
     70     assert_raises_full_stack(future, FunkyException)
     71     assert_raises_full_stack(future, FunkyException)
     72 
     73 if __name__ == '__main__':
     74   unittest.main()
     75