7f8f5a07a1a2d1f0fa7af2774f83d723b4033a72
[nepi.git] / test / util / parallel.py
1 #!/usr/bin/env python
2 #
3 #    NEPI, a framework to manage network experiments
4 #    Copyright (C) 2013 INRIA
5 #
6 #    This program is free software: you can redistribute it and/or modify
7 #    it under the terms of the GNU General Public License as published by
8 #    the Free Software Foundation, either version 3 of the License, or
9 #    (at your option) any later version.
10 #
11 #    This program is distributed in the hope that it will be useful,
12 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #    GNU General Public License for more details.
15 #
16 #    You should have received a copy of the GNU General Public License
17 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
20
21
22 from nepi.util.parallel import ParallelRun
23
24 import datetime
25 import unittest
26
27 class ParallelRunTestCase(unittest.TestCase):
28     def test_run_simple(self):
29         runner = ParallelRun(maxthreads = 4)
30         runner.start()
31
32         count = [0]
33
34         def inc(count):
35             count[0] += 1
36         
37         for x in xrange(10):
38             runner.put(inc, count)
39
40         runner.destroy()
41
42         self.assertEquals(count[0], 10)
43
44     def test_run_interrupt(self):
45
46         def sleep():
47             import time
48             time.sleep(5)
49
50         startt = datetime.datetime.now()
51
52         runner = ParallelRun(maxthreads = 4)
53         runner.start()
54        
55         for x in xrange(100):
56             runner.put(sleep)
57
58         runner.empty()
59         runner.destroy()
60
61         endt = datetime.datetime.now()
62         time_elapsed = (endt - startt).seconds
63         self.assertTrue( time_elapsed < 500)
64
65     def test_run_error(self):
66         count = [0]
67
68         def inc(count):
69             count[0] += 1
70  
71         def error():
72             raise RuntimeError()
73
74         runner = ParallelRun(maxthreads = 4)
75         runner.start()
76        
77         for x in xrange(4):
78             runner.put(inc, count)
79
80         runner.put(error)
81        
82         runner.destroy()
83       
84         self.assertEquals(count[0], 4)
85         
86         self.assertRaises(RuntimeError, runner.sync)
87
88 if __name__ == '__main__':
89     unittest.main()
90