1 // Licensed to the Apache Software Foundation(ASF) under one
2 // or more contributor license agreements.See the NOTICE file
3 // distributed with this work for additional information
4 // regarding copyright ownership.The ASF licenses this file
5 // to you under the Apache License, Version 2.0 (the
6 // "License"); you may not use this file except in compliance
7 // with the License. You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing,
12 // software distributed under the License is distributed on an
13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 // KIND, either express or implied. See the License for the
15 // specific language governing permissions and limitations
19 using System.Collections.Generic;
20 using System.Diagnostics;
24 using System.Reflection;
25 using System.Security.Authentication;
26 using System.Security.Cryptography.X509Certificates;
27 using System.ServiceModel;
29 using System.Threading;
30 using System.Threading.Tasks;
31 using Thrift.Collections;
32 using Thrift.Protocols;
33 using Thrift.Transports;
34 using Thrift.Transports.Client;
38 public class TestClient
40 private class TestParams
42 public int numIterations = 1;
43 public IPAddress host = IPAddress.Any;
44 public int port = 9090;
45 public int numThreads = 1;
50 public string protocol;
51 public bool encrypted = false;
53 internal void Parse( List<string> args)
55 for (var i = 0; i < args.Count; ++i)
61 else if (args[i] == "-n")
63 numIterations = Convert.ToInt32(args[++i]);
65 else if (args[i].StartsWith("--pipe="))
67 pipe = args[i].Substring(args[i].IndexOf("=") + 1);
68 Console.WriteLine("Using named pipes transport");
70 else if (args[i].StartsWith("--host="))
72 // check there for ipaddress
73 host = new IPAddress(Encoding.Unicode.GetBytes(args[i].Substring(args[i].IndexOf("=") + 1)));
75 else if (args[i].StartsWith("--port="))
77 port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
79 else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
82 Console.WriteLine("Using buffered sockets");
84 else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
87 Console.WriteLine("Using framed transport");
89 else if (args[i] == "-t")
91 numThreads = Convert.ToInt32(args[++i]);
93 else if (args[i] == "--binary" || args[i] == "--protocol=binary")
96 Console.WriteLine("Using binary protocol");
98 else if (args[i] == "--compact" || args[i] == "--protocol=compact")
100 protocol = "compact";
101 Console.WriteLine("Using compact protocol");
103 else if (args[i] == "--json" || args[i] == "--protocol=json")
106 Console.WriteLine("Using JSON protocol");
108 else if (args[i] == "--ssl")
111 Console.WriteLine("Using encrypted transport");
115 //throw new ArgumentException(args[i]);
120 private static X509Certificate2 GetClientCert()
122 var clientCertName = "client.p12";
123 var possiblePaths = new List<string>
131 string existingPath = null;
132 foreach (var possiblePath in possiblePaths)
134 var path = Path.GetFullPath(possiblePath + clientCertName);
135 if (File.Exists(path))
142 if (string.IsNullOrEmpty(existingPath))
144 throw new FileNotFoundException($"Cannot find file: {clientCertName}");
147 var cert = new X509Certificate2(existingPath, "thrift");
152 public TClientTransport CreateTransport()
156 // endpoint transport
157 TClientTransport trans = null;
161 trans = new TNamedPipeClientTransport(pipe);
167 var cert = GetClientCert();
169 if (cert == null || !cert.HasPrivateKey)
171 throw new InvalidOperationException("Certificate doesn't contain private key");
174 trans = new TTlsSocketClientTransport(host, port, 0, cert,
175 (sender, certificate, chain, errors) => true,
176 null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
180 trans = new TSocketClientTransport(host, port);
187 trans = new TBufferedClientTransport(trans);
192 trans = new TFramedClientTransport(trans);
198 return new THttpClientTransport(new Uri(url), null);
201 public TProtocol CreateProtocol(TClientTransport transport)
203 if (protocol == "compact")
205 return new TCompactProtocol(transport);
208 if (protocol == "json")
210 return new TJsonProtocol(transport);
213 return new TBinaryProtocol(transport);
218 private const int ErrorBaseTypes = 1;
219 private const int ErrorStructs = 2;
220 private const int ErrorContainers = 4;
221 private const int ErrorExceptions = 8;
222 private const int ErrorUnknown = 64;
224 private class ClientTest
226 private readonly TClientTransport transport;
227 private readonly ThriftTest.Client client;
228 private readonly int numIterations;
231 public int ReturnCode { get; set; }
233 public ClientTest(TestParams param)
235 transport = param.CreateTransport();
236 client = new ThriftTest.Client(param.CreateProtocol(transport));
237 numIterations = param.numIterations;
240 public void Execute()
242 var token = CancellationToken.None;
246 Console.WriteLine("Execute called more than once");
247 throw new InvalidOperationException();
250 for (var i = 0; i < numIterations; i++)
254 if (!transport.IsOpen)
256 transport.OpenAsync(token).GetAwaiter().GetResult();
259 catch (TTransportException ex)
261 Console.WriteLine("*** FAILED ***");
262 Console.WriteLine("Connect failed: " + ex.Message);
263 ReturnCode |= ErrorUnknown;
264 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
269 Console.WriteLine("*** FAILED ***");
270 Console.WriteLine("Connect failed: " + ex.Message);
271 ReturnCode |= ErrorUnknown;
272 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
278 ReturnCode |= ExecuteClientTestAsync(client).GetAwaiter().GetResult(); ;
282 Console.WriteLine("*** FAILED ***");
283 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
284 ReturnCode |= ErrorUnknown;
293 Console.WriteLine("Error while closing transport");
294 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
300 internal static void PrintOptionsHelp()
302 Console.WriteLine("Client options:");
303 Console.WriteLine(" -u <URL>");
304 Console.WriteLine(" -t <# of threads to run> default = 1");
305 Console.WriteLine(" -n <# of iterations> per thread");
306 Console.WriteLine(" --pipe=<pipe name>");
307 Console.WriteLine(" --host=<IP address>");
308 Console.WriteLine(" --port=<port number>");
309 Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
310 Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
311 Console.WriteLine(" --ssl");
315 public static int Execute(List<string> args)
319 var param = new TestParams();
327 Console.WriteLine("*** FAILED ***");
328 Console.WriteLine("Error while parsing arguments");
329 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
333 var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray();
335 //issue tests on separate threads simultaneously
336 var threads = tests.Select(test => new Task(test.Execute)).ToArray();
337 var start = DateTime.Now;
338 foreach (var t in threads)
343 Task.WaitAll(threads);
345 Console.WriteLine("Total time: " + (DateTime.Now - start));
347 return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
349 catch (Exception outerEx)
351 Console.WriteLine("*** FAILED ***");
352 Console.WriteLine("Unexpected error");
353 Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
358 public static string BytesToHex(byte[] data)
360 return BitConverter.ToString(data).Replace("-", string.Empty);
363 public static byte[] PrepareTestData(bool randomDist)
365 var retval = new byte[0x100];
366 var initLen = Math.Min(0x100, retval.Length);
368 // linear distribution, unless random is requested
371 for (var i = 0; i < initLen; ++i)
378 // random distribution
379 for (var i = 0; i < initLen; ++i)
383 var rnd = new Random();
384 for (var i = 1; i < initLen; ++i)
388 var nextPos = rnd.Next() % initLen;
389 if (retval[nextPos] == 0)
391 retval[nextPos] = (byte)i;
399 public static async Task<int> ExecuteClientTestAsync(ThriftTest.Client client)
401 var token = CancellationToken.None;
404 Console.Write("testVoid()");
405 await client.testVoidAsync(token);
406 Console.WriteLine(" = void");
408 Console.Write("testString(\"Test\")");
409 var s = await client.testStringAsync("Test", token);
410 Console.WriteLine(" = \"" + s + "\"");
413 Console.WriteLine("*** FAILED ***");
414 returnCode |= ErrorBaseTypes;
417 Console.Write("testBool(true)");
418 var t = await client.testBoolAsync((bool)true, token);
419 Console.WriteLine(" = " + t);
422 Console.WriteLine("*** FAILED ***");
423 returnCode |= ErrorBaseTypes;
425 Console.Write("testBool(false)");
426 var f = await client.testBoolAsync((bool)false, token);
427 Console.WriteLine(" = " + f);
430 Console.WriteLine("*** FAILED ***");
431 returnCode |= ErrorBaseTypes;
434 Console.Write("testByte(1)");
435 var i8 = await client.testByteAsync((sbyte)1, token);
436 Console.WriteLine(" = " + i8);
439 Console.WriteLine("*** FAILED ***");
440 returnCode |= ErrorBaseTypes;
443 Console.Write("testI32(-1)");
444 var i32 = await client.testI32Async(-1, token);
445 Console.WriteLine(" = " + i32);
448 Console.WriteLine("*** FAILED ***");
449 returnCode |= ErrorBaseTypes;
452 Console.Write("testI64(-34359738368)");
453 var i64 = await client.testI64Async(-34359738368, token);
454 Console.WriteLine(" = " + i64);
455 if (-34359738368 != i64)
457 Console.WriteLine("*** FAILED ***");
458 returnCode |= ErrorBaseTypes;
461 // TODO: Validate received message
462 Console.Write("testDouble(5.325098235)");
463 var dub = await client.testDoubleAsync(5.325098235, token);
464 Console.WriteLine(" = " + dub);
465 if (5.325098235 != dub)
467 Console.WriteLine("*** FAILED ***");
468 returnCode |= ErrorBaseTypes;
470 Console.Write("testDouble(-0.000341012439638598279)");
471 dub = await client.testDoubleAsync(-0.000341012439638598279, token);
472 Console.WriteLine(" = " + dub);
473 if (-0.000341012439638598279 != dub)
475 Console.WriteLine("*** FAILED ***");
476 returnCode |= ErrorBaseTypes;
479 var binOut = PrepareTestData(true);
480 Console.Write("testBinary(" + BytesToHex(binOut) + ")");
483 var binIn = await client.testBinaryAsync(binOut, token);
484 Console.WriteLine(" = " + BytesToHex(binIn));
485 if (binIn.Length != binOut.Length)
487 Console.WriteLine("*** FAILED ***");
488 returnCode |= ErrorBaseTypes;
490 for (var ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
491 if (binIn[ofs] != binOut[ofs])
493 Console.WriteLine("*** FAILED ***");
494 returnCode |= ErrorBaseTypes;
497 catch (Thrift.TApplicationException ex)
499 Console.WriteLine("*** FAILED ***");
500 returnCode |= ErrorBaseTypes;
501 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
504 // binary equals? only with hashcode option enabled ...
505 Console.WriteLine("Test CrazyNesting");
506 var one = new CrazyNesting();
507 var two = new CrazyNesting();
508 one.String_field = "crazy";
509 two.String_field = "crazy";
510 one.Binary_field = new byte[] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
511 two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
512 if (typeof(CrazyNesting).GetMethod("Equals")?.DeclaringType == typeof(CrazyNesting))
514 if (!one.Equals(two))
516 Console.WriteLine("*** FAILED ***");
517 returnCode |= ErrorContainers;
518 throw new Exception("CrazyNesting.Equals failed");
522 // TODO: Validate received message
523 Console.Write("testStruct({\"Zero\", 1, -3, -5})");
524 var o = new Xtruct();
525 o.String_thing = "Zero";
526 o.Byte_thing = (sbyte)1;
529 var i = await client.testStructAsync(o, token);
530 Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
532 // TODO: Validate received message
533 Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
534 var o2 = new Xtruct2();
535 o2.Byte_thing = (sbyte)1;
538 var i2 = await client.testNestAsync(o2, token);
540 Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
542 var mapout = new Dictionary<int, int>();
543 for (var j = 0; j < 5; j++)
547 Console.Write("testMap({");
549 foreach (var key in mapout.Keys)
559 Console.Write(key + " => " + mapout[key]);
563 var mapin = await client.testMapAsync(mapout, token);
565 Console.Write(" = {");
567 foreach (var key in mapin.Keys)
577 Console.Write(key + " => " + mapin[key]);
579 Console.WriteLine("}");
581 // TODO: Validate received message
582 var listout = new List<int>();
583 for (var j = -2; j < 3; j++)
587 Console.Write("testList({");
589 foreach (var j in listout)
603 var listin = await client.testListAsync(listout, token);
605 Console.Write(" = {");
607 foreach (var j in listin)
619 Console.WriteLine("}");
622 // TODO: Validate received message
623 var setout = new THashSet<int>();
624 for (var j = -2; j < 3; j++)
628 Console.Write("testSet({");
630 foreach (int j in setout)
644 var setin = await client.testSetAsync(setout, token);
646 Console.Write(" = {");
648 foreach (int j in setin)
660 Console.WriteLine("}");
663 Console.Write("testEnum(ONE)");
664 var ret = await client.testEnumAsync(Numberz.ONE, token);
665 Console.WriteLine(" = " + ret);
666 if (Numberz.ONE != ret)
668 Console.WriteLine("*** FAILED ***");
669 returnCode |= ErrorStructs;
672 Console.Write("testEnum(TWO)");
673 ret = await client.testEnumAsync(Numberz.TWO, token);
674 Console.WriteLine(" = " + ret);
675 if (Numberz.TWO != ret)
677 Console.WriteLine("*** FAILED ***");
678 returnCode |= ErrorStructs;
681 Console.Write("testEnum(THREE)");
682 ret = await client.testEnumAsync(Numberz.THREE, token);
683 Console.WriteLine(" = " + ret);
684 if (Numberz.THREE != ret)
686 Console.WriteLine("*** FAILED ***");
687 returnCode |= ErrorStructs;
690 Console.Write("testEnum(FIVE)");
691 ret = await client.testEnumAsync(Numberz.FIVE, token);
692 Console.WriteLine(" = " + ret);
693 if (Numberz.FIVE != ret)
695 Console.WriteLine("*** FAILED ***");
696 returnCode |= ErrorStructs;
699 Console.Write("testEnum(EIGHT)");
700 ret = await client.testEnumAsync(Numberz.EIGHT, token);
701 Console.WriteLine(" = " + ret);
702 if (Numberz.EIGHT != ret)
704 Console.WriteLine("*** FAILED ***");
705 returnCode |= ErrorStructs;
708 Console.Write("testTypedef(309858235082523)");
709 var uid = await client.testTypedefAsync(309858235082523L, token);
710 Console.WriteLine(" = " + uid);
711 if (309858235082523L != uid)
713 Console.WriteLine("*** FAILED ***");
714 returnCode |= ErrorStructs;
717 // TODO: Validate received message
718 Console.Write("testMapMap(1)");
719 var mm = await client.testMapMapAsync(1, token);
720 Console.Write(" = {");
721 foreach (var key in mm.Keys)
723 Console.Write(key + " => {");
725 foreach (var k2 in m2.Keys)
727 Console.Write(k2 + " => " + m2[k2] + ", ");
729 Console.Write("}, ");
731 Console.WriteLine("}");
733 // TODO: Validate received message
734 var insane = new Insanity();
735 insane.UserMap = new Dictionary<Numberz, long>();
736 insane.UserMap[Numberz.FIVE] = 5000L;
737 var truck = new Xtruct();
738 truck.String_thing = "Truck";
739 truck.Byte_thing = (sbyte)8;
742 insane.Xtructs = new List<Xtruct>();
743 insane.Xtructs.Add(truck);
744 Console.Write("testInsanity()");
745 var whoa = await client.testInsanityAsync(insane, token);
746 Console.Write(" = {");
747 foreach (var key in whoa.Keys)
750 Console.Write(key + " => {");
752 foreach (var k2 in val.Keys)
756 Console.Write(k2 + " => {");
757 var userMap = v2.UserMap;
762 foreach (var k3 in userMap.Keys)
764 Console.Write(k3 + " => " + userMap[k3] + ", ");
769 Console.Write("null");
771 Console.Write("}, ");
773 var xtructs = v2.Xtructs;
778 foreach (var x in xtructs)
780 Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
785 Console.Write("null");
789 Console.Write("}, ");
791 Console.Write("}, ");
793 Console.WriteLine("}");
797 var arg2 = long.MaxValue;
798 var multiDict = new Dictionary<short, string>();
799 multiDict[1] = "one";
801 var tmpMultiDict = new List<string>();
802 foreach (var pair in multiDict)
803 tmpMultiDict.Add(pair.Key +" => "+ pair.Value);
805 var arg4 = Numberz.FIVE;
807 Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + ",{" + string.Join(",", tmpMultiDict) + "}," + arg4 + "," + arg5 + ")");
808 var multiResponse = await client.testMultiAsync(arg0, arg1, arg2, multiDict, arg4, arg5, token);
809 Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
810 + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
814 Console.WriteLine("testException(\"Xception\")");
815 await client.testExceptionAsync("Xception", token);
816 Console.WriteLine("*** FAILED ***");
817 returnCode |= ErrorExceptions;
821 if (ex.ErrorCode != 1001 || ex.Message != "Xception")
823 Console.WriteLine("*** FAILED ***");
824 returnCode |= ErrorExceptions;
829 Console.WriteLine("*** FAILED ***");
830 returnCode |= ErrorExceptions;
831 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
835 Console.WriteLine("testException(\"TException\")");
836 await client.testExceptionAsync("TException", token);
837 Console.WriteLine("*** FAILED ***");
838 returnCode |= ErrorExceptions;
840 catch (Thrift.TException)
846 Console.WriteLine("*** FAILED ***");
847 returnCode |= ErrorExceptions;
848 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
852 Console.WriteLine("testException(\"ok\")");
853 await client.testExceptionAsync("ok", token);
858 Console.WriteLine("*** FAILED ***");
859 returnCode |= ErrorExceptions;
860 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
865 Console.WriteLine("testMultiException(\"Xception\", ...)");
866 await client.testMultiExceptionAsync("Xception", "ignore", token);
867 Console.WriteLine("*** FAILED ***");
868 returnCode |= ErrorExceptions;
872 if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception")
874 Console.WriteLine("*** FAILED ***");
875 returnCode |= ErrorExceptions;
880 Console.WriteLine("*** FAILED ***");
881 returnCode |= ErrorExceptions;
882 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
886 Console.WriteLine("testMultiException(\"Xception2\", ...)");
887 await client.testMultiExceptionAsync("Xception2", "ignore", token);
888 Console.WriteLine("*** FAILED ***");
889 returnCode |= ErrorExceptions;
893 if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2")
895 Console.WriteLine("*** FAILED ***");
896 returnCode |= ErrorExceptions;
901 Console.WriteLine("*** FAILED ***");
902 returnCode |= ErrorExceptions;
903 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
907 Console.WriteLine("testMultiException(\"success\", \"OK\")");
908 if ("OK" != (await client.testMultiExceptionAsync("success", "OK", token)).String_thing)
910 Console.WriteLine("*** FAILED ***");
911 returnCode |= ErrorExceptions;
916 Console.WriteLine("*** FAILED ***");
917 returnCode |= ErrorExceptions;
918 Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
921 var sw = new Stopwatch();
923 Console.WriteLine("Test Oneway(1)");
924 await client.testOnewayAsync(1, token);
926 if (sw.ElapsedMilliseconds > 1000)
928 Console.WriteLine("*** FAILED ***");
929 returnCode |= ErrorBaseTypes;
932 Console.Write("Test Calltime()");
936 for (var k = 0; k < times; ++k)
937 await client.testVoidAsync(token);
939 Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times);