| 1 |
# Copyright 2019 the gRPC 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 |
"""Test for multiprocessing example.""" |
| 15 |
|
| 16 |
import ast |
| 17 |
import logging |
| 18 |
import math |
| 19 |
import os |
| 20 |
import re |
| 21 |
import subprocess |
| 22 |
import tempfile |
| 23 |
import unittest |
| 24 |
|
| 25 |
_BINARY_DIR = os.path.realpath( |
| 26 |
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) |
| 27 |
_SERVER_PATH = os.path.join(_BINARY_DIR, 'server') |
| 28 |
_CLIENT_PATH = os.path.join(_BINARY_DIR, 'client') |
| 29 |
|
| 30 |
|
| 31 |
def is_prime(n): |
| 32 |
for i in range(2, int(math.ceil(math.sqrt(n)))): |
| 33 |
if n % i == 0: |
| 34 |
return False |
| 35 |
else: |
| 36 |
return True |
| 37 |
|
| 38 |
|
| 39 |
def _get_server_address(server_stream): |
| 40 |
while True: |
| 41 |
server_stream.seek(0) |
| 42 |
line = server_stream.readline() |
| 43 |
while line: |
| 44 |
matches = re.search('Binding to \'(.+)\'', line) |
| 45 |
if matches is not None: |
| 46 |
return matches.groups()[0] |
| 47 |
line = server_stream.readline() |
| 48 |
|
| 49 |
|
| 50 |
class MultiprocessingExampleTest(unittest.TestCase): |
| 51 |
|
| 52 |
def test_multiprocessing_example(self): |
| 53 |
server_stdout = tempfile.TemporaryFile(mode='r') |
| 54 |
server_process = subprocess.Popen((_SERVER_PATH,), stdout=server_stdout) |
| 55 |
server_address = _get_server_address(server_stdout) |
| 56 |
client_stdout = tempfile.TemporaryFile(mode='r') |
| 57 |
client_process = subprocess.Popen(( |
| 58 |
_CLIENT_PATH, |
| 59 |
server_address, |
| 60 |
), |
| 61 |
stdout=client_stdout) |
| 62 |
client_process.wait() |
| 63 |
server_process.terminate() |
| 64 |
client_stdout.seek(0) |
| 65 |
results = ast.literal_eval(client_stdout.read().strip().split('\n')[-1]) |
| 66 |
values = tuple(result[0] for result in results) |
| 67 |
self.assertSequenceEqual(range(2, 10000), values) |
| 68 |
for result in results: |
| 69 |
self.assertEqual(is_prime(result[0]), result[1]) |
| 70 |
|
| 71 |
|
| 72 |
if __name__ == '__main__': |
| 73 |
logging.basicConfig() |
| 74 |
unittest.main(verbosity=2) |