_auth_example_test.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 gRPC Python authentication example."""
  15. import asyncio
  16. import unittest
  17. import grpc
  18. from examples.python.auth import _credentials
  19. from examples.python.auth import async_customized_auth_client
  20. from examples.python.auth import async_customized_auth_server
  21. from examples.python.auth import customized_auth_client
  22. from examples.python.auth import customized_auth_server
  23. _SERVER_ADDR_TEMPLATE = 'localhost:%d'
  24. class AuthExampleTest(unittest.TestCase):
  25. def test_successful_call(self):
  26. with customized_auth_server.run_server(0) as (_, port):
  27. with customized_auth_client.create_client_channel(
  28. _SERVER_ADDR_TEMPLATE % port) as channel:
  29. customized_auth_client.send_rpc(channel)
  30. # No unhandled exception raised, test passed!
  31. def test_no_channel_credential(self):
  32. with customized_auth_server.run_server(0) as (_, port):
  33. with grpc.insecure_channel(_SERVER_ADDR_TEMPLATE % port) as channel:
  34. resp = customized_auth_client.send_rpc(channel)
  35. self.assertEqual(resp.code(), grpc.StatusCode.UNAVAILABLE)
  36. def test_no_call_credential(self):
  37. with customized_auth_server.run_server(0) as (_, port):
  38. channel_credential = grpc.ssl_channel_credentials(
  39. _credentials.ROOT_CERTIFICATE)
  40. with grpc.secure_channel(_SERVER_ADDR_TEMPLATE % port,
  41. channel_credential) as channel:
  42. resp = customized_auth_client.send_rpc(channel)
  43. self.assertEqual(resp.code(), grpc.StatusCode.UNAUTHENTICATED)
  44. def test_successful_call_asyncio(self):
  45. async def test_body():
  46. server, port = await async_customized_auth_server.run_server(0)
  47. channel = async_customized_auth_client.create_client_channel(
  48. _SERVER_ADDR_TEMPLATE % port)
  49. await async_customized_auth_client.send_rpc(channel)
  50. await channel.close()
  51. await server.stop(0)
  52. # No unhandled exception raised, test passed!
  53. asyncio.get_event_loop().run_until_complete(test_body())
  54. if __name__ == '__main__':
  55. unittest.main(verbosity=2)