1# Testoob, Python Testing Out Of (The) Box
2# Copyright (C) 2005-2006 The Testoob Team
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"Helper for processed running"
17
18class ProcessedRunnerHelper:
19    "A helper class to make ProcessedRunner shorter and clearer."
20    def __init__(self, max_processes):
21        self._fixturesList = [[] for i in xrange(max_processes)]
22        self._load_balance_idx = 0
23
24    def register_fixture(self, fixture):
25        self._fixturesList[self._load_balance_idx].append(fixture)
26        self._load_balance_idx = (self._load_balance_idx + 1) % len(self._fixturesList)
27
28    def start(self, reporter):
29        from os import fork, pipe, fdopen, waitpid
30        from sys import exit
31
32        children = []
33
34        for processFixtures in self._fixturesList:
35            pid = fork()
36            if pid == 0:
37                self._run_fixtures(processFixtures, reporter)
38                exit()
39            children.append(pid)
40
41        for child in children:
42            waitpid(child, 0)
43
44    def _run_fixtures(self, fixtures, reporter):
45        [fixture(reporter) for fixture in fixtures]
46
47