ClientServerTest.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #region Copyright notice and license
  2. // Copyright 2015, Google Inc.
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #endregion
  31. using System;
  32. using System.Diagnostics;
  33. using System.Linq;
  34. using System.Threading;
  35. using System.Threading.Tasks;
  36. using Grpc.Core;
  37. using Grpc.Core.Internal;
  38. using Grpc.Core.Utils;
  39. using NUnit.Framework;
  40. namespace Grpc.Core.Tests
  41. {
  42. public class ClientServerTest
  43. {
  44. const string Host = "127.0.0.1";
  45. const string ServiceName = "tests.Test";
  46. static readonly Method<string, string> EchoMethod = new Method<string, string>(
  47. MethodType.Unary,
  48. ServiceName,
  49. "Echo",
  50. Marshallers.StringMarshaller,
  51. Marshallers.StringMarshaller);
  52. static readonly Method<string, string> ConcatAndEchoMethod = new Method<string, string>(
  53. MethodType.ClientStreaming,
  54. ServiceName,
  55. "ConcatAndEcho",
  56. Marshallers.StringMarshaller,
  57. Marshallers.StringMarshaller);
  58. static readonly Method<string, string> NonexistentMethod = new Method<string, string>(
  59. MethodType.Unary,
  60. ServiceName,
  61. "NonexistentMethod",
  62. Marshallers.StringMarshaller,
  63. Marshallers.StringMarshaller);
  64. static readonly ServerServiceDefinition ServiceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName)
  65. .AddMethod(EchoMethod, EchoHandler)
  66. .AddMethod(ConcatAndEchoMethod, ConcatAndEchoHandler)
  67. .Build();
  68. Server server;
  69. Channel channel;
  70. [SetUp]
  71. public void Init()
  72. {
  73. server = new Server
  74. {
  75. Services = { ServiceDefinition },
  76. Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
  77. };
  78. server.Start();
  79. channel = new Channel(Host, server.Ports.Single().BoundPort, Credentials.Insecure);
  80. }
  81. [TearDown]
  82. public void Cleanup()
  83. {
  84. channel.Dispose();
  85. server.ShutdownAsync().Wait();
  86. }
  87. [TestFixtureTearDown]
  88. public void CleanupClass()
  89. {
  90. GrpcEnvironment.Shutdown();
  91. }
  92. [Test]
  93. public void UnaryCall()
  94. {
  95. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  96. Assert.AreEqual("ABC", Calls.BlockingUnaryCall(callDetails, "ABC"));
  97. }
  98. [Test]
  99. public void UnaryCall_ServerHandlerThrows()
  100. {
  101. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  102. try
  103. {
  104. Calls.BlockingUnaryCall(callDetails, "THROW");
  105. Assert.Fail();
  106. }
  107. catch (RpcException e)
  108. {
  109. Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
  110. }
  111. }
  112. [Test]
  113. public void UnaryCall_ServerHandlerThrowsRpcException()
  114. {
  115. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  116. try
  117. {
  118. Calls.BlockingUnaryCall(callDetails, "THROW_UNAUTHENTICATED");
  119. Assert.Fail();
  120. }
  121. catch (RpcException e)
  122. {
  123. Assert.AreEqual(StatusCode.Unauthenticated, e.Status.StatusCode);
  124. }
  125. }
  126. [Test]
  127. public void UnaryCall_ServerHandlerSetsStatus()
  128. {
  129. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  130. try
  131. {
  132. Calls.BlockingUnaryCall(callDetails, "SET_UNAUTHENTICATED");
  133. Assert.Fail();
  134. }
  135. catch (RpcException e)
  136. {
  137. Assert.AreEqual(StatusCode.Unauthenticated, e.Status.StatusCode);
  138. }
  139. }
  140. [Test]
  141. public async Task AsyncUnaryCall()
  142. {
  143. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  144. var result = await Calls.AsyncUnaryCall(callDetails, "ABC");
  145. Assert.AreEqual("ABC", result);
  146. }
  147. [Test]
  148. public async Task AsyncUnaryCall_ServerHandlerThrows()
  149. {
  150. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  151. try
  152. {
  153. await Calls.AsyncUnaryCall(callDetails, "THROW");
  154. Assert.Fail();
  155. }
  156. catch (RpcException e)
  157. {
  158. Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
  159. }
  160. }
  161. [Test]
  162. public async Task ClientStreamingCall()
  163. {
  164. var callDetails = new CallInvocationDetails<string, string>(channel, ConcatAndEchoMethod, new CallOptions());
  165. var call = Calls.AsyncClientStreamingCall(callDetails);
  166. await call.RequestStream.WriteAll(new string[] { "A", "B", "C" });
  167. Assert.AreEqual("ABC", await call.ResponseAsync);
  168. }
  169. [Test]
  170. public async Task ClientStreamingCall_CancelAfterBegin()
  171. {
  172. var cts = new CancellationTokenSource();
  173. var callDetails = new CallInvocationDetails<string, string>(channel, ConcatAndEchoMethod, new CallOptions(cancellationToken: cts.Token));
  174. var call = Calls.AsyncClientStreamingCall(callDetails);
  175. // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it.
  176. await Task.Delay(1000);
  177. cts.Cancel();
  178. try
  179. {
  180. await call.ResponseAsync;
  181. }
  182. catch (RpcException e)
  183. {
  184. Assert.AreEqual(StatusCode.Cancelled, e.Status.StatusCode);
  185. }
  186. }
  187. [Test]
  188. public void AsyncUnaryCall_EchoMetadata()
  189. {
  190. var headers = new Metadata
  191. {
  192. new Metadata.Entry("ascii-header", "abcdefg"),
  193. new Metadata.Entry("binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff }),
  194. };
  195. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions(headers: headers));
  196. var call = Calls.AsyncUnaryCall(callDetails, "ABC");
  197. Assert.AreEqual("ABC", call.ResponseAsync.Result);
  198. Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
  199. var trailers = call.GetTrailers();
  200. Assert.AreEqual(2, trailers.Count);
  201. Assert.AreEqual(headers[0].Key, trailers[0].Key);
  202. Assert.AreEqual(headers[0].Value, trailers[0].Value);
  203. Assert.AreEqual(headers[1].Key, trailers[1].Key);
  204. CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes);
  205. }
  206. [Test]
  207. public void UnaryCall_DisposedChannel()
  208. {
  209. channel.Dispose();
  210. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  211. Assert.Throws(typeof(ObjectDisposedException), () => Calls.BlockingUnaryCall(callDetails, "ABC"));
  212. }
  213. [Test]
  214. public void UnaryCallPerformance()
  215. {
  216. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  217. BenchmarkUtil.RunBenchmark(100, 100,
  218. () => { Calls.BlockingUnaryCall(callDetails, "ABC"); });
  219. }
  220. [Test]
  221. public void UnknownMethodHandler()
  222. {
  223. var callDetails = new CallInvocationDetails<string, string>(channel, NonexistentMethod, new CallOptions());
  224. try
  225. {
  226. Calls.BlockingUnaryCall(callDetails, "ABC");
  227. Assert.Fail();
  228. }
  229. catch (RpcException e)
  230. {
  231. Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode);
  232. }
  233. }
  234. [Test]
  235. public void UserAgentStringPresent()
  236. {
  237. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  238. string userAgent = Calls.BlockingUnaryCall(callDetails, "RETURN-USER-AGENT");
  239. Assert.IsTrue(userAgent.StartsWith("grpc-csharp/"));
  240. }
  241. [Test]
  242. public void PeerInfoPresent()
  243. {
  244. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  245. string peer = Calls.BlockingUnaryCall(callDetails, "RETURN-PEER");
  246. Assert.IsTrue(peer.Contains(Host));
  247. }
  248. [Test]
  249. public async Task Channel_WaitForStateChangedAsync()
  250. {
  251. Assert.Throws(typeof(TaskCanceledException),
  252. async () => await channel.WaitForStateChangedAsync(channel.State, DateTime.UtcNow.AddMilliseconds(10)));
  253. var stateChangedTask = channel.WaitForStateChangedAsync(channel.State);
  254. var callDetails = new CallInvocationDetails<string, string>(channel, EchoMethod, new CallOptions());
  255. await Calls.AsyncUnaryCall(callDetails, "abc");
  256. await stateChangedTask;
  257. Assert.AreEqual(ChannelState.Ready, channel.State);
  258. }
  259. [Test]
  260. public async Task Channel_ConnectAsync()
  261. {
  262. await channel.ConnectAsync();
  263. Assert.AreEqual(ChannelState.Ready, channel.State);
  264. await channel.ConnectAsync(DateTime.UtcNow.AddMilliseconds(1000));
  265. Assert.AreEqual(ChannelState.Ready, channel.State);
  266. }
  267. private static async Task<string> EchoHandler(string request, ServerCallContext context)
  268. {
  269. foreach (Metadata.Entry metadataEntry in context.RequestHeaders)
  270. {
  271. if (metadataEntry.Key != "user-agent")
  272. {
  273. context.ResponseTrailers.Add(metadataEntry);
  274. }
  275. }
  276. if (request == "RETURN-USER-AGENT")
  277. {
  278. return context.RequestHeaders.Where(entry => entry.Key == "user-agent").Single().Value;
  279. }
  280. if (request == "RETURN-PEER")
  281. {
  282. return context.Peer;
  283. }
  284. if (request == "THROW")
  285. {
  286. throw new Exception("This was thrown on purpose by a test");
  287. }
  288. if (request == "THROW_UNAUTHENTICATED")
  289. {
  290. throw new RpcException(new Status(StatusCode.Unauthenticated, ""));
  291. }
  292. if (request == "SET_UNAUTHENTICATED")
  293. {
  294. context.Status = new Status(StatusCode.Unauthenticated, "");
  295. }
  296. return request;
  297. }
  298. private static async Task<string> ConcatAndEchoHandler(IAsyncStreamReader<string> requestStream, ServerCallContext context)
  299. {
  300. string result = "";
  301. await requestStream.ForEach(async (request) =>
  302. {
  303. if (request == "THROW")
  304. {
  305. throw new Exception("This was thrown on purpose by a test");
  306. }
  307. result += request;
  308. });
  309. // simulate processing takes some time.
  310. await Task.Delay(250);
  311. return result;
  312. }
  313. }
  314. }