_multiprocessing_example_test.py 2.4 KB

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