You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@thrift.apache.org by jk...@apache.org on 2018/01/14 13:42:47 UTC
[1/9] thrift git commit: THRIFT-4434: .NET Core cleanup and the
beginnings of compiler unit tests Client: netcore
Repository: thrift
Updated Branches:
refs/heads/master 9a32f8af3 -> ad2385229
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/ThriftTest/ThriftTest.csproj
----------------------------------------------------------------------
diff --git a/test/netcore/ThriftTest/ThriftTest.csproj b/test/netcore/ThriftTest/ThriftTest.csproj
deleted file mode 100644
index 6647101..0000000
--- a/test/netcore/ThriftTest/ThriftTest.csproj
+++ /dev/null
@@ -1,27 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <TargetFramework>netcoreapp2.0</TargetFramework>
- <AssemblyName>ThriftTest</AssemblyName>
- <PackageId>ThriftTest</PackageId>
- <OutputType>Exe</OutputType>
- <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
- <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
- <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
- <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
- <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
- <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
- </PropertyGroup>
-
- <ItemGroup>
- <PackageReference Include="System.Net.Http.WinHttpHandler" Version="[4.4,)" />
- <PackageReference Include="System.Runtime.Serialization.Primitives" Version="[4.3,)" />
- <PackageReference Include="System.ServiceModel.Primitives" Version="[4.4,)" />
- <PackageReference Include="System.Threading" Version="[4.3,)" />
- </ItemGroup>
-
- <ItemGroup>
- <ProjectReference Include="..\..\..\lib\netcore\Thrift\Thrift.csproj" />
- </ItemGroup>
-
-</Project>
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/build.cmd
----------------------------------------------------------------------
diff --git a/test/netcore/build.cmd b/test/netcore/build.cmd
index e971799..9b84ef2 100644
--- a/test/netcore/build.cmd
+++ b/test/netcore/build.cmd
@@ -19,12 +19,7 @@ rem * under the License.
rem */
setlocal
-cd Interfaces
-thrift -gen netcore:wcf -r ..\..\tutorial.thrift
-cd ..
-
dotnet --info
-dotnet restore
dotnet build
:eof
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/build.sh
----------------------------------------------------------------------
diff --git a/test/netcore/build.sh b/test/netcore/build.sh
index 626635c..c97e310 100755
--- a/test/netcore/build.sh
+++ b/test/netcore/build.sh
@@ -22,10 +22,5 @@
#exit if any command fails
set -e
-cd ThriftTest
-../../../compiler/cpp/thrift -gen netcore:wcf -r ../../ThriftTest.thrift
-cd ..
-
dotnet --info
-dotnet restore
dotnet build
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/tests.json
----------------------------------------------------------------------
diff --git a/test/tests.json b/test/tests.json
index c4e07ee..fd79a9b 100644
--- a/test/tests.json
+++ b/test/tests.json
@@ -1,689 +1,686 @@
-[
- {
- "name": "c_glib",
- "platforms": [
- "Linux"
- ],
- "server": {
- "command": [
- "test_server",
- "--lt-debug"
- ],
- "protocols": [
- "binary:multi",
- "compact:multic"
- ]
- },
- "client": {
- "command": [
- "test_client",
- "--lt-debug"
- ],
- "protocols": [
- "multi:binary",
- "multic:compact"
- ],
- "sockets": [
- "ip-ssl"
- ]
- },
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip"
- ],
- "protocols": [
- "binary",
- "compact",
- "multi",
- "multic"
- ],
- "workdir": "c_glib"
- },
- {
- "name": "d",
- "server": {
- "command": [
- "thrift_test_server"
- ]
- },
- "client": {
- "command": [
- "thrift_test_client"
- ]
- },
- "transports": [
- "http",
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "binary",
- "compact",
- "json"
- ],
- "workdir": "../lib/d/test"
- },
- {
- "name": "go",
- "server": {
- "command": [
- "testserver",
- "--certPath=../../keys"
- ]
- },
- "client": {
- "timeout": 6,
- "command": [
- "testclient"
- ]
- },
- "transports": [
- "buffered",
- "framed",
- "http"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "binary",
- "compact",
- "json"
- ],
- "workdir": "go/bin"
- },
- {
- "name": "java",
- "join_args": true,
- "command": [
- "ant",
- "-f",
- "build.xml",
- "-Dno-gen-thrift=\"\"",
- "-Dtestargs"
- ],
- "prepare": [
- "ant",
- "-f",
- "build.xml",
- "compile-test"
- ],
- "server": {
- "delay": 10,
- "extra_args": ["run-testserver"],
- "protocols": [
- "binary:multi",
- "compact:multic",
- "json:multij"
- ]
- },
- "client": {
- "timeout": 13,
- "extra_args": ["run-testclient"],
- "transports": [
- "http"
- ],
- "protocols": [
- "multi:binary",
- "multic:compact",
- "multij:json"
- ]
- },
- "transports": [
- "buffered",
- "framed",
- "framed:fastframed"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "binary",
- "compact",
- "json",
- "multi",
- "multic",
- "multij"
- ],
- "workdir": "../lib/java"
- },
- {
- "name": "nodejs",
- "env": {
- "NODE_PATH": "../lib"
- },
- "server": {
- "command": [
- "node",
- "server.js",
- "--type=tcp"
- ]
- },
- "client": {
- "timeout": 6,
- "command": [
- "node",
- "client.js",
- "--type=tcp"
- ]
- },
- "transports": [
- "buffered",
- "framed",
- "http"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "compact",
- "binary",
- "json"
- ],
- "workdir": "../lib/nodejs/test"
- },
- {
- "name": "hs",
- "server": {
- "command": [
- "TestServer"
- ]
- },
- "client": {
- "timeout": 6,
- "transports": [
- "http"
- ],
- "command": [
- "TestClient"
- ]
- },
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip"
- ],
- "protocols": [
- "header",
- "compact",
- "binary",
- "json"
- ],
- "workdir": "hs"
- },
- {
- "name": "py",
- "server": {
- "extra_args": ["TSimpleServer"],
- "command": [
- "TestServer.py",
- "--verbose",
- "--genpydir=gen-py"
- ]
- },
- "client": {
- "timeout": 10,
- "command": [
- "TestClient.py",
- "--verbose",
- "--host=localhost",
- "--genpydir=gen-py"
- ]
- },
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "compact",
- "binary",
- "json",
- "binary:accel",
- "compact:accelc"
- ],
- "workdir": "py"
- },
- {
- "comment": "Using 'python3' executable to test py2 and 3 at once",
- "name": "py3",
- "server": {
- "extra_args": ["TSimpleServer"],
- "command": [
- "python3",
- "TestServer.py",
- "--verbose",
- "--genpydir=gen-py"
- ]
- },
- "client": {
- "timeout": 10,
- "command": [
- "python3",
- "TestClient.py",
- "--host=localhost",
- "--genpydir=gen-py"
- ]
- },
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip-ssl",
- "ip"
- ],
- "protocols": [
- "compact",
- "binary",
- "json",
- "binary:accel",
- "compact:accelc"
- ],
- "workdir": "py"
- },
- {
- "name": "cpp",
- "server": {
- "command": [
- "TestServer"
- ],
- "protocols": [
- "binary:multi",
- "compact:multic",
- "header:multih",
- "json:multij"
- ]
- },
- "client": {
- "timeout": 8,
- "command": [
- "TestClient"
- ],
- "protocols": [
- "multi:binary",
- "multic:compact",
- "multih:header",
- "multij:json"
- ]
- },
- "transports": [
- "buffered",
- "http",
- "framed"
- ],
- "sockets": [
- "ip",
- "ip-ssl",
- "domain"
- ],
- "protocols": [
- "compact",
- "binary",
- "json",
- "header",
- "multi",
- "multic",
- "multih",
- "multij"
- ],
- "workdir": "cpp"
- },
- {
- "name": "rb",
- "server": {
- "command": [
- "ruby",
- "../integration/TestServer.rb"
- ]
- },
- "client": {
- "timeout": 5,
- "command": [
- "ruby",
- "../integration/TestClient.rb"
- ]
- },
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip"
- ],
- "protocols": [
- "compact",
- "binary",
- "json",
- "binary:accel"
- ],
- "workdir": "rb/gen-rb"
- },
- {
- "name": "csharp",
- "env": {
- "MONO_PATH": "../../lib/csharp/"
- },
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "binary",
- "compact",
- "json"
- ],
- "server": {
- "command": [
- "mono",
- "TestClientServer.exe",
- "server"
- ]
- },
- "client": {
- "timeout": 9,
- "command": [
- "mono",
- "TestClientServer.exe",
- "client"
- ],
- "protocols": [
- "multi",
- "multic",
- "multi:binary",
- "multic:compact"
- ]
- },
- "workdir": "csharp"
- },
- {
- "name": "netcore",
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "binary",
- "compact",
- "json"
- ],
- "server-disabled": {
- "command": [
- "dotnet",
- "run",
- "--no-build",
- "--no-restore",
- "--",
- "server"
- ]
- },
- "client": {
- "timeout": 10,
- "command": [
- "dotnet",
- "run",
- "--no-build",
- "--no-restore",
- "--",
- "client"
- ]
- },
- "workdir": "netcore/ThriftTest"
- },
- {
- "name": "perl",
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip",
- "ip-ssl",
- "domain"
- ],
- "protocols": [
- "binary",
- "multi"
- ],
- "client": {
- "command": [
- "perl",
- "-Igen-perl/",
- "-I../../lib/perl/lib/",
- "TestClient.pl",
- "--ca=../keys/CA.pem",
- "--cert=../keys/client.crt",
- "--key=../keys/client.key"
- ],
- "protocols": [
- "multi:binary"
- ]
- },
- "server": {
- "command": [
- "perl",
- "-Igen-perl/",
- "-I../../lib/perl/lib/",
- "TestServer.pl",
- "--cert=../keys/server.crt",
- "--key=../keys/server.key"
- ],
- "protocols": [
- "binary:multi"
- ]
- },
- "workdir": "perl"
- },
- {
- "name": "php",
- "client": {
- "timeout": 6,
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip"
- ],
- "protocols": [
- "binary",
- "compact",
- "binary:accel"
- ],
- "command": [
- "php",
- "-dextension_dir=php_ext_dir",
- "--php-ini=test_php.ini",
- "--no-php-ini",
- "-ddisplay_errors=stderr",
- "-dlog_errors=0",
- "-derror_reporting=E_ALL",
- "TestClient.php"
- ]
- },
- "workdir": "php"
- },
- {
- "name": "dart",
- "client": {
- "transports": [
- "buffered",
- "framed",
- "http"
- ],
- "sockets": [
- "ip"
- ],
- "protocols": [
- "binary",
- "compact",
- "json"
- ],
- "command": [
- "dart",
- "test_client/bin/main.dart"
- ]
- },
- "workdir": "dart"
- },
- {
- "name": "erl",
- "transports": [
- "buffered",
- "framed"
- ],
- "sockets": [
- "ip",
- "ip-ssl"
- ],
- "protocols": [
- "binary",
- "compact"
- ],
- "client": {
- "command": [
- "erl",
- "+K",
- "true",
- "-noshell",
- "-pa",
- "../../lib/erl/ebin/",
- "-pa",
- "./ebin",
- "-s",
- "test_client",
- "-s",
- "init",
- "stop",
- "-extra"
- ]
- },
- "server": {
- "command": [
- "erl",
- "+K",
- "true",
- "-noshell",
- "-pa",
- "../../lib/erl/ebin/",
- "-pa",
- "./ebin",
- "-s",
- "test_thrift_server",
- "-extra"
- ]
- },
- "workdir": "erl"
- },
- {
- "name": "js",
- "transports": [
- "http"
- ],
- "sockets": [
- "ip"
- ],
- "protocols": [
- "json"
- ],
- "client": {
- "command": [
- "phantomjs",
- "test/phantom-client.js"
- ]
- },
- "workdir": "../lib/js"
- },
- {
- "name": "lua",
- "TODO": "Add dll to LUA_CPATH",
- "env": {
- "LUA_PATH": ";;gen-lua/?.lua;../../lib/lua/?.lua",
- "LUA_CPATH": ";;../../lib/lua/.libs/?.so"
- },
- "client": {
- "timeout": 5,
- "transports": [
- "buffered",
- "framed",
- "http"
- ],
- "sockets": [
- "ip"
- ],
- "protocols": [
- "binary",
- "compact",
- "json"
- ],
- "command": [
- "lua",
- "test_basic_client.lua"
- ]
- },
- "workdir": "lua"
- },
- {
- "name": "rs",
- "env": {
- "RUST_BACKTRACE": "1",
- "RUST_LOG": "info"
- },
- "server": {
- "command": [
- "test_server"
- ],
- "protocols": [
- "binary:multi",
- "compact:multic"
- ]
- },
- "client": {
- "timeout": 6,
- "command": [
- "test_client"
- ],
- "protocols": [
- "multi:binary",
- "multic:compact"
- ]
- },
- "sockets": [
- "ip"
- ],
- "transports": [
- "buffered",
- "framed"
- ],
- "protocols": [
- "binary",
- "compact",
- "multi",
- "multic"
- ],
- "workdir": "rs/bin"
- }
-]
+[{
+ "name": "c_glib",
+ "platforms": [
+ "Linux"
+ ],
+ "server": {
+ "command": [
+ "test_server",
+ "--lt-debug"
+ ],
+ "protocols": [
+ "binary:multi",
+ "compact:multic"
+ ]
+ },
+ "client": {
+ "command": [
+ "test_client",
+ "--lt-debug"
+ ],
+ "protocols": [
+ "multi:binary",
+ "multic:compact"
+ ],
+ "sockets": [
+ "ip-ssl"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "multi",
+ "multic"
+ ],
+ "workdir": "c_glib"
+ },
+ {
+ "name": "d",
+ "server": {
+ "command": [
+ "thrift_test_server"
+ ]
+ },
+ "client": {
+ "command": [
+ "thrift_test_client"
+ ]
+ },
+ "transports": [
+ "http",
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "json"
+ ],
+ "workdir": "../lib/d/test"
+ },
+ {
+ "name": "go",
+ "server": {
+ "command": [
+ "testserver",
+ "--certPath=../../keys"
+ ]
+ },
+ "client": {
+ "timeout": 6,
+ "command": [
+ "testclient"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed",
+ "http"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "json"
+ ],
+ "workdir": "go/bin"
+ },
+ {
+ "name": "java",
+ "join_args": true,
+ "command": [
+ "ant",
+ "-f",
+ "build.xml",
+ "-Dno-gen-thrift=\"\"",
+ "-Dtestargs"
+ ],
+ "prepare": [
+ "ant",
+ "-f",
+ "build.xml",
+ "compile-test"
+ ],
+ "server": {
+ "delay": 10,
+ "extra_args": ["run-testserver"],
+ "protocols": [
+ "binary:multi",
+ "compact:multic",
+ "json:multij"
+ ]
+ },
+ "client": {
+ "timeout": 13,
+ "extra_args": ["run-testclient"],
+ "transports": [
+ "http"
+ ],
+ "protocols": [
+ "multi:binary",
+ "multic:compact",
+ "multij:json"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed",
+ "framed:fastframed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "json",
+ "multi",
+ "multic",
+ "multij"
+ ],
+ "workdir": "../lib/java"
+ },
+ {
+ "name": "nodejs",
+ "env": {
+ "NODE_PATH": "../lib"
+ },
+ "server": {
+ "command": [
+ "node",
+ "server.js",
+ "--type=tcp"
+ ]
+ },
+ "client": {
+ "timeout": 6,
+ "command": [
+ "node",
+ "client.js",
+ "--type=tcp"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed",
+ "http"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "compact",
+ "binary",
+ "json"
+ ],
+ "workdir": "../lib/nodejs/test"
+ },
+ {
+ "name": "hs",
+ "server": {
+ "command": [
+ "TestServer"
+ ]
+ },
+ "client": {
+ "timeout": 6,
+ "transports": [
+ "http"
+ ],
+ "command": [
+ "TestClient"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip"
+ ],
+ "protocols": [
+ "header",
+ "compact",
+ "binary",
+ "json"
+ ],
+ "workdir": "hs"
+ },
+ {
+ "name": "py",
+ "server": {
+ "extra_args": ["TSimpleServer"],
+ "command": [
+ "TestServer.py",
+ "--verbose",
+ "--genpydir=gen-py"
+ ]
+ },
+ "client": {
+ "timeout": 10,
+ "command": [
+ "TestClient.py",
+ "--verbose",
+ "--host=localhost",
+ "--genpydir=gen-py"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "compact",
+ "binary",
+ "json",
+ "binary:accel",
+ "compact:accelc"
+ ],
+ "workdir": "py"
+ },
+ {
+ "comment": "Using 'python3' executable to test py2 and 3 at once",
+ "name": "py3",
+ "server": {
+ "extra_args": ["TSimpleServer"],
+ "command": [
+ "python3",
+ "TestServer.py",
+ "--verbose",
+ "--genpydir=gen-py"
+ ]
+ },
+ "client": {
+ "timeout": 10,
+ "command": [
+ "python3",
+ "TestClient.py",
+ "--host=localhost",
+ "--genpydir=gen-py"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip-ssl",
+ "ip"
+ ],
+ "protocols": [
+ "compact",
+ "binary",
+ "json",
+ "binary:accel",
+ "compact:accelc"
+ ],
+ "workdir": "py"
+ },
+ {
+ "name": "cpp",
+ "server": {
+ "command": [
+ "TestServer"
+ ],
+ "protocols": [
+ "binary:multi",
+ "compact:multic",
+ "header:multih",
+ "json:multij"
+ ]
+ },
+ "client": {
+ "timeout": 8,
+ "command": [
+ "TestClient"
+ ],
+ "protocols": [
+ "multi:binary",
+ "multic:compact",
+ "multih:header",
+ "multij:json"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "http",
+ "framed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl",
+ "domain"
+ ],
+ "protocols": [
+ "compact",
+ "binary",
+ "json",
+ "header",
+ "multi",
+ "multic",
+ "multih",
+ "multij"
+ ],
+ "workdir": "cpp"
+ },
+ {
+ "name": "rb",
+ "server": {
+ "command": [
+ "ruby",
+ "../integration/TestServer.rb"
+ ]
+ },
+ "client": {
+ "timeout": 5,
+ "command": [
+ "ruby",
+ "../integration/TestClient.rb"
+ ]
+ },
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip"
+ ],
+ "protocols": [
+ "compact",
+ "binary",
+ "json",
+ "binary:accel"
+ ],
+ "workdir": "rb/gen-rb"
+ },
+ {
+ "name": "csharp",
+ "env": {
+ "MONO_PATH": "../../lib/csharp/"
+ },
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "json"
+ ],
+ "server": {
+ "command": [
+ "mono",
+ "TestClientServer.exe",
+ "server"
+ ]
+ },
+ "client": {
+ "timeout": 9,
+ "command": [
+ "mono",
+ "TestClientServer.exe",
+ "client"
+ ],
+ "protocols": [
+ "multi",
+ "multic",
+ "multi:binary",
+ "multic:compact"
+ ]
+ },
+ "workdir": "csharp"
+ },
+ {
+ "name": "netcore",
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "json"
+ ],
+ "server": {
+ "command": [
+ "dotnet",
+ "run",
+ "--no-build",
+ "--project=Server/Server.csproj",
+ "server"
+ ]
+ },
+ "client": {
+ "timeout": 10,
+ "command": [
+ "dotnet",
+ "run",
+ "--no-build",
+ "--project=Client/Client.csproj",
+ "client"
+ ]
+ },
+ "workdir": "netcore"
+ },
+ {
+ "name": "perl",
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl",
+ "domain"
+ ],
+ "protocols": [
+ "binary",
+ "multi"
+ ],
+ "client": {
+ "command": [
+ "perl",
+ "-Igen-perl/",
+ "-I../../lib/perl/lib/",
+ "TestClient.pl",
+ "--ca=../keys/CA.pem",
+ "--cert=../keys/client.crt",
+ "--key=../keys/client.key"
+ ],
+ "protocols": [
+ "multi:binary"
+ ]
+ },
+ "server": {
+ "command": [
+ "perl",
+ "-Igen-perl/",
+ "-I../../lib/perl/lib/",
+ "TestServer.pl",
+ "--cert=../keys/server.crt",
+ "--key=../keys/server.key"
+ ],
+ "protocols": [
+ "binary:multi"
+ ]
+ },
+ "workdir": "perl"
+ },
+ {
+ "name": "php",
+ "client": {
+ "timeout": 6,
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "binary:accel"
+ ],
+ "command": [
+ "php",
+ "-dextension_dir=php_ext_dir",
+ "--php-ini=test_php.ini",
+ "--no-php-ini",
+ "-ddisplay_errors=stderr",
+ "-dlog_errors=0",
+ "-derror_reporting=E_ALL",
+ "TestClient.php"
+ ]
+ },
+ "workdir": "php"
+ },
+ {
+ "name": "dart",
+ "client": {
+ "transports": [
+ "buffered",
+ "framed",
+ "http"
+ ],
+ "sockets": [
+ "ip"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "json"
+ ],
+ "command": [
+ "dart",
+ "test_client/bin/main.dart"
+ ]
+ },
+ "workdir": "dart"
+ },
+ {
+ "name": "erl",
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "sockets": [
+ "ip",
+ "ip-ssl"
+ ],
+ "protocols": [
+ "binary",
+ "compact"
+ ],
+ "client": {
+ "command": [
+ "erl",
+ "+K",
+ "true",
+ "-noshell",
+ "-pa",
+ "../../lib/erl/ebin/",
+ "-pa",
+ "./ebin",
+ "-s",
+ "test_client",
+ "-s",
+ "init",
+ "stop",
+ "-extra"
+ ]
+ },
+ "server": {
+ "command": [
+ "erl",
+ "+K",
+ "true",
+ "-noshell",
+ "-pa",
+ "../../lib/erl/ebin/",
+ "-pa",
+ "./ebin",
+ "-s",
+ "test_thrift_server",
+ "-extra"
+ ]
+ },
+ "workdir": "erl"
+ },
+ {
+ "name": "js",
+ "transports": [
+ "http"
+ ],
+ "sockets": [
+ "ip"
+ ],
+ "protocols": [
+ "json"
+ ],
+ "client": {
+ "command": [
+ "phantomjs",
+ "test/phantom-client.js"
+ ]
+ },
+ "workdir": "../lib/js"
+ },
+ {
+ "name": "lua",
+ "TODO": "Add dll to LUA_CPATH",
+ "env": {
+ "LUA_PATH": ";;gen-lua/?.lua;../../lib/lua/?.lua",
+ "LUA_CPATH": ";;../../lib/lua/.libs/?.so"
+ },
+ "client": {
+ "timeout": 5,
+ "transports": [
+ "buffered",
+ "framed",
+ "http"
+ ],
+ "sockets": [
+ "ip"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "json"
+ ],
+ "command": [
+ "lua",
+ "test_basic_client.lua"
+ ]
+ },
+ "workdir": "lua"
+ },
+ {
+ "name": "rs",
+ "env": {
+ "RUST_BACKTRACE": "1",
+ "RUST_LOG": "info"
+ },
+ "server": {
+ "command": [
+ "test_server"
+ ],
+ "protocols": [
+ "binary:multi",
+ "compact:multic"
+ ]
+ },
+ "client": {
+ "timeout": 6,
+ "command": [
+ "test_client"
+ ],
+ "protocols": [
+ "multi:binary",
+ "multic:compact"
+ ]
+ },
+ "sockets": [
+ "ip"
+ ],
+ "transports": [
+ "buffered",
+ "framed"
+ ],
+ "protocols": [
+ "binary",
+ "compact",
+ "multi",
+ "multic"
+ ],
+ "workdir": "rs/bin"
+ }
+]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/Client/Program.cs
----------------------------------------------------------------------
diff --git a/tutorial/netcore/Client/Program.cs b/tutorial/netcore/Client/Program.cs
index ae1837b..ce5d8c7 100644
--- a/tutorial/netcore/Client/Program.cs
+++ b/tutorial/netcore/Client/Program.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -42,14 +42,14 @@ namespace Client
{
Logger.LogInformation(@"
Usage:
- Client.exe -h
+ Client.exe -help
will diplay help information
- Client.exe -t:<transport> -p:<protocol> -mc:<numClients>
+ Client.exe -tr:<transport> -pr:<protocol> -mc:<numClients>
will run client with specified arguments (tcp transport and binary protocol by default) and with 1 client
Options:
- -t (transport):
+ -tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - buffered transport over tcp will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
@@ -57,7 +57,7 @@ Options:
tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
- -p (protocol):
+ -pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
@@ -67,7 +67,7 @@ Options:
<numClients> - number of multiple clients to connect to server (max 100, default 1)
Sample:
- Client.exe -t:tcp -p:binary
+ Client.exe -tr:tcp -p:binary
");
}
@@ -75,7 +75,7 @@ Sample:
{
args = args ?? new string[0];
- if (args.Any(x => x.StartsWith("-h", StringComparison.OrdinalIgnoreCase)))
+ if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
@@ -127,7 +127,7 @@ Sample:
private static TClientTransport GetTransport(string[] args)
{
- var transport = args.FirstOrDefault(x => x.StartsWith("-t"))?.Split(':')?[1];
+ var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
Transport selectedTransport;
if (Enum.TryParse(transport, true, out selectedTransport))
@@ -203,7 +203,7 @@ Sample:
private static Tuple<Protocol, TProtocol> GetProtocol(string[] args, TClientTransport transport)
{
- var protocol = args.FirstOrDefault(x => x.StartsWith("-p"))?.Split(':')?[1];
+ var protocol = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
Protocol selectedProtocol;
if (Enum.TryParse(protocol, true, out selectedProtocol))
@@ -352,4 +352,4 @@ Sample:
Multiplexed
}
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/Interfaces/.gitignore
----------------------------------------------------------------------
diff --git a/tutorial/netcore/Interfaces/.gitignore b/tutorial/netcore/Interfaces/.gitignore
new file mode 100644
index 0000000..2e7446e
--- /dev/null
+++ b/tutorial/netcore/Interfaces/.gitignore
@@ -0,0 +1,3 @@
+# ignore for autogenerated files
+/shared
+/tutorial
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/Interfaces/Interfaces.csproj
----------------------------------------------------------------------
diff --git a/tutorial/netcore/Interfaces/Interfaces.csproj b/tutorial/netcore/Interfaces/Interfaces.csproj
index 14fad79..4297a06 100644
--- a/tutorial/netcore/Interfaces/Interfaces.csproj
+++ b/tutorial/netcore/Interfaces/Interfaces.csproj
@@ -17,4 +17,14 @@
<ItemGroup>
<PackageReference Include="System.ServiceModel.Primitives" Version="[4.4,)" />
</ItemGroup>
+
+ <Target Name="PreBuild" BeforeTargets="_GenerateRestoreProjectSpec;Restore;Compile">
+ <Exec Condition="'$(OS)' == 'Windows_NT'" Command="where thrift" ConsoleToMSBuild="true">
+ <Output TaskParameter="ConsoleOutput" PropertyName="PathToThrift" />
+ </Exec>
+ <Exec Condition="Exists('$(PathToThrift)')" Command="$(PathToThrift) -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../tutorial.thrift" />
+ <Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../tutorial.thrift" />
+ <Exec Condition="Exists('./../../../compiler/cpp/thrift')" Command="./../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../tutorial.thrift" />
+ </Target>
+
</Project>
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/Makefile.am
----------------------------------------------------------------------
diff --git a/tutorial/netcore/Makefile.am b/tutorial/netcore/Makefile.am
index ef3d618..d1d788f 100644
--- a/tutorial/netcore/Makefile.am
+++ b/tutorial/netcore/Makefile.am
@@ -19,39 +19,17 @@
SUBDIRS = .
-THRIFT = $(top_builddir)/compiler/cpp/thrift
-
-GENDIR = Interfaces/gen-netcore
-
-# Due to a known issue with "dotnet restore" the Thrift.dll dependency cannot be resolved from cmdline.
-# The problem does NOT affect Visual Studio builds, only cmdline.
-# - For details see https://github.com/dotnet/cli/issues/3199 and related tickets.
-# - Workaround is to temporarily copy the Thrift project into the solution
-COPYCMD = cp -u -p -r
-
-
THRIFTCODE = \
- Interfaces/Properties/AssemblyInfo.cs \
- Client/Properties/AssemblyInfo.cs \
- Client/Program.cs \
- Server/Properties/AssemblyInfo.cs \
- Server/Program.cs
+ Tutorial.sln
all-local: \
Client.exe
Client.exe: $(THRIFTCODE)
- $(MKDIR_P) $(GENDIR)
- $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/tutorial/tutorial.thrift
- $(DOTNETCORE) --info
- $(DOTNETCORE) restore
$(DOTNETCORE) build
clean-local:
- $(RM) Client.exe
- $(RM) Server.exe
$(RM) Interfaces.dll
- $(RM) -r $(GENDIR)
$(RM) -r Client/bin
$(RM) -r Client/obj
$(RM) -r Server/bin
@@ -60,15 +38,10 @@ clean-local:
$(RM) -r Interfaces/obj
EXTRA_DIST = \
- $(THRIFTCODE) \
Tutorial.sln \
- Interfaces/Interfaces.csproj \
- Client/Client.csproj \
- Client/ThriftTest.pfx \
- Client/Properties/launchSettings.json \
- Server/Server.csproj \
- Server/ThriftTest.pfx \
- Server/Properties/launchSettings.json \
+ Interfaces \
+ Client \
+ Server \
build.cmd \
build.sh \
README.md
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/README.md
----------------------------------------------------------------------
diff --git a/tutorial/netcore/README.md b/tutorial/netcore/README.md
index 6b2f660..626ef92 100644
--- a/tutorial/netcore/README.md
+++ b/tutorial/netcore/README.md
@@ -1,11 +1,11 @@
# Building of samples for different platforms
# Reused components
-- NET Core Standard 1.6 (SDK 1.0.0-preview2-003121)
-- NET Core App 1.1
+- NET Core Standard 2.0
+- NET Core App 2.0
# How to build
-- Download and install .NET Core SDK for your platform https://www.microsoft.com/net/core#windowsvs2015 (archive for SDK 1.0.0-preview2-003121 located by: https://github.com/dotnet/core/blob/master/release-notes/download-archive.md)
+- Download and install the latest .NET Core SDK for your platform https://www.microsoft.com/net/core#windowsvs2015 (archive for SDK 1.0.0-preview2-003121 located by: https://github.com/dotnet/core/blob/master/release-notes/download-archive.md)
- Ensure that you have thrift.exe which supports netcore lib and it added to PATH
- Go to current folder
- Run **build.sh** or **build.cmd** from the root of cloned repository
@@ -18,16 +18,13 @@ Notes: dotnet run supports passing arguments to app after -- symbols (https://do
- build
- go to folder (Client/Server)
-- run with specifying of correct parameters **dotnet run -t:tcp -p:multiplexed**, **dotnet run -help** (later, after migration to csproj and latest SDK will be possibility to use more usable form **dotnet run -- arguments**)
+- run with specifying of correct parameters **dotnet run -tr:tcp -pr:multiplexed**, **dotnet run -help** (later, after migration to csproj and latest SDK will be possibility to use more usable form **dotnet run -- arguments**)
#Notes
-- Migration to .NET Standard 2.0 planned for later (Q1 2017) according to https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/
- Possible adding additional platforms after stabilization of .NET Core (runtimes, platforms (Red Hat Linux, OpenSuse, etc.)
#Known issues
- In trace logging mode you can see some not important internal exceptions
-- Ubuntu 16.10 still not supported fully
-- There is some problems with .NET Core CLI and usage specific -r|--runtime for building and publishing projects with different target frameworks (netstandard1.6 and netcoreapp1.1)
# Running of samples
Please install Thrift C# .NET Core library or copy sources and build them to correcly build and run samples
@@ -39,12 +36,12 @@ Usage:
Server.exe -h
will diplay help information
- Server.exe -t:<transport> -p:<protocol>
+ Server.exe -tr:<transport> -pr:<protocol>
will run server with specified arguments (tcp transport and binary protocol by default)
Options:
- -t (transport):
+ -tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - tcp buffered transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
@@ -52,14 +49,14 @@ Options:
tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
- -p (protocol):
+ -pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
Sample:
- Server.exe -t:tcp
+ Server.exe -tr:tcp
**Remarks**:
@@ -75,12 +72,12 @@ Usage:
Client.exe -h
will diplay help information
- Client.exe -t:<transport> -p:<protocol> -mc:<numClients>
+ Client.exe -tr:<transport> -pr:<protocol> -mc:<numClients>
will run client with specified arguments (tcp transport and binary protocol by default)
Options:
- -t (transport):
+ -tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - buffered transport over tcp will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
@@ -88,7 +85,7 @@ Options:
tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
- -p (protocol):
+ -pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
@@ -98,7 +95,7 @@ Options:
Sample:
- Client.exe -t:tcp -p:binary -mc:10
+ Client.exe -tr:tcp -pr:binary -mc:10
Remarks:
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/Server/Program.cs
----------------------------------------------------------------------
diff --git a/tutorial/netcore/Server/Program.cs b/tutorial/netcore/Server/Program.cs
index b8cc02e..6a181ba 100644
--- a/tutorial/netcore/Server/Program.cs
+++ b/tutorial/netcore/Server/Program.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -46,7 +46,7 @@ namespace Server
{
args = args ?? new string[0];
- if (args.Any(x => x.StartsWith("-h", StringComparison.OrdinalIgnoreCase)))
+ if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
@@ -69,14 +69,14 @@ namespace Server
{
Logger.LogInformation(@"
Usage:
- Server.exe -h
+ Server.exe -help
will diplay help information
- Server.exe -t:<transport> -p:<protocol>
+ Server.exe -tr:<transport> -pr:<protocol>
will run server with specified arguments (tcp transport and binary protocol by default)
Options:
- -t (transport):
+ -tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - tcp buffered transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
@@ -84,14 +84,14 @@ Options:
tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
- -p (protocol):
+ -pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
multiplexed - multiplexed protocol will be used
Sample:
- Server.exe -t:tcp
+ Server.exe -tr:tcp
");
}
@@ -112,20 +112,18 @@ Sample:
private static Protocol GetProtocol(string[] args)
{
- var transport = args.FirstOrDefault(x => x.StartsWith("-p"))?.Split(':')?[1];
- Protocol selectedProtocol;
+ var transport = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
- Enum.TryParse(transport, true, out selectedProtocol);
+ Enum.TryParse(transport, true, out Protocol selectedProtocol);
return selectedProtocol;
}
private static Transport GetTransport(string[] args)
{
- var transport = args.FirstOrDefault(x => x.StartsWith("-t"))?.Split(':')?[1];
- Transport selectedTransport;
+ var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
- Enum.TryParse(transport, true, out selectedTransport);
+ Enum.TryParse(transport, true, out Transport selectedTransport);
return selectedTransport;
}
@@ -288,11 +286,10 @@ Sample:
.UseKestrel()
.UseUrls("http://localhost:9090")
.UseContentRoot(Directory.GetCurrentDirectory())
- .UseIISIntegration()
.UseStartup<Startup>()
.Build();
- host.StartAsync(cancellationToken); // was Run() in earlier .NET Core SDKs?
+ host.RunAsync(cancellationToken).GetAwaiter().GetResult();
}
public class Startup
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/Tutorial.sln
----------------------------------------------------------------------
diff --git a/tutorial/netcore/Tutorial.sln b/tutorial/netcore/Tutorial.sln
index bff110c..2ddcd46 100644
--- a/tutorial/netcore/Tutorial.sln
+++ b/tutorial/netcore/Tutorial.sln
@@ -1,68 +1,78 @@
-
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26114.2
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Thrift", "..\..\lib\netcore\Thrift\Thrift.csproj", "{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "..\..\lib\netcore\Thrift\Thrift.csproj", "{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interfaces", "Interfaces\Interfaces.csproj", "{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Interfaces", "Interfaces\Interfaces.csproj", "{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client", "Client\Client.csproj", "{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "Client\Client.csproj", "{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Server\Server.csproj", "{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Server", "Server\Server.csproj", "{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {6850CF46-5467-4C65-BD78-871581C539FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {6850CF46-5467-4C65-BD78-871581C539FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {6850CF46-5467-4C65-BD78-871581C539FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {6850CF46-5467-4C65-BD78-871581C539FC}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.Build.0 = Debug|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x86.Build.0 = Debug|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.ActiveCfg = Release|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.Build.0 = Release|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.ActiveCfg = Release|Any CPU
+ {C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.Build.0 = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.ActiveCfg = Debug|x64
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.Build.0 = Debug|x64
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.ActiveCfg = Debug|x86
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.Build.0 = Debug|x86
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x64.Build.0 = Debug|Any CPU
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Debug|x86.Build.0 = Debug|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|Any CPU.Build.0 = Release|Any CPU
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.ActiveCfg = Release|x64
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.Build.0 = Release|x64
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.ActiveCfg = Release|x86
- {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.Build.0 = Release|x86
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.ActiveCfg = Release|Any CPU
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x64.Build.0 = Release|Any CPU
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.ActiveCfg = Release|Any CPU
+ {B9E24D84-2712-4158-8F1A-DDE44CD1BB0A}.Release|x86.Build.0 = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.ActiveCfg = Debug|x64
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.Build.0 = Debug|x64
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.ActiveCfg = Debug|x86
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.Build.0 = Debug|x86
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x64.Build.0 = Debug|Any CPU
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Debug|x86.Build.0 = Debug|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|Any CPU.Build.0 = Release|Any CPU
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.ActiveCfg = Release|x64
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.Build.0 = Release|x64
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.ActiveCfg = Release|x86
- {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.Build.0 = Release|x86
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.ActiveCfg = Release|Any CPU
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x64.Build.0 = Release|Any CPU
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.ActiveCfg = Release|Any CPU
+ {E4CA1EF0-B181-4A5D-A02C-DB0750A59CDF}.Release|x86.Build.0 = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.ActiveCfg = Debug|x64
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.Build.0 = Debug|x64
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.ActiveCfg = Debug|x86
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.Build.0 = Debug|x86
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x64.Build.0 = Debug|Any CPU
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Debug|x86.Build.0 = Debug|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|Any CPU.Build.0 = Release|Any CPU
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.ActiveCfg = Release|x64
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.Build.0 = Release|x64
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.ActiveCfg = Release|x86
- {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.Build.0 = Release|x86
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.ActiveCfg = Release|Any CPU
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x64.Build.0 = Release|Any CPU
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.ActiveCfg = Release|Any CPU
+ {E08F5B84-2B4A-4E09-82D1-E0715775CE5E}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {070A5D1D-B29D-4603-999D-693DB444AD0D}
+ EndGlobalSection
EndGlobal
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/build.cmd
----------------------------------------------------------------------
diff --git a/tutorial/netcore/build.cmd b/tutorial/netcore/build.cmd
index e971799..9b84ef2 100644
--- a/tutorial/netcore/build.cmd
+++ b/tutorial/netcore/build.cmd
@@ -19,12 +19,7 @@ rem * under the License.
rem */
setlocal
-cd Interfaces
-thrift -gen netcore:wcf -r ..\..\tutorial.thrift
-cd ..
-
dotnet --info
-dotnet restore
dotnet build
:eof
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/tutorial/netcore/build.sh
----------------------------------------------------------------------
diff --git a/tutorial/netcore/build.sh b/tutorial/netcore/build.sh
index d2cb465..c97e310 100755
--- a/tutorial/netcore/build.sh
+++ b/tutorial/netcore/build.sh
@@ -22,10 +22,5 @@
#exit if any command fails
set -e
-cd Interfaces
-../../../compiler/cpp/thrift -gen netcore:wcf -r ../../tutorial.thrift
-cd ..
-
dotnet --info
-dotnet restore
dotnet build
[9/9] thrift git commit: THRIFT-4344: some docker updates for xenial
and for trusty to fix build issues
Posted by jk...@apache.org.
THRIFT-4344: some docker updates for xenial and for trusty to fix build issues
Project: http://git-wip-us.apache.org/repos/asf/thrift/repo
Commit: http://git-wip-us.apache.org/repos/asf/thrift/commit/ad238522
Tree: http://git-wip-us.apache.org/repos/asf/thrift/tree/ad238522
Diff: http://git-wip-us.apache.org/repos/asf/thrift/diff/ad238522
Branch: refs/heads/master
Commit: ad238522946a69ebebb310e2e8e9479a3f6a613c
Parents: b56fc70
Author: James E. King III <jk...@apache.org>
Authored: Sat Jan 13 19:52:31 2018 -0500
Committer: James E. King III <jk...@apache.org>
Committed: Sun Jan 14 08:42:28 2018 -0500
----------------------------------------------------------------------
build/docker/README.md | 12 ++++++------
build/docker/ubuntu-xenial/Dockerfile | 10 ++++++----
lib/rb/thrift.gemspec | 2 +-
3 files changed, 13 insertions(+), 11 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/thrift/blob/ad238522/build/docker/README.md
----------------------------------------------------------------------
diff --git a/build/docker/README.md b/build/docker/README.md
index a8d9501..4b59e03 100644
--- a/build/docker/README.md
+++ b/build/docker/README.md
@@ -134,25 +134,24 @@ Last updated: October 1, 2017
## Compiler/Language Versions per Dockerfile ##
-Last updated: October 1, 2017
-
| Language | ubuntu-trusty | ubuntu-xenial | ubuntu-artful | Notes |
| :-------- | :------------ | :------------ | :------------ | :---- |
+| as of | Oct 01, 2017 | Jan 11, 2018 | Oct 01, 2017 | |
| as3 | | | | Not in CI |
| C++ gcc | 4.8.4 | 5.4.0 | 7.2.0 | |
| C++ clang | 3.4 | 3.8 | 4.0 | |
-| C# (mono) | 3.2.8.0 | 4.2.1 | 4.6.2.7 | |
+| C# (mono) | 3.2.8.0 | 4.2.1.0 | 4.6.2.7 | |
| c_glib | 2.40.2 | 2.48.2 | 2.54.0 | |
| cocoa | | | | Not in CI |
| d | 2.070.2 | 2.073.2 | 2.076.0 | |
-| dart | 1.20.1 | 1.24.2 | 1.24.2 | |
+| dart | 1.20.1 | 1.22.1 | 1.24.2 | |
| delphi | | | | Not in CI |
| dotnet | | 2.0.3 | 2.0.3 | |
| erlang | R16B03 | 18.3 | 20.0.4 | |
| go | 1.2.1 | 1.6.2 | 1.8.3 | |
| haskell | 7.6.3 | 7.10.3 | 8.0.2 | |
| haxe | | 3.2.1 | 3.4.2 | disabled in trusty builds - cores on install v3.0.0, disabled in artful builds - see THRIFT-4352 |
-| java | 1.7.0_151 | 1.8.0_131 | 1.8.0_151 | |
+| java | 1.7.0_151 | 1.8.0_151 | 1.8.0_151 | |
| js | | | | Unsure how to look for version info? |
| lua | 5.1.5 | 5.2.4 | 5.2.4 | Lua 5.3: see THRIFT-4386 |
| nodejs | | 4.2.6 | 8.9.1 | trusty has node.js 0.10.0 which is too old |
@@ -162,7 +161,8 @@ Last updated: October 1, 2017
| python | 2.7.6 | 2.7.12 | 2.7.14 | |
| python3 | 3.4.3 | 3.5.2 | 3.6.3 | |
| ruby | 1.9.3p484 | 2.3.1p112 | 2.3.3p222 | |
-| rust | 1.15.1 | 1.15.1 | 1.18.0 | |
+| rust | 1.15.1 | 1.17.0 | 1.18.0 | |
| smalltalk | | | | Not in CI |
| swift | | | | Not in CI |
+
http://git-wip-us.apache.org/repos/asf/thrift/blob/ad238522/build/docker/ubuntu-xenial/Dockerfile
----------------------------------------------------------------------
diff --git a/build/docker/ubuntu-xenial/Dockerfile b/build/docker/ubuntu-xenial/Dockerfile
index a254a14..acf3d12 100644
--- a/build/docker/ubuntu-xenial/Dockerfile
+++ b/build/docker/ubuntu-xenial/Dockerfile
@@ -34,6 +34,7 @@ RUN apt-get update && \
apt-transport-https \
apt-utils \
curl \
+ software-properties-common \
wget
# csharp (mono)
@@ -41,7 +42,8 @@ RUN apt-get update && \
# apt-key adv --keyserver keyserver.ubuntu.com --recv-keys A6A19B38D3D831EF
# D
-RUN wget http://master.dl.sourceforge.net/project/d-apt/files/d-apt.list -O /etc/apt/sources.list.d/d-apt.list && \
+RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EBCF975E5BA24D5E && \
+ wget http://master.dl.sourceforge.net/project/d-apt/files/d-apt.list -O /etc/apt/sources.list.d/d-apt.list && \
wget -qO - https://dlang.org/d-keyring.gpg | apt-key add -
ENV D_VERSION 2.073.2-0
@@ -49,7 +51,7 @@ ENV D_VERSION 2.073.2-0
RUN curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \
curl https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > \
/etc/apt/sources.list.d/dart_stable.list
-ENV DART_VERSION 1.24.2-1
+ENV DART_VERSION 1.22.1-1
# dotnet (core)
RUN curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /etc/apt/trusted.gpg.d/microsoft.gpg && \
@@ -152,8 +154,8 @@ RUN apt-get install -y --no-install-recommends \
haxe \
neko \
neko-dev \
- libneko0
-RUN haxelib setup --always /usr/share/haxe/lib && \
+ libneko0 && \
+ haxelib setup --always /usr/share/haxe/lib && \
haxelib install --quiet --always hxcpp 3.4.64
# note: hxcpp 3.4.185 (latest) no longer ships static libraries, and caused a build failure
http://git-wip-us.apache.org/repos/asf/thrift/blob/ad238522/lib/rb/thrift.gemspec
----------------------------------------------------------------------
diff --git a/lib/rb/thrift.gemspec b/lib/rb/thrift.gemspec
index 166a93f..c2533fd 100644
--- a/lib/rb/thrift.gemspec
+++ b/lib/rb/thrift.gemspec
@@ -29,7 +29,7 @@ Gem::Specification.new do |s|
s.add_development_dependency 'rspec', ['>= 2.10.0', '< 2.14.0']
s.add_development_dependency "rack", "~> 1.5"
- s.add_development_dependency "rack-test", "~> 0.6"
+ s.add_development_dependency "rack-test", "< 0.8.0" # until we no longer build on trusty, then "~> 0.8.2"
s.add_development_dependency "thin", "~> 1.5"
s.add_development_dependency "bundler", "~> 1"
s.add_development_dependency 'rake', '~> 10.5'
[3/9] thrift git commit: THRIFT-4434: .NET Core cleanup and the
beginnings of compiler unit tests Client: netcore
Posted by jk...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs b/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs
index bc36bb3..16754b2 100644
--- a/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs
+++ b/lib/netcore/Thrift/Transports/Client/THttpClientTransport.cs
@@ -16,11 +16,9 @@
// under the License.
using System;
-using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
-using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
@@ -198,7 +196,7 @@ namespace Thrift.Transports.Client
{
throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString());
}
- catch (WebException wx)
+ catch (HttpRequestException wx)
{
throw new TTransportException(TTransportException.ExceptionType.Unknown,
"Couldn't connect to server: " + wx);
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs b/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs
index a44efe6..e769d14 100644
--- a/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs
+++ b/lib/netcore/Thrift/Transports/Client/TSocketClientTransport.cs
@@ -30,12 +30,7 @@ namespace Thrift.Transports.Client
public TSocketClientTransport(TcpClient client)
{
- if (client == null)
- {
- throw new ArgumentNullException(nameof(client));
- }
-
- TcpClient = client;
+ TcpClient = client ?? throw new ArgumentNullException(nameof(client));
if (IsOpen)
{
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs b/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs
index a21977b..c8be4ed 100644
--- a/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs
+++ b/lib/netcore/Thrift/Transports/Client/TTlsSocketClientTransport.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -57,7 +57,7 @@ namespace Thrift.Transports.Client
if (isServer && certificate == null)
{
throw new ArgumentException("TTlsSocketClientTransport needs certificate to be used for server",
- "certificate");
+ nameof(certificate));
}
if (IsOpen)
@@ -204,7 +204,8 @@ namespace Thrift.Transports.Client
? new X509CertificateCollection {_certificate}
: new X509CertificateCollection();
- await _secureStream.AuthenticateAsClientAsync(_host.ToString(), certs, _sslProtocols, true);
+ var targetHost = _host.ToString();
+ await _secureStream.AuthenticateAsClientAsync(targetHost, certs, _sslProtocols, true);
}
}
catch (Exception)
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs b/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs
index 6073741..032063a 100644
--- a/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs
+++ b/lib/netcore/Thrift/Transports/Server/THttpServerTransport.cs
@@ -53,29 +53,14 @@ namespace Thrift.Transports.Server
public THttpServerTransport(ITAsyncProcessor processor, ITProtocolFactory inputProtocolFactory,
ITProtocolFactory outputProtocolFactory, RequestDelegate next, ILoggerFactory loggerFactory)
{
- if (processor == null)
- {
- throw new ArgumentNullException(nameof(processor));
- }
-
- if (inputProtocolFactory == null)
- {
- throw new ArgumentNullException(nameof(inputProtocolFactory));
- }
-
- if (outputProtocolFactory == null)
- {
- throw new ArgumentNullException(nameof(outputProtocolFactory));
- }
-
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
- Processor = processor;
- InputProtocolFactory = inputProtocolFactory;
- OutputProtocolFactory = outputProtocolFactory;
+ Processor = processor ?? throw new ArgumentNullException(nameof(processor));
+ InputProtocolFactory = inputProtocolFactory ?? throw new ArgumentNullException(nameof(inputProtocolFactory));
+ OutputProtocolFactory = outputProtocolFactory ?? throw new ArgumentNullException(nameof(outputProtocolFactory));
_next = next;
_logger = loggerFactory.CreateLogger<THttpServerTransport>();
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs b/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs
index 01195d4..186786e 100644
--- a/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs
+++ b/lib/netcore/Thrift/Transports/Server/TNamedPipeServerTransport.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs b/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs
index af154ef..3a9d8a1 100644
--- a/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs
+++ b/lib/netcore/Thrift/Transports/Server/TServerSocketTransport.cs
@@ -30,6 +30,7 @@ namespace Thrift.Transports.Server
private readonly int _clientTimeout;
private readonly int _port;
private readonly bool _useBufferedSockets;
+ private readonly bool _useFramedTransport;
private TcpListener _server;
public TServerSocketTransport(TcpListener listener)
@@ -53,11 +54,17 @@ namespace Thrift.Transports.Server
{
}
- public TServerSocketTransport(int port, int clientTimeout, bool useBufferedSockets)
+ public TServerSocketTransport(int port, int clientTimeout, bool useBufferedSockets):
+ this(port, clientTimeout, useBufferedSockets, false)
+ {
+ }
+
+ public TServerSocketTransport(int port, int clientTimeout, bool useBufferedSockets, bool useFramedTransport)
{
_port = port;
_clientTimeout = clientTimeout;
_useBufferedSockets = useBufferedSockets;
+ _useFramedTransport = useFramedTransport;
try
{
// Make server socket
@@ -106,7 +113,7 @@ namespace Thrift.Transports.Server
try
{
- TSocketClientTransport tSocketTransport = null;
+ TClientTransport tSocketTransport = null;
var tcpClient = await _server.AcceptTcpClientAsync();
try
@@ -118,7 +125,12 @@ namespace Thrift.Transports.Server
if (_useBufferedSockets)
{
- return new TBufferedClientTransport(tSocketTransport);
+ tSocketTransport = new TBufferedClientTransport(tSocketTransport);
+ }
+
+ if (_useFramedTransport)
+ {
+ tSocketTransport = new TFramedClientTransport(tSocketTransport);
}
return tSocketTransport;
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs b/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs
index 49abdac..759feed 100644
--- a/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs
+++ b/lib/netcore/Thrift/Transports/Server/TTlsServerSocketTransport.cs
@@ -37,6 +37,7 @@ namespace Thrift.Transports.Server
private readonly X509Certificate2 _serverCertificate;
private readonly SslProtocols _sslProtocols;
private readonly bool _useBufferedSockets;
+ private readonly bool _useFramedTransport;
private TcpListener _server;
public TTlsServerSocketTransport(int port, X509Certificate2 certificate)
@@ -50,6 +51,19 @@ namespace Thrift.Transports.Server
X509Certificate2 certificate,
RemoteCertificateValidationCallback clientCertValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
+ SslProtocols sslProtocols = SslProtocols.Tls12)
+ : this(port, useBufferedSockets, false, certificate,
+ clientCertValidator, localCertificateSelectionCallback, sslProtocols)
+ {
+ }
+
+ public TTlsServerSocketTransport(
+ int port,
+ bool useBufferedSockets,
+ bool useFramedTransport,
+ X509Certificate2 certificate,
+ RemoteCertificateValidationCallback clientCertValidator = null,
+ LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
SslProtocols sslProtocols = SslProtocols.Tls12)
{
if (!certificate.HasPrivateKey)
@@ -61,6 +75,7 @@ namespace Thrift.Transports.Server
_port = port;
_serverCertificate = certificate;
_useBufferedSockets = useBufferedSockets;
+ _useFramedTransport = useFramedTransport;
_clientCertValidator = clientCertValidator;
_localCertificateSelectionCallback = localCertificateSelectionCallback;
_sslProtocols = sslProtocols;
@@ -122,13 +137,19 @@ namespace Thrift.Transports.Server
await tTlsSocket.SetupTlsAsync();
+ TClientTransport trans = tTlsSocket;
+
if (_useBufferedSockets)
{
- var trans = new TBufferedClientTransport(tTlsSocket);
- return trans;
+ trans = new TBufferedClientTransport(trans);
}
- return tTlsSocket;
+ if (_useFramedTransport)
+ {
+ trans = new TFramedClientTransport(trans);
+ }
+
+ return trans;
}
catch (Exception ex)
{
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/TClientTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/TClientTransport.cs b/lib/netcore/Thrift/Transports/TClientTransport.cs
index cee0a00..0dd96cb 100644
--- a/lib/netcore/Thrift/Transports/TClientTransport.cs
+++ b/lib/netcore/Thrift/Transports/TClientTransport.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -26,6 +26,7 @@ namespace Thrift.Transports
// ReSharper disable once InconsistentNaming
public abstract class TClientTransport : IDisposable
{
+ //TODO: think how to avoid peek byte
private readonly byte[] _peekBuffer = new byte[1];
private bool _hasPeekByte;
public abstract bool IsOpen { get; }
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/TServerTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/TServerTransport.cs b/lib/netcore/Thrift/Transports/TServerTransport.cs
index d49feb6..0d45a55 100644
--- a/lib/netcore/Thrift/Transports/TServerTransport.cs
+++ b/lib/netcore/Thrift/Transports/TServerTransport.cs
@@ -45,7 +45,7 @@ namespace Thrift.Transports
if (transport == null)
{
- throw new TTransportException("AcceptAsync() should not return null");
+ throw new TTransportException($"{nameof(AcceptImplementationAsync)} should not return null");
}
return transport;
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/build.cmd
----------------------------------------------------------------------
diff --git a/lib/netcore/build.cmd b/lib/netcore/build.cmd
new file mode 100644
index 0000000..863c4b4
--- /dev/null
+++ b/lib/netcore/build.cmd
@@ -0,0 +1,27 @@
+@echo off
+rem /*
+rem * Licensed to the Apache Software Foundation (ASF) under one
+rem * or more contributor license agreements. See the NOTICE file
+rem * distributed with this work for additional information
+rem * regarding copyright ownership. The ASF licenses this file
+rem * to you under the Apache License, Version 2.0 (the
+rem * "License"); you may not use this file except in compliance
+rem * with the License. You may obtain a copy of the License at
+rem *
+rem * http://www.apache.org/licenses/LICENSE-2.0
+rem *
+rem * Unless required by applicable law or agreed to in writing,
+rem * software distributed under the License is distributed on an
+rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+rem * KIND, either express or implied. See the License for the
+rem * specific language governing permissions and limitations
+rem * under the License.
+rem */
+
+setlocal
+
+thrift -version
+dotnet --info
+dotnet build
+
+:eof
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/build.sh
----------------------------------------------------------------------
diff --git a/lib/netcore/build.sh b/lib/netcore/build.sh
new file mode 100644
index 0000000..ae18bce
--- /dev/null
+++ b/lib/netcore/build.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+#exit if any command fails
+#set -e
+
+thrift --version
+dotnet --info
+dotnet build
+
+#revision=${TRAVIS_JOB_ID:=1}
+#revision=$(printf "%04d" $revision)
+
+#dotnet pack ./src/PROJECT_NAME -c Release -o ./artifacts --version-suffix=$revision
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/runtests.cmd
----------------------------------------------------------------------
diff --git a/lib/netcore/runtests.cmd b/lib/netcore/runtests.cmd
new file mode 100644
index 0000000..5114bc5
--- /dev/null
+++ b/lib/netcore/runtests.cmd
@@ -0,0 +1,28 @@
+@echo off
+rem /*
+rem * Licensed to the Apache Software Foundation (ASF) under one
+rem * or more contributor license agreements. See the NOTICE file
+rem * distributed with this work for additional information
+rem * regarding copyright ownership. The ASF licenses this file
+rem * to you under the Apache License, Version 2.0 (the
+rem * "License"); you may not use this file except in compliance
+rem * with the License. You may obtain a copy of the License at
+rem *
+rem * http://www.apache.org/licenses/LICENSE-2.0
+rem *
+rem * Unless required by applicable law or agreed to in writing,
+rem * software distributed under the License is distributed on an
+rem * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+rem * KIND, either express or implied. See the License for the
+rem * specific language governing permissions and limitations
+rem * under the License.
+rem */
+setlocal
+
+thrift -version
+dotnet --info
+
+dotnet test Tests\Thrift.IntegrationTests\Thrift.IntegrationTests.csproj
+dotnet test Tests\Thrift.Tests\Thrift.Tests.csproj
+
+:eof
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/runtests.sh
----------------------------------------------------------------------
diff --git a/lib/netcore/runtests.sh b/lib/netcore/runtests.sh
new file mode 100644
index 0000000..a26cc36
--- /dev/null
+++ b/lib/netcore/runtests.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+thrift -version
+dotnet --info
+
+dotnet test Tests\Thrift.IntegrationTests\Thrift.IntegrationTests.csproj
+dotnet test Tests\Thrift.Tests\Thrift.Tests.csproj
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/ThriftTest.thrift
----------------------------------------------------------------------
diff --git a/test/ThriftTest.thrift b/test/ThriftTest.thrift
index 24dcbb9..bff4e52 100644
--- a/test/ThriftTest.thrift
+++ b/test/ThriftTest.thrift
@@ -37,7 +37,7 @@ namespace delphi Thrift.Test
namespace cocoa ThriftTest
namespace lua ThriftTest
namespace xsd test (uri = 'http://thrift.apache.org/ns/ThriftTest')
-namespace netcore ThriftAsync.Test
+namespace netcore ThriftTest
// Presence of namespaces and sub-namespaces for which there is
// no generator should compile with warnings only
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/csharp/TestClient.cs
----------------------------------------------------------------------
diff --git a/test/csharp/TestClient.cs b/test/csharp/TestClient.cs
index 17e5978..949c06e 100644
--- a/test/csharp/TestClient.cs
+++ b/test/csharp/TestClient.cs
@@ -62,7 +62,9 @@ namespace Test
{
string certPath = "../keys/client.p12";
X509Certificate cert = new X509Certificate2(certPath, "thrift");
- trans = new TTLSSocket(host, port, 0, cert, (o, c, chain, errors) => true, null, SslProtocols.Tls);
+ trans = new TTLSSocket(host, port, 0, cert,
+ (o, c, chain, errors) => true,
+ null, SslProtocols.Tls);
}
else
{
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/csharp/TestServer.cs
----------------------------------------------------------------------
diff --git a/test/csharp/TestServer.cs b/test/csharp/TestServer.cs
index e9c7168..bf645c2 100644
--- a/test/csharp/TestServer.cs
+++ b/test/csharp/TestServer.cs
@@ -455,7 +455,9 @@ namespace Test
if (useEncryption)
{
string certPath = "../keys/server.p12";
- trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"), null, null, SslProtocols.Tls);
+ trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"),
+ null,
+ null, SslProtocols.Tls);
}
else
{
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/features/known_failures_Linux.json
----------------------------------------------------------------------
diff --git a/test/features/known_failures_Linux.json b/test/features/known_failures_Linux.json
index f96356d..6d1ed1f 100644
--- a/test/features/known_failures_Linux.json
+++ b/test/features/known_failures_Linux.json
@@ -1,46 +1,48 @@
[
- "c_glib-limit_container_length_binary_buffered-ip",
- "c_glib-limit_string_length_binary_buffered-ip",
- "cpp-theader_framed_binary_multih-header_buffered-ip",
- "cpp-theader_framed_compact_multih-header_buffered-ip",
- "cpp-theader_unframed_binary_multih-header_buffered-ip",
- "cpp-theader_unframed_compact_multih-header_buffered-ip",
- "csharp-limit_container_length_binary_buffered-ip",
- "csharp-limit_container_length_compact_buffered-ip",
- "csharp-limit_string_length_binary_buffered-ip",
- "csharp-limit_string_length_compact_buffered-ip",
- "d-limit_container_length_binary_buffered-ip",
- "d-limit_container_length_compact_buffered-ip",
- "d-limit_string_length_binary_buffered-ip",
- "d-limit_string_length_compact_buffered-ip",
- "erl-limit_container_length_binary_buffered-ip",
- "erl-limit_container_length_compact_buffered-ip",
- "erl-limit_string_length_binary_buffered-ip",
- "erl-limit_string_length_compact_buffered-ip",
- "go-limit_container_length_binary_buffered-ip",
- "go-limit_container_length_compact_buffered-ip",
- "go-limit_string_length_binary_buffered-ip",
- "go-limit_string_length_compact_buffered-ip",
- "hs-limit_container_length_binary_buffered-ip",
- "hs-limit_container_length_compact_buffered-ip",
- "hs-limit_string_length_binary_buffered-ip",
- "hs-limit_string_length_compact_buffered-ip",
- "nodejs-limit_container_length_binary_buffered-ip",
- "nodejs-limit_container_length_compact_buffered-ip",
- "nodejs-limit_string_length_binary_buffered-ip",
- "nodejs-limit_string_length_compact_buffered-ip",
- "perl-limit_container_length_binary_buffered-ip",
- "perl-limit_string_length_binary_buffered-ip",
- "rb-limit_container_length_accel-binary_buffered-ip",
- "rb-limit_container_length_binary_buffered-ip",
- "rb-limit_container_length_compact_buffered-ip",
- "rb-limit_string_length_accel-binary_buffered-ip",
- "rb-limit_string_length_binary_buffered-ip",
- "rb-limit_string_length_compact_buffered-ip",
- "rs-limit_container_length_binary_buffered-ip",
- "rs-limit_container_length_compact_buffered-ip",
- "rs-limit_container_length_multic-compact_buffered-ip",
- "rs-limit_string_length_binary_buffered-ip",
- "rs-limit_string_length_compact_buffered-ip",
- "rs-limit_string_length_multic-compact_buffered-ip"
+ "c_glib-limit_container_length_binary_buffered-ip",
+ "c_glib-limit_string_length_binary_buffered-ip",
+ "cpp-theader_framed_binary_multih-header_buffered-ip",
+ "cpp-theader_framed_compact_multih-header_buffered-ip",
+ "cpp-theader_unframed_binary_multih-header_buffered-ip",
+ "cpp-theader_unframed_compact_multih-header_buffered-ip",
+ "csharp-limit_container_length_binary_buffered-ip",
+ "csharp-limit_container_length_compact_buffered-ip",
+ "csharp-limit_string_length_binary_buffered-ip",
+ "csharp-limit_string_length_compact_buffered-ip",
+ "d-limit_container_length_binary_buffered-ip",
+ "d-limit_container_length_compact_buffered-ip",
+ "d-limit_string_length_binary_buffered-ip",
+ "d-limit_string_length_compact_buffered-ip",
+ "erl-limit_container_length_binary_buffered-ip",
+ "erl-limit_container_length_compact_buffered-ip",
+ "erl-limit_string_length_binary_buffered-ip",
+ "erl-limit_string_length_compact_buffered-ip",
+ "go-limit_container_length_binary_buffered-ip",
+ "go-limit_container_length_compact_buffered-ip",
+ "go-limit_string_length_binary_buffered-ip",
+ "go-limit_string_length_compact_buffered-ip",
+ "hs-limit_container_length_binary_buffered-ip",
+ "hs-limit_container_length_compact_buffered-ip",
+ "hs-limit_string_length_binary_buffered-ip",
+ "hs-limit_string_length_compact_buffered-ip",
+ "nodejs-limit_container_length_binary_buffered-ip",
+ "nodejs-limit_container_length_compact_buffered-ip",
+ "nodejs-limit_string_length_binary_buffered-ip",
+ "nodejs-limit_string_length_compact_buffered-ip",
+ "perl-limit_container_length_binary_buffered-ip",
+ "perl-limit_string_length_binary_buffered-ip",
+ "rb-limit_container_length_accel-binary_buffered-ip",
+ "rb-limit_container_length_binary_buffered-ip",
+ "rb-limit_container_length_compact_buffered-ip",
+ "rb-limit_string_length_accel-binary_buffered-ip",
+ "rb-limit_string_length_binary_buffered-ip",
+ "rb-limit_string_length_compact_buffered-ip",
+ "rs-limit_container_length_binary_buffered-ip",
+ "rs-limit_container_length_compact_buffered-ip",
+ "rs-limit_container_length_multic-compact_buffered-ip",
+ "rs-limit_string_length_binary_buffered-ip",
+ "rs-limit_string_length_compact_buffered-ip",
+ "rs-limit_string_length_multic-compact_buffered-ip",
+ "netcore-limit_string_length_compact_buffered-ip",
+ "netcore-limit_container_length_compact_buffered-ip"
]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/known_failures_Linux.json
----------------------------------------------------------------------
diff --git a/test/known_failures_Linux.json b/test/known_failures_Linux.json
index 658577d..a142796 100644
--- a/test/known_failures_Linux.json
+++ b/test/known_failures_Linux.json
@@ -215,6 +215,12 @@
"java-d_compact_buffered-ip",
"java-d_compact_buffered-ip-ssl",
"java-d_compact_framed-ip",
+ "netcore-csharp_binary_buffered-ip-ssl",
+ "netcore-csharp_binary_framed-ip-ssl",
+ "netcore-csharp_json_framed-ip-ssl",
+ "netcore-csharp_json_buffered-ip-ssl",
+ "netcore-csharp_compact_buffered-ip-ssl",
+ "netcore-csharp_compact_framed-ip-ssl",
"nodejs-cpp_binary_http-ip",
"nodejs-cpp_binary_http-ip-ssl",
"nodejs-cpp_compact_http-ip",
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Client/.gitignore
----------------------------------------------------------------------
diff --git a/test/netcore/Client/.gitignore b/test/netcore/Client/.gitignore
new file mode 100644
index 0000000..67d5510
--- /dev/null
+++ b/test/netcore/Client/.gitignore
@@ -0,0 +1,2 @@
+# ignore for autogenerated files
+/ThriftTest
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Client/Client.csproj
----------------------------------------------------------------------
diff --git a/test/netcore/Client/Client.csproj b/test/netcore/Client/Client.csproj
new file mode 100644
index 0000000..4b31a7d
--- /dev/null
+++ b/test/netcore/Client/Client.csproj
@@ -0,0 +1,31 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>netcoreapp2.0</TargetFramework>
+ <AssemblyName>Client</AssemblyName>
+ <PackageId>Client</PackageId>
+ <OutputType>Exe</OutputType>
+ <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
+ <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
+ <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
+ <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
+ <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
+ <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="System.Net.Http.WinHttpHandler" Version="[4.4,)" />
+ <PackageReference Include="System.Runtime.Serialization.Primitives" Version="[4.3,)" />
+ <PackageReference Include="System.ServiceModel.Primitives" Version="[4.4,)" />
+ <PackageReference Include="System.Threading" Version="[4.3,)" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\..\lib\netcore\Thrift\Thrift.csproj" />
+ </ItemGroup>
+ <Target Name="PreBuild" BeforeTargets="_GenerateRestoreProjectSpec;Restore;Compile">
+ <Exec Condition="'$(OS)' == 'Windows_NT'" Command="where thrift" ConsoleToMSBuild="true">
+ <Output TaskParameter="ConsoleOutput" PropertyName="PathToThrift" />
+ </Exec>
+ <Exec Condition="Exists('$(PathToThrift)')" Command="$(PathToThrift) -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
+ <Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
+ <Exec Condition="Exists('$(ProjectDir)/../../../compiler/cpp/thrift')" Command="$(ProjectDir)/../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
+ </Target>
+</Project>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Client/Program.cs
----------------------------------------------------------------------
diff --git a/test/netcore/Client/Program.cs b/test/netcore/Client/Program.cs
new file mode 100644
index 0000000..72139d9
--- /dev/null
+++ b/test/netcore/Client/Program.cs
@@ -0,0 +1,72 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using ThriftTest;
+
+namespace Client
+{
+ public class Program
+ {
+ public static int Main(string[] args)
+ {
+ try
+ {
+ Console.SetBufferSize(Console.BufferWidth, 4096);
+ }
+ catch (Exception)
+ {
+ Console.WriteLine("Failed to grow scroll-back buffer");
+ }
+
+ // split mode and options
+ var subArgs = new List<string>(args);
+ var firstArg = string.Empty;
+ if (subArgs.Count > 0)
+ {
+ firstArg = subArgs[0];
+ subArgs.RemoveAt(0);
+ }
+
+ // run whatever mode is choosen
+ switch(firstArg)
+ {
+ case "client":
+ return TestClient.Execute(subArgs);
+ case "--help":
+ PrintHelp();
+ return 0;
+ default:
+ PrintHelp();
+ return -1;
+ }
+ }
+
+ private static void PrintHelp()
+ {
+ Console.WriteLine("Usage:");
+ Console.WriteLine(" Client client [options]'");
+ Console.WriteLine(" Client --help");
+ Console.WriteLine("");
+
+ TestClient.PrintOptionsHelp();
+ }
+ }
+}
+
+
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Client/Properties/AssemblyInfo.cs
----------------------------------------------------------------------
diff --git a/test/netcore/Client/Properties/AssemblyInfo.cs b/test/netcore/Client/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..157152b
--- /dev/null
+++ b/test/netcore/Client/Properties/AssemblyInfo.cs
@@ -0,0 +1,43 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+
+[assembly: AssemblyTitle("Client")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("The Apache Software Foundation")]
+[assembly: AssemblyProduct("Thrift")]
+[assembly: AssemblyCopyright("The Apache Software Foundation")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+
+[assembly: Guid("B0C13DA0-3117-4844-8AE8-B1775E46223D")]
+
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Client/TestClient.cs
----------------------------------------------------------------------
diff --git a/test/netcore/Client/TestClient.cs b/test/netcore/Client/TestClient.cs
new file mode 100644
index 0000000..8be198c
--- /dev/null
+++ b/test/netcore/Client/TestClient.cs
@@ -0,0 +1,943 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Reflection;
+using System.Security.Authentication;
+using System.Security.Cryptography.X509Certificates;
+using System.ServiceModel;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Thrift.Collections;
+using Thrift.Protocols;
+using Thrift.Transports;
+using Thrift.Transports.Client;
+
+namespace ThriftTest
+{
+ public class TestClient
+ {
+ private class TestParams
+ {
+ public int numIterations = 1;
+ public IPAddress host = IPAddress.Any;
+ public int port = 9090;
+ public int numThreads = 1;
+ public string url;
+ public string pipe;
+ public bool buffered;
+ public bool framed;
+ public string protocol;
+ public bool encrypted = false;
+
+ internal void Parse( List<string> args)
+ {
+ for (var i = 0; i < args.Count; ++i)
+ {
+ if (args[i] == "-u")
+ {
+ url = args[++i];
+ }
+ else if (args[i] == "-n")
+ {
+ numIterations = Convert.ToInt32(args[++i]);
+ }
+ else if (args[i].StartsWith("--pipe="))
+ {
+ pipe = args[i].Substring(args[i].IndexOf("=") + 1);
+ Console.WriteLine("Using named pipes transport");
+ }
+ else if (args[i].StartsWith("--host="))
+ {
+ // check there for ipaddress
+ host = new IPAddress(Encoding.Unicode.GetBytes(args[i].Substring(args[i].IndexOf("=") + 1)));
+ }
+ else if (args[i].StartsWith("--port="))
+ {
+ port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
+ }
+ else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
+ {
+ buffered = true;
+ Console.WriteLine("Using buffered sockets");
+ }
+ else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
+ {
+ framed = true;
+ Console.WriteLine("Using framed transport");
+ }
+ else if (args[i] == "-t")
+ {
+ numThreads = Convert.ToInt32(args[++i]);
+ }
+ else if (args[i] == "--binary" || args[i] == "--protocol=binary")
+ {
+ protocol = "binary";
+ Console.WriteLine("Using binary protocol");
+ }
+ else if (args[i] == "--compact" || args[i] == "--protocol=compact")
+ {
+ protocol = "compact";
+ Console.WriteLine("Using compact protocol");
+ }
+ else if (args[i] == "--json" || args[i] == "--protocol=json")
+ {
+ protocol = "json";
+ Console.WriteLine("Using JSON protocol");
+ }
+ else if (args[i] == "--ssl")
+ {
+ encrypted = true;
+ Console.WriteLine("Using encrypted transport");
+ }
+ else
+ {
+ //throw new ArgumentException(args[i]);
+ }
+ }
+ }
+
+ private static X509Certificate2 GetClientCert()
+ {
+ var clientCertName = "client.p12";
+ var possiblePaths = new List<string>
+ {
+ "../../../keys/",
+ "../../keys/",
+ "../keys/",
+ "keys/",
+ };
+
+ string existingPath = null;
+ foreach (var possiblePath in possiblePaths)
+ {
+ var path = Path.GetFullPath(possiblePath + clientCertName);
+ if (File.Exists(path))
+ {
+ existingPath = path;
+ break;
+ }
+ }
+
+ if (string.IsNullOrEmpty(existingPath))
+ {
+ throw new FileNotFoundException($"Cannot find file: {clientCertName}");
+ }
+
+ var cert = new X509Certificate2(existingPath, "thrift");
+
+ return cert;
+ }
+
+ public TClientTransport CreateTransport()
+ {
+ if (url == null)
+ {
+ // endpoint transport
+ TClientTransport trans = null;
+
+ if (pipe != null)
+ {
+ trans = new TNamedPipeClientTransport(pipe);
+ }
+ else
+ {
+ if (encrypted)
+ {
+ var cert = GetClientCert();
+
+ if (cert == null || !cert.HasPrivateKey)
+ {
+ throw new InvalidOperationException("Certificate doesn't contain private key");
+ }
+
+ trans = new TTlsSocketClientTransport(host, port, 0, cert,
+ (sender, certificate, chain, errors) => true,
+ null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
+ }
+ else
+ {
+ trans = new TSocketClientTransport(host, port);
+ }
+ }
+
+ // layered transport
+ if (buffered)
+ {
+ trans = new TBufferedClientTransport(trans);
+ }
+
+ if (framed)
+ {
+ trans = new TFramedClientTransport(trans);
+ }
+
+ return trans;
+ }
+
+ return new THttpClientTransport(new Uri(url), null);
+ }
+
+ public TProtocol CreateProtocol(TClientTransport transport)
+ {
+ if (protocol == "compact")
+ {
+ return new TCompactProtocol(transport);
+ }
+
+ if (protocol == "json")
+ {
+ return new TJsonProtocol(transport);
+ }
+
+ return new TBinaryProtocol(transport);
+ }
+ }
+
+
+ private const int ErrorBaseTypes = 1;
+ private const int ErrorStructs = 2;
+ private const int ErrorContainers = 4;
+ private const int ErrorExceptions = 8;
+ private const int ErrorUnknown = 64;
+
+ private class ClientTest
+ {
+ private readonly TClientTransport transport;
+ private readonly ThriftTest.Client client;
+ private readonly int numIterations;
+ private bool done;
+
+ public int ReturnCode { get; set; }
+
+ public ClientTest(TestParams param)
+ {
+ transport = param.CreateTransport();
+ client = new ThriftTest.Client(param.CreateProtocol(transport));
+ numIterations = param.numIterations;
+ }
+
+ public void Execute()
+ {
+ var token = CancellationToken.None;
+
+ if (done)
+ {
+ Console.WriteLine("Execute called more than once");
+ throw new InvalidOperationException();
+ }
+
+ for (var i = 0; i < numIterations; i++)
+ {
+ try
+ {
+ if (!transport.IsOpen)
+ {
+ transport.OpenAsync(token).GetAwaiter().GetResult();
+ }
+ }
+ catch (TTransportException ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ Console.WriteLine("Connect failed: " + ex.Message);
+ ReturnCode |= ErrorUnknown;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ continue;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ Console.WriteLine("Connect failed: " + ex.Message);
+ ReturnCode |= ErrorUnknown;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ continue;
+ }
+
+ try
+ {
+ ReturnCode |= ExecuteClientTestAsync(client).GetAwaiter().GetResult(); ;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ ReturnCode |= ErrorUnknown;
+ }
+ }
+ try
+ {
+ transport.Close();
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("Error while closing transport");
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+ done = true;
+ }
+ }
+
+ internal static void PrintOptionsHelp()
+ {
+ Console.WriteLine("Client options:");
+ Console.WriteLine(" -u <URL>");
+ Console.WriteLine(" -t <# of threads to run> default = 1");
+ Console.WriteLine(" -n <# of iterations> per thread");
+ Console.WriteLine(" --pipe=<pipe name>");
+ Console.WriteLine(" --host=<IP address>");
+ Console.WriteLine(" --port=<port number>");
+ Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
+ Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
+ Console.WriteLine(" --ssl");
+ Console.WriteLine();
+ }
+
+ public static int Execute(List<string> args)
+ {
+ try
+ {
+ var param = new TestParams();
+
+ try
+ {
+ param.Parse(args);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ Console.WriteLine("Error while parsing arguments");
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ return ErrorUnknown;
+ }
+
+ var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray();
+
+ //issue tests on separate threads simultaneously
+ var threads = tests.Select(test => new Task(test.Execute)).ToArray();
+ var start = DateTime.Now;
+ foreach (var t in threads)
+ {
+ t.Start();
+ }
+
+ Task.WaitAll(threads);
+
+ Console.WriteLine("Total time: " + (DateTime.Now - start));
+ Console.WriteLine();
+ return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
+ }
+ catch (Exception outerEx)
+ {
+ Console.WriteLine("*** FAILED ***");
+ Console.WriteLine("Unexpected error");
+ Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
+ return ErrorUnknown;
+ }
+ }
+
+ public static string BytesToHex(byte[] data)
+ {
+ return BitConverter.ToString(data).Replace("-", string.Empty);
+ }
+
+ public static byte[] PrepareTestData(bool randomDist)
+ {
+ var retval = new byte[0x100];
+ var initLen = Math.Min(0x100, retval.Length);
+
+ // linear distribution, unless random is requested
+ if (!randomDist)
+ {
+ for (var i = 0; i < initLen; ++i)
+ {
+ retval[i] = (byte)i;
+ }
+ return retval;
+ }
+
+ // random distribution
+ for (var i = 0; i < initLen; ++i)
+ {
+ retval[i] = (byte)0;
+ }
+ var rnd = new Random();
+ for (var i = 1; i < initLen; ++i)
+ {
+ while (true)
+ {
+ var nextPos = rnd.Next() % initLen;
+ if (retval[nextPos] == 0)
+ {
+ retval[nextPos] = (byte)i;
+ break;
+ }
+ }
+ }
+ return retval;
+ }
+
+ public static async Task<int> ExecuteClientTestAsync(ThriftTest.Client client)
+ {
+ var token = CancellationToken.None;
+ var returnCode = 0;
+
+ Console.Write("testVoid()");
+ await client.testVoidAsync(token);
+ Console.WriteLine(" = void");
+
+ Console.Write("testString(\"Test\")");
+ var s = await client.testStringAsync("Test", token);
+ Console.WriteLine(" = \"" + s + "\"");
+ if ("Test" != s)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+
+ Console.Write("testBool(true)");
+ var t = await client.testBoolAsync((bool)true, token);
+ Console.WriteLine(" = " + t);
+ if (!t)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+ Console.Write("testBool(false)");
+ var f = await client.testBoolAsync((bool)false, token);
+ Console.WriteLine(" = " + f);
+ if (f)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+
+ Console.Write("testByte(1)");
+ var i8 = await client.testByteAsync((sbyte)1, token);
+ Console.WriteLine(" = " + i8);
+ if (1 != i8)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+
+ Console.Write("testI32(-1)");
+ var i32 = await client.testI32Async(-1, token);
+ Console.WriteLine(" = " + i32);
+ if (-1 != i32)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+
+ Console.Write("testI64(-34359738368)");
+ var i64 = await client.testI64Async(-34359738368, token);
+ Console.WriteLine(" = " + i64);
+ if (-34359738368 != i64)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+
+ // TODO: Validate received message
+ Console.Write("testDouble(5.325098235)");
+ var dub = await client.testDoubleAsync(5.325098235, token);
+ Console.WriteLine(" = " + dub);
+ if (5.325098235 != dub)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+ Console.Write("testDouble(-0.000341012439638598279)");
+ dub = await client.testDoubleAsync(-0.000341012439638598279, token);
+ Console.WriteLine(" = " + dub);
+ if (-0.000341012439638598279 != dub)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+
+ var binOut = PrepareTestData(true);
+ Console.Write("testBinary(" + BytesToHex(binOut) + ")");
+ try
+ {
+ var binIn = await client.testBinaryAsync(binOut, token);
+ Console.WriteLine(" = " + BytesToHex(binIn));
+ if (binIn.Length != binOut.Length)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+ for (var ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
+ if (binIn[ofs] != binOut[ofs])
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+ }
+ catch (Thrift.TApplicationException ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+
+ // binary equals? only with hashcode option enabled ...
+ Console.WriteLine("Test CrazyNesting");
+ var one = new CrazyNesting();
+ var two = new CrazyNesting();
+ one.String_field = "crazy";
+ two.String_field = "crazy";
+ one.Binary_field = new byte[] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
+ two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
+ if (typeof(CrazyNesting).GetMethod("Equals")?.DeclaringType == typeof(CrazyNesting))
+ {
+ if (!one.Equals(two))
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorContainers;
+ throw new Exception("CrazyNesting.Equals failed");
+ }
+ }
+
+ // TODO: Validate received message
+ Console.Write("testStruct({\"Zero\", 1, -3, -5})");
+ var o = new Xtruct();
+ o.String_thing = "Zero";
+ o.Byte_thing = (sbyte)1;
+ o.I32_thing = -3;
+ o.I64_thing = -5;
+ var i = await client.testStructAsync(o, token);
+ Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
+
+ // TODO: Validate received message
+ Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
+ var o2 = new Xtruct2();
+ o2.Byte_thing = (sbyte)1;
+ o2.Struct_thing = o;
+ o2.I32_thing = 5;
+ var i2 = await client.testNestAsync(o2, token);
+ i = i2.Struct_thing;
+ Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
+
+ var mapout = new Dictionary<int, int>();
+ for (var j = 0; j < 5; j++)
+ {
+ mapout[j] = j - 10;
+ }
+ Console.Write("testMap({");
+ var first = true;
+ foreach (var key in mapout.Keys)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ Console.Write(", ");
+ }
+ Console.Write(key + " => " + mapout[key]);
+ }
+ Console.Write("})");
+
+ var mapin = await client.testMapAsync(mapout, token);
+
+ Console.Write(" = {");
+ first = true;
+ foreach (var key in mapin.Keys)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ Console.Write(", ");
+ }
+ Console.Write(key + " => " + mapin[key]);
+ }
+ Console.WriteLine("}");
+
+ // TODO: Validate received message
+ var listout = new List<int>();
+ for (var j = -2; j < 3; j++)
+ {
+ listout.Add(j);
+ }
+ Console.Write("testList({");
+ first = true;
+ foreach (var j in listout)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ Console.Write(", ");
+ }
+ Console.Write(j);
+ }
+ Console.Write("})");
+
+ var listin = await client.testListAsync(listout, token);
+
+ Console.Write(" = {");
+ first = true;
+ foreach (var j in listin)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ Console.Write(", ");
+ }
+ Console.Write(j);
+ }
+ Console.WriteLine("}");
+
+ //set
+ // TODO: Validate received message
+ var setout = new THashSet<int>();
+ for (var j = -2; j < 3; j++)
+ {
+ setout.Add(j);
+ }
+ Console.Write("testSet({");
+ first = true;
+ foreach (int j in setout)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ Console.Write(", ");
+ }
+ Console.Write(j);
+ }
+ Console.Write("})");
+
+ var setin = await client.testSetAsync(setout, token);
+
+ Console.Write(" = {");
+ first = true;
+ foreach (int j in setin)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ Console.Write(", ");
+ }
+ Console.Write(j);
+ }
+ Console.WriteLine("}");
+
+
+ Console.Write("testEnum(ONE)");
+ var ret = await client.testEnumAsync(Numberz.ONE, token);
+ Console.WriteLine(" = " + ret);
+ if (Numberz.ONE != ret)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorStructs;
+ }
+
+ Console.Write("testEnum(TWO)");
+ ret = await client.testEnumAsync(Numberz.TWO, token);
+ Console.WriteLine(" = " + ret);
+ if (Numberz.TWO != ret)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorStructs;
+ }
+
+ Console.Write("testEnum(THREE)");
+ ret = await client.testEnumAsync(Numberz.THREE, token);
+ Console.WriteLine(" = " + ret);
+ if (Numberz.THREE != ret)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorStructs;
+ }
+
+ Console.Write("testEnum(FIVE)");
+ ret = await client.testEnumAsync(Numberz.FIVE, token);
+ Console.WriteLine(" = " + ret);
+ if (Numberz.FIVE != ret)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorStructs;
+ }
+
+ Console.Write("testEnum(EIGHT)");
+ ret = await client.testEnumAsync(Numberz.EIGHT, token);
+ Console.WriteLine(" = " + ret);
+ if (Numberz.EIGHT != ret)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorStructs;
+ }
+
+ Console.Write("testTypedef(309858235082523)");
+ var uid = await client.testTypedefAsync(309858235082523L, token);
+ Console.WriteLine(" = " + uid);
+ if (309858235082523L != uid)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorStructs;
+ }
+
+ // TODO: Validate received message
+ Console.Write("testMapMap(1)");
+ var mm = await client.testMapMapAsync(1, token);
+ Console.Write(" = {");
+ foreach (var key in mm.Keys)
+ {
+ Console.Write(key + " => {");
+ var m2 = mm[key];
+ foreach (var k2 in m2.Keys)
+ {
+ Console.Write(k2 + " => " + m2[k2] + ", ");
+ }
+ Console.Write("}, ");
+ }
+ Console.WriteLine("}");
+
+ // TODO: Validate received message
+ var insane = new Insanity();
+ insane.UserMap = new Dictionary<Numberz, long>();
+ insane.UserMap[Numberz.FIVE] = 5000L;
+ var truck = new Xtruct();
+ truck.String_thing = "Truck";
+ truck.Byte_thing = (sbyte)8;
+ truck.I32_thing = 8;
+ truck.I64_thing = 8;
+ insane.Xtructs = new List<Xtruct>();
+ insane.Xtructs.Add(truck);
+ Console.Write("testInsanity()");
+ var whoa = await client.testInsanityAsync(insane, token);
+ Console.Write(" = {");
+ foreach (var key in whoa.Keys)
+ {
+ var val = whoa[key];
+ Console.Write(key + " => {");
+
+ foreach (var k2 in val.Keys)
+ {
+ var v2 = val[k2];
+
+ Console.Write(k2 + " => {");
+ var userMap = v2.UserMap;
+
+ Console.Write("{");
+ if (userMap != null)
+ {
+ foreach (var k3 in userMap.Keys)
+ {
+ Console.Write(k3 + " => " + userMap[k3] + ", ");
+ }
+ }
+ else
+ {
+ Console.Write("null");
+ }
+ Console.Write("}, ");
+
+ var xtructs = v2.Xtructs;
+
+ Console.Write("{");
+ if (xtructs != null)
+ {
+ foreach (var x in xtructs)
+ {
+ Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
+ }
+ }
+ else
+ {
+ Console.Write("null");
+ }
+ Console.Write("}");
+
+ Console.Write("}, ");
+ }
+ Console.Write("}, ");
+ }
+ Console.WriteLine("}");
+
+ sbyte arg0 = 1;
+ var arg1 = 2;
+ var arg2 = long.MaxValue;
+ var multiDict = new Dictionary<short, string>();
+ multiDict[1] = "one";
+
+ var tmpMultiDict = new List<string>();
+ foreach (var pair in multiDict)
+ tmpMultiDict.Add(pair.Key +" => "+ pair.Value);
+
+ var arg4 = Numberz.FIVE;
+ long arg5 = 5000000;
+ Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + ",{" + string.Join(",", tmpMultiDict) + "}," + arg4 + "," + arg5 + ")");
+ var multiResponse = await client.testMultiAsync(arg0, arg1, arg2, multiDict, arg4, arg5, token);
+ Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
+
+ try
+ {
+ Console.WriteLine("testException(\"Xception\")");
+ await client.testExceptionAsync("Xception", token);
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ catch (Xception ex)
+ {
+ if (ex.ErrorCode != 1001 || ex.Message != "Xception")
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+ try
+ {
+ Console.WriteLine("testException(\"TException\")");
+ await client.testExceptionAsync("TException", token);
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ catch (Thrift.TException)
+ {
+ // OK
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+ try
+ {
+ Console.WriteLine("testException(\"ok\")");
+ await client.testExceptionAsync("ok", token);
+ // OK
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+
+ try
+ {
+ Console.WriteLine("testMultiException(\"Xception\", ...)");
+ await client.testMultiExceptionAsync("Xception", "ignore", token);
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ catch (Xception ex)
+ {
+ if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception")
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+ try
+ {
+ Console.WriteLine("testMultiException(\"Xception2\", ...)");
+ await client.testMultiExceptionAsync("Xception2", "ignore", token);
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ catch (Xception2 ex)
+ {
+ if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2")
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+ try
+ {
+ Console.WriteLine("testMultiException(\"success\", \"OK\")");
+ if ("OK" != (await client.testMultiExceptionAsync("success", "OK", token)).String_thing)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorExceptions;
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ }
+
+ var sw = new Stopwatch();
+ sw.Start();
+ Console.WriteLine("Test Oneway(1)");
+ await client.testOnewayAsync(1, token);
+ sw.Stop();
+ if (sw.ElapsedMilliseconds > 1000)
+ {
+ Console.WriteLine("*** FAILED ***");
+ returnCode |= ErrorBaseTypes;
+ }
+
+ Console.Write("Test Calltime()");
+ var times = 50;
+ sw.Reset();
+ sw.Start();
+ for (var k = 0; k < times; ++k)
+ await client.testVoidAsync(token);
+ sw.Stop();
+ Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times);
+ return returnCode;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Makefile.am
----------------------------------------------------------------------
diff --git a/test/netcore/Makefile.am b/test/netcore/Makefile.am
index e029a24..65833b9 100644
--- a/test/netcore/Makefile.am
+++ b/test/netcore/Makefile.am
@@ -19,41 +19,28 @@
SUBDIRS = .
-THRIFT = $(top_builddir)/compiler/cpp/thrift
-
-GENDIR = ThriftTest/gen-netcore
-
THRIFTCODE = \
- ThriftTest/TestClient.cs \
- ThriftTest/TestServer.cs \
- ThriftTest/Properties/AssemblyInfo.cs \
- ThriftTest/Program.cs
+ ThriftTest.sln
all-local: \
- ThriftTest/stage/ThriftTest.dll
+ ThriftTest/stage/binaries
-ThriftTest/stage/ThriftTest.dll: $(THRIFTCODE)
- $(MKDIR_P) $(GENDIR)
- $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/test/ThriftTest.thrift
- $(DOTNETCORE) --info
- $(DOTNETCORE) restore
+ThriftTest/stage/binaries: $(THRIFTCODE)
$(DOTNETCORE) build
precross: \
- ThriftTest/stage/ThriftTest.dll
+ ThriftTest/stage/binaries
clean-local:
- $(RM) ThriftTest.exe
- $(RM) -r $(GENDIR)
- $(RM) -r ThriftTest/bin
- $(RM) -r ThriftTest/obj
+ $(RM) -r Client/bin
+ $(RM) -r Server/bin
+ $(RM) -r Client/obj
+ $(RM) -r Server/obj
+ $(RM) -r ThriftTest/ThriftTest
EXTRA_DIST = \
- $(THRIFTCODE) \
ThriftTest.sln \
- ThriftTest/ThriftTest.csproj \
- ThriftTest/Properties/launchSettings.json \
- build.cmd \
- build.sh \
+ Server \
+ Client \
README.md
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/README.md
----------------------------------------------------------------------
diff --git a/test/netcore/README.md b/test/netcore/README.md
index 05eb0e2..ed728d1 100644
--- a/test/netcore/README.md
+++ b/test/netcore/README.md
@@ -9,7 +9,10 @@ Tests for Thrift client library ported to Microsoft .Net Core
- NET Core Standard 1.6 (SDK 2.0.0)
# How to build on Windows
+- Get Thrift IDL compiler executable, add to some folder and add path to this folder into PATH variable
- Open ThriftTest.sln in Visual Studio and build
+or
+- Build with scripts
# How to build on Unix
- Ensure you have .NET Core 2.0.0 SDK installed or use the Ubuntu Xenial docker image
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Server/.gitignore
----------------------------------------------------------------------
diff --git a/test/netcore/Server/.gitignore b/test/netcore/Server/.gitignore
new file mode 100644
index 0000000..67d5510
--- /dev/null
+++ b/test/netcore/Server/.gitignore
@@ -0,0 +1,2 @@
+# ignore for autogenerated files
+/ThriftTest
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Server/Program.cs
----------------------------------------------------------------------
diff --git a/test/netcore/Server/Program.cs b/test/netcore/Server/Program.cs
new file mode 100644
index 0000000..e647e5b
--- /dev/null
+++ b/test/netcore/Server/Program.cs
@@ -0,0 +1,72 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using ThriftTest;
+
+namespace Server
+{
+ public class Program
+ {
+ public static int Main(string[] args)
+ {
+ try
+ {
+ Console.SetBufferSize(Console.BufferWidth, 4096);
+ }
+ catch (Exception)
+ {
+ Console.WriteLine("Failed to grow scroll-back buffer");
+ }
+
+ // split mode and options
+ var subArgs = new List<string>(args);
+ var firstArg = string.Empty;
+ if (subArgs.Count > 0)
+ {
+ firstArg = subArgs[0];
+ subArgs.RemoveAt(0);
+ }
+
+ // run whatever mode is choosen
+ switch(firstArg)
+ {
+ case "server":
+ return TestServer.Execute(subArgs);
+ case "--help":
+ PrintHelp();
+ return 0;
+ default:
+ PrintHelp();
+ return -1;
+ }
+ }
+
+ private static void PrintHelp()
+ {
+ Console.WriteLine("Usage:");
+ Console.WriteLine(" Server server [options]'");
+ Console.WriteLine(" Server --help");
+ Console.WriteLine("");
+
+ TestServer.PrintOptionsHelp();
+ }
+ }
+}
+
+
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Server/Properties/AssemblyInfo.cs
----------------------------------------------------------------------
diff --git a/test/netcore/Server/Properties/AssemblyInfo.cs b/test/netcore/Server/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..265495c
--- /dev/null
+++ b/test/netcore/Server/Properties/AssemblyInfo.cs
@@ -0,0 +1,43 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+
+[assembly: AssemblyTitle("Server")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("The Apache Software Foundation")]
+[assembly: AssemblyProduct("Thrift")]
+[assembly: AssemblyCopyright("The Apache Software Foundation")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+
+[assembly: Guid("B0C13DA0-3117-4844-8AE8-B1775E46223D")]
+
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Server/Server.csproj
----------------------------------------------------------------------
diff --git a/test/netcore/Server/Server.csproj b/test/netcore/Server/Server.csproj
new file mode 100644
index 0000000..ad2fb7c
--- /dev/null
+++ b/test/netcore/Server/Server.csproj
@@ -0,0 +1,31 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>netcoreapp2.0</TargetFramework>
+ <AssemblyName>Server</AssemblyName>
+ <PackageId>Server</PackageId>
+ <OutputType>Exe</OutputType>
+ <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
+ <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
+ <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
+ <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
+ <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
+ <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="System.Net.Http.WinHttpHandler" Version="[4.4,)" />
+ <PackageReference Include="System.Runtime.Serialization.Primitives" Version="[4.3,)" />
+ <PackageReference Include="System.ServiceModel.Primitives" Version="[4.4,)" />
+ <PackageReference Include="System.Threading" Version="[4.3,)" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\..\lib\netcore\Thrift\Thrift.csproj" />
+ </ItemGroup>
+ <Target Name="PreBuild" BeforeTargets="_GenerateRestoreProjectSpec;Restore;Compile">
+ <Exec Condition="'$(OS)' == 'Windows_NT'" Command="where thrift" ConsoleToMSBuild="true">
+ <Output TaskParameter="ConsoleOutput" PropertyName="PathToThrift" />
+ </Exec>
+ <Exec Condition="Exists('$(PathToThrift)')" Command="$(PathToThrift) -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
+ <Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
+ <Exec Condition="Exists('$(ProjectDir)/../../../compiler/cpp/thrift')" Command="$(ProjectDir)/../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../ThriftTest.thrift" />
+ </Target>
+</Project>
\ No newline at end of file
[8/9] thrift git commit: THRIFT-4434: fixes to delegate all
dependency responsibility from make to the dotnet build Client: dotnet
Posted by jk...@apache.org.
THRIFT-4434: fixes to delegate all dependency responsibility from make to the dotnet build
Client: dotnet
This closes #1469
Project: http://git-wip-us.apache.org/repos/asf/thrift/repo
Commit: http://git-wip-us.apache.org/repos/asf/thrift/commit/b56fc700
Tree: http://git-wip-us.apache.org/repos/asf/thrift/tree/b56fc700
Diff: http://git-wip-us.apache.org/repos/asf/thrift/diff/b56fc700
Branch: refs/heads/master
Commit: b56fc700d6ff3086c4704c5c4cae3c8ec2a06228
Parents: 5499329
Author: James E. King III <jk...@apache.org>
Authored: Sat Jan 13 11:29:14 2018 -0500
Committer: James E. King III <jk...@apache.org>
Committed: Sun Jan 14 08:41:10 2018 -0500
----------------------------------------------------------------------
lib/netcore/Makefile.am | 29 +++++++++++++----------------
test/netcore/Makefile.am | 23 +++++++++--------------
tutorial/netcore/Makefile.am | 22 ++++++++--------------
3 files changed, 30 insertions(+), 44 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/thrift/blob/b56fc700/lib/netcore/Makefile.am
----------------------------------------------------------------------
diff --git a/lib/netcore/Makefile.am b/lib/netcore/Makefile.am
index 992558b..caf3f34 100644
--- a/lib/netcore/Makefile.am
+++ b/lib/netcore/Makefile.am
@@ -19,26 +19,23 @@
SUBDIRS = .
-THRIFTCODE = \
- Thrift/Thrift.csproj
-
-all-local: \
- Thrift.dll
-
-Thrift.dll: $(THRIFTCODE)
-# $(MKDIR_P) $(GENDIR)
-# $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(TESTDIR)/CassandraTest.thrift
-# $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/test/ThriftTest.thrift
-# $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/contrib/fb303/if/fb303.thrift
+all-local:
$(DOTNETCORE) build
+check-local:
+ $(DOTNETCORE) test Tests/Thrift.Tests/Thrift.Tests.csproj
+ ${DOTNETCORE} test Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj
+
clean-local:
$(RM) -r Thrift/bin
$(RM) -r Thrift/obj
EXTRA_DIST = \
- Thrift \
- Thrift.sln \
- Tests \
- README.md
-
+ README.md \
+ Tests \
+ Thrift \
+ Thrift.sln \
+ build.cmd \
+ build.sh \
+ runtests.cmd \
+ runtests.sh
http://git-wip-us.apache.org/repos/asf/thrift/blob/b56fc700/test/netcore/Makefile.am
----------------------------------------------------------------------
diff --git a/test/netcore/Makefile.am b/test/netcore/Makefile.am
index 65833b9..376ffb7 100644
--- a/test/netcore/Makefile.am
+++ b/test/netcore/Makefile.am
@@ -19,17 +19,11 @@
SUBDIRS = .
-THRIFTCODE = \
- ThriftTest.sln
-
-all-local: \
- ThriftTest/stage/binaries
-
-ThriftTest/stage/binaries: $(THRIFTCODE)
+all-local:
$(DOTNETCORE) build
-precross: \
- ThriftTest/stage/binaries
+precross:
+ $(DOTNETCORE) build
clean-local:
$(RM) -r Client/bin
@@ -39,8 +33,9 @@ clean-local:
$(RM) -r ThriftTest/ThriftTest
EXTRA_DIST = \
- ThriftTest.sln \
- Server \
- Client \
- README.md
-
+ Client \
+ README.md \
+ Server \
+ ThriftTest.sln \
+ build.cmd \
+ build.sh
http://git-wip-us.apache.org/repos/asf/thrift/blob/b56fc700/tutorial/netcore/Makefile.am
----------------------------------------------------------------------
diff --git a/tutorial/netcore/Makefile.am b/tutorial/netcore/Makefile.am
index d1d788f..e305556 100644
--- a/tutorial/netcore/Makefile.am
+++ b/tutorial/netcore/Makefile.am
@@ -19,13 +19,7 @@
SUBDIRS = .
-THRIFTCODE = \
- Tutorial.sln
-
-all-local: \
- Client.exe
-
-Client.exe: $(THRIFTCODE)
+all-local:
$(DOTNETCORE) build
clean-local:
@@ -38,11 +32,11 @@ clean-local:
$(RM) -r Interfaces/obj
EXTRA_DIST = \
- Tutorial.sln \
- Interfaces \
- Client \
- Server \
- build.cmd \
- build.sh \
- README.md
+ Client \
+ Interfaces \
+ README.md \
+ Server \
+ Tutorial.sln \
+ build.cmd \
+ build.sh
[7/9] thrift git commit: THRIFT-4434: .NET Core cleanup and the
beginnings of compiler unit tests Client: netcore
Posted by jk...@apache.org.
THRIFT-4434: .NET Core cleanup and the beginnings of compiler unit tests
Client: netcore
This closes #1449
Project: http://git-wip-us.apache.org/repos/asf/thrift/repo
Commit: http://git-wip-us.apache.org/repos/asf/thrift/commit/54993296
Tree: http://git-wip-us.apache.org/repos/asf/thrift/tree/54993296
Diff: http://git-wip-us.apache.org/repos/asf/thrift/diff/54993296
Branch: refs/heads/master
Commit: 54993296c413ad0ba295148af5a905d11d671ce9
Parents: 9a32f8a
Author: Volodymyr Gotra <vo...@evolute.com>
Authored: Mon Dec 18 02:08:09 2017 +0200
Committer: James E. King III <jk...@apache.org>
Committed: Sun Jan 14 08:39:32 2018 -0500
----------------------------------------------------------------------
.gitignore | 1 +
compiler/cpp/Makefile.am | 5 +-
compiler/cpp/README.md | 148 +-
.../src/thrift/generate/t_netcore_generator.cc | 396 +-
.../src/thrift/generate/t_netcore_generator.h | 137 +
compiler/cpp/tests/CMakeLists.txt | 153 +
compiler/cpp/tests/README.md | 88 +
compiler/cpp/tests/catch/catch.hpp | 11508 +++++++++++++++++
.../t_netcore_generator_functional_tests.cc | 339 +
...etcore_generator_functional_tests_helpers.cc | 237 +
...netcore_generator_functional_tests_helpers.h | 34 +
.../t_netcore_generator_helpers_tests.cc | 209 +
.../t_netcore_generator_initialization_tests.cc | 74 +
compiler/cpp/tests/tests_main.cc | 19 +
lib/netcore/Makefile.am | 73 +-
lib/netcore/README.md | 3 +
.../Tests/Thrift.IntegrationTests/.gitignore | 2 +
.../Protocols/ProtocolsOperationsTests.cs | 502 +
.../Thrift.IntegrationTests.csproj | 29 +
.../.gitignore | 4 +
...Thrift.PublicInterfaces.Compile.Tests.csproj | 15 +
.../Collections/TCollectionsTests.cs | 83 +
.../Thrift.Tests/Collections/THashSetTests.cs | 71 +
.../Protocols/TJsonProtocolHelperTests.cs | 172 +
.../Protocols/TJsonProtocolTests.cs | 67 +
.../Tests/Thrift.Tests/Thrift.Tests.csproj | 18 +
lib/netcore/Thrift.sln | 60 +-
lib/netcore/Thrift/Protocols/TAbstractBase.cs | 2 +-
lib/netcore/Thrift/Protocols/TBase.cs | 2 +-
lib/netcore/Thrift/Protocols/TBinaryProtocol.cs | 19 +-
.../Thrift/Protocols/TCompactProtocol.cs | 10 +-
lib/netcore/Thrift/Protocols/TJSONProtocol.cs | 383 +-
.../Thrift/Protocols/TMultiplexedProtocol.cs | 13 +-
lib/netcore/Thrift/Protocols/TProtocol.cs | 17 +-
.../Thrift/Protocols/TProtocolDecorator.cs | 17 +-
.../Thrift/Protocols/TProtocolException.cs | 5 +-
.../Thrift/Protocols/Utilities/TBase64Helper.cs | 101 +
.../Utilities/TJsonProtocolConstants.cs | 61 +
.../Protocols/Utilities/TJsonProtocolHelper.cs | 176 +
.../Thrift/Protocols/Utilities/TProtocolUtil.cs | 54 +-
lib/netcore/Thrift/Server/AsyncBaseServer.cs | 17 +-
lib/netcore/Thrift/Server/TBaseServer.cs | 19 +-
lib/netcore/Thrift/TApplicationException.cs | 43 +-
lib/netcore/Thrift/TBaseClient.cs | 19 +-
.../Client/TBufferedClientTransport.cs | 14 +-
.../Transports/Client/TFramedClientTransport.cs | 14 +-
.../Transports/Client/THttpClientTransport.cs | 4 +-
.../Transports/Client/TSocketClientTransport.cs | 7 +-
.../Client/TTlsSocketClientTransport.cs | 7 +-
.../Transports/Server/THttpServerTransport.cs | 21 +-
.../Server/TNamedPipeServerTransport.cs | 2 +-
.../Transports/Server/TServerSocketTransport.cs | 18 +-
.../Server/TTlsServerSocketTransport.cs | 27 +-
.../Thrift/Transports/TClientTransport.cs | 3 +-
.../Thrift/Transports/TServerTransport.cs | 2 +-
lib/netcore/build.cmd | 27 +
lib/netcore/build.sh | 32 +
lib/netcore/runtests.cmd | 28 +
lib/netcore/runtests.sh | 26 +
test/ThriftTest.thrift | 2 +-
test/csharp/TestClient.cs | 4 +-
test/csharp/TestServer.cs | 4 +-
test/features/known_failures_Linux.json | 90 +-
test/known_failures_Linux.json | 6 +
test/netcore/Client/.gitignore | 2 +
test/netcore/Client/Client.csproj | 31 +
test/netcore/Client/Program.cs | 72 +
test/netcore/Client/Properties/AssemblyInfo.cs | 43 +
test/netcore/Client/TestClient.cs | 943 ++
test/netcore/Makefile.am | 35 +-
test/netcore/README.md | 3 +
test/netcore/Server/.gitignore | 2 +
test/netcore/Server/Program.cs | 72 +
test/netcore/Server/Properties/AssemblyInfo.cs | 43 +
test/netcore/Server/Server.csproj | 31 +
test/netcore/Server/TestServer.cs | 594 +
test/netcore/ThriftTest.sln | 44 +-
test/netcore/ThriftTest/Program.cs | 76 -
.../ThriftTest/Properties/AssemblyInfo.cs | 43 -
.../ThriftTest/Properties/launchSettings.json | 7 -
test/netcore/ThriftTest/TestClient.cs | 898 --
test/netcore/ThriftTest/TestServer.cs | 560 -
test/netcore/ThriftTest/ThriftTest.csproj | 27 -
test/netcore/build.cmd | 5 -
test/netcore/build.sh | 5 -
test/tests.json | 1375 +-
tutorial/netcore/Client/Program.cs | 20 +-
tutorial/netcore/Interfaces/.gitignore | 3 +
tutorial/netcore/Interfaces/Interfaces.csproj | 10 +
tutorial/netcore/Makefile.am | 35 +-
tutorial/netcore/README.md | 27 +-
tutorial/netcore/Server/Program.cs | 27 +-
tutorial/netcore/Tutorial.sln | 78 +-
tutorial/netcore/build.cmd | 5 -
tutorial/netcore/build.sh | 5 -
95 files changed, 17526 insertions(+), 3338 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index fe9be57..b4cd1a3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -45,6 +45,7 @@ project.lock.json
.DS_Store
.svn
.vagrant
+.vscode
/contrib/.vagrant/
/aclocal/libtool.m4
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/Makefile.am
----------------------------------------------------------------------
diff --git a/compiler/cpp/Makefile.am b/compiler/cpp/Makefile.am
index 482a89a..bd2ba80 100644
--- a/compiler/cpp/Makefile.am
+++ b/compiler/cpp/Makefile.am
@@ -71,7 +71,7 @@ compiler_core = src/thrift/common.h \
src/thrift/parse/parse.cc \
src/thrift/generate/t_generator.h \
src/thrift/generate/t_oop_generator.h \
- src/thrift/generate/t_html_generator.h
+ src/thrift/generate/t_html_generator.h
thrift_SOURCES = src/thrift/main.h \
src/thrift/main.cc \
@@ -88,6 +88,7 @@ thrift_SOURCES += src/thrift/generate/t_c_glib_generator.cc \
src/thrift/generate/t_haxe_generator.cc \
src/thrift/generate/t_csharp_generator.cc \
src/thrift/generate/t_netcore_generator.cc \
+ src/thrift/generate/t_netcore_generator.h \
src/thrift/generate/t_py_generator.cc \
src/thrift/generate/t_rb_generator.cc \
src/thrift/generate/t_perl_generator.cc \
@@ -153,7 +154,7 @@ include_generatedir = $(include_thriftdir)/generate
include_generate_HEADERS = src/thrift/generate/t_generator.h \
src/thrift/generate/t_generator_registry.h \
src/thrift/generate/t_oop_generator.h \
- src/thrift/generate/t_html_generator.h
+ src/thrift/generate/t_html_generator.h
include_parsedir = $(include_thriftdir)/parse
include_parse_HEADERS = src/thrift/parse/t_service.h \
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/README.md
----------------------------------------------------------------------
diff --git a/compiler/cpp/README.md b/compiler/cpp/README.md
index 2fff0d8..32eac9f 100644
--- a/compiler/cpp/README.md
+++ b/compiler/cpp/README.md
@@ -1,19 +1,49 @@
-# Build compiler using CMake
+# Build Thrift IDL compiler using CMake
-## build on Unix-like System
+<!-- TOC -->
-### build using cmake
+- [Build Thrift IDL compiler using CMake](#build-thrift-idl-compiler-using-cmake)
+ - [Build on Unix-like System](#build-on-unix-like-system)
+ - [Prerequisites](#prerequisites)
+ - [Build using CMake](#build-using-cmake)
+ - [Build with Eclipse IDE](#build-with-eclipse-ide)
+ - [Build with XCode IDE in MacOS](#build-with-xcode-ide-in-macos)
+ - [Usage of other IDEs](#usage-of-other-ides)
+ - [Build on Windows](#build-on-windows)
+ - [Prerequisites](#prerequisites-1)
+ - [Build using Git Bash](#build-using-git-bash)
+ - [Using Visual Studio and Win flex-bison](#using-visual-studio-and-win-flex-bison)
+ - [Cross compile using mingw32 and generate a Windows Installer with CPack](#cross-compile-using-mingw32-and-generate-a-windows-installer-with-cpack)
+- [Other cases](#other-cases)
+ - [Building the Thrift IDL compiler in Windows without CMake](#building-the-thrift-idl-compiler-in-windows-without-cmake)
+- [Unit tests for compiler](#unit-tests-for-compiler)
+ - [Using boost test](#using-boost-test)
+ - [Using Catch C++ test library](#using-catch-c-test-library)
+- [Have a Happy free time and holidays](#have-a-happy-free-time-and-holidays)
-Use the following steps to build using cmake:
+<!-- /TOC -->
+
+## Build on Unix-like System
+
+### Prerequisites
+- Install CMake
+- Install flex and bison
+
+### Build using CMake
+
+- Go to **thrift\compiler\cpp**
+- Use the following steps to build using cmake:
```
-mkdir cmake-build
-cd cmake-build
+mkdir cmake-build && cd cmake-build
cmake ..
make
```
-### Create an eclipse project
+#### Build with Eclipse IDE
+
+- Go to **thrift\compiler\cpp**
+- Use the following steps to build using cmake:
```
mkdir cmake-ec && cd cmake-ec
@@ -23,58 +53,89 @@ make
Now open the folder cmake-ec using eclipse.
+#### Build with XCode IDE in MacOS
-## Cross compile using mingw32 and generate a Windows Installer with CPack
+- Install/update flex, bison and cmake with brew
```
-mkdir cmake-mingw32 && cd cmake-mingw32
-cmake -DCMAKE_TOOLCHAIN_FILE=../build/cmake/mingw32-toolchain.cmake -DBUILD_COMPILER=ON -DBUILD_LIBRARIES=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF ..
-cpack
+brew install cmake
+brew install bison
```
-# Build on windows
+- Go to **thrift\compiler\cpp**
+- Run commands in command line:
+
+```
+mkdir cmake-build && cd cmake-build
+cmake -G "Xcode" -DWITH_PLUGIN=OFF ..
+cmake --build .
+```
+
+#### Usage of other IDEs
+
+Please check list of supported IDE
+
+```
+cmake --help
+```
+
+## Build on Windows
+
+### Prerequisites
+- Install CMake - https://cmake.org/download/
+- In case if you want to build without Git Bash - install winflexbison - https://sourceforge.net/projects/winflexbison/
+- In case if you want to build with Visual Studio - install Visual Studio
+ - Better to use the latest stable Visual Studio Community Edition - https://www.visualstudio.com/vs/whatsnew/ (ensure that you installed workload "Desktop Development with C++" for VS2017) - Microsoft added some support for CMake and improving it in Visual Studio
+
+### Build using Git Bash
-### using Git Bash
+Git Bash provides flex and bison
-Git Bash provides flex and bison, so you just need to do this:
+- Go to **thrift\compiler\cpp**
+- Use the following steps to build using cmake:
```
mkdir cmake-vs && cd cmake-vs
cmake -DWITH_SHARED_LIB=off ..
+cmake --build .
```
-### using Win flex-bison
+### Using Visual Studio and Win flex-bison
-In order to build on windows with winflexbison a few additional steps are necessary:
+- Generate a Visual Studio project for version of Visual Studio which you have (**cmake --help** can show list of supportable VS versions):
+- Run commands in command line:
+```
+mkdir cmake-vs
+cd cmake-vs
+cmake -G "Visual Studio 15 2017" -DWITH_PLUGIN=OFF ..
+```
+- Now open the folder cmake-vs using Visual Studio.
+
+### Cross compile using mingw32 and generate a Windows Installer with CPack
-1. Download winflexbison from http://sourceforge.net/projects/winflexbison/
-2. Extract the winflex bison files to for e.g. C:\winflexbison
-3. Make the CMake variables point to the correct binaries.
- * FLEX_EXECUTABLE = C:/winbuild/win_flex.exe
- * BISON_EXECUTABLE = C:/winbuild/win_bison.exe
-4. Generate a Visual Studio project:
```
-mkdir cmake-vs && cd cmake-vs
-cmake -G "Visual Studio 12" -DWITH_SHARED_LIB=off ..
+mkdir cmake-mingw32 && cd cmake-mingw32
+cmake -DCMAKE_TOOLCHAIN_FILE=../build/cmake/mingw32-toolchain.cmake -DBUILD_COMPILER=ON -DBUILD_LIBRARIES=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF ..
+cpack
```
-5. Now open the folder build_vs using Visual Studio 2013.
-# Building the Thrift IDL compiler in Windows
+# Other cases
+
+## Building the Thrift IDL compiler in Windows without CMake
+
+If you don't want to use CMake you can use the already available Visual Studio 2010 solution.
-If you don't want to use CMake you can use the already available Visual Studio
-2010 solution.
-The Visual Studio project contains pre-build commands to generate the
-thriftl.cc, thrifty.cc and thrifty.hh files which are necessary to build
-the compiler. These depend on bison, flex and their dependencies to
-work properly.
-Download flex & bison as described above.
-Place these binaries somewhere in the path and
-rename win_flex.exe and win_bison.exe to flex.exe and bison.exe respectively.
+The Visual Studio project contains pre-build commands to generate the thriftl.cc, thrifty.cc and thrifty.hh files which are necessary to build the compiler.
+
+These depend on bison, flex and their dependencies to work properly.
+
+Download flex & bison as described above.
+
+Place these binaries somewhere in the path and rename win_flex.exe and win_bison.exe to flex.exe and bison.exe respectively.
If this doesn't work on a system, try these manual pre-build steps.
-Open compiler.sln and remove the Pre-build commands under the project's
- Properties -> Build Events -> Pre-Build Events.
+Open compiler.sln and remove the Pre-build commands under the project's: Properties -> Build Events -> Pre-Build Events.
From a command prompt:
```
@@ -99,3 +160,16 @@ Download inttypes.h from the interwebs and place it in an include path
location (e.g. thrift/compiler/cpp/src).
Build the compiler in Visual Studio.
+
+# Unit tests for compiler
+
+## Using boost test
+- pls check **test** folder
+
+## Using Catch C++ test library
+
+Added generic way to cover code by tests for many languages (you just need to make a correct header file for generator for your language - example in **netcore** implementation)
+
+- pls check **tests** folder
+
+# Have a Happy free time and holidays
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/src/thrift/generate/t_netcore_generator.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/src/thrift/generate/t_netcore_generator.cc b/compiler/cpp/src/thrift/generate/t_netcore_generator.cc
index 8d157a9..9334f5f 100644
--- a/compiler/cpp/src/thrift/generate/t_netcore_generator.cc
+++ b/compiler/cpp/src/thrift/generate/t_netcore_generator.cc
@@ -35,6 +35,7 @@
#include "thrift/platform.h"
#include "thrift/generate/t_oop_generator.h"
+#include "thrift/generate/t_netcore_generator.h"
using std::map;
using std::ofstream;
@@ -46,208 +47,121 @@ using std::vector;
//TODO: check for indentation
//TODO: Do we need seqId_ in generation?
-static const string endl = "\n"; // avoid ostream << std::endl flushes
+t_netcore_generator::t_netcore_generator(t_program* program, const map<string, string>& parsed_options, const string& option_string)
+ : t_oop_generator(program)
+{
+ (void)option_string;
+
+ nullable_ = false;
+ hashcode_ = false;
+ union_ = false;
+ serialize_ = false;
+ wcf_ = false;
+ wcf_namespace_.clear();
+
+ map<string, string>::const_iterator iter;
+
+ for (iter = parsed_options.begin(); iter != parsed_options.end(); ++iter)
+ {
+ if (iter->first.compare("nullable") == 0)
+ {
+ nullable_ = true;
+ }
+ else if (iter->first.compare("hashcode") == 0)
+ {
+ hashcode_ = true;
+ }
+ else if (iter->first.compare("union") == 0)
+ {
+ union_ = true;
+ }
+ else if (iter->first.compare("serial") == 0)
+ {
+ serialize_ = true;
+ wcf_namespace_ = iter->second; // since there can be only one namespace
+ }
+ else if (iter->first.compare("wcf") == 0)
+ {
+ wcf_ = true;
+ wcf_namespace_ = iter->second;
+ }
+ else
+ {
+ throw "unknown option netcore:" + iter->first;
+ }
+ }
+
+ out_dir_base_ = "gen-netcore";
+}
-struct member_mapping_scope
+static string correct_function_name_for_async(string const& function_name)
{
- void* scope_member;
- map<string, string> mapping_table;
-};
+ string const async_end = "Async";
+ size_t i = function_name.find(async_end);
+ if (i != string::npos)
+ {
+ return function_name + async_end;
+ }
+
+ return function_name;
+}
-class t_netcore_generator : public t_oop_generator
+/**
+* \brief Search and replace "_args" substring in struct name if exist (for C# class naming)
+* \param struct_name
+* \return Modified struct name ("Struct_args" -> "StructArgs") or original name
+*/
+static string check_and_correct_struct_name(const string& struct_name)
{
-public:
- t_netcore_generator(t_program* program, const map<string, string>& parsed_options, const string& option_string)
- : t_oop_generator(program)
+ string args_end = "_args";
+ size_t i = struct_name.find(args_end);
+ if (i != string::npos)
{
- (void)option_string;
+ string new_struct_name = struct_name;
+ new_struct_name.replace(i, args_end.length(), "Args");
+ return new_struct_name;
+ }
- nullable_ = false;
- hashcode_ = false;
- union_ = false;
- serialize_ = false;
- wcf_ = false;
- wcf_namespace_.clear();
+ string result_end = "_result";
+ size_t j = struct_name.find(result_end);
+ if (j != string::npos)
+ {
+ string new_struct_name = struct_name;
+ new_struct_name.replace(j, result_end.length(), "Result");
+ return new_struct_name;
+ }
- map<string, string>::const_iterator iter;
+ return struct_name;
+}
- for (iter = parsed_options.begin(); iter != parsed_options.end(); ++iter)
- {
- if (iter->first.compare("nullable") == 0)
- {
- nullable_ = true;
- }
- else if (iter->first.compare("hashcode") == 0)
- {
- hashcode_ = true;
- }
- else if (iter->first.compare("union") == 0)
- {
- union_ = true;
- }
- else if (iter->first.compare("serial") == 0)
- {
- serialize_ = true;
- wcf_namespace_ = iter->second; // since there can be only one namespace
- }
- else if (iter->first.compare("wcf") == 0)
- {
- wcf_ = true;
- wcf_namespace_ = iter->second;
- }
- else
- {
- throw "unknown option netcore:" + iter->first;
- }
- }
+static bool field_has_default(t_field* tfield) { return tfield->get_value() != NULL; }
- out_dir_base_ = "gen-netcore";
- }
-
- // overrides
- void init_generator();
- void close_generator();
- void generate_consts(vector<t_const*> consts);
- void generate_typedef(t_typedef* ttypedef);
- void generate_enum(t_enum* tenum);
- void generate_struct(t_struct* tstruct);
- void generate_xception(t_struct* txception);
- void generate_service(t_service* tservice);
-
- void generate_property(ofstream& out, t_field* tfield, bool isPublic, bool generateIsset);
- void generate_netcore_property(ofstream& out, t_field* tfield, bool isPublic, bool includeIsset = true, string fieldPrefix = "");
- bool print_const_value(ofstream& out, string name, t_type* type, t_const_value* value, bool in_static, bool defval = false, bool needtype = false);
- string render_const_value(ofstream& out, string name, t_type* type, t_const_value* value);
- void print_const_constructor(ofstream& out, vector<t_const*> consts);
- void print_const_def_value(ofstream& out, string name, t_type* type, t_const_value* value);
- void generate_netcore_struct(t_struct* tstruct, bool is_exception);
- void generate_netcore_union(t_struct* tunion);
- void generate_netcore_struct_definition(ofstream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false);
- void generate_netcore_union_definition(ofstream& out, t_struct* tunion);
- void generate_netcore_union_class(ofstream& out, t_struct* tunion, t_field* tfield);
- void generate_netcore_wcffault(ofstream& out, t_struct* tstruct);
- void generate_netcore_struct_reader(ofstream& out, t_struct* tstruct);
- void generate_netcore_struct_result_writer(ofstream& out, t_struct* tstruct);
- void generate_netcore_struct_writer(ofstream& out, t_struct* tstruct);
- void generate_netcore_struct_tostring(ofstream& out, t_struct* tstruct);
- void generate_netcore_struct_equals(ofstream& out, t_struct* tstruct);
- void generate_netcore_struct_hashcode(ofstream& out, t_struct* tstruct);
- void generate_netcore_union_reader(ofstream& out, t_struct* tunion);
- void generate_function_helpers(ofstream& out, t_function* tfunction);
- void generate_service_interface(ofstream& out, t_service* tservice);
- void generate_service_helpers(ofstream& out, t_service* tservice);
- void generate_service_client(ofstream& out, t_service* tservice);
- void generate_service_server(ofstream& out, t_service* tservice);
- void generate_process_function_async(ofstream& out, t_service* tservice, t_function* function);
- void generate_deserialize_field(ofstream& out, t_field* tfield, string prefix = "", bool is_propertyless = false);
- void generate_deserialize_struct(ofstream& out, t_struct* tstruct, string prefix = "");
- void generate_deserialize_container(ofstream& out, t_type* ttype, string prefix = "");
- void generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix = "");
- void generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix = "");
- void generate_deserialize_list_element(ofstream& out, t_list* list, string prefix = "");
- void generate_serialize_field(ofstream& out, t_field* tfield, string prefix = "", bool is_element = false, bool is_propertyless = false);
- void generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix = "");
- void generate_serialize_container(ofstream& out, t_type* ttype, string prefix = "");
- void generate_serialize_map_element(ofstream& out, t_map* tmap, string iter, string map);
- void generate_serialize_set_element(ofstream& out, t_set* tmap, string iter);
- void generate_serialize_list_element(ofstream& out, t_list* tlist, string iter);
- void generate_netcore_doc(ofstream& out, t_field* field);
- void generate_netcore_doc(ofstream& out, t_doc* tdoc);
- void generate_netcore_doc(ofstream& out, t_function* tdoc);
- void generate_netcore_docstring_comment(ofstream& out, string contents);
- void docstring_comment(ofstream& out, const string& comment_start, const string& line_prefix, const string& contents, const string& comment_end);
- void start_netcore_namespace(ofstream& out);
- void end_netcore_namespace(ofstream& out);
-
- string netcore_type_usings() const;
- string netcore_thrift_usings() const;
- string type_name(t_type* ttype, bool in_countainer = false, bool in_init = false, bool in_param = false, bool is_required = false);
- string base_type_name(t_base_type* tbase, bool in_container = false, bool in_param = false, bool is_required = false);
- string declare_field(t_field* tfield, bool init = false, string prefix = "");
- string function_signature_async(t_function* tfunction, string prefix = "");
- string function_signature(t_function* tfunction, string prefix = "");
- string argument_list(t_struct* tstruct);
- string type_to_enum(t_type* ttype);
- string prop_name(t_field* tfield, bool suppress_mapping = false);
- string get_enum_class_name(t_type* type);
-
- static string correct_function_name_for_async(string const& function_name)
- {
- string const async_end = "Async";
- size_t i = function_name.find(async_end);
- if (i != string::npos)
- {
- return function_name + async_end;
- }
-
- return function_name;
- }
-
- /**
- * \brief Search and replace "_args" substring in struct name if exist (for C# class naming)
- * \param struct_name
- * \return Modified struct name ("Struct_args" -> "StructArgs") or original name
- */
- static string check_and_correct_struct_name(const string& struct_name)
- {
- string args_end = "_args";
- size_t i = struct_name.find(args_end);
- if (i != string::npos)
- {
- string new_struct_name = struct_name;
- new_struct_name.replace(i, args_end.length(), "Args");
- return new_struct_name;
- }
-
- string result_end = "_result";
- size_t j = struct_name.find(result_end);
- if (j != string::npos)
- {
- string new_struct_name = struct_name;
- new_struct_name.replace(j, result_end.length(), "Result");
- return new_struct_name;
- }
-
- return struct_name;
- }
-
- static bool field_has_default(t_field* tfield) { return tfield->get_value() != NULL; }
-
- static bool field_is_required(t_field* tfield) { return tfield->get_req() == t_field::T_REQUIRED; }
-
- static bool type_can_be_null(t_type* ttype)
- {
- while (ttype->is_typedef())
- {
- ttype = static_cast<t_typedef*>(ttype)->get_type();
- }
+static bool field_is_required(t_field* tfield) { return tfield->get_req() == t_field::T_REQUIRED; }
- return ttype->is_container() || ttype->is_struct() || ttype->is_xception() || ttype->is_string();
+static bool type_can_be_null(t_type* ttype)
+{
+ while (ttype->is_typedef())
+ {
+ ttype = static_cast<t_typedef*>(ttype)->get_type();
}
+ return ttype->is_container() || ttype->is_struct() || ttype->is_xception() || ttype->is_string();
+}
+
+bool t_netcore_generator::is_wcf_enabled() const { return wcf_; }
+
+bool t_netcore_generator::is_nullable_enabled() const { return nullable_; }
-private:
- string namespace_name_;
- string namespace_dir_;
+bool t_netcore_generator::is_hashcode_enabled() const { return hashcode_; }
- bool nullable_;
- bool union_;
- bool hashcode_;
- bool serialize_;
- bool wcf_;
+bool t_netcore_generator::is_serialize_enabled() const { return serialize_; }
- string wcf_namespace_;
- map<string, int> netcore_keywords;
- vector<member_mapping_scope> member_mapping_scopes;
+bool t_netcore_generator::is_union_enabled() const { return union_; }
- void init_keywords();
- string normalize_name(string name);
- string make_valid_csharp_identifier(string const& fromName);
- void prepare_member_name_mapping(t_struct* tstruct);
- void prepare_member_name_mapping(void* scope, const vector<t_field*>& members, const string& structname);
- void cleanup_member_name_mapping(void* scope);
- string get_mapped_member_name(string oldname);
-};
+map<string, int> t_netcore_generator::get_keywords_list() const
+{
+ return netcore_keywords;
+}
void t_netcore_generator::init_generator()
{
@@ -414,6 +328,8 @@ void t_netcore_generator::init_keywords()
netcore_keywords["var"] = 1;
netcore_keywords["where"] = 1;
netcore_keywords["yield"] = 1;
+
+ netcore_keywords["when"] = 1;
}
void t_netcore_generator::start_netcore_namespace(ofstream& out)
@@ -479,35 +395,40 @@ void t_netcore_generator::generate_typedef(t_typedef* ttypedef)
void t_netcore_generator::generate_enum(t_enum* tenum)
{
- int ic = indent_count();
-
+ int ic = indent_count();
string f_enum_name = namespace_dir_ + "/" + tenum->get_name() + ".cs";
ofstream f_enum;
f_enum.open(f_enum_name.c_str());
- f_enum << autogen_comment() << endl;
+
+ generate_enum(f_enum, tenum);
+
+ f_enum.close();
+ indent_validate(ic, "generate_enum");
+}
- start_netcore_namespace(f_enum);
- generate_netcore_doc(f_enum, tenum);
+void t_netcore_generator::generate_enum(ofstream& out, t_enum* tenum)
+{
+ out << autogen_comment() << endl;
- f_enum << indent() << "public enum " << tenum->get_name() << endl;
- scope_up(f_enum);
+ start_netcore_namespace(out);
+ generate_netcore_doc(out, tenum);
- vector<t_enum_value*> constants = tenum->get_constants();
- vector<t_enum_value*>::iterator c_iter;
+ out << indent() << "public enum " << tenum->get_name() << endl;
+ scope_up(out);
- for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter)
- {
- generate_netcore_doc(f_enum, *c_iter);
- int value = (*c_iter)->get_value();
- f_enum << indent() << (*c_iter)->get_name() << " = " << value << "," << endl;
- }
+ vector<t_enum_value*> constants = tenum->get_constants();
+ vector<t_enum_value*>::iterator c_iter;
- scope_down(f_enum);
- end_netcore_namespace(f_enum);
- f_enum.close();
+ for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter)
+ {
+ generate_netcore_doc(out, *c_iter);
+ int value = (*c_iter)->get_value();
+ out << indent() << (*c_iter)->get_name() << " = " << value << "," << endl;
+ }
- indent_validate(ic, "generate_enum");
+ scope_down(out);
+ end_netcore_namespace(out);
}
void t_netcore_generator::generate_consts(vector<t_const*> consts)
@@ -521,20 +442,32 @@ void t_netcore_generator::generate_consts(vector<t_const*> consts)
ofstream f_consts;
f_consts.open(f_consts_name.c_str());
- f_consts << autogen_comment() << netcore_type_usings() << endl;
+ generate_consts(f_consts, consts);
+
+ f_consts.close();
+}
- start_netcore_namespace(f_consts);
+void t_netcore_generator::generate_consts(ofstream& out, vector<t_const*> consts)
+{
+ if (consts.empty())
+ {
+ return;
+ }
+
+ out << autogen_comment() << netcore_type_usings() << endl;
+
+ start_netcore_namespace(out);
- f_consts << indent() << "public static class " << make_valid_csharp_identifier(program_name_) << "Constants" << endl;
+ out << indent() << "public static class " << make_valid_csharp_identifier(program_name_) << "Constants" << endl;
- scope_up(f_consts);
+ scope_up(out);
vector<t_const*>::iterator c_iter;
bool need_static_constructor = false;
for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter)
{
- generate_netcore_doc(f_consts, *c_iter);
- if (print_const_value(f_consts, (*c_iter)->get_name(), (*c_iter)->get_type(), (*c_iter)->get_value(), false))
+ generate_netcore_doc(out, *c_iter);
+ if (print_const_value(out, (*c_iter)->get_name(), (*c_iter)->get_type(), (*c_iter)->get_value(), false))
{
need_static_constructor = true;
}
@@ -542,12 +475,11 @@ void t_netcore_generator::generate_consts(vector<t_const*> consts)
if (need_static_constructor)
{
- print_const_constructor(f_consts, consts);
+ print_const_constructor(out, consts);
}
- scope_down(f_consts);
- end_netcore_namespace(f_consts);
- f_consts.close();
+ scope_down(out);
+ end_netcore_namespace(out);
}
void t_netcore_generator::print_const_def_value(ofstream& out, string name, t_type* type, t_const_value* value)
@@ -654,7 +586,7 @@ bool t_netcore_generator::print_const_value(ofstream& out, string name, t_type*
if (type->is_base_type())
{
string v2 = render_const_value(out, name, type, value);
- out << name << " = " << v2 << ";" << endl;
+ out << normalize_name(name) << " = " << v2 << ";" << endl;
need_static_construction = false;
}
else if (type->is_enum())
@@ -1414,7 +1346,7 @@ void t_netcore_generator::generate_netcore_union_definition(ofstream& out, t_str
<< indent() << "{" << endl;
indent_up();
- out << indent() << "public abstract void Write(TProtocol protocol);" << endl
+ out << indent() << "public abstract Task WriteAsync(TProtocol tProtocol, CancellationToken cancellationToken);" << endl
<< indent() << "public readonly bool Isset;" << endl
<< indent() << "public abstract object Data { get; }" << endl
<< indent() << "protected " << tunion->get_name() << "(bool isset)" << endl
@@ -1431,7 +1363,7 @@ void t_netcore_generator::generate_netcore_union_definition(ofstream& out, t_str
out << indent() << "public override object Data { get { return null; } }" << endl
<< indent() << "public ___undefined() : base(false) {}" << endl << endl;
- out << indent() << "public override void Write(TProtocol protocol)" << endl
+ out << indent() << "public override Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)" << endl
<< indent() << "{" << endl;
indent_up();
out << indent() << "throw new TProtocolException( TProtocolException.INVALID_DATA, \"Cannot persist an union type which is not set.\");" << endl;
@@ -1491,8 +1423,8 @@ void t_netcore_generator::generate_netcore_union_class(ofstream& out, t_struct*
generate_serialize_field(out, tfield, "_data", true, true);
out << indent() << "await oprot.WriteFieldEndAsync(cancellationToken);" << endl
- << indent() << "await oprot.WriteFieldStop(cancellationToken);" << endl
- << indent() << "await oprot.WriteStructEnd(cancellationToken);" << endl;
+ << indent() << "await oprot.WriteFieldStopAsync(cancellationToken);" << endl
+ << indent() << "await oprot.WriteStructEndAsync(cancellationToken);" << endl;
indent_down();
out << indent() << "}" << endl
<< indent() << "finally" << endl
@@ -1511,7 +1443,7 @@ void t_netcore_generator::generate_netcore_struct_equals(ofstream& out, t_struct
out << indent() << "public override bool Equals(object that)" << endl
<< indent() << "{" << endl;
indent_up();
- out << indent() << "var other = that as " << type_name(tstruct) << ";" << endl
+ out << indent() << "var other = that as " << check_and_correct_struct_name(normalize_name(tstruct->get_name())) << ";" << endl
<< indent() << "if (other == null) return false;" << endl
<< indent() << "if (ReferenceEquals(this, other)) return true;" << endl;
@@ -2178,7 +2110,7 @@ void t_netcore_generator::generate_netcore_union_reader(ofstream& out, t_struct*
const vector<t_field*>& fields = tunion->get_members();
vector<t_field*>::const_iterator f_iter;
- out << indent() << "public static " << tunion->get_name() << " Read(TProtocol iprot)" << endl;
+ out << indent() << "public static async Task<" << tunion->get_name() << "> ReadAsync(TProtocol iprot, CancellationToken cancellationToken)" << endl;
scope_up(out);
out << indent() << "iprot.IncrementRecursionDepth();" << endl;
@@ -2186,12 +2118,12 @@ void t_netcore_generator::generate_netcore_union_reader(ofstream& out, t_struct*
scope_up(out);
out << indent() << tunion->get_name() << " retval;" << endl;
- out << indent() << "iprot.ReadStructBegin();" << endl;
- out << indent() << "TField field = iprot.ReadFieldBegin();" << endl;
+ out << indent() << "await iprot.ReadStructBeginAsync(cancellationToken);" << endl;
+ out << indent() << "TField field = await iprot.ReadFieldBeginAsync(cancellationToken);" << endl;
// we cannot have the first field be a stop -- we must have a single field defined
out << indent() << "if (field.Type == TType.Stop)" << endl;
scope_up(out);
- out << indent() << "iprot.ReadFieldEnd();" << endl;
+ out << indent() << "await iprot.ReadFieldEndAsync(cancellationToken);" << endl;
out << indent() << "retval = new ___undefined();" << endl;
scope_down(out);
out << indent() << "else" << endl;
@@ -2211,7 +2143,7 @@ void t_netcore_generator::generate_netcore_union_reader(ofstream& out, t_struct*
out << indent() << "retval = new " << (*f_iter)->get_name() << "(temp);" << endl;
indent_down();
- out << indent() << "} else { " << endl << indent() << " TProtocolUtil.Skip(iprot, field.Type);"
+ out << indent() << "} else { " << endl << indent() << " await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);"
<< endl << indent() << " retval = new ___undefined();" << endl << indent() << "}" << endl
<< indent() << "break;" << endl;
indent_down();
@@ -2219,23 +2151,23 @@ void t_netcore_generator::generate_netcore_union_reader(ofstream& out, t_struct*
out << indent() << "default: " << endl;
indent_up();
- out << indent() << "TProtocolUtil.Skip(iprot, field.Type);" << endl << indent()
+ out << indent() << "await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);" << endl << indent()
<< "retval = new ___undefined();" << endl;
out << indent() << "break;" << endl;
indent_down();
scope_down(out);
- out << indent() << "iprot.ReadFieldEnd();" << endl;
+ out << indent() << "await iprot.ReadFieldEndAsync(cancellationToken);" << endl;
- out << indent() << "if (iprot.ReadFieldBegin().Type != TType.Stop)" << endl;
+ out << indent() << "if ((await iprot.ReadFieldBeginAsync(cancellationToken)).Type != TType.Stop)" << endl;
scope_up(out);
out << indent() << "throw new TProtocolException(TProtocolException.INVALID_DATA);" << endl;
scope_down(out);
// end of else for TStop
scope_down(out);
- out << indent() << "iprot.ReadStructEnd();" << endl;
+ out << indent() << "await iprot.ReadStructEndAsync(cancellationToken);" << endl;
out << indent() << "return retval;" << endl;
indent_down();
@@ -2788,9 +2720,7 @@ void t_netcore_generator::prepare_member_name_mapping(t_struct* tstruct)
void t_netcore_generator::prepare_member_name_mapping(void* scope, const vector<t_field*>& members, const string& structname)
{
// begin new scope
- member_mapping_scope dummy;
- dummy.scope_member = 0;
- member_mapping_scopes.push_back(dummy);
+ member_mapping_scopes.push_back(member_mapping_scope());
member_mapping_scope& active = member_mapping_scopes.back();
active.scope_member = scope;
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/src/thrift/generate/t_netcore_generator.h
----------------------------------------------------------------------
diff --git a/compiler/cpp/src/thrift/generate/t_netcore_generator.h b/compiler/cpp/src/thrift/generate/t_netcore_generator.h
new file mode 100644
index 0000000..8d52307
--- /dev/null
+++ b/compiler/cpp/src/thrift/generate/t_netcore_generator.h
@@ -0,0 +1,137 @@
+#include <cassert>
+
+#include <string>
+#include <fstream>
+#include <iostream>
+#include <vector>
+#include <cctype>
+
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sstream>
+
+#include "thrift/platform.h"
+#include "thrift/generate/t_oop_generator.h"
+
+using std::map;
+using std::ofstream;
+using std::ostringstream;
+using std::string;
+using std::stringstream;
+using std::vector;
+
+static const string endl = "\n"; // avoid ostream << std::endl flushes
+
+class t_netcore_generator : public t_oop_generator
+{
+
+ struct member_mapping_scope
+ {
+ public:
+ member_mapping_scope() : scope_member(0) { }
+ void* scope_member;
+ map<string, string> mapping_table;
+ };
+
+public:
+ t_netcore_generator(t_program* program, const map<string, string>& parsed_options, const string& option_string);
+
+ bool is_wcf_enabled() const;
+ bool is_nullable_enabled() const;
+ bool is_hashcode_enabled() const;
+ bool is_serialize_enabled() const;
+ bool is_union_enabled() const;
+ map<string, int> get_keywords_list() const;
+
+ // overrides
+ void init_generator();
+ void close_generator();
+ void generate_consts(vector<t_const*> consts);
+ void generate_consts(ofstream& out, vector<t_const*> consts);
+ void generate_typedef(t_typedef* ttypedef);
+ void generate_enum(t_enum* tenum);
+ void generate_enum(ofstream& out, t_enum* tenum);
+ void generate_struct(t_struct* tstruct);
+ void generate_xception(t_struct* txception);
+ void generate_service(t_service* tservice);
+
+ void generate_property(ofstream& out, t_field* tfield, bool isPublic, bool generateIsset);
+ void generate_netcore_property(ofstream& out, t_field* tfield, bool isPublic, bool includeIsset = true, string fieldPrefix = "");
+ bool print_const_value(ofstream& out, string name, t_type* type, t_const_value* value, bool in_static, bool defval = false, bool needtype = false);
+ string render_const_value(ofstream& out, string name, t_type* type, t_const_value* value);
+ void print_const_constructor(ofstream& out, vector<t_const*> consts);
+ void print_const_def_value(ofstream& out, string name, t_type* type, t_const_value* value);
+ void generate_netcore_struct(t_struct* tstruct, bool is_exception);
+ void generate_netcore_union(t_struct* tunion);
+ void generate_netcore_struct_definition(ofstream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false);
+ void generate_netcore_union_definition(ofstream& out, t_struct* tunion);
+ void generate_netcore_union_class(ofstream& out, t_struct* tunion, t_field* tfield);
+ void generate_netcore_wcffault(ofstream& out, t_struct* tstruct);
+ void generate_netcore_struct_reader(ofstream& out, t_struct* tstruct);
+ void generate_netcore_struct_result_writer(ofstream& out, t_struct* tstruct);
+ void generate_netcore_struct_writer(ofstream& out, t_struct* tstruct);
+ void generate_netcore_struct_tostring(ofstream& out, t_struct* tstruct);
+ void generate_netcore_struct_equals(ofstream& out, t_struct* tstruct);
+ void generate_netcore_struct_hashcode(ofstream& out, t_struct* tstruct);
+ void generate_netcore_union_reader(ofstream& out, t_struct* tunion);
+ void generate_function_helpers(ofstream& out, t_function* tfunction);
+ void generate_service_interface(ofstream& out, t_service* tservice);
+ void generate_service_helpers(ofstream& out, t_service* tservice);
+ void generate_service_client(ofstream& out, t_service* tservice);
+ void generate_service_server(ofstream& out, t_service* tservice);
+ void generate_process_function_async(ofstream& out, t_service* tservice, t_function* function);
+ void generate_deserialize_field(ofstream& out, t_field* tfield, string prefix = "", bool is_propertyless = false);
+ void generate_deserialize_struct(ofstream& out, t_struct* tstruct, string prefix = "");
+ void generate_deserialize_container(ofstream& out, t_type* ttype, string prefix = "");
+ void generate_deserialize_set_element(ofstream& out, t_set* tset, string prefix = "");
+ void generate_deserialize_map_element(ofstream& out, t_map* tmap, string prefix = "");
+ void generate_deserialize_list_element(ofstream& out, t_list* list, string prefix = "");
+ void generate_serialize_field(ofstream& out, t_field* tfield, string prefix = "", bool is_element = false, bool is_propertyless = false);
+ void generate_serialize_struct(ofstream& out, t_struct* tstruct, string prefix = "");
+ void generate_serialize_container(ofstream& out, t_type* ttype, string prefix = "");
+ void generate_serialize_map_element(ofstream& out, t_map* tmap, string iter, string map);
+ void generate_serialize_set_element(ofstream& out, t_set* tmap, string iter);
+ void generate_serialize_list_element(ofstream& out, t_list* tlist, string iter);
+ void generate_netcore_doc(ofstream& out, t_field* field);
+ void generate_netcore_doc(ofstream& out, t_doc* tdoc);
+ void generate_netcore_doc(ofstream& out, t_function* tdoc);
+ void generate_netcore_docstring_comment(ofstream& out, string contents);
+ void docstring_comment(ofstream& out, const string& comment_start, const string& line_prefix, const string& contents, const string& comment_end);
+ void start_netcore_namespace(ofstream& out);
+ void end_netcore_namespace(ofstream& out);
+
+ string netcore_type_usings() const;
+ string netcore_thrift_usings() const;
+
+ string type_name(t_type* ttype, bool in_countainer = false, bool in_init = false, bool in_param = false, bool is_required = false);
+ string base_type_name(t_base_type* tbase, bool in_container = false, bool in_param = false, bool is_required = false);
+ string declare_field(t_field* tfield, bool init = false, string prefix = "");
+ string function_signature_async(t_function* tfunction, string prefix = "");
+ string function_signature(t_function* tfunction, string prefix = "");
+ string argument_list(t_struct* tstruct);
+ string type_to_enum(t_type* ttype);
+ string prop_name(t_field* tfield, bool suppress_mapping = false);
+ string get_enum_class_name(t_type* type);
+
+private:
+ string namespace_name_;
+ string namespace_dir_;
+
+ bool nullable_;
+ bool union_;
+ bool hashcode_;
+ bool serialize_;
+ bool wcf_;
+
+ string wcf_namespace_;
+ map<string, int> netcore_keywords;
+ vector<member_mapping_scope> member_mapping_scopes;
+
+ void init_keywords();
+ string normalize_name(string name);
+ string make_valid_csharp_identifier(string const& fromName);
+ void prepare_member_name_mapping(t_struct* tstruct);
+ void prepare_member_name_mapping(void* scope, const vector<t_field*>& members, const string& structname);
+ void cleanup_member_name_mapping(void* scope);
+ string get_mapped_member_name(string oldname);
+};
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/CMakeLists.txt b/compiler/cpp/tests/CMakeLists.txt
new file mode 100644
index 0000000..e2b100c
--- /dev/null
+++ b/compiler/cpp/tests/CMakeLists.txt
@@ -0,0 +1,153 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+cmake_minimum_required(VERSION 2.8.12)
+
+project(thrift_compiler_tests)
+
+set(THRIFT_COMPILER_SOURCE_DIR
+ ${CMAKE_CURRENT_SOURCE_DIR}/..
+)
+
+# don't generate ZERO_CHECK
+set(CMAKE_SUPPRESS_REGENERATION true)
+
+configure_file(${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/thrift/version.h)
+if(MSVC)
+ # The winflexbison generator outputs some macros that conflict with the Visual Studio 2010 copy of stdint.h
+ # This might be fixed in later versions of Visual Studio, but an easy solution is to include stdint.h first
+ if(HAVE_STDINT_H)
+ add_definitions(-D__STDC_LIMIT_MACROS)
+ add_definitions(/FI"stdint.h")
+ endif(HAVE_STDINT_H)
+endif()
+
+find_package(FLEX REQUIRED)
+find_package(BISON REQUIRED)
+
+# create directory for thrifty and thriftl
+file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/thrift/)
+
+# Create flex and bison files and build the lib parse static library
+BISON_TARGET(thrifty ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/thrifty.yy ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.cc)
+FLEX_TARGET(thriftl ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/thriftl.ll ${CMAKE_CURRENT_BINARY_DIR}/thrift/thriftl.cc)
+ADD_FLEX_BISON_DEPENDENCY(thriftl thrifty)
+
+set(parse_SOURCES
+ ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.cc
+ ${CMAKE_CURRENT_BINARY_DIR}/thrift/thriftl.cc
+ ${CMAKE_CURRENT_BINARY_DIR}/thrift/thrifty.hh
+)
+
+add_library(parse STATIC ${parse_SOURCES})
+
+# Thrift compiler tests
+set(thrift_compiler_tests
+)
+
+# you can add some files manually there
+set(thrift_compiler_tests_manual_SOURCES
+ # tests file to avoid main in every test file
+ ${CMAKE_CURRENT_SOURCE_DIR}/tests_main.cc
+)
+
+# set variable for tests sources - will be filled later
+set(thrift_compiler_tests_SOURCES
+)
+
+set(thrift_compiler_SOURCES
+ ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/logging.cc # we use logging instead of main to avoid breaking compillation (2 main v)
+ ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/audit/t_audit.cpp
+ ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/common.cc
+ ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/generate/t_generator.cc
+ ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/parse/t_typedef.cc
+ ${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/parse/parse.cc
+ ${CMAKE_CURRENT_BINARY_DIR}/thrift/version.h
+)
+
+# This macro adds an option THRIFT_COMPILER_${NAME}
+# that allows enabling or disabling certain languages
+macro(THRIFT_ADD_COMPILER name description initial)
+ string(TOUPPER "THRIFT_COMPILER_${name}" enabler)
+ set(src "${THRIFT_COMPILER_SOURCE_DIR}/src/thrift/generate/t_${name}_generator.cc")
+ option(${enabler} ${description} ${initial})
+ if(${enabler})
+ list(APPEND thrift_compiler_SOURCES ${src})
+ file(GLOB thrift_compiler_tests_SOURCES
+ "${CMAKE_CURRENT_SOURCE_DIR}/${name}/*.c*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/${name}/*.thrift"
+ )
+ endif()
+endmacro()
+
+# The following compiler with unit tests can be enabled or disabled
+THRIFT_ADD_COMPILER(c_glib "Enable compiler for C with Glib" OFF)
+THRIFT_ADD_COMPILER(cpp "Enable compiler for C++" OFF)
+THRIFT_ADD_COMPILER(java "Enable compiler for Java" OFF)
+THRIFT_ADD_COMPILER(as3 "Enable compiler for ActionScript 3" OFF)
+THRIFT_ADD_COMPILER(dart "Enable compiler for Dart" OFF)
+THRIFT_ADD_COMPILER(haxe "Enable compiler for Haxe" OFF)
+THRIFT_ADD_COMPILER(csharp "Enable compiler for C#" OFF)
+THRIFT_ADD_COMPILER(netcore "Enable compiler for .NET Core" ON)
+THRIFT_ADD_COMPILER(py "Enable compiler for Python 2.0" OFF)
+THRIFT_ADD_COMPILER(rb "Enable compiler for Ruby" OFF)
+THRIFT_ADD_COMPILER(perl "Enable compiler for Perl" OFF)
+THRIFT_ADD_COMPILER(php "Enable compiler for PHP" OFF)
+THRIFT_ADD_COMPILER(erl "Enable compiler for Erlang" OFF)
+THRIFT_ADD_COMPILER(cocoa "Enable compiler for Cocoa Objective-C" OFF)
+THRIFT_ADD_COMPILER(swift "Enable compiler for Cocoa Swift" OFF)
+THRIFT_ADD_COMPILER(st "Enable compiler for Smalltalk" OFF)
+THRIFT_ADD_COMPILER(ocaml "Enable compiler for OCaml" OFF)
+THRIFT_ADD_COMPILER(hs "Enable compiler for Haskell" OFF)
+THRIFT_ADD_COMPILER(xsd "Enable compiler for XSD" OFF)
+THRIFT_ADD_COMPILER(html "Enable compiler for HTML Documentation" OFF)
+THRIFT_ADD_COMPILER(js "Enable compiler for JavaScript" OFF)
+THRIFT_ADD_COMPILER(json "Enable compiler for JSON" OFF)
+THRIFT_ADD_COMPILER(javame "Enable compiler for Java ME" OFF)
+THRIFT_ADD_COMPILER(delphi "Enable compiler for Delphi" OFF)
+THRIFT_ADD_COMPILER(go "Enable compiler for Go" OFF)
+THRIFT_ADD_COMPILER(d "Enable compiler for D" OFF)
+THRIFT_ADD_COMPILER(lua "Enable compiler for Lua" OFF)
+THRIFT_ADD_COMPILER(gv "Enable compiler for GraphViz" OFF)
+THRIFT_ADD_COMPILER(rs "Enable compiler for Rust" OFF)
+THRIFT_ADD_COMPILER(xml "Enable compiler for XML" OFF)
+
+# Thrift is looking for include files in the src directory
+# we also add the current binary directory for generated files
+include_directories(${CMAKE_CURRENT_BINARY_DIR} ${THRIFT_COMPILER_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/catch)
+
+add_library(thrift_compiler ${thrift_compiler_SOURCES})
+
+#link parse lib to thrift_compiler lib
+target_link_libraries(thrift_compiler parse)
+
+# add tests executable
+add_executable(thrift_compiler_tests ${thrift_compiler_tests_manual_SOURCES} ${thrift_compiler_tests_SOURCES})
+
+# if generates for Visual Studio set thrift_compiler_tests as default project
+if(MSVC)
+ set_property(TARGET thrift_compiler_tests PROPERTY VS_STARTUP_PROJECT thrift_compiler_tests)
+endif()
+
+set_target_properties(thrift_compiler_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY bin/)
+set_target_properties(thrift_compiler_tests PROPERTIES OUTPUT_NAME thrift_compiler_tests)
+
+target_link_libraries(thrift_compiler_tests thrift_compiler)
+
+enable_testing()
+add_test(NAME ThriftTests COMMAND thrift_compiler_tests)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/README.md
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/README.md b/compiler/cpp/tests/README.md
new file mode 100644
index 0000000..27be491
--- /dev/null
+++ b/compiler/cpp/tests/README.md
@@ -0,0 +1,88 @@
+# Build and run compiler tests using CMake
+
+<!-- TOC -->
+
+- [Build and run compiler tests using CMake](#build-and-run-compiler-tests-using-cmake)
+ - [General information](#general-information)
+ - [How to add your tests](#how-to-add-your-tests)
+ - [Build and run tests on Unix-like systems](#build-and-run-tests-on-unix-like-systems)
+ - [Prerequisites:](#prerequisites)
+ - [Build and run test with CMake](#build-and-run-test-with-cmake)
+ - [Build and run tests on Windows](#build-and-run-tests-on-windows)
+ - [Prerequisites:](#prerequisites-1)
+ - [Generation of VS project with CMake, build and run on Windows](#generation-of-vs-project-with-cmake-build-and-run-on-windows)
+
+<!-- /TOC -->
+
+## General information
+
+Added generic way to cover code by tests for many languages (you just need to make a correct header file for generator for your language - example in **netcore** implementation)
+
+At current moment these tests use free Catch library (https://github.com/catchorg/Catch2/tree/Catch1.x) for easy test creation and usage.
+Decision to use it was because of simplicity, easy usage, one header file to use, stable community and growing interest (https://cpp.libhunt.com/project/googletest-google/vs/catch?rel=cmp-cmp)
+
+Also, maybe, later it will be migrated to Catch2 (https://github.com/philsquared/Catch) - depends on need to support legacy compilers (c++98)
+
+## How to add your tests
+
+- Open **CMakeLists.txt**
+- Set **On** to call of **THRIFT_ADD_COMPILER** for your language
+
+``` cmake
+THRIFT_ADD_COMPILER(netcore "Enable compiler for .NET Core" ON)
+```
+
+- Create folder with name specified in list of languages in **CMakeLists.txt**
+- Create tests in folder for your language (with extensions like *.c* - cc, cpp, etc)
+ - Don't forget to add include of catch.hpp in your test file
+ ``` C
+ #include "../catch/catch.hpp"
+ ```
+
+- If you need - add files manually to **thrift_compiler_tests_manual_SOURCES** in **CMakeLists.txt** similar to
+
+``` cmake
+# you can add some files manually there
+set(thrift_compiler_tests_manual_SOURCES
+ # tests file to avoid main in every test file
+ ${CMAKE_CURRENT_SOURCE_DIR}/tests_main.cc
+)
+```
+
+- Run **cmake** with arguments for your environment and compiler
+- Enjoy
+
+## Build and run tests on Unix-like systems
+
+### Prerequisites:
+- Install CMake - <https://cmake.org/download/>
+- Install winflexbison - <https://sourceforge.net/projects/winflexbison/>
+
+### Build and run test with CMake
+
+- Run commands in command line in current directory:
+
+```
+mkdir cmake-vs && cd cmake-vs
+cmake ..
+cmake --build .
+ctest -C Debug -V
+```
+
+## Build and run tests on Windows
+
+### Prerequisites:
+- Install CMake - <https://cmake.org/download/>
+- Install winflexbison - <https://sourceforge.net/projects/winflexbison/>
+- Install VS2017 Community Edition - <https://www.visualstudio.com/vs/whatsnew/> (ensure that you installed workload "Desktop Development with C++" for VS2017)
+
+### Generation of VS project with CMake, build and run on Windows
+- Run commands in command line in current directory (ensure that VS installed):
+
+```
+mkdir cmake-vs
+cd cmake-vs
+cmake ..
+cmake --build .
+ctest -C Debug -V
+```
\ No newline at end of file
[5/9] thrift git commit: THRIFT-4434: .NET Core cleanup and the
beginnings of compiler unit tests Client: netcore
Posted by jk...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc b/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc
new file mode 100644
index 0000000..0b8c837
--- /dev/null
+++ b/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests.cc
@@ -0,0 +1,339 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "../catch/catch.hpp"
+#include <thrift/parse/t_program.h>
+#include <thrift/generate/t_netcore_generator.h>
+#include "t_netcore_generator_functional_tests_helpers.h"
+
+TEST_CASE( "t_netcore_generator should generate valid enum", "[functional]" )
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+
+ std::pair<string, t_enum*> pair = TestDataGenerator::get_test_enum_data(program);
+ string expected_result = pair.first;
+ t_enum* test_enum = pair.second;
+
+ string file_path = test_enum->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_enum(out, test_enum));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete test_enum;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid void", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_void_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_THROWS(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ delete const_;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid string with escaping keyword", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_string_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete const_;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid bool with escaping keyword", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_bool_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete const_;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid sbyte (i8) with escaping keyword", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_i8_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete const_;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid short (i16) with escaping keyword", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_i16_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete const_;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid integer (i32) with escaping keyword", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_i32_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete const_;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid long (i64) with escaping keyword", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_i64_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete const_;
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should generate valid double with escaping keyword", "[functional]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+
+ std::pair<string, t_const*> pair = TestDataGenerator::get_test_double_const_data(gen);
+ string expected_result = pair.first;
+ t_const* const_ = pair.second;
+ vector<t_const*> consts_;
+ consts_.push_back(const_);
+
+ string file_path = const_->get_name() + ".cs";
+ ofstream out;
+ out.open(file_path.c_str());
+
+ REQUIRE_NOTHROW(gen->generate_consts(out, consts_));
+
+ out.close();
+
+ std::ifstream ifs(file_path);
+ string actual_result((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
+ std::remove(file_path.c_str());
+
+ REQUIRE(expected_result == actual_result);
+
+ delete const_;
+ delete gen;
+ delete program;
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc b/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc
new file mode 100644
index 0000000..92c170b
--- /dev/null
+++ b/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.cc
@@ -0,0 +1,237 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <thrift/parse/t_program.h>
+#include "thrift/common.h"
+#include <thrift/generate/t_netcore_generator.h>
+#include "t_netcore_generator_functional_tests_helpers.h"
+
+const string TestDataGenerator::DEFAULT_FILE_HEADER = "/**" "\n"
+ " * Autogenerated by Thrift Compiler ()" "\n"
+ " *" "\n"
+ " * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING" "\n"
+ " * @generated" "\n"
+ " */";
+
+std::pair<string, t_enum*> TestDataGenerator::get_test_enum_data(t_program* program)
+{
+ string expected_result = DEFAULT_FILE_HEADER +
+ "\n"
+ "\n"
+ "/// <summary>\n"
+ "/// TestDoc\n"
+ "/// </summary>\n"
+ "public enum TestName\n"
+ "{\n"
+ " None = 0,\n"
+ " First = 1,\n"
+ " Second = 2,\n"
+ "}\n";
+
+ t_enum* enum_ = new t_enum(program);
+ enum_->set_name("TestName");
+ enum_->set_doc("TestDoc");
+ enum_->append(new t_enum_value("None", 0));
+ enum_->append(new t_enum_value("First", 1));
+ enum_->append(new t_enum_value("Second", 2));
+
+ return std::pair<string, t_enum*>(expected_result, enum_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_void_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER;
+
+ t_type* type_ = new t_base_type("void", t_base_type::TYPE_VOID);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_string("VoidValue");
+
+ t_const* const_ = new t_const(type_, "void", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_string_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() +
+ "\n"
+ "public static class netcoreConstants\n"
+ "{\n"
+ " /// <summary>\n"
+ " /// TestDoc\n"
+ " /// </summary>\n"
+ " public const string @string = \"StringValue\";\n"
+ "}\n";
+
+ t_type* type_ = new t_base_type("string", t_base_type::TYPE_STRING);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_string("StringValue");
+
+ t_const* const_ = new t_const(type_, "string", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_bool_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() +
+ "\n"
+ "public static class netcoreConstants\n"
+ "{\n"
+ " /// <summary>\n"
+ " /// TestDoc\n"
+ " /// </summary>\n"
+ " public const bool @bool = true;\n"
+ "}\n";
+
+ t_type* type_ = new t_base_type("bool", t_base_type::TYPE_BOOL);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_integer(1);
+
+ t_const* const_ = new t_const(type_, "bool", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_i8_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() +
+ "\n"
+ "public static class netcoreConstants\n"
+ "{\n"
+ " /// <summary>\n"
+ " /// TestDoc\n"
+ " /// </summary>\n"
+ " public const sbyte @sbyte = 127;\n"
+ "}\n";
+
+ t_type* type_ = new t_base_type("I8", t_base_type::TYPE_I8);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_integer(127);
+
+ t_const* const_ = new t_const(type_, "sbyte", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_i16_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() +
+ "\n"
+ "public static class netcoreConstants\n"
+ "{\n"
+ " /// <summary>\n"
+ " /// TestDoc\n"
+ " /// </summary>\n"
+ " public const short @short = 32767;\n"
+ "}\n";
+
+ t_type* type_ = new t_base_type("i16", t_base_type::TYPE_I16);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_integer(32767);
+
+ t_const* const_ = new t_const(type_, "short", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_i32_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() +
+ "\n"
+ "public static class netcoreConstants\n"
+ "{\n"
+ " /// <summary>\n"
+ " /// TestDoc\n"
+ " /// </summary>\n"
+ " public const int @int = 2147483647;\n"
+ "}\n";
+
+ t_type* type_ = new t_base_type("i32", t_base_type::TYPE_I32);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_integer(2147483647);
+
+ t_const* const_ = new t_const(type_, "int", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_i64_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() +
+ "\n"
+ "public static class netcoreConstants\n"
+ "{\n"
+ " /// <summary>\n"
+ " /// TestDoc\n"
+ " /// </summary>\n"
+ " public const long @long = 9223372036854775807;\n"
+ "}\n";
+
+ t_type* type_ = new t_base_type("i64", t_base_type::TYPE_I64);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_integer(9223372036854775807);
+
+ t_const* const_ = new t_const(type_, "long", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
+
+std::pair<string, t_const*> TestDataGenerator::get_test_double_const_data(t_netcore_generator* gen)
+{
+ string expected_result = DEFAULT_FILE_HEADER + "\n" +gen->netcore_type_usings() +
+ "\n"
+ "public static class netcoreConstants\n"
+ "{\n"
+ " /// <summary>\n"
+ " /// TestDoc\n"
+ " /// </summary>\n"
+ " public const double @double = 9.22337e+18;\n"
+ "}\n";
+
+ t_type* type_ = new t_base_type("double", t_base_type::TYPE_DOUBLE);
+ type_->set_doc("TestDoc");
+
+ t_const_value* const_value_ = new t_const_value();
+ const_value_->set_double(9223372036854775807.1);
+
+ t_const* const_ = new t_const(type_, "double", const_value_);
+ const_->set_doc("TestDoc");
+
+ return std::pair<string, t_const*>(expected_result, const_);
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h b/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h
new file mode 100644
index 0000000..c6eaac2
--- /dev/null
+++ b/compiler/cpp/tests/netcore/t_netcore_generator_functional_tests_helpers.h
@@ -0,0 +1,34 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <thrift/parse/t_program.h>
+
+class TestDataGenerator
+{
+public:
+ static const string DEFAULT_FILE_HEADER;
+
+ static std::pair<string, t_enum*> get_test_enum_data(t_program* program);
+ static std::pair<string, t_const*> get_test_void_const_data(t_netcore_generator* gen);
+ static std::pair<string, t_const*> get_test_string_const_data(t_netcore_generator* gen);
+ static std::pair<string, t_const*> get_test_bool_const_data(t_netcore_generator* gen);
+ static std::pair<string, t_const*> get_test_i8_const_data(t_netcore_generator* gen);
+ static std::pair<string, t_const*> get_test_i16_const_data(t_netcore_generator* gen);
+ static std::pair<string, t_const*> get_test_i32_const_data(t_netcore_generator* gen);
+ static std::pair<string, t_const*> get_test_i64_const_data(t_netcore_generator* gen);
+ static std::pair<string, t_const*> get_test_double_const_data(t_netcore_generator* gen);
+};
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc b/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc
new file mode 100644
index 0000000..0bcbeed
--- /dev/null
+++ b/compiler/cpp/tests/netcore/t_netcore_generator_helpers_tests.cc
@@ -0,0 +1,209 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "../catch/catch.hpp"
+#include <thrift/parse/t_program.h>
+#include <thrift/generate/t_netcore_generator.h>
+
+using std::vector;
+
+TEST_CASE("t_netcore_generator::netcore_type_usings() without option wcf should return valid namespaces", "[helpers]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "union", "union" } };
+ string option_string = "";
+
+ string expected_namespaces = "using System;\n"
+ "using System.Collections;\n"
+ "using System.Collections.Generic;\n"
+ "using System.Text;\n"
+ "using System.IO;\n"
+ "using System.Threading;\n"
+ "using System.Threading.Tasks;\n"
+ "using Thrift;\n"
+ "using Thrift.Collections;\n" + endl;
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+
+ REQUIRE_FALSE(gen->is_wcf_enabled());
+ REQUIRE(gen->netcore_type_usings() == expected_namespaces);
+
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator::netcore_type_usings() with option wcf should return valid namespaces", "[helpers]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+
+ string expected_namespaces_wcf = "using System;\n"
+ "using System.Collections;\n"
+ "using System.Collections.Generic;\n"
+ "using System.Text;\n"
+ "using System.IO;\n"
+ "using System.Threading;\n"
+ "using System.Threading.Tasks;\n"
+ "using Thrift;\n"
+ "using Thrift.Collections;\n"
+ "using System.ServiceModel;\n"
+ "using System.Runtime.Serialization;\n" + endl;
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+
+ REQUIRE(gen->is_wcf_enabled());
+ REQUIRE(gen->netcore_type_usings() == expected_namespaces_wcf);
+
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should contains latest C# keywords to normalize with @", "[helpers]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" } };
+ string option_string = "";
+ vector<string> current_keywords = {
+ { "abstract" },
+ { "as" },
+ { "base" },
+ { "bool" },
+ { "break" },
+ { "byte" },
+ { "case" },
+ { "catch" },
+ { "char" },
+ { "checked" },
+ { "class" },
+ { "const" },
+ { "continue" },
+ { "decimal" },
+ { "default" },
+ { "delegate" },
+ { "do" },
+ { "double" },
+ { "else" },
+ { "enum" },
+ { "event" },
+ { "explicit" },
+ { "extern" },
+ { "false" },
+ { "finally" },
+ { "fixed" },
+ { "float" },
+ { "for" },
+ { "foreach" },
+ { "goto" },
+ { "if" },
+ { "implicit" },
+ { "in" },
+ { "int" },
+ { "interface" },
+ { "internal" },
+ { "is" },
+ { "lock" },
+ { "long" },
+ { "namespace" },
+ { "new" },
+ { "null" },
+ { "object" },
+ { "operator" },
+ { "out" },
+ { "override" },
+ { "params" },
+ { "private" },
+ { "protected" },
+ { "public" },
+ { "readonly" },
+ { "ref" },
+ { "return" },
+ { "sbyte" },
+ { "sealed" },
+ { "short" },
+ { "sizeof" },
+ { "stackalloc" },
+ { "static" },
+ { "string" },
+ { "struct" },
+ { "switch" },
+ { "this" },
+ { "throw" },
+ { "true" },
+ { "try" },
+ { "typeof" },
+ { "uint" },
+ { "ulong" },
+ { "unchecked" },
+ { "unsafe" },
+ { "ushort" },
+ { "using" },
+ { "void" },
+ { "volatile" },
+ { "while" },
+ // Contextual Keywords
+ { "add" },
+ { "alias" },
+ { "ascending" },
+ { "async" },
+ { "await" },
+ { "descending" },
+ { "dynamic" },
+ { "from" },
+ { "get" },
+ { "global" },
+ { "group" },
+ { "into" },
+ { "join" },
+ { "let" },
+ { "orderby" },
+ { "partial" },
+ { "remove" },
+ { "select" },
+ { "set" },
+ { "value" },
+ { "var" },
+ { "when" },
+ { "where" },
+ { "yield" }
+ };
+
+ string missed_keywords = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+ gen->init_generator();
+ map<string, int> generators_keywords = gen->get_keywords_list();
+
+ for (vector<string>::iterator it = current_keywords.begin(); it != current_keywords.end(); ++it)
+ {
+ if (generators_keywords.find(*it) == generators_keywords.end())
+ {
+ missed_keywords = missed_keywords + *it + ",";
+ }
+ }
+
+ REQUIRE(missed_keywords == "");
+
+ delete gen;
+ delete program;
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc b/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc
new file mode 100644
index 0000000..ec17733
--- /dev/null
+++ b/compiler/cpp/tests/netcore/t_netcore_generator_initialization_tests.cc
@@ -0,0 +1,74 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "../catch/catch.hpp"
+#include <thrift/parse/t_program.h>
+#include <thrift/generate/t_netcore_generator.h>
+
+TEST_CASE( "t_netcore_generator should throw error with unknown options", "[initialization]" )
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "keys", "keys" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = nullptr;
+
+ REQUIRE_THROWS(gen = new t_netcore_generator(program, parsed_options, option_string));
+
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should create valid instance with valid options", "[initialization]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" }, { "nullable", "nullable"} };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = nullptr;
+
+ REQUIRE_NOTHROW(gen = new t_netcore_generator(program, parsed_options, option_string));
+ REQUIRE(gen != nullptr);
+ REQUIRE(gen->is_wcf_enabled());
+ REQUIRE(gen->is_nullable_enabled());
+ REQUIRE_FALSE(gen->is_hashcode_enabled());
+ REQUIRE_FALSE(gen->is_serialize_enabled());
+ REQUIRE_FALSE(gen->is_union_enabled());
+
+ delete gen;
+ delete program;
+}
+
+TEST_CASE("t_netcore_generator should pass init succesfully", "[initialization]")
+{
+ string path = "CassandraTest.thrift";
+ string name = "netcore";
+ map<string, string> parsed_options = { { "wcf", "wcf" },{ "nullable", "nullable" } };
+ string option_string = "";
+
+ t_program* program = new t_program(path, name);
+ t_netcore_generator* gen = new t_netcore_generator(program, parsed_options, option_string);
+
+ REQUIRE_NOTHROW(gen->init_generator());
+
+ delete gen;
+ delete program;
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/tests_main.cc
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/tests_main.cc b/compiler/cpp/tests/tests_main.cc
new file mode 100644
index 0000000..21d09b9
--- /dev/null
+++ b/compiler/cpp/tests/tests_main.cc
@@ -0,0 +1,19 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#define CATCH_CONFIG_MAIN
+#include "catch/catch.hpp"
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Makefile.am
----------------------------------------------------------------------
diff --git a/lib/netcore/Makefile.am b/lib/netcore/Makefile.am
index facee11..992558b 100644
--- a/lib/netcore/Makefile.am
+++ b/lib/netcore/Makefile.am
@@ -19,86 +19,25 @@
SUBDIRS = .
-THRIFT = $(top_builddir)/compiler/cpp/thrift
-
-TESTDIR = Tests/Thrift.PublicInterfaces.Compile.Tests
-GENDIR = $(TESTDIR)/gen-netcore
-
THRIFTCODE = \
- Thrift/Thrift.csproj \
- Thrift/ITAsyncProcessor.cs \
- Thrift/ITProcessorFactory.cs \
- Thrift/SingletonTProcessorFactory.cs \
- Thrift/TApplicationException.cs \
- Thrift/TBaseClient.cs \
- Thrift/TException.cs \
- Thrift/TMultiplexedProcessor.cs \
- Thrift/Collections/TCollections.cs \
- Thrift/Collections/THashSet.cs \
- Thrift/Properties/AssemblyInfo.cs \
- Thrift/Protocols/ITProtocolFactory.cs \
- Thrift/Protocols/TAbstractBase.cs \
- Thrift/Protocols/TBase.cs \
- Thrift/Protocols/TBinaryProtocol.cs \
- Thrift/Protocols/TCompactProtocol.cs \
- Thrift/Protocols/TJSONProtocol.cs \
- Thrift/Protocols/TMultiplexedProtocol.cs \
- Thrift/Protocols/TProtocol.cs \
- Thrift/Protocols/TProtocolDecorator.cs \
- Thrift/Protocols/TProtocolException.cs \
- Thrift/Protocols/Entities/TField.cs \
- Thrift/Protocols/Entities/TList.cs \
- Thrift/Protocols/Entities/TMap.cs \
- Thrift/Protocols/Entities/TMessage.cs \
- Thrift/Protocols/Entities/TMessageType.cs \
- Thrift/Protocols/Entities/TSet.cs \
- Thrift/Protocols/Entities/TStruct.cs \
- Thrift/Protocols/Entities/TType.cs \
- Thrift/Protocols/Utilities/TBase64Utils.cs \
- Thrift/Protocols/Utilities/TProtocolUtil.cs \
- Thrift/Server/AsyncBaseServer.cs \
- Thrift/Server/TBaseServer.cs \
- Thrift/Server/TServerEventHandler.cs \
- Thrift/Transports/TClientTransport.cs \
- Thrift/Transports/TServerTransport.cs \
- Thrift/Transports/TTransportException.cs \
- Thrift/Transports/TTransportFactory.cs \
- Thrift/Transports/Client/TBufferedClientTransport.cs \
- Thrift/Transports/Client/TFramedClientTransport.cs \
- Thrift/Transports/Client/THttpClientTransport.cs \
- Thrift/Transports/Client/TMemoryBufferClientTransport.cs \
- Thrift/Transports/Client/TNamedPipeClientTransport.cs \
- Thrift/Transports/Client/TSocketClientTransport.cs \
- Thrift/Transports/Client/TStreamClientTransport.cs \
- Thrift/Transports/Client/TTlsSocketClientTransport.cs \
- Thrift/Transports/Server/THttpServerTransport.cs \
- Thrift/Transports/Server/TNamedPipeServerTransport.cs \
- Thrift/Transports/Server/TServerFramedTransport.cs \
- Thrift/Transports/Server/TServerSocketTransport.cs \
- Thrift/Transports/Server/TTlsServerSocketTransport.cs
+ Thrift/Thrift.csproj
all-local: \
Thrift.dll
Thrift.dll: $(THRIFTCODE)
- $(MKDIR_P) $(GENDIR)
- $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(TESTDIR)/CassandraTest.thrift
- $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/test/ThriftTest.thrift
- $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/contrib/fb303/if/fb303.thrift
- $(DOTNETCORE) --info
- $(DOTNETCORE) restore
+# $(MKDIR_P) $(GENDIR)
+# $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(TESTDIR)/CassandraTest.thrift
+# $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/test/ThriftTest.thrift
+# $(THRIFT) -gen netcore:wcf -r -out $(GENDIR) $(top_srcdir)/contrib/fb303/if/fb303.thrift
$(DOTNETCORE) build
clean-local:
- $(RM) Thrift.dll
- $(RM) -r $(GENDIR)
$(RM) -r Thrift/bin
$(RM) -r Thrift/obj
- $(RM) -r Tests/Thrift.PublicInterfaces.Compile.Tests/bin
- $(RM) -r Tests/Thrift.PublicInterfaces.Compile.Tests/obj
EXTRA_DIST = \
- $(THRIFTCODE) \
+ Thrift \
Thrift.sln \
Tests \
README.md
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/README.md
----------------------------------------------------------------------
diff --git a/lib/netcore/README.md b/lib/netcore/README.md
index 39492f3..94b047f 100644
--- a/lib/netcore/README.md
+++ b/lib/netcore/README.md
@@ -10,7 +10,10 @@ Thrift client library ported to Microsoft .Net Core
- .NET Standard 1.6 (SDK 2.0.0)
# How to build on Windows
+- Get Thrift IDL compiler executable, add to some folder and add path to this folder into PATH variable
- Open the Thrift.sln project with Visual Studio and build.
+or
+- Build with scripts
# How to build on Unix
- Ensure you have .NET Core 2.0.0 SDK installed or use the Ubuntu Xenial docker image
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore b/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore
new file mode 100644
index 0000000..7254c31
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.IntegrationTests/.gitignore
@@ -0,0 +1,2 @@
+# ignore for autogenerated files
+/Apache
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs b/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs
new file mode 100644
index 0000000..bc4afa1
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.IntegrationTests/Protocols/ProtocolsOperationsTests.cs
@@ -0,0 +1,502 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.IO;
+using System.Text;
+using System.Threading.Tasks;
+using KellermanSoftware.CompareNetObjects;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Thrift.Protocols;
+using Thrift.Protocols.Entities;
+using Thrift.Transports.Client;
+
+namespace Thrift.IntegrationTests.Protocols
+{
+ [TestClass]
+ public class ProtocolsOperationsTests
+ {
+ private readonly CompareLogic _compareLogic = new CompareLogic();
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol), TMessageType.Call)]
+ [DataRow(typeof(TBinaryProtocol), TMessageType.Exception)]
+ [DataRow(typeof(TBinaryProtocol), TMessageType.Oneway)]
+ [DataRow(typeof(TBinaryProtocol), TMessageType.Reply)]
+ [DataRow(typeof(TCompactProtocol), TMessageType.Call)]
+ [DataRow(typeof(TCompactProtocol), TMessageType.Exception)]
+ [DataRow(typeof(TCompactProtocol), TMessageType.Oneway)]
+ [DataRow(typeof(TCompactProtocol), TMessageType.Reply)]
+ [DataRow(typeof(TJsonProtocol), TMessageType.Call)]
+ [DataRow(typeof(TJsonProtocol), TMessageType.Exception)]
+ [DataRow(typeof(TJsonProtocol), TMessageType.Oneway)]
+ [DataRow(typeof(TJsonProtocol), TMessageType.Reply)]
+ public async Task WriteReadMessage_Test(Type protocolType, TMessageType messageType)
+ {
+ var expected = new TMessage(nameof(TMessage), messageType, 1);
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteMessageBeginAsync(expected);
+ await protocol.WriteMessageEndAsync();
+
+ stream.Seek(0, SeekOrigin.Begin);
+
+ var actualMessage = await protocol.ReadMessageBeginAsync();
+ await protocol.ReadMessageEndAsync();
+
+ var result = _compareLogic.Compare(expected, actualMessage);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ [ExpectedException(typeof(Exception))]
+ public async Task WriteReadStruct_Test(Type protocolType)
+ {
+ var expected = new TStruct(nameof(TStruct));
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteStructBeginAsync(expected);
+ await protocol.WriteStructEndAsync();
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadStructBeginAsync();
+ await protocol.ReadStructEndAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ [ExpectedException(typeof(Exception))]
+ public async Task WriteReadField_Test(Type protocolType)
+ {
+ var expected = new TField(nameof(TField), TType.String, 1);
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteFieldBeginAsync(expected);
+ await protocol.WriteFieldEndAsync();
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadFieldBeginAsync();
+ await protocol.ReadFieldEndAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadMap_Test(Type protocolType)
+ {
+ var expected = new TMap(TType.String, TType.String, 1);
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteMapBeginAsync(expected);
+ await protocol.WriteMapEndAsync();
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadMapBeginAsync();
+ await protocol.ReadMapEndAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadList_Test(Type protocolType)
+ {
+ var expected = new TList(TType.String, 1);
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteListBeginAsync(expected);
+ await protocol.WriteListEndAsync();
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadListBeginAsync();
+ await protocol.ReadListEndAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadSet_Test(Type protocolType)
+ {
+ var expected = new TSet(TType.String, 1);
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteSetBeginAsync(expected);
+ await protocol.WriteSetEndAsync();
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadSetBeginAsync();
+ await protocol.ReadSetEndAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadBool_Test(Type protocolType)
+ {
+ var expected = true;
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteBoolAsync(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadBoolAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadByte_Test(Type protocolType)
+ {
+ var expected = sbyte.MaxValue;
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteByteAsync(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadByteAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadI16_Test(Type protocolType)
+ {
+ var expected = short.MaxValue;
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteI16Async(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadI16Async();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadI32_Test(Type protocolType)
+ {
+ var expected = int.MaxValue;
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteI32Async(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadI32Async();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadI64_Test(Type protocolType)
+ {
+ var expected = long.MaxValue;
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteI64Async(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadI64Async();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadDouble_Test(Type protocolType)
+ {
+ var expected = double.MaxValue;
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteDoubleAsync(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadDoubleAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadString_Test(Type protocolType)
+ {
+ var expected = nameof(String);
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteStringAsync(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadStringAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ [DataTestMethod]
+ [DataRow(typeof(TBinaryProtocol))]
+ [DataRow(typeof(TCompactProtocol))]
+ [DataRow(typeof(TJsonProtocol))]
+ public async Task WriteReadBinary_Test(Type protocolType)
+ {
+ var expected = Encoding.UTF8.GetBytes(nameof(String));
+
+ try
+ {
+ var tuple = GetProtocolInstance(protocolType);
+ using (var stream = tuple.Item1)
+ {
+ var protocol = tuple.Item2;
+
+ await protocol.WriteBinaryAsync(expected);
+
+ stream?.Seek(0, SeekOrigin.Begin);
+
+ var actual = await protocol.ReadBinaryAsync();
+
+ var result = _compareLogic.Compare(expected, actual);
+ Assert.IsTrue(result.AreEqual, result.DifferencesString);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
+ }
+ }
+
+ private static Tuple<Stream, TProtocol> GetProtocolInstance(Type protocolType)
+ {
+ var memoryStream = new MemoryStream();
+ var streamClientTransport = new TStreamClientTransport(memoryStream, memoryStream);
+ var protocol = (TProtocol) Activator.CreateInstance(protocolType, streamClientTransport);
+ return new Tuple<Stream, TProtocol>(memoryStream, protocol);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj b/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj
new file mode 100644
index 0000000..f25dac5
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.IntegrationTests/Thrift.IntegrationTests.csproj
@@ -0,0 +1,29 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>netcoreapp2.0</TargetFramework>
+ <AssemblyName>Thrift.IntegrationTests</AssemblyName>
+ <PackageId>Thrift.IntegrationTests</PackageId>
+ <OutputType>Exe</OutputType>
+ <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
+ <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
+ <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
+ <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
+ <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
+ <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="CompareNETObjects" Version="4.3.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
+ <PackageReference Include="MSTest.TestAdapter" Version="1.2.0" />
+ <PackageReference Include="MSTest.TestFramework" Version="1.2.0" />
+ <PackageReference Include="System.ServiceModel.Primitives" Version="4.4.0" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\Thrift\Thrift.csproj" />
+ </ItemGroup>
+ <ItemGroup>
+ <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
+ </ItemGroup>
+
+</Project>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore b/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore
new file mode 100644
index 0000000..ae929a3
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/.gitignore
@@ -0,0 +1,4 @@
+# ignore for autogenerated files
+/ThriftTest
+/Apache
+/Facebook
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj b/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj
index f551116..c4a84a3 100644
--- a/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj
+++ b/lib/netcore/Tests/Thrift.PublicInterfaces.Compile.Tests/Thrift.PublicInterfaces.Compile.Tests.csproj
@@ -18,4 +18,19 @@
<PackageReference Include="System.ServiceModel.Primitives" Version="[4.1.0,)" />
</ItemGroup>
+ <Target Name="PreBuild" BeforeTargets="_GenerateRestoreProjectSpec;Restore;Compile">
+ <Exec Condition="'$(OS)' == 'Windows_NT'" Command="where thrift" ConsoleToMSBuild="true">
+ <Output TaskParameter="ConsoleOutput" PropertyName="PathToThrift" />
+ </Exec>
+ <Exec Condition="Exists('$(PathToThrift)')" Command="$(PathToThrift) -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./CassandraTest.thrift" />
+ <Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./CassandraTest.thrift" />
+ <Exec Condition="Exists('$(ProjectDir)/../../../compiler/cpp/thrift')" Command="$(ProjectDir)/../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./CassandraTest.thrift" />
+ <Exec Condition="Exists('$(PathToThrift)')" Command="$(PathToThrift) -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../../../test/ThriftTest.thrift" />
+ <Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../../../test/ThriftTest.thrift" />
+ <Exec Condition="Exists('$(ProjectDir)/../../../compiler/cpp/thrift')" Command="$(ProjectDir)/../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../../../test/ThriftTest.thrift" />
+ <Exec Condition="Exists('$(PathToThrift)')" Command="$(PathToThrift) -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../../../contrib/fb303/if/fb303.thrift" />
+ <Exec Condition="Exists('thrift')" Command="thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../../../contrib/fb303/if/fb303.thrift" />
+ <Exec Condition="Exists('$(ProjectDir)/../../../compiler/cpp/thrift')" Command="$(ProjectDir)/../../../compiler/cpp/thrift -out $(ProjectDir) -gen netcore:wcf,union,serial,hashcode -r ./../../../../contrib/fb303/if/fb303.thrift" />
+ </Target>
+
</Project>
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs b/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs
new file mode 100644
index 0000000..1be99b4
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.Tests/Collections/TCollectionsTests.cs
@@ -0,0 +1,83 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Thrift.Collections;
+
+namespace Thrift.Tests.Collections
+{
+ // ReSharper disable once InconsistentNaming
+ [TestClass]
+ public class TCollectionsTests
+ {
+ //TODO: Add tests for IEnumerable with objects and primitive values inside
+
+ [TestMethod]
+ public void TCollection_Equals_Primitive_Test()
+ {
+ var collection1 = new List<int> {1,2,3};
+ var collection2 = new List<int> {1,2,3};
+
+ var result = TCollections.Equals(collection1, collection2);
+
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public void TCollection_Equals_Primitive_Different_Test()
+ {
+ var collection1 = new List<int> { 1, 2, 3 };
+ var collection2 = new List<int> { 1, 2 };
+
+ var result = TCollections.Equals(collection1, collection2);
+
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public void TCollection_Equals_Objects_Test()
+ {
+ var collection1 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
+ var collection2 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
+
+ var result = TCollections.Equals(collection1, collection2);
+
+ // references to different collections
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public void TCollection_Equals_OneAndTheSameObject_Test()
+ {
+ var collection1 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
+ var collection2 = collection1;
+
+ var result = TCollections.Equals(collection1, collection2);
+
+ // references to one and the same collection
+ Assert.IsTrue(result);
+ }
+
+ private class ExampleClass
+ {
+ public int X { get; set; }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs b/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs
new file mode 100644
index 0000000..8de573e
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.Tests/Collections/THashSetTests.cs
@@ -0,0 +1,71 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Thrift.Collections;
+
+namespace Thrift.Tests.Collections
+{
+ // ReSharper disable once InconsistentNaming
+ [TestClass]
+ public class THashSetTests
+ {
+ [TestMethod]
+ public void THashSet_Equals_Primitive_Test()
+ {
+ const int value = 1;
+
+ var hashSet = new THashSet<int> {value};
+
+ Assert.IsTrue(hashSet.Contains(value));
+
+ hashSet.Remove(value);
+
+ Assert.IsTrue(hashSet.Count == 0);
+
+ hashSet.Add(value);
+
+ Assert.IsTrue(hashSet.Contains(value));
+
+ hashSet.Clear();
+
+ Assert.IsTrue(hashSet.Count == 0);
+
+ var newArr = new int[1];
+ hashSet.Add(value);
+ hashSet.CopyTo(newArr, 0);
+
+ Assert.IsTrue(newArr.Contains(value));
+
+ var en = hashSet.GetEnumerator();
+ en.MoveNext();
+
+ Assert.IsTrue((int)en.Current == value);
+
+ using (var ien = ((IEnumerable<int>)hashSet).GetEnumerator())
+ {
+ ien.MoveNext();
+
+ Assert.IsTrue(ien.Current == value);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs b/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs
new file mode 100644
index 0000000..cdc8317
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolHelperTests.cs
@@ -0,0 +1,172 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Thrift.Protocols;
+using Thrift.Protocols.Entities;
+using Thrift.Protocols.Utilities;
+
+namespace Thrift.Tests.Protocols
+{
+ [TestClass]
+ public class TJSONProtocolHelperTests
+ {
+ [TestMethod]
+ public void GetTypeNameForTypeId_Test()
+ {
+ // input/output
+ var sets = new List<Tuple<TType, byte[]>>
+ {
+ new Tuple<TType, byte[]>(TType.Bool, TJSONProtocolConstants.TypeNames.NameBool),
+ new Tuple<TType, byte[]>(TType.Byte, TJSONProtocolConstants.TypeNames.NameByte),
+ new Tuple<TType, byte[]>(TType.I16, TJSONProtocolConstants.TypeNames.NameI16),
+ new Tuple<TType, byte[]>(TType.I32, TJSONProtocolConstants.TypeNames.NameI32),
+ new Tuple<TType, byte[]>(TType.I64, TJSONProtocolConstants.TypeNames.NameI64),
+ new Tuple<TType, byte[]>(TType.Double, TJSONProtocolConstants.TypeNames.NameDouble),
+ new Tuple<TType, byte[]>(TType.String, TJSONProtocolConstants.TypeNames.NameString),
+ new Tuple<TType, byte[]>(TType.Struct, TJSONProtocolConstants.TypeNames.NameStruct),
+ new Tuple<TType, byte[]>(TType.Map, TJSONProtocolConstants.TypeNames.NameMap),
+ new Tuple<TType, byte[]>(TType.Set, TJSONProtocolConstants.TypeNames.NameSet),
+ new Tuple<TType, byte[]>(TType.List, TJSONProtocolConstants.TypeNames.NameList),
+ };
+
+ foreach (var t in sets)
+ {
+ Assert.IsTrue(TJSONProtocolHelper.GetTypeNameForTypeId(t.Item1) == t.Item2, $"Wrong mapping of TypeName {t.Item2} to TType: {t.Item1}");
+ }
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(TProtocolException))]
+ public void GetTypeNameForTypeId_TStop_Test()
+ {
+ TJSONProtocolHelper.GetTypeNameForTypeId(TType.Stop);
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(TProtocolException))]
+ public void GetTypeNameForTypeId_NonExistingTType_Test()
+ {
+ TJSONProtocolHelper.GetTypeNameForTypeId((TType)100);
+ }
+
+ [TestMethod]
+ public void GetTypeIdForTypeName_Test()
+ {
+ // input/output
+ var sets = new List<Tuple<TType, byte[]>>
+ {
+ new Tuple<TType, byte[]>(TType.Bool, TJSONProtocolConstants.TypeNames.NameBool),
+ new Tuple<TType, byte[]>(TType.Byte, TJSONProtocolConstants.TypeNames.NameByte),
+ new Tuple<TType, byte[]>(TType.I16, TJSONProtocolConstants.TypeNames.NameI16),
+ new Tuple<TType, byte[]>(TType.I32, TJSONProtocolConstants.TypeNames.NameI32),
+ new Tuple<TType, byte[]>(TType.I64, TJSONProtocolConstants.TypeNames.NameI64),
+ new Tuple<TType, byte[]>(TType.Double, TJSONProtocolConstants.TypeNames.NameDouble),
+ new Tuple<TType, byte[]>(TType.String, TJSONProtocolConstants.TypeNames.NameString),
+ new Tuple<TType, byte[]>(TType.Struct, TJSONProtocolConstants.TypeNames.NameStruct),
+ new Tuple<TType, byte[]>(TType.Map, TJSONProtocolConstants.TypeNames.NameMap),
+ new Tuple<TType, byte[]>(TType.Set, TJSONProtocolConstants.TypeNames.NameSet),
+ new Tuple<TType, byte[]>(TType.List, TJSONProtocolConstants.TypeNames.NameList),
+ };
+
+ foreach (var t in sets)
+ {
+ Assert.IsTrue(TJSONProtocolHelper.GetTypeIdForTypeName(t.Item2) == t.Item1, $"Wrong mapping of TypeName {t.Item2} to TType: {t.Item1}");
+ }
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(TProtocolException))]
+ public void GetTypeIdForTypeName_TStopTypeName_Test()
+ {
+ TJSONProtocolHelper.GetTypeIdForTypeName(new []{(byte)TType.Stop, (byte)TType.Stop});
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(TProtocolException))]
+ public void GetTypeIdForTypeName_NonExistingTypeName_Test()
+ {
+ TJSONProtocolHelper.GetTypeIdForTypeName(new byte[]{100});
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(TProtocolException))]
+ public void GetTypeIdForTypeName_EmptyName_Test()
+ {
+ TJSONProtocolHelper.GetTypeIdForTypeName(new byte[] {});
+ }
+
+ [TestMethod]
+ public void IsJsonNumeric_Test()
+ {
+ // input/output
+ var correctJsonNumeric = "+-.0123456789Ee";
+ var incorrectJsonNumeric = "AaBcDd/*\\";
+
+ var sets = correctJsonNumeric.Select(ch => new Tuple<byte, bool>((byte) ch, true)).ToList();
+ sets.AddRange(incorrectJsonNumeric.Select(ch => new Tuple<byte, bool>((byte) ch, false)));
+
+ foreach (var t in sets)
+ {
+ Assert.IsTrue(TJSONProtocolHelper.IsJsonNumeric(t.Item1) == t.Item2, $"Wrong mapping of Char {t.Item1} to bool: {t.Item2}");
+ }
+ }
+
+ [TestMethod]
+ public void ToHexVal_Test()
+ {
+ // input/output
+ var chars = "0123456789abcdef";
+ var expectedHexValues = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
+
+ var sets = chars.Select((ch, i) => new Tuple<char, byte>(ch, expectedHexValues[i])).ToList();
+
+ foreach (var t in sets)
+ {
+ var actualResult = TJSONProtocolHelper.ToHexVal((byte)t.Item1);
+ Assert.IsTrue(actualResult == t.Item2, $"Wrong mapping of char byte {t.Item1} to it expected hex value: {t.Item2}. Actual hex value: {actualResult}");
+ }
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(TProtocolException))]
+ public void ToHexVal_WrongInputChar_Test()
+ {
+ TJSONProtocolHelper.ToHexVal((byte)'s');
+ }
+
+ [TestMethod]
+ public void ToHexChar_Test()
+ {
+ // input/output
+ var hexValues = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
+ var expectedChars = "0123456789abcdef";
+
+
+ var sets = hexValues.Select((hv, i) => new Tuple<byte, char>(hv, expectedChars[i])).ToList();
+
+ foreach (var t in sets)
+ {
+ var actualResult = TJSONProtocolHelper.ToHexChar(t.Item1);
+ Assert.IsTrue(actualResult == t.Item2, $"Wrong mapping of hex value {t.Item1} to it expected char: {t.Item2}. Actual hex value: {actualResult}");
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs b/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs
new file mode 100644
index 0000000..5237360
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.Tests/Protocols/TJsonProtocolTests.cs
@@ -0,0 +1,67 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using NSubstitute;
+using Thrift.Protocols;
+using Thrift.Protocols.Entities;
+using Thrift.Transports;
+using Thrift.Transports.Client;
+
+namespace Thrift.Tests.Protocols
+{
+ // ReSharper disable once InconsistentNaming
+ [TestClass]
+ public class TJSONProtocolTests
+ {
+ [TestMethod]
+ public void TJSONProtocol_Can_Create_Instance_Test()
+ {
+ var httpClientTransport = Substitute.For<THttpClientTransport>(new Uri("http://localhost"), null);
+
+ var result = new TJSONProtocolWrapper(httpClientTransport);
+
+ Assert.IsNotNull(result);
+ Assert.IsNotNull(result.WrappedContext);
+ Assert.IsNotNull(result.WrappedReader);
+ Assert.IsNotNull(result.Transport);
+ Assert.IsTrue(result.WrappedRecursionDepth == 0);
+ Assert.IsTrue(result.WrappedRecursionLimit == TProtocol.DefaultRecursionDepth);
+
+ Assert.IsTrue(result.Transport.Equals(httpClientTransport));
+ Assert.IsTrue(result.WrappedContext.GetType().Name.Equals("JSONBaseContext", StringComparison.OrdinalIgnoreCase));
+ Assert.IsTrue(result.WrappedReader.GetType().Name.Equals("LookaheadReader", StringComparison.OrdinalIgnoreCase));
+ }
+
+ private class TJSONProtocolWrapper : TJsonProtocol
+ {
+ public TJSONProtocolWrapper(TClientTransport trans) : base(trans)
+ {
+ }
+
+ public object WrappedContext => Context;
+ public object WrappedReader => Reader;
+ public int WrappedRecursionDepth => RecursionDepth;
+ public int WrappedRecursionLimit => RecursionLimit;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj
----------------------------------------------------------------------
diff --git a/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj b/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj
new file mode 100644
index 0000000..e46f165
--- /dev/null
+++ b/lib/netcore/Tests/Thrift.Tests/Thrift.Tests.csproj
@@ -0,0 +1,18 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>netcoreapp2.0</TargetFramework>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="CompareNETObjects" Version="4.3.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
+ <PackageReference Include="MSTest.TestAdapter" Version="1.2.0" />
+ <PackageReference Include="MSTest.TestFramework" Version="1.2.0" />
+ <PackageReference Include="NSubstitute" Version="3.1.0" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\Thrift\Thrift.csproj" />
+ </ItemGroup>
+ <ItemGroup>
+ <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
+ </ItemGroup>
+</Project>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift.sln
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift.sln b/lib/netcore/Thrift.sln
index a730269..fe30aa5 100644
--- a/lib/netcore/Thrift.sln
+++ b/lib/netcore/Thrift.sln
@@ -4,10 +4,14 @@ VisualStudioVersion = 15.0.26730.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift.PublicInterfaces.Compile.Tests", "Tests\Thrift.PublicInterfaces.Compile.Tests\Thrift.PublicInterfaces.Compile.Tests.csproj", "{0676962B-98C2-49EC-B4C4-7A0451D0640B}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "Thrift\Thrift.csproj", "{D85F572F-7D80-40A4-9A9B-2731ED187C24}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift.IntegrationTests", "Tests\Thrift.IntegrationTests\Thrift.IntegrationTests.csproj", "{9F9A11BF-3C95-4E80-AFBF-768541996844}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift.Tests", "Tests\Thrift.Tests\Thrift.Tests.csproj", "{75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift.PublicInterfaces.Compile.Tests", "Tests\Thrift.PublicInterfaces.Compile.Tests\Thrift.PublicInterfaces.Compile.Tests.csproj", "{A429F05B-F511-45EF-AE7B-04E1AE9C9367}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -18,18 +22,6 @@ Global
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Debug|x64.ActiveCfg = Debug|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Debug|x64.Build.0 = Debug|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Debug|x86.ActiveCfg = Debug|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Debug|x86.Build.0 = Debug|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Release|Any CPU.Build.0 = Release|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Release|x64.ActiveCfg = Release|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Release|x64.Build.0 = Release|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Release|x86.ActiveCfg = Release|Any CPU
- {0676962B-98C2-49EC-B4C4-7A0451D0640B}.Release|x86.Build.0 = Release|Any CPU
{D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D85F572F-7D80-40A4-9A9B-2731ED187C24}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -42,12 +34,50 @@ Global
{D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|x64.Build.0 = Release|Any CPU
{D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|x86.ActiveCfg = Release|Any CPU
{D85F572F-7D80-40A4-9A9B-2731ED187C24}.Release|x86.Build.0 = Release|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x64.Build.0 = Debug|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Debug|x86.Build.0 = Debug|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x64.ActiveCfg = Release|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x64.Build.0 = Release|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x86.ActiveCfg = Release|Any CPU
+ {9F9A11BF-3C95-4E80-AFBF-768541996844}.Release|x86.Build.0 = Release|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x64.Build.0 = Debug|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Debug|x86.Build.0 = Debug|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|Any CPU.Build.0 = Release|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x64.ActiveCfg = Release|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x64.Build.0 = Release|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x86.ActiveCfg = Release|Any CPU
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1}.Release|x86.Build.0 = Release|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x64.Build.0 = Debug|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Debug|x86.Build.0 = Debug|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x64.ActiveCfg = Release|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x64.Build.0 = Release|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x86.ActiveCfg = Release|Any CPU
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
- {0676962B-98C2-49EC-B4C4-7A0451D0640B} = {F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE}
+ {9F9A11BF-3C95-4E80-AFBF-768541996844} = {F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE}
+ {75C2F9DC-3546-4D0A-A2DF-31C93516B6C1} = {F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE}
+ {A429F05B-F511-45EF-AE7B-04E1AE9C9367} = {F51FC4DA-CAC0-48B1-A069-B1712BCAA5BE}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FD20BC4A-0109-41D8-8C0C-893E784D7EF9}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TAbstractBase.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TAbstractBase.cs b/lib/netcore/Thrift/Protocols/TAbstractBase.cs
index eddb85e..4e18681 100644
--- a/lib/netcore/Thrift/Protocols/TAbstractBase.cs
+++ b/lib/netcore/Thrift/Protocols/TAbstractBase.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
[4/9] thrift git commit: THRIFT-4434: .NET Core cleanup and the
beginnings of compiler unit tests Client: netcore
Posted by jk...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TBase.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TBase.cs b/lib/netcore/Thrift/Protocols/TBase.cs
index cd11099..014e1ae 100644
--- a/lib/netcore/Thrift/Protocols/TBase.cs
+++ b/lib/netcore/Thrift/Protocols/TBase.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs b/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs
index fa0c5fc..deec85c 100644
--- a/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs
+++ b/lib/netcore/Thrift/Protocols/TBinaryProtocol.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -79,7 +79,7 @@ namespace Thrift.Protocols
}
}
- public override async Task WriteStructBeginAsync(TStruct struc, CancellationToken cancellationToken)
+ public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -293,15 +293,15 @@ namespace Thrift.Protocols
await WriteI64Async(BitConverter.DoubleToInt64Bits(d), cancellationToken);
}
- public override async Task WriteBinaryAsync(byte[] b, CancellationToken cancellationToken)
+ public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
- await WriteI32Async(b.Length, cancellationToken);
- await Trans.WriteAsync(b, 0, b.Length, cancellationToken);
+ await WriteI32Async(bytes.Length, cancellationToken);
+ await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
public override async Task<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
@@ -511,8 +511,13 @@ namespace Thrift.Protocols
var i32In = new byte[4];
await Trans.ReadAllAsync(i32In, 0, 4, cancellationToken);
- var result = ((i32In[0] & 0xff) << 24) | ((i32In[1] & 0xff) << 16) | ((i32In[2] & 0xff) << 8) |
- i32In[3] & 0xff;
+
+ var result =
+ ((i32In[0] & 0xff) << 24) |
+ ((i32In[1] & 0xff) << 16) |
+ ((i32In[2] & 0xff) << 8) |
+ i32In[3] & 0xff;
+
return result;
}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TCompactProtocol.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TCompactProtocol.cs b/lib/netcore/Thrift/Protocols/TCompactProtocol.cs
index 6d5e0bf..cecdf03 100644
--- a/lib/netcore/Thrift/Protocols/TCompactProtocol.cs
+++ b/lib/netcore/Thrift/Protocols/TCompactProtocol.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -114,7 +114,7 @@ namespace Thrift.Protocols
/// use it as an opportunity to put special placeholder markers on the field
/// stack so we can get the field id deltas correct.
/// </summary>
- public override async Task WriteStructBeginAsync(TStruct struc, CancellationToken cancellationToken)
+ public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -383,16 +383,16 @@ namespace Thrift.Protocols
await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
- public override async Task WriteBinaryAsync(byte[] b, CancellationToken cancellationToken)
+ public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
- var bufferTuple = CreateWriteVarInt32((uint) b.Length);
+ var bufferTuple = CreateWriteVarInt32((uint) bytes.Length);
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
- await Trans.WriteAsync(b, 0, b.Length, cancellationToken);
+ await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TJSONProtocol.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TJSONProtocol.cs b/lib/netcore/Thrift/Protocols/TJSONProtocol.cs
index 17aa5f7..6d33f02 100644
--- a/lib/netcore/Thrift/Protocols/TJSONProtocol.cs
+++ b/lib/netcore/Thrift/Protocols/TJSONProtocol.cs
@@ -19,6 +19,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
+using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@@ -28,8 +29,6 @@ using Thrift.Transports;
namespace Thrift.Protocols
{
- //TODO: implementation of TProtocol
-
/// <summary>
/// JSON protocol implementation for thrift.
/// This is a full-featured protocol supporting Write and Read.
@@ -42,53 +41,14 @@ namespace Thrift.Protocols
{
private const long Version = 1;
- private const int DefStringSize = 16;
-
- private static readonly byte[] Comma = {(byte) ','};
- private static readonly byte[] Colon = {(byte) ':'};
- private static readonly byte[] Lbrace = {(byte) '{'};
- private static readonly byte[] Rbrace = {(byte) '}'};
- private static readonly byte[] Lbracket = {(byte) '['};
- private static readonly byte[] Rbracket = {(byte) ']'};
- private static readonly byte[] Quote = {(byte) '"'};
- private static readonly byte[] Backslash = {(byte) '\\'};
-
- private static readonly byte[] NameBool = {(byte) 't', (byte) 'f'};
- private static readonly byte[] NameByte = {(byte) 'i', (byte) '8'};
- private static readonly byte[] NameI16 = {(byte) 'i', (byte) '1', (byte) '6'};
- private static readonly byte[] NameI32 = {(byte) 'i', (byte) '3', (byte) '2'};
- private static readonly byte[] NameI64 = {(byte) 'i', (byte) '6', (byte) '4'};
- private static readonly byte[] NameDouble = {(byte) 'd', (byte) 'b', (byte) 'l'};
- private static readonly byte[] NameStruct = {(byte) 'r', (byte) 'e', (byte) 'c'};
- private static readonly byte[] NameString = {(byte) 's', (byte) 't', (byte) 'r'};
- private static readonly byte[] NameMap = {(byte) 'm', (byte) 'a', (byte) 'p'};
- private static readonly byte[] NameList = {(byte) 'l', (byte) 's', (byte) 't'};
- private static readonly byte[] NameSet = {(byte) 's', (byte) 'e', (byte) 't'};
-
- private readonly char[] _escapeChars = "\"\\/bfnrt".ToCharArray();
-
- private readonly byte[] _escapeCharVals =
- {
- (byte) '"', (byte) '\\', (byte) '/', (byte) '\b', (byte) '\f', (byte) '\n', (byte) '\r', (byte) '\t'
- };
-
- private readonly byte[] _escseq = {(byte) '\\', (byte) 'u', (byte) '0', (byte) '0'};
-
- private readonly byte[] _jsonCharTable =
- {
- 0, 0, 0, 0, 0, 0, 0, 0, (byte) 'b', (byte) 't', (byte) 'n', 0, (byte) 'f', (byte) 'r', 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, (byte) '"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
- };
-
// Temporary buffer used by several methods
private readonly byte[] _tempBuffer = new byte[4];
// Current context that we are in
- protected JsonBaseContext Context;
+ protected JSONBaseContext Context;
// Stack of nested contexts that we may be in
- protected Stack<JsonBaseContext> ContextStack = new Stack<JsonBaseContext>();
+ protected Stack<JSONBaseContext> ContextStack = new Stack<JSONBaseContext>();
// Reader that manages a 1-byte buffer
protected LookaheadReader Reader;
@@ -102,105 +62,14 @@ namespace Thrift.Protocols
public TJsonProtocol(TClientTransport trans)
: base(trans)
{
- //throw new NotImplementedException("TJsonProtocol is not fully ready for usage");
-
- Context = new JsonBaseContext(this);
+ Context = new JSONBaseContext(this);
Reader = new LookaheadReader(this);
}
- private static byte[] GetTypeNameForTypeId(TType typeId)
- {
- switch (typeId)
- {
- case TType.Bool:
- return NameBool;
- case TType.Byte:
- return NameByte;
- case TType.I16:
- return NameI16;
- case TType.I32:
- return NameI32;
- case TType.I64:
- return NameI64;
- case TType.Double:
- return NameDouble;
- case TType.String:
- return NameString;
- case TType.Struct:
- return NameStruct;
- case TType.Map:
- return NameMap;
- case TType.Set:
- return NameSet;
- case TType.List:
- return NameList;
- default:
- throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized exType");
- }
- }
-
- private static TType GetTypeIdForTypeName(byte[] name)
- {
- var result = TType.Stop;
- if (name.Length > 1)
- {
- switch (name[0])
- {
- case (byte) 'd':
- result = TType.Double;
- break;
- case (byte) 'i':
- switch (name[1])
- {
- case (byte) '8':
- result = TType.Byte;
- break;
- case (byte) '1':
- result = TType.I16;
- break;
- case (byte) '3':
- result = TType.I32;
- break;
- case (byte) '6':
- result = TType.I64;
- break;
- }
- break;
- case (byte) 'l':
- result = TType.List;
- break;
- case (byte) 'm':
- result = TType.Map;
- break;
- case (byte) 'r':
- result = TType.Struct;
- break;
- case (byte) 's':
- if (name[1] == (byte) 't')
- {
- result = TType.String;
- }
- else if (name[1] == (byte) 'e')
- {
- result = TType.Set;
- }
- break;
- case (byte) 't':
- result = TType.Bool;
- break;
- }
- }
- if (result == TType.Stop)
- {
- throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized exType");
- }
- return result;
- }
-
/// <summary>
/// Push a new JSON context onto the stack.
/// </summary>
- protected void PushContext(JsonBaseContext c)
+ protected void PushContext(JSONBaseContext c)
{
ContextStack.Push(Context);
Context = c;
@@ -219,94 +88,60 @@ namespace Thrift.Protocols
/// Marked protected to avoid synthetic accessor in JSONListContext.Read
/// and JSONPairContext.Read
/// </summary>
- protected async Task ReadJsonSyntaxCharAsync(byte[] b, CancellationToken cancellationToken)
+ protected async Task ReadJsonSyntaxCharAsync(byte[] bytes, CancellationToken cancellationToken)
{
var ch = await Reader.ReadAsync(cancellationToken);
- if (ch != b[0])
+ if (ch != bytes[0])
{
throw new TProtocolException(TProtocolException.INVALID_DATA, $"Unexpected character: {(char) ch}");
}
}
/// <summary>
- /// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its
- /// corresponding hex value
- /// </summary>
- private static byte HexVal(byte ch)
- {
- if ((ch >= '0') && (ch <= '9'))
- {
- return (byte) ((char) ch - '0');
- }
-
- if ((ch >= 'a') && (ch <= 'f'))
- {
- ch += 10;
- return (byte) ((char) ch - 'a');
- }
-
- throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected hex character");
- }
-
- /// <summary>
- /// Convert a byte containing a hex value to its corresponding hex character
- /// </summary>
- private static byte HexChar(byte val)
- {
- val &= 0x0F;
- if (val < 10)
- {
- return (byte) ((char) val + '0');
- }
- val -= 10;
- return (byte) ((char) val + 'a');
- }
-
- /// <summary>
/// Write the bytes in array buf as a JSON characters, escaping as needed
/// </summary>
- private async Task WriteJsonStringAsync(byte[] b, CancellationToken cancellationToken)
+ private async Task WriteJsonStringAsync(byte[] bytes, CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
- var len = b.Length;
+ var len = bytes.Length;
for (var i = 0; i < len; i++)
{
- if ((b[i] & 0x00FF) >= 0x30)
+ if ((bytes[i] & 0x00FF) >= 0x30)
{
- if (b[i] == Backslash[0])
+ if (bytes[i] == TJSONProtocolConstants.Backslash[0])
{
- await Trans.WriteAsync(Backslash, cancellationToken);
- await Trans.WriteAsync(Backslash, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
}
else
{
- await Trans.WriteAsync(b, i, 1, cancellationToken);
+ await Trans.WriteAsync(bytes.ToArray(), i, 1, cancellationToken);
}
}
else
{
- _tempBuffer[0] = _jsonCharTable[b[i]];
+ _tempBuffer[0] = TJSONProtocolConstants.JsonCharTable[bytes[i]];
if (_tempBuffer[0] == 1)
{
- await Trans.WriteAsync(b, i, 1, cancellationToken);
+ await Trans.WriteAsync(bytes, i, 1, cancellationToken);
}
else if (_tempBuffer[0] > 1)
{
- await Trans.WriteAsync(Backslash, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
await Trans.WriteAsync(_tempBuffer, 0, 1, cancellationToken);
}
else
{
- await Trans.WriteAsync(_escseq, cancellationToken);
- _tempBuffer[0] = HexChar((byte) (b[i] >> 4));
- _tempBuffer[1] = HexChar(b[i]);
+ await Trans.WriteAsync(TJSONProtocolConstants.EscSequences, cancellationToken);
+ _tempBuffer[0] = TJSONProtocolHelper.ToHexChar((byte) (bytes[i] >> 4));
+ _tempBuffer[1] = TJSONProtocolHelper.ToHexChar(bytes[i]);
await Trans.WriteAsync(_tempBuffer, 0, 2, cancellationToken);
}
}
}
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
/// <summary>
@@ -321,14 +156,15 @@ namespace Thrift.Protocols
var escapeNum = Context.EscapeNumbers();
if (escapeNum)
{
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
- await Trans.WriteAsync(Utf8Encoding.GetBytes(str), cancellationToken);
+ var bytes = Utf8Encoding.GetBytes(str);
+ await Trans.WriteAsync(bytes, cancellationToken);
if (escapeNum)
{
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
}
@@ -361,14 +197,14 @@ namespace Thrift.Protocols
if (escapeNum)
{
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
await Trans.WriteAsync(Utf8Encoding.GetBytes(str), cancellationToken);
if (escapeNum)
{
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
}
@@ -376,18 +212,18 @@ namespace Thrift.Protocols
/// Write out contents of byte array b as a JSON string with base-64 encoded
/// data
/// </summary>
- private async Task WriteJsonBase64Async(byte[] b, CancellationToken cancellationToken)
+ private async Task WriteJsonBase64Async(byte[] bytes, CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
- var len = b.Length;
+ var len = bytes.Length;
var off = 0;
while (len >= 3)
{
// Encode 3 bytes at a time
- TBase64Utils.Encode(b, off, 3, _tempBuffer, 0);
+ TBase64Helper.Encode(bytes, off, 3, _tempBuffer, 0);
await Trans.WriteAsync(_tempBuffer, 0, 4, cancellationToken);
off += 3;
len -= 3;
@@ -396,37 +232,37 @@ namespace Thrift.Protocols
if (len > 0)
{
// Encode remainder
- TBase64Utils.Encode(b, off, len, _tempBuffer, 0);
+ TBase64Helper.Encode(bytes, off, len, _tempBuffer, 0);
await Trans.WriteAsync(_tempBuffer, 0, len + 1, cancellationToken);
}
- await Trans.WriteAsync(Quote, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
private async Task WriteJsonObjectStartAsync(CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
- await Trans.WriteAsync(Lbrace, cancellationToken);
- PushContext(new JsonPairContext(this));
+ await Trans.WriteAsync(TJSONProtocolConstants.LeftBrace, cancellationToken);
+ PushContext(new JSONPairContext(this));
}
private async Task WriteJsonObjectEndAsync(CancellationToken cancellationToken)
{
PopContext();
- await Trans.WriteAsync(Rbrace, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.RightBrace, cancellationToken);
}
private async Task WriteJsonArrayStartAsync(CancellationToken cancellationToken)
{
await Context.WriteAsync(cancellationToken);
- await Trans.WriteAsync(Lbracket, cancellationToken);
- PushContext(new JsonListContext(this));
+ await Trans.WriteAsync(TJSONProtocolConstants.LeftBracket, cancellationToken);
+ PushContext(new JSONListContext(this));
}
private async Task WriteJsonArrayEndAsync(CancellationToken cancellationToken)
{
PopContext();
- await Trans.WriteAsync(Rbracket, cancellationToken);
+ await Trans.WriteAsync(TJSONProtocolConstants.RightBracket, cancellationToken);
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
@@ -446,7 +282,7 @@ namespace Thrift.Protocols
await WriteJsonArrayEndAsync(cancellationToken);
}
- public override async Task WriteStructBeginAsync(TStruct struc, CancellationToken cancellationToken)
+ public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
await WriteJsonObjectStartAsync(cancellationToken);
}
@@ -460,7 +296,7 @@ namespace Thrift.Protocols
{
await WriteJsonIntegerAsync(field.ID, cancellationToken);
await WriteJsonObjectStartAsync(cancellationToken);
- await WriteJsonStringAsync(GetTypeNameForTypeId(field.Type), cancellationToken);
+ await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(field.Type), cancellationToken);
}
public override async Task WriteFieldEndAsync(CancellationToken cancellationToken)
@@ -479,8 +315,8 @@ namespace Thrift.Protocols
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
- await WriteJsonStringAsync(GetTypeNameForTypeId(map.KeyType), cancellationToken);
- await WriteJsonStringAsync(GetTypeNameForTypeId(map.ValueType), cancellationToken);
+ await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.KeyType), cancellationToken);
+ await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.ValueType), cancellationToken);
await WriteJsonIntegerAsync(map.Count, cancellationToken);
await WriteJsonObjectStartAsync(cancellationToken);
}
@@ -494,7 +330,7 @@ namespace Thrift.Protocols
public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
- await WriteJsonStringAsync(GetTypeNameForTypeId(list.ElementType), cancellationToken);
+ await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(list.ElementType), cancellationToken);
await WriteJsonIntegerAsync(list.Count, cancellationToken);
}
@@ -506,7 +342,7 @@ namespace Thrift.Protocols
public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
- await WriteJsonStringAsync(GetTypeNameForTypeId(set.ElementType), cancellationToken);
+ await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(set.ElementType), cancellationToken);
await WriteJsonIntegerAsync(set.Count, cancellationToken);
}
@@ -551,9 +387,9 @@ namespace Thrift.Protocols
await WriteJsonStringAsync(b, cancellationToken);
}
- public override async Task WriteBinaryAsync(byte[] b, CancellationToken cancellationToken)
+ public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
- await WriteJsonBase64Async(b, cancellationToken);
+ await WriteJsonBase64Async(bytes, cancellationToken);
}
/// <summary>
@@ -572,18 +408,18 @@ namespace Thrift.Protocols
await Context.ReadAsync(cancellationToken);
}
- await ReadJsonSyntaxCharAsync(Quote, cancellationToken);
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
while (true)
{
var ch = await Reader.ReadAsync(cancellationToken);
- if (ch == Quote[0])
+ if (ch == TJSONProtocolConstants.Quote[0])
{
break;
}
// escaped?
- if (ch != _escseq[0])
+ if (ch != TJSONProtocolConstants.EscSequences[0])
{
await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken);
continue;
@@ -591,26 +427,25 @@ namespace Thrift.Protocols
// distinguish between \uXXXX and \?
ch = await Reader.ReadAsync(cancellationToken);
- if (ch != _escseq[1]) // control chars like \n
+ if (ch != TJSONProtocolConstants.EscSequences[1]) // control chars like \n
{
- var off = Array.IndexOf(_escapeChars, (char) ch);
+ var off = Array.IndexOf(TJSONProtocolConstants.EscapeChars, (char) ch);
if (off == -1)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char");
}
- ch = _escapeCharVals[off];
+ ch = TJSONProtocolConstants.EscapeCharValues[off];
await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken);
continue;
}
-
// it's \uXXXX
await Trans.ReadAllAsync(_tempBuffer, 0, 4, cancellationToken);
- var wch = (short) ((HexVal(_tempBuffer[0]) << 12) +
- (HexVal(_tempBuffer[1]) << 8) +
- (HexVal(_tempBuffer[2]) << 4) +
- HexVal(_tempBuffer[3]));
+ var wch = (short) ((TJSONProtocolHelper.ToHexVal(_tempBuffer[0]) << 12) +
+ (TJSONProtocolHelper.ToHexVal(_tempBuffer[1]) << 8) +
+ (TJSONProtocolHelper.ToHexVal(_tempBuffer[2]) << 4) +
+ TJSONProtocolHelper.ToHexVal(_tempBuffer[3]));
if (char.IsHighSurrogate((char) wch))
{
@@ -649,34 +484,6 @@ namespace Thrift.Protocols
}
/// <summary>
- /// Return true if the given byte could be a valid part of a JSON number.
- /// </summary>
- private static bool IsJsonNumeric(byte b)
- {
- switch (b)
- {
- case (byte) '+':
- case (byte) '-':
- case (byte) '.':
- case (byte) '0':
- case (byte) '1':
- case (byte) '2':
- case (byte) '3':
- case (byte) '4':
- case (byte) '5':
- case (byte) '6':
- case (byte) '7':
- case (byte) '8':
- case (byte) '9':
- case (byte) 'E':
- case (byte) 'e':
- return true;
- }
-
- return false;
- }
-
- /// <summary>
/// Read in a sequence of characters that are all valid in JSON numbers. Does
/// not do a complete regex check to validate that this is actually a number.
/// </summary>
@@ -685,12 +492,21 @@ namespace Thrift.Protocols
var strbld = new StringBuilder();
while (true)
{
- var ch = await Reader.PeekAsync(cancellationToken);
- if (!IsJsonNumeric(ch))
+ //TODO: workaround for primitive types with TJsonProtocol, think - how to rewrite into more easy form without exceptions
+ try
+ {
+ var ch = await Reader.PeekAsync(cancellationToken);
+ if (!TJSONProtocolHelper.IsJsonNumeric(ch))
+ {
+ break;
+ }
+ var c = (char)await Reader.ReadAsync(cancellationToken);
+ strbld.Append(c);
+ }
+ catch (TTransportException)
{
break;
}
- strbld.Append((char) await Reader.ReadAsync(cancellationToken));
}
return strbld.ToString();
}
@@ -703,13 +519,13 @@ namespace Thrift.Protocols
await Context.ReadAsync(cancellationToken);
if (Context.EscapeNumbers())
{
- await ReadJsonSyntaxCharAsync(Quote, cancellationToken);
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
var str = await ReadJsonNumericCharsAsync(cancellationToken);
if (Context.EscapeNumbers())
{
- await ReadJsonSyntaxCharAsync(Quote, cancellationToken);
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
try
@@ -729,7 +545,7 @@ namespace Thrift.Protocols
private async Task<double> ReadJsonDoubleAsync(CancellationToken cancellationToken)
{
await Context.ReadAsync(cancellationToken);
- if (await Reader.PeekAsync(cancellationToken) == Quote[0])
+ if (await Reader.PeekAsync(cancellationToken) == TJSONProtocolConstants.Quote[0])
{
var arr = await ReadJsonStringAsync(true, cancellationToken);
var dub = double.Parse(Utf8Encoding.GetString(arr, 0, arr.Length), CultureInfo.InvariantCulture);
@@ -746,7 +562,7 @@ namespace Thrift.Protocols
if (Context.EscapeNumbers())
{
// This will throw - we should have had a quote if escapeNum == true
- await ReadJsonSyntaxCharAsync(Quote, cancellationToken);
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
try
@@ -779,7 +595,7 @@ namespace Thrift.Protocols
while (len > 4)
{
// Decode 4 bytes at a time
- TBase64Utils.Decode(b, off, 4, b, size); // NB: decoded in place
+ TBase64Helper.Decode(b, off, 4, b, size); // NB: decoded in place
off += 4;
len -= 4;
size += 3;
@@ -790,7 +606,7 @@ namespace Thrift.Protocols
if (len > 1)
{
// Decode remainder
- TBase64Utils.Decode(b, off, len, b, size); // NB: decoded in place
+ TBase64Helper.Decode(b, off, len, b, size); // NB: decoded in place
size += len - 1;
}
@@ -803,26 +619,26 @@ namespace Thrift.Protocols
private async Task ReadJsonObjectStartAsync(CancellationToken cancellationToken)
{
await Context.ReadAsync(cancellationToken);
- await ReadJsonSyntaxCharAsync(Lbrace, cancellationToken);
- PushContext(new JsonPairContext(this));
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBrace, cancellationToken);
+ PushContext(new JSONPairContext(this));
}
private async Task ReadJsonObjectEndAsync(CancellationToken cancellationToken)
{
- await ReadJsonSyntaxCharAsync(Rbrace, cancellationToken);
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBrace, cancellationToken);
PopContext();
}
private async Task ReadJsonArrayStartAsync(CancellationToken cancellationToken)
{
await Context.ReadAsync(cancellationToken);
- await ReadJsonSyntaxCharAsync(Lbracket, cancellationToken);
- PushContext(new JsonListContext(this));
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBracket, cancellationToken);
+ PushContext(new JSONListContext(this));
}
private async Task ReadJsonArrayEndAsync(CancellationToken cancellationToken)
{
- await ReadJsonSyntaxCharAsync(Rbracket, cancellationToken);
+ await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBracket, cancellationToken);
PopContext();
}
@@ -862,7 +678,7 @@ namespace Thrift.Protocols
{
var field = new TField();
var ch = await Reader.PeekAsync(cancellationToken);
- if (ch == Rbrace[0])
+ if (ch == TJSONProtocolConstants.RightBrace[0])
{
field.Type = TType.Stop;
}
@@ -870,7 +686,7 @@ namespace Thrift.Protocols
{
field.ID = (short) await ReadJsonIntegerAsync(cancellationToken);
await ReadJsonObjectStartAsync(cancellationToken);
- field.Type = GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
+ field.Type = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
}
return field;
}
@@ -884,8 +700,8 @@ namespace Thrift.Protocols
{
var map = new TMap();
await ReadJsonArrayStartAsync(cancellationToken);
- map.KeyType = GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
- map.ValueType = GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
+ map.KeyType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
+ map.ValueType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
map.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
await ReadJsonObjectStartAsync(cancellationToken);
return map;
@@ -901,7 +717,7 @@ namespace Thrift.Protocols
{
var list = new TList();
await ReadJsonArrayStartAsync(cancellationToken);
- list.ElementType = GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
+ list.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
list.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
return list;
}
@@ -915,7 +731,7 @@ namespace Thrift.Protocols
{
var set = new TSet();
await ReadJsonArrayStartAsync(cancellationToken);
- set.ElementType = GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
+ set.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
set.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
return set;
}
@@ -982,11 +798,11 @@ namespace Thrift.Protocols
/// inserting/Reading additional JSON syntax characters
/// This base context does nothing.
/// </summary>
- protected class JsonBaseContext
+ protected class JSONBaseContext
{
protected TJsonProtocol Proto;
- public JsonBaseContext(TJsonProtocol proto)
+ public JSONBaseContext(TJsonProtocol proto)
{
Proto = proto;
}
@@ -1017,11 +833,11 @@ namespace Thrift.Protocols
/// Context for JSON lists. Will insert/Read commas before each item except
/// for the first one
/// </summary>
- protected class JsonListContext : JsonBaseContext
+ protected class JSONListContext : JSONBaseContext
{
private bool _first = true;
- public JsonListContext(TJsonProtocol protocol)
+ public JSONListContext(TJsonProtocol protocol)
: base(protocol)
{
}
@@ -1034,7 +850,7 @@ namespace Thrift.Protocols
}
else
{
- await Proto.Trans.WriteAsync(Comma, cancellationToken);
+ await Proto.Trans.WriteAsync(TJSONProtocolConstants.Comma, cancellationToken);
}
}
@@ -1046,7 +862,7 @@ namespace Thrift.Protocols
}
else
{
- await Proto.ReadJsonSyntaxCharAsync(Comma, cancellationToken);
+ await Proto.ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Comma, cancellationToken);
}
}
}
@@ -1057,13 +873,14 @@ namespace Thrift.Protocols
/// addition, will indicate that numbers in the key position need to be
/// escaped in quotes (since JSON keys must be strings).
/// </summary>
- protected class JsonPairContext : JsonBaseContext
+ // ReSharper disable once InconsistentNaming
+ protected class JSONPairContext : JSONBaseContext
{
private bool _colon = true;
private bool _first = true;
- public JsonPairContext(TJsonProtocol proto)
+ public JSONPairContext(TJsonProtocol proto)
: base(proto)
{
}
@@ -1077,7 +894,7 @@ namespace Thrift.Protocols
}
else
{
- await Proto.Trans.WriteAsync(_colon ? Colon : Comma, cancellationToken);
+ await Proto.Trans.WriteAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken);
_colon = !_colon;
}
}
@@ -1091,7 +908,7 @@ namespace Thrift.Protocols
}
else
{
- await Proto.ReadJsonSyntaxCharAsync(_colon ? Colon : Comma, cancellationToken);
+ await Proto.ReadJsonSyntaxCharAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken);
_colon = !_colon;
}
}
@@ -1134,6 +951,7 @@ namespace Thrift.Protocols
}
else
{
+ // find more easy way to avoid exception on reading primitive types
await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken);
}
return _data[0];
@@ -1152,6 +970,7 @@ namespace Thrift.Protocols
if (!_hasData)
{
+ // find more easy way to avoid exception on reading primitive types
await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken);
}
_hasData = true;
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs b/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs
index 5b2202e..367e4e6 100644
--- a/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs
+++ b/lib/netcore/Thrift/Protocols/TMultiplexedProtocol.cs
@@ -74,22 +74,13 @@ namespace Thrift.Protocols
_serviceName = serviceName;
}
- /**
- * Prepends the service name to the function name, separated by TMultiplexedProtocol.SEPARATOR.
- * Args:
- * tMessage The original message.
- */
-
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
{
switch (message.Type)
{
case TMessageType.Call:
case TMessageType.Oneway:
- await
- base.WriteMessageBeginAsync(
- new TMessage($"{_serviceName}{Separator}{message.Name}", message.Type, message.SeqID),
- cancellationToken);
+ await base.WriteMessageBeginAsync(new TMessage($"{_serviceName}{Separator}{message.Name}", message.Type, message.SeqID), cancellationToken);
break;
default:
await base.WriteMessageBeginAsync(message, cancellationToken);
@@ -97,4 +88,4 @@ namespace Thrift.Protocols
}
}
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TProtocol.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TProtocol.cs b/lib/netcore/Thrift/Protocols/TProtocol.cs
index 8fef861..91e009d 100644
--- a/lib/netcore/Thrift/Protocols/TProtocol.cs
+++ b/lib/netcore/Thrift/Protocols/TProtocol.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -27,7 +27,7 @@ namespace Thrift.Protocols
// ReSharper disable once InconsistentNaming
public abstract class TProtocol : IDisposable
{
- private const int DefaultRecursionDepth = 64;
+ public const int DefaultRecursionDepth = 64;
private bool _isDisposed;
protected int RecursionDepth;
@@ -42,7 +42,6 @@ namespace Thrift.Protocols
public TClientTransport Transport => Trans;
- //TODO: check for protected
protected int RecursionLimit { get; set; }
public void Dispose()
@@ -93,12 +92,12 @@ namespace Thrift.Protocols
public abstract Task WriteMessageEndAsync(CancellationToken cancellationToken);
- public virtual async Task WriteStructBeginAsync(TStruct struc)
+ public virtual async Task WriteStructBeginAsync(TStruct @struct)
{
- await WriteStructBeginAsync(struc, CancellationToken.None);
+ await WriteStructBeginAsync(@struct, CancellationToken.None);
}
- public abstract Task WriteStructBeginAsync(TStruct struc, CancellationToken cancellationToken);
+ public abstract Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken);
public virtual async Task WriteStructEndAsync()
{
@@ -223,12 +222,12 @@ namespace Thrift.Protocols
await WriteBinaryAsync(bytes, cancellationToken);
}
- public virtual async Task WriteBinaryAsync(byte[] b)
+ public virtual async Task WriteBinaryAsync(byte[] bytes)
{
- await WriteBinaryAsync(b, CancellationToken.None);
+ await WriteBinaryAsync(bytes, CancellationToken.None);
}
- public abstract Task WriteBinaryAsync(byte[] b, CancellationToken cancellationToken);
+ public abstract Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken);
public virtual async Task<TMessage> ReadMessageBeginAsync()
{
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs b/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs
index 458b117..3222754 100644
--- a/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs
+++ b/lib/netcore/Thrift/Protocols/TProtocolDecorator.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -36,12 +36,7 @@ namespace Thrift.Protocols
protected TProtocolDecorator(TProtocol protocol)
: base(protocol.Transport)
{
- if (protocol == null)
- {
- throw new ArgumentNullException(nameof(protocol));
- }
-
- _wrappedProtocol = protocol;
+ _wrappedProtocol = protocol ?? throw new ArgumentNullException(nameof(protocol));
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
@@ -54,9 +49,9 @@ namespace Thrift.Protocols
await _wrappedProtocol.WriteMessageEndAsync(cancellationToken);
}
- public override async Task WriteStructBeginAsync(TStruct struc, CancellationToken cancellationToken)
+ public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
- await _wrappedProtocol.WriteStructBeginAsync(struc, cancellationToken);
+ await _wrappedProtocol.WriteStructBeginAsync(@struct, cancellationToken);
}
public override async Task WriteStructEndAsync(CancellationToken cancellationToken)
@@ -144,9 +139,9 @@ namespace Thrift.Protocols
await _wrappedProtocol.WriteStringAsync(s, cancellationToken);
}
- public override async Task WriteBinaryAsync(byte[] b, CancellationToken cancellationToken)
+ public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
- await _wrappedProtocol.WriteBinaryAsync(b, cancellationToken);
+ await _wrappedProtocol.WriteBinaryAsync(bytes, cancellationToken);
}
public override async Task<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/TProtocolException.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/TProtocolException.cs b/lib/netcore/Thrift/Protocols/TProtocolException.cs
index 02d0d3f..8c67c3b 100644
--- a/lib/netcore/Thrift/Protocols/TProtocolException.cs
+++ b/lib/netcore/Thrift/Protocols/TProtocolException.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -15,11 +15,12 @@
// specific language governing permissions and limitations
// under the License.
+// ReSharper disable InconsistentNaming
namespace Thrift.Protocols
{
public class TProtocolException : TException
{
- // do not rename public contants - they used in generated files
+ // do not rename public constants - they used in generated files
public const int UNKNOWN = 0;
public const int INVALID_DATA = 1;
public const int NEGATIVE_SIZE = 2;
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs b/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs
new file mode 100644
index 0000000..7eff5e1
--- /dev/null
+++ b/lib/netcore/Thrift/Protocols/Utilities/TBase64Helper.cs
@@ -0,0 +1,101 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+
+namespace Thrift.Protocols.Utilities
+{
+ // ReSharper disable once InconsistentNaming
+ internal static class TBase64Helper
+ {
+ //TODO: Constants
+ //TODO: Check for args
+ //TODO: Unitests
+
+ internal const string EncodeTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+ private static readonly int[] DecodeTable =
+ {
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
+ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
+ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
+ };
+
+ internal static void Encode(byte[] src, int srcOff, int len, byte[] dst, int dstOff)
+ {
+ if (src == null)
+ {
+ throw new ArgumentNullException(nameof(src));
+ }
+
+ dst[dstOff] = (byte) EncodeTable[(src[srcOff] >> 2) & 0x3F];
+
+ if (len == 3)
+ {
+ dst[dstOff + 1] = (byte) EncodeTable[((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)];
+ dst[dstOff + 2] = (byte) EncodeTable[((src[srcOff + 1] << 2) & 0x3C) | ((src[srcOff + 2] >> 6) & 0x03)];
+ dst[dstOff + 3] = (byte) EncodeTable[src[srcOff + 2] & 0x3F];
+ }
+ else if (len == 2)
+ {
+ dst[dstOff + 1] = (byte) EncodeTable[((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)];
+ dst[dstOff + 2] = (byte) EncodeTable[(src[srcOff + 1] << 2) & 0x3C];
+ }
+ else
+ {
+ // len == 1
+ dst[dstOff + 1] = (byte) EncodeTable[(src[srcOff] << 4) & 0x30];
+ }
+ }
+
+ internal static void Decode(byte[] src, int srcOff, int len, byte[] dst, int dstOff)
+ {
+ if (src == null)
+ {
+ throw new ArgumentNullException(nameof(src));
+ }
+
+ dst[dstOff] = (byte) ((DecodeTable[src[srcOff] & 0x0FF] << 2) | (DecodeTable[src[srcOff + 1] & 0x0FF] >> 4));
+
+ if (len > 2)
+ {
+ dst[dstOff + 1] =
+ (byte)
+ (((DecodeTable[src[srcOff + 1] & 0x0FF] << 4) & 0xF0) | (DecodeTable[src[srcOff + 2] & 0x0FF] >> 2));
+ if (len > 3)
+ {
+ dst[dstOff + 2] =
+ (byte)
+ (((DecodeTable[src[srcOff + 2] & 0x0FF] << 6) & 0xC0) | DecodeTable[src[srcOff + 3] & 0x0FF]);
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs b/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs
new file mode 100644
index 0000000..93eff78
--- /dev/null
+++ b/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolConstants.cs
@@ -0,0 +1,61 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+namespace Thrift.Protocols.Utilities
+{
+ // ReSharper disable once InconsistentNaming
+ public static class TJSONProtocolConstants
+ {
+ //TODO Check for performance for reusing ImmutableArray from System.Collections.Immutable (https://blogs.msdn.microsoft.com/dotnet/2013/06/24/please-welcome-immutablearrayt/)
+ // can be possible to get better performance and also better GC
+
+ public static readonly byte[] Comma = {(byte) ','};
+ public static readonly byte[] Colon = {(byte) ':'};
+ public static readonly byte[] LeftBrace = {(byte) '{'};
+ public static readonly byte[] RightBrace = {(byte) '}'};
+ public static readonly byte[] LeftBracket = {(byte) '['};
+ public static readonly byte[] RightBracket = {(byte) ']'};
+ public static readonly byte[] Quote = {(byte) '"'};
+ public static readonly byte[] Backslash = {(byte) '\\'};
+
+ public static readonly byte[] JsonCharTable =
+ {
+ 0, 0, 0, 0, 0, 0, 0, 0, (byte) 'b', (byte) 't', (byte) 'n', 0, (byte) 'f', (byte) 'r', 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, (byte) '"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
+ };
+
+ public static readonly char[] EscapeChars = "\"\\/bfnrt".ToCharArray();
+ public static readonly byte[] EscapeCharValues = {(byte) '"', (byte) '\\', (byte) '/', (byte) '\b', (byte) '\f', (byte) '\n', (byte) '\r', (byte) '\t'};
+ public static readonly byte[] EscSequences = {(byte) '\\', (byte) 'u', (byte) '0', (byte) '0'};
+
+ public static class TypeNames
+ {
+ public static readonly byte[] NameBool = { (byte)'t', (byte)'f' };
+ public static readonly byte[] NameByte = { (byte)'i', (byte)'8' };
+ public static readonly byte[] NameI16 = { (byte)'i', (byte)'1', (byte)'6' };
+ public static readonly byte[] NameI32 = { (byte)'i', (byte)'3', (byte)'2' };
+ public static readonly byte[] NameI64 = { (byte)'i', (byte)'6', (byte)'4' };
+ public static readonly byte[] NameDouble = { (byte)'d', (byte)'b', (byte)'l' };
+ public static readonly byte[] NameStruct = { (byte)'r', (byte)'e', (byte)'c' };
+ public static readonly byte[] NameString = { (byte)'s', (byte)'t', (byte)'r' };
+ public static readonly byte[] NameMap = { (byte)'m', (byte)'a', (byte)'p' };
+ public static readonly byte[] NameList = { (byte)'l', (byte)'s', (byte)'t' };
+ public static readonly byte[] NameSet = { (byte)'s', (byte)'e', (byte)'t' };
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs b/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs
new file mode 100644
index 0000000..adc26a9
--- /dev/null
+++ b/lib/netcore/Thrift/Protocols/Utilities/TJsonProtocolHelper.cs
@@ -0,0 +1,176 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using Thrift.Protocols.Entities;
+
+namespace Thrift.Protocols.Utilities
+{
+ // ReSharper disable once InconsistentNaming
+ public static class TJSONProtocolHelper
+ {
+ public static byte[] GetTypeNameForTypeId(TType typeId)
+ {
+ switch (typeId)
+ {
+ case TType.Bool:
+ return TJSONProtocolConstants.TypeNames.NameBool;
+ case TType.Byte:
+ return TJSONProtocolConstants.TypeNames.NameByte;
+ case TType.I16:
+ return TJSONProtocolConstants.TypeNames.NameI16;
+ case TType.I32:
+ return TJSONProtocolConstants.TypeNames.NameI32;
+ case TType.I64:
+ return TJSONProtocolConstants.TypeNames.NameI64;
+ case TType.Double:
+ return TJSONProtocolConstants.TypeNames.NameDouble;
+ case TType.String:
+ return TJSONProtocolConstants.TypeNames.NameString;
+ case TType.Struct:
+ return TJSONProtocolConstants.TypeNames.NameStruct;
+ case TType.Map:
+ return TJSONProtocolConstants.TypeNames.NameMap;
+ case TType.Set:
+ return TJSONProtocolConstants.TypeNames.NameSet;
+ case TType.List:
+ return TJSONProtocolConstants.TypeNames.NameList;
+ default:
+ throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized exType");
+ }
+ }
+
+ public static TType GetTypeIdForTypeName(byte[] name)
+ {
+ var result = TType.Stop;
+ if (name.Length > 1)
+ {
+ switch (name[0])
+ {
+ case (byte) 'd':
+ result = TType.Double;
+ break;
+ case (byte) 'i':
+ switch (name[1])
+ {
+ case (byte) '8':
+ result = TType.Byte;
+ break;
+ case (byte) '1':
+ result = TType.I16;
+ break;
+ case (byte) '3':
+ result = TType.I32;
+ break;
+ case (byte) '6':
+ result = TType.I64;
+ break;
+ }
+ break;
+ case (byte) 'l':
+ result = TType.List;
+ break;
+ case (byte) 'm':
+ result = TType.Map;
+ break;
+ case (byte) 'r':
+ result = TType.Struct;
+ break;
+ case (byte) 's':
+ if (name[1] == (byte) 't')
+ {
+ result = TType.String;
+ }
+ else if (name[1] == (byte) 'e')
+ {
+ result = TType.Set;
+ }
+ break;
+ case (byte) 't':
+ result = TType.Bool;
+ break;
+ }
+ }
+ if (result == TType.Stop)
+ {
+ throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "Unrecognized exType");
+ }
+ return result;
+ }
+
+ /// <summary>
+ /// Return true if the given byte could be a valid part of a JSON number.
+ /// </summary>
+ public static bool IsJsonNumeric(byte b)
+ {
+ switch (b)
+ {
+ case (byte)'+':
+ case (byte)'-':
+ case (byte)'.':
+ case (byte)'0':
+ case (byte)'1':
+ case (byte)'2':
+ case (byte)'3':
+ case (byte)'4':
+ case (byte)'5':
+ case (byte)'6':
+ case (byte)'7':
+ case (byte)'8':
+ case (byte)'9':
+ case (byte)'E':
+ case (byte)'e':
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its
+ /// corresponding hex value
+ /// </summary>
+ public static byte ToHexVal(byte ch)
+ {
+ if (ch >= '0' && ch <= '9')
+ {
+ return (byte)((char)ch - '0');
+ }
+
+ if (ch >= 'a' && ch <= 'f')
+ {
+ ch += 10;
+ return (byte)((char)ch - 'a');
+ }
+
+ throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected hex character");
+ }
+
+ /// <summary>
+ /// Convert a byte containing a hex value to its corresponding hex character
+ /// </summary>
+ public static byte ToHexChar(byte val)
+ {
+ val &= 0x0F;
+ if (val < 10)
+ {
+ return (byte)((char)val + '0');
+ }
+ val -= 10;
+ return (byte)((char)val + 'a');
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs b/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs
index 038edb9..50b0385 100644
--- a/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs
+++ b/lib/netcore/Thrift/Protocols/Utilities/TProtocolUtil.cs
@@ -19,83 +19,83 @@ using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocols.Entities;
-namespace Thrift.Protocols
+namespace Thrift.Protocols.Utilities
{
// ReSharper disable once InconsistentNaming
public static class TProtocolUtil
{
- public static async Task SkipAsync(TProtocol prot, TType type, CancellationToken cancellationToken)
+ public static async Task SkipAsync(TProtocol protocol, TType type, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
- prot.IncrementRecursionDepth();
+ protocol.IncrementRecursionDepth();
try
{
switch (type)
{
case TType.Bool:
- await prot.ReadBoolAsync(cancellationToken);
+ await protocol.ReadBoolAsync(cancellationToken);
break;
case TType.Byte:
- await prot.ReadByteAsync(cancellationToken);
+ await protocol.ReadByteAsync(cancellationToken);
break;
case TType.I16:
- await prot.ReadI16Async(cancellationToken);
+ await protocol.ReadI16Async(cancellationToken);
break;
case TType.I32:
- await prot.ReadI32Async(cancellationToken);
+ await protocol.ReadI32Async(cancellationToken);
break;
case TType.I64:
- await prot.ReadI64Async(cancellationToken);
+ await protocol.ReadI64Async(cancellationToken);
break;
case TType.Double:
- await prot.ReadDoubleAsync(cancellationToken);
+ await protocol.ReadDoubleAsync(cancellationToken);
break;
case TType.String:
// Don't try to decode the string, just skip it.
- await prot.ReadBinaryAsync(cancellationToken);
+ await protocol.ReadBinaryAsync(cancellationToken);
break;
case TType.Struct:
- await prot.ReadStructBeginAsync(cancellationToken);
+ await protocol.ReadStructBeginAsync(cancellationToken);
while (true)
{
- var field = await prot.ReadFieldBeginAsync(cancellationToken);
+ var field = await protocol.ReadFieldBeginAsync(cancellationToken);
if (field.Type == TType.Stop)
{
break;
}
- await SkipAsync(prot, field.Type, cancellationToken);
- await prot.ReadFieldEndAsync(cancellationToken);
+ await SkipAsync(protocol, field.Type, cancellationToken);
+ await protocol.ReadFieldEndAsync(cancellationToken);
}
- await prot.ReadStructEndAsync(cancellationToken);
+ await protocol.ReadStructEndAsync(cancellationToken);
break;
case TType.Map:
- var map = await prot.ReadMapBeginAsync(cancellationToken);
+ var map = await protocol.ReadMapBeginAsync(cancellationToken);
for (var i = 0; i < map.Count; i++)
{
- await SkipAsync(prot, map.KeyType, cancellationToken);
- await SkipAsync(prot, map.ValueType, cancellationToken);
+ await SkipAsync(protocol, map.KeyType, cancellationToken);
+ await SkipAsync(protocol, map.ValueType, cancellationToken);
}
- await prot.ReadMapEndAsync(cancellationToken);
+ await protocol.ReadMapEndAsync(cancellationToken);
break;
case TType.Set:
- var set = await prot.ReadSetBeginAsync(cancellationToken);
+ var set = await protocol.ReadSetBeginAsync(cancellationToken);
for (var i = 0; i < set.Count; i++)
{
- await SkipAsync(prot, set.ElementType, cancellationToken);
+ await SkipAsync(protocol, set.ElementType, cancellationToken);
}
- await prot.ReadSetEndAsync(cancellationToken);
+ await protocol.ReadSetEndAsync(cancellationToken);
break;
case TType.List:
- var list = await prot.ReadListBeginAsync(cancellationToken);
+ var list = await protocol.ReadListBeginAsync(cancellationToken);
for (var i = 0; i < list.Count; i++)
{
- await SkipAsync(prot, list.ElementType, cancellationToken);
+ await SkipAsync(protocol, list.ElementType, cancellationToken);
}
- await prot.ReadListEndAsync(cancellationToken);
+ await protocol.ReadListEndAsync(cancellationToken);
break;
default:
throw new TProtocolException(TProtocolException.INVALID_DATA, "Unknown data type " + type.ToString("d"));
@@ -103,8 +103,8 @@ namespace Thrift.Protocols
}
finally
{
- prot.DecrementRecursionDepth();
+ protocol.DecrementRecursionDepth();
}
}
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Server/AsyncBaseServer.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Server/AsyncBaseServer.cs b/lib/netcore/Thrift/Server/AsyncBaseServer.cs
index 5ff7a32..0032ca3 100644
--- a/lib/netcore/Thrift/Server/AsyncBaseServer.cs
+++ b/lib/netcore/Thrift/Server/AsyncBaseServer.cs
@@ -57,8 +57,7 @@ namespace Thrift.Server
try
{
// cancelation token
- _serverTask = Task.Factory.StartNew(() => StartListening(cancellationToken),
- TaskCreationOptions.LongRunning);
+ _serverTask = Task.Factory.StartNew(() => StartListening(cancellationToken), TaskCreationOptions.LongRunning);
await _serverTask;
}
catch (Exception ex)
@@ -87,7 +86,7 @@ namespace Thrift.Server
try
{
var client = await ServerTransport.AcceptAsync(cancellationToken);
- await Task.Factory.StartNew(() => Execute(client, cancellationToken));
+ await Task.Factory.StartNew(() => Execute(client, cancellationToken), cancellationToken);
}
catch (TTransportException ttx)
{
@@ -136,8 +135,7 @@ namespace Thrift.Server
if (ServerEventHandler != null)
{
- connectionContext =
- await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken);
+ connectionContext = await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken);
}
while (!cancellationToken.IsCancellationRequested)
@@ -149,8 +147,7 @@ namespace Thrift.Server
if (ServerEventHandler != null)
{
- await
- ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken);
+ await ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken);
}
if (!await processor.ProcessAsync(inputProtocol, outputProtocol, cancellationToken))
@@ -170,9 +167,7 @@ namespace Thrift.Server
if (ServerEventHandler != null)
{
- await
- ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol,
- cancellationToken);
+ await ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol, cancellationToken);
}
inputTransport?.Close();
@@ -181,4 +176,4 @@ namespace Thrift.Server
Logger.LogTrace("Completed client request processing");
}
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Server/TBaseServer.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Server/TBaseServer.cs b/lib/netcore/Thrift/Server/TBaseServer.cs
index 97cc7ff..741dd5c 100644
--- a/lib/netcore/Thrift/Server/TBaseServer.cs
+++ b/lib/netcore/Thrift/Server/TBaseServer.cs
@@ -42,20 +42,13 @@ namespace Thrift.Server
ITProtocolFactory inputProtocolFactory, ITProtocolFactory outputProtocolFactory,
ILogger logger)
{
- if (itProcessorFactory == null) throw new ArgumentNullException(nameof(itProcessorFactory));
- if (inputTransportFactory == null) throw new ArgumentNullException(nameof(inputTransportFactory));
- if (outputTransportFactory == null) throw new ArgumentNullException(nameof(outputTransportFactory));
- if (inputProtocolFactory == null) throw new ArgumentNullException(nameof(inputProtocolFactory));
- if (outputProtocolFactory == null) throw new ArgumentNullException(nameof(outputProtocolFactory));
- if (logger == null) throw new ArgumentNullException(nameof(logger));
-
- ItProcessorFactory = itProcessorFactory;
+ ItProcessorFactory = itProcessorFactory ?? throw new ArgumentNullException(nameof(itProcessorFactory));
ServerTransport = serverTransport;
- InputTransportFactory = inputTransportFactory;
- OutputTransportFactory = outputTransportFactory;
- InputProtocolFactory = inputProtocolFactory;
- OutputProtocolFactory = outputProtocolFactory;
- Logger = logger;
+ InputTransportFactory = inputTransportFactory ?? throw new ArgumentNullException(nameof(inputTransportFactory));
+ OutputTransportFactory = outputTransportFactory ?? throw new ArgumentNullException(nameof(outputTransportFactory));
+ InputProtocolFactory = inputProtocolFactory ?? throw new ArgumentNullException(nameof(inputProtocolFactory));
+ OutputProtocolFactory = outputProtocolFactory ?? throw new ArgumentNullException(nameof(outputProtocolFactory));
+ Logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void SetEventHandler(TServerEventHandler seh)
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/TApplicationException.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/TApplicationException.cs b/lib/netcore/Thrift/TApplicationException.cs
index f1ea252..9ec145a 100644
--- a/lib/netcore/Thrift/TApplicationException.cs
+++ b/lib/netcore/Thrift/TApplicationException.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -19,6 +19,7 @@ using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocols;
using Thrift.Protocols.Entities;
+using Thrift.Protocols.Utilities;
namespace Thrift
{
@@ -60,15 +61,15 @@ namespace Thrift
Type = type;
}
- public static async Task<TApplicationException> ReadAsync(TProtocol iprot, CancellationToken cancellationToken)
+ public static async Task<TApplicationException> ReadAsync(TProtocol inputProtocol, CancellationToken cancellationToken)
{
string message = null;
var type = ExceptionType.Unknown;
- await iprot.ReadStructBeginAsync(cancellationToken);
+ await inputProtocol.ReadStructBeginAsync(cancellationToken);
while (true)
{
- var field = await iprot.ReadFieldBeginAsync(cancellationToken);
+ var field = await inputProtocol.ReadFieldBeginAsync(cancellationToken);
if (field.Type == TType.Stop)
{
break;
@@ -79,37 +80,37 @@ namespace Thrift
case MessageTypeFieldId:
if (field.Type == TType.String)
{
- message = await iprot.ReadStringAsync(cancellationToken);
+ message = await inputProtocol.ReadStringAsync(cancellationToken);
}
else
{
- await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
+ await TProtocolUtil.SkipAsync(inputProtocol, field.Type, cancellationToken);
}
break;
case ExTypeFieldId:
if (field.Type == TType.I32)
{
- type = (ExceptionType) await iprot.ReadI32Async(cancellationToken);
+ type = (ExceptionType) await inputProtocol.ReadI32Async(cancellationToken);
}
else
{
- await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
+ await TProtocolUtil.SkipAsync(inputProtocol, field.Type, cancellationToken);
}
break;
default:
- await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
+ await TProtocolUtil.SkipAsync(inputProtocol, field.Type, cancellationToken);
break;
}
- await iprot.ReadFieldEndAsync(cancellationToken);
+ await inputProtocol.ReadFieldEndAsync(cancellationToken);
}
- await iprot.ReadStructEndAsync(cancellationToken);
+ await inputProtocol.ReadStructEndAsync(cancellationToken);
return new TApplicationException(type, message);
}
- public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)
+ public async Task WriteAsync(TProtocol outputProtocol, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -123,27 +124,27 @@ namespace Thrift
var struc = new TStruct(structApplicationExceptionName);
var field = new TField();
- await oprot.WriteStructBeginAsync(struc, cancellationToken);
+ await outputProtocol.WriteStructBeginAsync(struc, cancellationToken);
if (!string.IsNullOrEmpty(Message))
{
field.Name = messageTypeFieldName;
field.Type = TType.String;
field.ID = MessageTypeFieldId;
- await oprot.WriteFieldBeginAsync(field, cancellationToken);
- await oprot.WriteStringAsync(Message, cancellationToken);
- await oprot.WriteFieldEndAsync(cancellationToken);
+ await outputProtocol.WriteFieldBeginAsync(field, cancellationToken);
+ await outputProtocol.WriteStringAsync(Message, cancellationToken);
+ await outputProtocol.WriteFieldEndAsync(cancellationToken);
}
field.Name = exTypeFieldName;
field.Type = TType.I32;
field.ID = ExTypeFieldId;
- await oprot.WriteFieldBeginAsync(field, cancellationToken);
- await oprot.WriteI32Async((int) Type, cancellationToken);
- await oprot.WriteFieldEndAsync(cancellationToken);
- await oprot.WriteFieldStopAsync(cancellationToken);
- await oprot.WriteStructEndAsync(cancellationToken);
+ await outputProtocol.WriteFieldBeginAsync(field, cancellationToken);
+ await outputProtocol.WriteI32Async((int) Type, cancellationToken);
+ await outputProtocol.WriteFieldEndAsync(cancellationToken);
+ await outputProtocol.WriteFieldStopAsync(cancellationToken);
+ await outputProtocol.WriteStructEndAsync(cancellationToken);
}
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/TBaseClient.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/TBaseClient.cs b/lib/netcore/Thrift/TBaseClient.cs
index ca403e5..e019251 100644
--- a/lib/netcore/Thrift/TBaseClient.cs
+++ b/lib/netcore/Thrift/TBaseClient.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -16,14 +16,13 @@
// under the License.
using System;
-using System.Collections.Generic;
-using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocols;
namespace Thrift
{
+ // ReSharper disable once InconsistentNaming
/// <summary>
/// TBaseClient.
/// Base client for generated clients.
@@ -39,18 +38,8 @@ namespace Thrift
protected TBaseClient(TProtocol inputProtocol, TProtocol outputProtocol)
{
- if (inputProtocol == null)
- {
- throw new ArgumentNullException(nameof(inputProtocol));
- }
-
- if (outputProtocol == null)
- {
- throw new ArgumentNullException(nameof(outputProtocol));
- }
-
- _inputProtocol = inputProtocol;
- _outputProtocol = outputProtocol;
+ _inputProtocol = inputProtocol ?? throw new ArgumentNullException(nameof(inputProtocol));
+ _outputProtocol = outputProtocol ?? throw new ArgumentNullException(nameof(outputProtocol));
}
public TProtocol InputProtocol => _inputProtocol;
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs b/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs
index 86eb735..761f1ac 100644
--- a/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs
+++ b/lib/netcore/Thrift/Transports/Client/TBufferedClientTransport.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -34,17 +34,12 @@ namespace Thrift.Transports.Client
//TODO: should support only specified input transport?
public TBufferedClientTransport(TClientTransport transport, int bufSize = 1024)
{
- if (transport == null)
- {
- throw new ArgumentNullException(nameof(transport));
- }
-
if (bufSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufSize), "Buffer size must be a positive number.");
}
- _transport = transport;
+ _transport = transport ?? throw new ArgumentNullException(nameof(transport));
_bufSize = bufSize;
}
@@ -200,8 +195,9 @@ namespace Thrift.Transports.Client
{
if (disposing)
{
- _inputBuffer.Dispose();
- _outputBuffer.Dispose();
+ _inputBuffer?.Dispose();
+ _outputBuffer?.Dispose();
+ _transport?.Dispose();
}
}
_isDisposed = true;
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs
----------------------------------------------------------------------
diff --git a/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs b/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs
index f54a42a..d11bb95 100644
--- a/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs
+++ b/lib/netcore/Thrift/Transports/Client/TFramedClientTransport.cs
@@ -1,4 +1,4 @@
-// Licensed to the Apache Software Foundation(ASF) under one
+// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
@@ -37,12 +37,7 @@ namespace Thrift.Transports.Client
public TFramedClientTransport(TClientTransport transport)
{
- if (transport == null)
- {
- throw new ArgumentNullException(nameof(transport));
- }
-
- _transport = transport;
+ _transport = transport ?? throw new ArgumentNullException(nameof(transport));
InitWriteBuffer();
}
@@ -195,8 +190,9 @@ namespace Thrift.Transports.Client
{
if (disposing)
{
- _readBuffer.Dispose();
- _writeBuffer.Dispose();
+ _readBuffer?.Dispose();
+ _writeBuffer?.Dispose();
+ _transport?.Dispose();
}
}
_isDisposed = true;
[2/9] thrift git commit: THRIFT-4434: .NET Core cleanup and the
beginnings of compiler unit tests Client: netcore
Posted by jk...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/Server/TestServer.cs
----------------------------------------------------------------------
diff --git a/test/netcore/Server/TestServer.cs b/test/netcore/Server/TestServer.cs
new file mode 100644
index 0000000..bfd3335
--- /dev/null
+++ b/test/netcore/Server/TestServer.cs
@@ -0,0 +1,594 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.Authentication;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Extensions.Logging;
+using Thrift;
+using Thrift.Collections;
+using Thrift.Protocols;
+using Thrift.Server;
+using Thrift.Transports;
+using Thrift.Transports.Server;
+
+namespace ThriftTest
+{
+ internal class ServerParam
+ {
+ internal bool useBufferedSockets = false;
+ internal bool useFramed = false;
+ internal bool useEncryption = false;
+ internal bool compact = false;
+ internal bool json = false;
+ internal int port = 9090;
+ internal string pipe = null;
+
+ internal void Parse(List<string> args)
+ {
+ for (var i = 0; i < args.Count; i++)
+ {
+ if (args[i].StartsWith("--pipe="))
+ {
+ pipe = args[i].Substring(args[i].IndexOf("=") + 1);
+ }
+ else if (args[i].StartsWith("--port="))
+ {
+ port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
+ }
+ else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
+ {
+ useBufferedSockets = true;
+ }
+ else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
+ {
+ useFramed = true;
+ }
+ else if (args[i] == "--binary" || args[i] == "--protocol=binary")
+ {
+ // nothing needed
+ }
+ else if (args[i] == "--compact" || args[i] == "--protocol=compact")
+ {
+ compact = true;
+ }
+ else if (args[i] == "--json" || args[i] == "--protocol=json")
+ {
+ json = true;
+ }
+ else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
+ {
+ throw new NotImplementedException(args[i]);
+ }
+ else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
+ {
+ throw new NotImplementedException(args[i]);
+ }
+ else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
+ {
+ throw new NotImplementedException(args[i]);
+ }
+ else if (args[i] == "--ssl")
+ {
+ useEncryption = true;
+ }
+ else
+ {
+ //throw new ArgumentException(args[i]);
+ }
+ }
+
+ }
+ }
+
+ public class TestServer
+ {
+ public static int _clientID = -1;
+ public delegate void TestLogDelegate(string msg, params object[] values);
+
+ public class MyServerEventHandler : TServerEventHandler
+ {
+ public int callCount = 0;
+
+ public Task PreServeAsync(CancellationToken cancellationToken)
+ {
+ callCount++;
+ return Task.CompletedTask;
+ }
+
+ public Task<object> CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken)
+ {
+ callCount++;
+ return Task.FromResult<object>(null);
+ }
+
+ public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken)
+ {
+ callCount++;
+ return Task.CompletedTask;
+ }
+
+ public Task ProcessContextAsync(object serverContext, TClientTransport transport, CancellationToken cancellationToken)
+ {
+ callCount++;
+ return Task.CompletedTask;
+ }
+ }
+
+ public class TestHandlerAsync : ThriftTest.IAsync
+ {
+ public TBaseServer server { get; set; }
+ private int handlerID;
+ private StringBuilder sb = new StringBuilder();
+ private TestLogDelegate logger;
+
+ public TestHandlerAsync()
+ {
+ handlerID = Interlocked.Increment(ref _clientID);
+ logger += testConsoleLogger;
+ logger.Invoke("New TestHandler instance created");
+ }
+
+ public void testConsoleLogger(string msg, params object[] values)
+ {
+ sb.Clear();
+ sb.AppendFormat("handler{0:D3}:", handlerID);
+ sb.AppendFormat(msg, values);
+ sb.AppendLine();
+ Console.Write(sb.ToString());
+ }
+
+ public Task testVoidAsync(CancellationToken cancellationToken)
+ {
+ logger.Invoke("testVoid()");
+ return Task.CompletedTask;
+ }
+
+ public Task<string> testStringAsync(string thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testString({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<bool> testBoolAsync(bool thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testBool({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<sbyte> testByteAsync(sbyte thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testByte({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<int> testI32Async(int thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testI32({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<long> testI64Async(long thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testI64({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<double> testDoubleAsync(double thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testDouble({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<byte[]> testBinaryAsync(byte[] thing, CancellationToken cancellationToken)
+ {
+ var hex = BitConverter.ToString(thing).Replace("-", string.Empty);
+ logger.Invoke("testBinary({0:X})", hex);
+ return Task.FromResult(thing);
+ }
+
+ public Task<Xtruct> testStructAsync(Xtruct thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<Xtruct2> testNestAsync(Xtruct2 nest, CancellationToken cancellationToken)
+ {
+ var thing = nest.Struct_thing;
+ logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
+ nest.Byte_thing,
+ thing.String_thing,
+ thing.Byte_thing,
+ thing.I32_thing,
+ thing.I64_thing,
+ nest.I32_thing);
+ return Task.FromResult(nest);
+ }
+
+ public Task<Dictionary<int, int>> testMapAsync(Dictionary<int, int> thing, CancellationToken cancellationToken)
+ {
+ sb.Clear();
+ sb.Append("testMap({{");
+ var first = true;
+ foreach (var key in thing.Keys)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ sb.Append(", ");
+ }
+ sb.AppendFormat("{0} => {1}", key, thing[key]);
+ }
+ sb.Append("}})");
+ logger.Invoke(sb.ToString());
+ return Task.FromResult(thing);
+ }
+
+ public Task<Dictionary<string, string>> testStringMapAsync(Dictionary<string, string> thing, CancellationToken cancellationToken)
+ {
+ sb.Clear();
+ sb.Append("testStringMap({{");
+ var first = true;
+ foreach (var key in thing.Keys)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ sb.Append(", ");
+ }
+ sb.AppendFormat("{0} => {1}", key, thing[key]);
+ }
+ sb.Append("}})");
+ logger.Invoke(sb.ToString());
+ return Task.FromResult(thing);
+ }
+
+ public Task<THashSet<int>> testSetAsync(THashSet<int> thing, CancellationToken cancellationToken)
+ {
+ sb.Clear();
+ sb.Append("testSet({{");
+ var first = true;
+ foreach (int elem in thing)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ sb.Append(", ");
+ }
+ sb.AppendFormat("{0}", elem);
+ }
+ sb.Append("}})");
+ logger.Invoke(sb.ToString());
+ return Task.FromResult(thing);
+ }
+
+ public Task<List<int>> testListAsync(List<int> thing, CancellationToken cancellationToken)
+ {
+ sb.Clear();
+ sb.Append("testList({{");
+ var first = true;
+ foreach (var elem in thing)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ sb.Append(", ");
+ }
+ sb.AppendFormat("{0}", elem);
+ }
+ sb.Append("}})");
+ logger.Invoke(sb.ToString());
+ return Task.FromResult(thing);
+ }
+
+ public Task<Numberz> testEnumAsync(Numberz thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testEnum({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<long> testTypedefAsync(long thing, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testTypedef({0})", thing);
+ return Task.FromResult(thing);
+ }
+
+ public Task<Dictionary<int, Dictionary<int, int>>> testMapMapAsync(int hello, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testMapMap({0})", hello);
+ var mapmap = new Dictionary<int, Dictionary<int, int>>();
+
+ var pos = new Dictionary<int, int>();
+ var neg = new Dictionary<int, int>();
+ for (var i = 1; i < 5; i++)
+ {
+ pos[i] = i;
+ neg[-i] = -i;
+ }
+
+ mapmap[4] = pos;
+ mapmap[-4] = neg;
+
+ return Task.FromResult(mapmap);
+ }
+
+ public Task<Dictionary<long, Dictionary<Numberz, Insanity>>> testInsanityAsync(Insanity argument, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testInsanity()");
+
+ /** from ThriftTest.thrift:
+ * So you think you've got this all worked, out eh?
+ *
+ * Creates a the returned map with these values and prints it out:
+ * { 1 => { 2 => argument,
+ * 3 => argument,
+ * },
+ * 2 => { 6 => <empty Insanity struct>, },
+ * }
+ * @return map<UserId, map<Numberz,Insanity>> - a map with the above values
+ */
+
+ var first_map = new Dictionary<Numberz, Insanity>();
+ var second_map = new Dictionary<Numberz, Insanity>(); ;
+
+ first_map[Numberz.TWO] = argument;
+ first_map[Numberz.THREE] = argument;
+
+ second_map[Numberz.SIX] = new Insanity();
+
+ var insane = new Dictionary<long, Dictionary<Numberz, Insanity>>
+ {
+ [1] = first_map,
+ [2] = second_map
+ };
+
+ return Task.FromResult(insane);
+ }
+
+ public Task<Xtruct> testMultiAsync(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5,
+ CancellationToken cancellationToken)
+ {
+ logger.Invoke("testMulti()");
+
+ var hello = new Xtruct(); ;
+ hello.String_thing = "Hello2";
+ hello.Byte_thing = arg0;
+ hello.I32_thing = arg1;
+ hello.I64_thing = arg2;
+ return Task.FromResult(hello);
+ }
+
+ public Task testExceptionAsync(string arg, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testException({0})", arg);
+ if (arg == "Xception")
+ {
+ var x = new Xception
+ {
+ ErrorCode = 1001,
+ Message = arg
+ };
+ throw x;
+ }
+ if (arg == "TException")
+ {
+ throw new TException();
+ }
+ return Task.CompletedTask;
+ }
+
+ public Task<Xtruct> testMultiExceptionAsync(string arg0, string arg1, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testMultiException({0}, {1})", arg0, arg1);
+ if (arg0 == "Xception")
+ {
+ var x = new Xception
+ {
+ ErrorCode = 1001,
+ Message = "This is an Xception"
+ };
+ throw x;
+ }
+
+ if (arg0 == "Xception2")
+ {
+ var x = new Xception2
+ {
+ ErrorCode = 2002,
+ Struct_thing = new Xtruct { String_thing = "This is an Xception2" }
+ };
+ throw x;
+ }
+
+ var result = new Xtruct { String_thing = arg1 };
+ return Task.FromResult(result);
+ }
+
+ public Task testOnewayAsync(int secondsToSleep, CancellationToken cancellationToken)
+ {
+ logger.Invoke("testOneway({0}), sleeping...", secondsToSleep);
+ Task.Delay(secondsToSleep * 1000, cancellationToken).GetAwaiter().GetResult();
+ logger.Invoke("testOneway finished");
+
+ return Task.CompletedTask;
+ }
+ }
+
+ internal static void PrintOptionsHelp()
+ {
+ Console.WriteLine("Server options:");
+ Console.WriteLine(" --pipe=<pipe name>");
+ Console.WriteLine(" --port=<port number>");
+ Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
+ Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
+ Console.WriteLine(" --server-type=<type> one of threaded,threadpool (defaults to simple)");
+ Console.WriteLine(" --processor=<prototype>");
+ Console.WriteLine(" --ssl");
+ Console.WriteLine();
+ }
+
+ private static X509Certificate2 GetServerCert()
+ {
+ var serverCertName = "server.p12";
+ var possiblePaths = new List<string>
+ {
+ "../../../keys/",
+ "../../keys/",
+ "../keys/",
+ "keys/",
+ };
+
+ string existingPath = null;
+ foreach (var possiblePath in possiblePaths)
+ {
+ var path = Path.GetFullPath(possiblePath + serverCertName);
+ if (File.Exists(path))
+ {
+ existingPath = path;
+ break;
+ }
+ }
+
+ if (string.IsNullOrEmpty(existingPath))
+ {
+ throw new FileNotFoundException($"Cannot find file: {serverCertName}");
+ }
+
+ var cert = new X509Certificate2(existingPath, "thrift");
+
+ return cert;
+ }
+
+ public static int Execute(List<string> args)
+ {
+ var loggerFactory = new LoggerFactory();//.AddConsole().AddDebug();
+ var logger = new LoggerFactory().CreateLogger("Test");
+
+ try
+ {
+ var param = new ServerParam();
+
+ try
+ {
+ param.Parse(args);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("*** FAILED ***");
+ Console.WriteLine("Error while parsing arguments");
+ Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
+ return 1;
+ }
+
+
+ // Transport
+ TServerTransport trans;
+ if (param.pipe != null)
+ {
+ trans = new TNamedPipeServerTransport(param.pipe);
+ }
+// else if (param.useFramed)
+// {
+// trans = new TServerFramedTransport(param.port);
+// }
+ else
+ {
+ if (param.useEncryption)
+ {
+ var cert = GetServerCert();
+
+ if (cert == null || !cert.HasPrivateKey)
+ {
+ throw new InvalidOperationException("Certificate doesn't contain private key");
+ }
+
+ trans = new TTlsServerSocketTransport(param.port, param.useBufferedSockets, param.useFramed, cert,
+ (sender, certificate, chain, errors) => true,
+ null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
+ }
+ else
+ {
+ trans = new TServerSocketTransport(param.port, 0, param.useBufferedSockets, param.useFramed);
+ }
+ }
+
+ ITProtocolFactory proto;
+ if (param.compact)
+ proto = new TCompactProtocol.Factory();
+ else if (param.json)
+ proto = new TJsonProtocol.Factory();
+ else
+ proto = new TBinaryProtocol.Factory();
+
+ ITProcessorFactory processorFactory;
+
+ // Processor
+ var testHandler = new TestHandlerAsync();
+ var testProcessor = new ThriftTest.AsyncProcessor(testHandler);
+ processorFactory = new SingletonTProcessorFactory(testProcessor);
+
+ TTransportFactory transFactory = new TTransportFactory();
+
+ TBaseServer serverEngine = new AsyncBaseServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger);
+
+ //Server event handler
+ var serverEvents = new MyServerEventHandler();
+ serverEngine.SetEventHandler(serverEvents);
+
+ // Run it
+ var where = (! string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port;
+ Console.WriteLine("Starting the AsyncBaseServer " + where +
+ " with processor TPrototypeProcessorFactory prototype factory " +
+ (param.useBufferedSockets ? " with buffered socket" : "") +
+ (param.useFramed ? " with framed transport" : "") +
+ (param.useEncryption ? " with encryption" : "") +
+ (param.compact ? " with compact protocol" : "") +
+ (param.json ? " with json protocol" : "") +
+ "...");
+ serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
+ Console.ReadLine();
+ }
+ catch (Exception x)
+ {
+ Console.Error.Write(x);
+ return 1;
+ }
+ Console.WriteLine("done.");
+ return 0;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/ThriftTest.sln
----------------------------------------------------------------------
diff --git a/test/netcore/ThriftTest.sln b/test/netcore/ThriftTest.sln
index c3f194b..2ab241a 100644
--- a/test/netcore/ThriftTest.sln
+++ b/test/netcore/ThriftTest.sln
@@ -1,11 +1,13 @@
-Microsoft Visual Studio Solution File, Format Version 12.00
+Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.12
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThriftTest", "ThriftTest\ThriftTest.csproj", "{DDED46FF-F359-47B4-BA7E-9B70F216BD44}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Thrift", "..\..\lib\netcore\Thrift\Thrift.csproj", "{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client", "Client\Client.csproj", "{21039F25-6ED7-4E80-A545-EBC93472EBD1}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Server\Server.csproj", "{0C6E8685-F191-4479-9842-882A38961127}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -16,18 +18,6 @@ Global
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Debug|x64.ActiveCfg = Debug|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Debug|x64.Build.0 = Debug|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Debug|x86.ActiveCfg = Debug|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Debug|x86.Build.0 = Debug|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Release|Any CPU.Build.0 = Release|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Release|x64.ActiveCfg = Release|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Release|x64.Build.0 = Release|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Release|x86.ActiveCfg = Release|Any CPU
- {DDED46FF-F359-47B4-BA7E-9B70F216BD44}.Release|x86.Build.0 = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -40,6 +30,30 @@ Global
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x64.Build.0 = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.ActiveCfg = Release|Any CPU
{C20EA2A9-7660-47DE-9A49-D1EF12FB2895}.Release|x86.Build.0 = Release|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x64.Build.0 = Debug|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Debug|x86.Build.0 = Debug|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|Any CPU.Build.0 = Release|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x64.ActiveCfg = Release|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x64.Build.0 = Release|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x86.ActiveCfg = Release|Any CPU
+ {21039F25-6ED7-4E80-A545-EBC93472EBD1}.Release|x86.Build.0 = Release|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Debug|x64.Build.0 = Debug|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Debug|x86.Build.0 = Debug|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Release|x64.ActiveCfg = Release|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Release|x64.Build.0 = Release|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Release|x86.ActiveCfg = Release|Any CPU
+ {0C6E8685-F191-4479-9842-882A38961127}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/ThriftTest/Program.cs
----------------------------------------------------------------------
diff --git a/test/netcore/ThriftTest/Program.cs b/test/netcore/ThriftTest/Program.cs
deleted file mode 100644
index 94ed9d9..0000000
--- a/test/netcore/ThriftTest/Program.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-// Licensed to the Apache Software Foundation(ASF) under one
-// or more contributor license agreements.See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-using System;
-using System.Collections.Generic;
-using Test;
-
-namespace ThriftTest
-{
- public class Program
- {
- public static int Main(string[] args)
- {
- try
- {
- Console.SetBufferSize(Console.BufferWidth, 4096);
- }
- catch (Exception)
- {
- Console.WriteLine("Failed to grow scroll-back buffer");
- }
-
- // split mode and options
- var subArgs = new List<string>(args);
- var firstArg = string.Empty;
- if (subArgs.Count > 0)
- {
- firstArg = subArgs[0];
- subArgs.RemoveAt(0);
- }
-
- // run whatever mode is choosen
- switch(firstArg)
- {
- case "client":
- return TestClient.Execute(subArgs);
- case "server":
- return TestServer.Execute(subArgs);
- case "--help":
- PrintHelp();
- return 0;
- default:
- PrintHelp();
- return -1;
- }
- }
-
- private static void PrintHelp()
- {
- Console.WriteLine("Usage:");
- Console.WriteLine(" ThriftTest server [options]'");
- Console.WriteLine(" ThriftTest client [options]'");
- Console.WriteLine(" ThriftTest --help");
- Console.WriteLine("");
-
- TestServer.PrintOptionsHelp();
- TestClient.PrintOptionsHelp();
- }
- }
-}
-
-
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/ThriftTest/Properties/AssemblyInfo.cs
----------------------------------------------------------------------
diff --git a/test/netcore/ThriftTest/Properties/AssemblyInfo.cs b/test/netcore/ThriftTest/Properties/AssemblyInfo.cs
deleted file mode 100644
index efc9e33..0000000
--- a/test/netcore/ThriftTest/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the Apache Software Foundation(ASF) under one
-// or more contributor license agreements.See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-
-[assembly: AssemblyTitle("ThriftTest")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("The Apache Software Foundation")]
-[assembly: AssemblyProduct("Thrift")]
-[assembly: AssemblyCopyright("The Apache Software Foundation")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-
-[assembly: Guid("B0C13DA0-3117-4844-8AE8-B1775E46223D")]
-
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/ThriftTest/Properties/launchSettings.json
----------------------------------------------------------------------
diff --git a/test/netcore/ThriftTest/Properties/launchSettings.json b/test/netcore/ThriftTest/Properties/launchSettings.json
deleted file mode 100644
index ddafa79..0000000
--- a/test/netcore/ThriftTest/Properties/launchSettings.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "profiles": {
- "ThriftTest": {
- "commandName": "Project"
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/ThriftTest/TestClient.cs
----------------------------------------------------------------------
diff --git a/test/netcore/ThriftTest/TestClient.cs b/test/netcore/ThriftTest/TestClient.cs
deleted file mode 100644
index f6cc900..0000000
--- a/test/netcore/ThriftTest/TestClient.cs
+++ /dev/null
@@ -1,898 +0,0 @@
-// Licensed to the Apache Software Foundation(ASF) under one
-// or more contributor license agreements.See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Net;
-using System.Reflection;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using ThriftAsync.Test;
-using Thrift.Collections;
-using Thrift.Protocols;
-using Thrift.Transports;
-using Thrift.Transports.Client;
-
-namespace Test
-{
- public class TestClient
- {
- private class TestParams
- {
- public int numIterations = 1;
- public IPAddress host = IPAddress.Loopback;
- public int port = 9090;
- public int numThreads = 1;
- public string url;
- public string pipe;
- public bool buffered;
- public bool framed;
- public string protocol;
- public bool encrypted = false;
-
- internal void Parse( List<string> args)
- {
- for (var i = 0; i < args.Count; ++i)
- {
- if (args[i] == "-u")
- {
- url = args[++i];
- }
- else if (args[i] == "-n")
- {
- numIterations = Convert.ToInt32(args[++i]);
- }
- else if (args[i].StartsWith("--pipe="))
- {
- pipe = args[i].Substring(args[i].IndexOf("=") + 1);
- Console.WriteLine("Using named pipes transport");
- }
- else if (args[i].StartsWith("--host="))
- {
- // check there for ipaddress
- host = new IPAddress(Encoding.Unicode.GetBytes(args[i].Substring(args[i].IndexOf("=") + 1)));
- }
- else if (args[i].StartsWith("--port="))
- {
- port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
- }
- else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
- {
- buffered = true;
- Console.WriteLine("Using buffered sockets");
- }
- else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
- {
- framed = true;
- Console.WriteLine("Using framed transport");
- }
- else if (args[i] == "-t")
- {
- numThreads = Convert.ToInt32(args[++i]);
- }
- else if (args[i] == "--binary" || args[i] == "--protocol=binary")
- {
- protocol = "binary";
- Console.WriteLine("Using binary protocol");
- }
- else if (args[i] == "--compact" || args[i] == "--protocol=compact")
- {
- protocol = "compact";
- Console.WriteLine("Using compact protocol");
- }
- else if (args[i] == "--json" || args[i] == "--protocol=json")
- {
- protocol = "json";
- Console.WriteLine("Using JSON protocol");
- }
- else if (args[i] == "--ssl")
- {
- encrypted = true;
- Console.WriteLine("Using encrypted transport");
- }
- else
- {
- throw new ArgumentException(args[i]);
- }
- }
- }
-
- public TClientTransport CreateTransport()
- {
- if (url == null)
- {
- // endpoint transport
- TClientTransport trans = null;
-
- if (pipe != null)
- {
- trans = new TNamedPipeClientTransport(pipe);
- }
- else
- {
- if (encrypted)
- {
- var certPath = "../../keys/client.p12";
- var cert = new X509Certificate2(certPath, "thrift");
- trans = new TTlsSocketClientTransport(host, port, 0, cert, (o, c, chain, errors) => true, null, SslProtocols.Tls);
- }
- else
- {
- trans = new TSocketClientTransport(host, port);
- }
- }
-
- // layered transport
- if (buffered)
- {
- trans = new TBufferedClientTransport(trans);
- }
-
- if (framed)
- {
- trans = new TFramedClientTransport(trans);
- }
-
- return trans;
- }
-
- return new THttpClientTransport(new Uri(url), null);
- }
-
- public TProtocol CreateProtocol(TClientTransport transport)
- {
- if (protocol == "compact")
- {
- return new TCompactProtocol(transport);
- }
-
- if (protocol == "json")
- {
- return new TJsonProtocol(transport);
- }
-
- return new TBinaryProtocol(transport);
- }
- }
-
-
- private const int ErrorBaseTypes = 1;
- private const int ErrorStructs = 2;
- private const int ErrorContainers = 4;
- private const int ErrorExceptions = 8;
- private const int ErrorUnknown = 64;
-
- private class ClientTest
- {
- private readonly TClientTransport transport;
- private readonly ThriftAsync.Test.ThriftTest.Client client;
- private readonly int numIterations;
- private bool done;
-
- public int ReturnCode { get; set; }
-
- public ClientTest(TestParams param)
- {
- transport = param.CreateTransport();
- client = new ThriftAsync.Test.ThriftTest.Client(param.CreateProtocol(transport));
- numIterations = param.numIterations;
- }
-
- public void Execute()
- {
- var token = CancellationToken.None;
-
- if (done)
- {
- Console.WriteLine("Execute called more than once");
- throw new InvalidOperationException();
- }
-
- for (var i = 0; i < numIterations; i++)
- {
- try
- {
- if (!transport.IsOpen)
- {
- transport.OpenAsync(token).GetAwaiter().GetResult();
- }
- }
- catch (TTransportException ex)
- {
- Console.WriteLine("*** FAILED ***");
- Console.WriteLine("Connect failed: " + ex.Message);
- ReturnCode |= ErrorUnknown;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- continue;
- }
-
- try
- {
- ReturnCode |= ExecuteClientTestAsync(client).GetAwaiter().GetResult(); ;
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- ReturnCode |= ErrorUnknown;
- }
- }
- try
- {
- transport.Close();
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error while closing transport");
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
- done = true;
- }
- }
-
- internal static void PrintOptionsHelp()
- {
- Console.WriteLine("Client options:");
- Console.WriteLine(" -u <URL>");
- Console.WriteLine(" -t <# of threads to run> default = 1");
- Console.WriteLine(" -n <# of iterations> per thread");
- Console.WriteLine(" --pipe=<pipe name>");
- Console.WriteLine(" --host=<IP address>");
- Console.WriteLine(" --port=<port number>");
- Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
- Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
- Console.WriteLine(" --ssl");
- Console.WriteLine();
- }
-
- public static int Execute(List<string> args)
- {
- try
- {
- var param = new TestParams();
-
- try
- {
- param.Parse(args);
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- Console.WriteLine("Error while parsing arguments");
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- return ErrorUnknown;
- }
-
- var tests = Enumerable.Range(0, param.numThreads).Select(_ => new ClientTest(param)).ToArray();
-
- //issue tests on separate threads simultaneously
- var threads = tests.Select(test => new Thread(test.Execute)).ToArray();
- var start = DateTime.Now;
- foreach (var t in threads)
- {
- t.Start();
- }
-
- foreach (var t in threads)
- {
- t.Join();
- }
-
- Console.WriteLine("Total time: " + (DateTime.Now - start));
- Console.WriteLine();
- return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
- }
- catch (Exception outerEx)
- {
- Console.WriteLine("*** FAILED ***");
- Console.WriteLine("Unexpected error");
- Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
- return ErrorUnknown;
- }
- }
-
- public static string BytesToHex(byte[] data)
- {
- return BitConverter.ToString(data).Replace("-", string.Empty);
- }
-
- public static byte[] PrepareTestData(bool randomDist)
- {
- var retval = new byte[0x100];
- var initLen = Math.Min(0x100, retval.Length);
-
- // linear distribution, unless random is requested
- if (!randomDist)
- {
- for (var i = 0; i < initLen; ++i)
- {
- retval[i] = (byte)i;
- }
- return retval;
- }
-
- // random distribution
- for (var i = 0; i < initLen; ++i)
- {
- retval[i] = (byte)0;
- }
- var rnd = new Random();
- for (var i = 1; i < initLen; ++i)
- {
- while (true)
- {
- var nextPos = rnd.Next() % initLen;
- if (retval[nextPos] == 0)
- {
- retval[nextPos] = (byte)i;
- break;
- }
- }
- }
- return retval;
- }
-
- public static async Task<int> ExecuteClientTestAsync(ThriftAsync.Test.ThriftTest.Client client)
- {
- var token = CancellationToken.None;
- var returnCode = 0;
-
- Console.Write("testVoid()");
- await client.testVoidAsync(token);
- Console.WriteLine(" = void");
-
- Console.Write("testString(\"Test\")");
- var s = await client.testStringAsync("Test", token);
- Console.WriteLine(" = \"" + s + "\"");
- if ("Test" != s)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
-
- Console.Write("testBool(true)");
- var t = await client.testBoolAsync((bool)true, token);
- Console.WriteLine(" = " + t);
- if (!t)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
- Console.Write("testBool(false)");
- var f = await client.testBoolAsync((bool)false, token);
- Console.WriteLine(" = " + f);
- if (f)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
-
- Console.Write("testByte(1)");
- var i8 = await client.testByteAsync((sbyte)1, token);
- Console.WriteLine(" = " + i8);
- if (1 != i8)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
-
- Console.Write("testI32(-1)");
- var i32 = await client.testI32Async(-1, token);
- Console.WriteLine(" = " + i32);
- if (-1 != i32)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
-
- Console.Write("testI64(-34359738368)");
- var i64 = await client.testI64Async(-34359738368, token);
- Console.WriteLine(" = " + i64);
- if (-34359738368 != i64)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
-
- // TODO: Validate received message
- Console.Write("testDouble(5.325098235)");
- var dub = await client.testDoubleAsync(5.325098235, token);
- Console.WriteLine(" = " + dub);
- if (5.325098235 != dub)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
- Console.Write("testDouble(-0.000341012439638598279)");
- dub = await client.testDoubleAsync(-0.000341012439638598279, token);
- Console.WriteLine(" = " + dub);
- if (-0.000341012439638598279 != dub)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
-
- var binOut = PrepareTestData(true);
- Console.Write("testBinary(" + BytesToHex(binOut) + ")");
- try
- {
- var binIn = await client.testBinaryAsync(binOut, token);
- Console.WriteLine(" = " + BytesToHex(binIn));
- if (binIn.Length != binOut.Length)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
- for (var ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
- if (binIn[ofs] != binOut[ofs])
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
- }
- catch (Thrift.TApplicationException ex)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
-
- // binary equals? only with hashcode option enabled ...
- Console.WriteLine("Test CrazyNesting");
- var one = new CrazyNesting();
- var two = new CrazyNesting();
- one.String_field = "crazy";
- two.String_field = "crazy";
- one.Binary_field = new byte[] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
- two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
- if (typeof(CrazyNesting).GetMethod("Equals")?.DeclaringType == typeof(CrazyNesting))
- {
- if (!one.Equals(two))
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorContainers;
- throw new Exception("CrazyNesting.Equals failed");
- }
- }
-
- // TODO: Validate received message
- Console.Write("testStruct({\"Zero\", 1, -3, -5})");
- var o = new Xtruct();
- o.String_thing = "Zero";
- o.Byte_thing = (sbyte)1;
- o.I32_thing = -3;
- o.I64_thing = -5;
- var i = await client.testStructAsync(o, token);
- Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
-
- // TODO: Validate received message
- Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
- var o2 = new Xtruct2();
- o2.Byte_thing = (sbyte)1;
- o2.Struct_thing = o;
- o2.I32_thing = 5;
- var i2 = await client.testNestAsync(o2, token);
- i = i2.Struct_thing;
- Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
-
- var mapout = new Dictionary<int, int>();
- for (var j = 0; j < 5; j++)
- {
- mapout[j] = j - 10;
- }
- Console.Write("testMap({");
- var first = true;
- foreach (var key in mapout.Keys)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- Console.Write(", ");
- }
- Console.Write(key + " => " + mapout[key]);
- }
- Console.Write("})");
-
- var mapin = await client.testMapAsync(mapout, token);
-
- Console.Write(" = {");
- first = true;
- foreach (var key in mapin.Keys)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- Console.Write(", ");
- }
- Console.Write(key + " => " + mapin[key]);
- }
- Console.WriteLine("}");
-
- // TODO: Validate received message
- var listout = new List<int>();
- for (var j = -2; j < 3; j++)
- {
- listout.Add(j);
- }
- Console.Write("testList({");
- first = true;
- foreach (var j in listout)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- Console.Write(", ");
- }
- Console.Write(j);
- }
- Console.Write("})");
-
- var listin = await client.testListAsync(listout, token);
-
- Console.Write(" = {");
- first = true;
- foreach (var j in listin)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- Console.Write(", ");
- }
- Console.Write(j);
- }
- Console.WriteLine("}");
-
- //set
- // TODO: Validate received message
- var setout = new THashSet<int>();
- for (var j = -2; j < 3; j++)
- {
- setout.Add(j);
- }
- Console.Write("testSet({");
- first = true;
- foreach (int j in setout)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- Console.Write(", ");
- }
- Console.Write(j);
- }
- Console.Write("})");
-
- var setin = await client.testSetAsync(setout, token);
-
- Console.Write(" = {");
- first = true;
- foreach (int j in setin)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- Console.Write(", ");
- }
- Console.Write(j);
- }
- Console.WriteLine("}");
-
-
- Console.Write("testEnum(ONE)");
- var ret = await client.testEnumAsync(Numberz.ONE, token);
- Console.WriteLine(" = " + ret);
- if (Numberz.ONE != ret)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorStructs;
- }
-
- Console.Write("testEnum(TWO)");
- ret = await client.testEnumAsync(Numberz.TWO, token);
- Console.WriteLine(" = " + ret);
- if (Numberz.TWO != ret)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorStructs;
- }
-
- Console.Write("testEnum(THREE)");
- ret = await client.testEnumAsync(Numberz.THREE, token);
- Console.WriteLine(" = " + ret);
- if (Numberz.THREE != ret)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorStructs;
- }
-
- Console.Write("testEnum(FIVE)");
- ret = await client.testEnumAsync(Numberz.FIVE, token);
- Console.WriteLine(" = " + ret);
- if (Numberz.FIVE != ret)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorStructs;
- }
-
- Console.Write("testEnum(EIGHT)");
- ret = await client.testEnumAsync(Numberz.EIGHT, token);
- Console.WriteLine(" = " + ret);
- if (Numberz.EIGHT != ret)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorStructs;
- }
-
- Console.Write("testTypedef(309858235082523)");
- var uid = await client.testTypedefAsync(309858235082523L, token);
- Console.WriteLine(" = " + uid);
- if (309858235082523L != uid)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorStructs;
- }
-
- // TODO: Validate received message
- Console.Write("testMapMap(1)");
- var mm = await client.testMapMapAsync(1, token);
- Console.Write(" = {");
- foreach (var key in mm.Keys)
- {
- Console.Write(key + " => {");
- var m2 = mm[key];
- foreach (var k2 in m2.Keys)
- {
- Console.Write(k2 + " => " + m2[k2] + ", ");
- }
- Console.Write("}, ");
- }
- Console.WriteLine("}");
-
- // TODO: Validate received message
- var insane = new Insanity();
- insane.UserMap = new Dictionary<Numberz, long>();
- insane.UserMap[Numberz.FIVE] = 5000L;
- var truck = new Xtruct();
- truck.String_thing = "Truck";
- truck.Byte_thing = (sbyte)8;
- truck.I32_thing = 8;
- truck.I64_thing = 8;
- insane.Xtructs = new List<Xtruct>();
- insane.Xtructs.Add(truck);
- Console.Write("testInsanity()");
- var whoa = await client.testInsanityAsync(insane, token);
- Console.Write(" = {");
- foreach (var key in whoa.Keys)
- {
- var val = whoa[key];
- Console.Write(key + " => {");
-
- foreach (var k2 in val.Keys)
- {
- var v2 = val[k2];
-
- Console.Write(k2 + " => {");
- var userMap = v2.UserMap;
-
- Console.Write("{");
- if (userMap != null)
- {
- foreach (var k3 in userMap.Keys)
- {
- Console.Write(k3 + " => " + userMap[k3] + ", ");
- }
- }
- else
- {
- Console.Write("null");
- }
- Console.Write("}, ");
-
- var xtructs = v2.Xtructs;
-
- Console.Write("{");
- if (xtructs != null)
- {
- foreach (var x in xtructs)
- {
- Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
- }
- }
- else
- {
- Console.Write("null");
- }
- Console.Write("}");
-
- Console.Write("}, ");
- }
- Console.Write("}, ");
- }
- Console.WriteLine("}");
-
- sbyte arg0 = 1;
- var arg1 = 2;
- var arg2 = long.MaxValue;
- var multiDict = new Dictionary<short, string>();
- multiDict[1] = "one";
-
- var tmpMultiDict = new List<string>();
- foreach (var pair in multiDict)
- tmpMultiDict.Add(pair.Key +" => "+ pair.Value);
-
- var arg4 = Numberz.FIVE;
- long arg5 = 5000000;
- Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + ",{" + string.Join(",", tmpMultiDict) + "}," + arg4 + "," + arg5 + ")");
- var multiResponse = await client.testMultiAsync(arg0, arg1, arg2, multiDict, arg4, arg5, token);
- Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
- + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
-
- try
- {
- Console.WriteLine("testException(\"Xception\")");
- await client.testExceptionAsync("Xception", token);
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- catch (Xception ex)
- {
- if (ex.ErrorCode != 1001 || ex.Message != "Xception")
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
- try
- {
- Console.WriteLine("testException(\"TException\")");
- await client.testExceptionAsync("TException", token);
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- catch (Thrift.TException)
- {
- // OK
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
- try
- {
- Console.WriteLine("testException(\"ok\")");
- await client.testExceptionAsync("ok", token);
- // OK
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
-
- try
- {
- Console.WriteLine("testMultiException(\"Xception\", ...)");
- await client.testMultiExceptionAsync("Xception", "ignore", token);
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- catch (Xception ex)
- {
- if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception")
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
- try
- {
- Console.WriteLine("testMultiException(\"Xception2\", ...)");
- await client.testMultiExceptionAsync("Xception2", "ignore", token);
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- catch (Xception2 ex)
- {
- if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2")
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
- try
- {
- Console.WriteLine("testMultiException(\"success\", \"OK\")");
- if ("OK" != (await client.testMultiExceptionAsync("success", "OK", token)).String_thing)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorExceptions;
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- }
-
- var sw = new Stopwatch();
- sw.Start();
- Console.WriteLine("Test Oneway(1)");
- await client.testOnewayAsync(1, token);
- sw.Stop();
- if (sw.ElapsedMilliseconds > 1000)
- {
- Console.WriteLine("*** FAILED ***");
- returnCode |= ErrorBaseTypes;
- }
-
- Console.Write("Test Calltime()");
- var times = 50;
- sw.Reset();
- sw.Start();
- for (var k = 0; k < times; ++k)
- await client.testVoidAsync(token);
- sw.Stop();
- Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times);
- return returnCode;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/test/netcore/ThriftTest/TestServer.cs
----------------------------------------------------------------------
diff --git a/test/netcore/ThriftTest/TestServer.cs b/test/netcore/ThriftTest/TestServer.cs
deleted file mode 100644
index aa25c91..0000000
--- a/test/netcore/ThriftTest/TestServer.cs
+++ /dev/null
@@ -1,560 +0,0 @@
-// Licensed to the Apache Software Foundation(ASF) under one
-// or more contributor license agreements.See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-using System;
-using System.Collections.Generic;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.Extensions.Logging;
-using ThriftAsync.Test;
-using Thrift;
-using Thrift.Collections;
-using Thrift.Protocols;
-using Thrift.Server;
-using Thrift.Transports;
-using Thrift.Transports.Server;
-
-namespace Test
-{
- internal class ServerParam
- {
- internal bool useBufferedSockets = false;
- internal bool useFramed = false;
- internal bool useEncryption = false;
- internal bool compact = false;
- internal bool json = false;
- internal int port = 9090;
- internal string pipe = null;
-
- internal void Parse(List<string> args)
- {
- for (var i = 0; i < args.Count; i++)
- {
- if (args[i].StartsWith("--pipe="))
- {
- pipe = args[i].Substring(args[i].IndexOf("=") + 1);
- }
- else if (args[i].StartsWith("--port="))
- {
- port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
- }
- else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
- {
- useBufferedSockets = true;
- }
- else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
- {
- useFramed = true;
- }
- else if (args[i] == "--binary" || args[i] == "--protocol=binary")
- {
- // nothing needed
- }
- else if (args[i] == "--compact" || args[i] == "--protocol=compact")
- {
- compact = true;
- }
- else if (args[i] == "--json" || args[i] == "--protocol=json")
- {
- json = true;
- }
- else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
- {
- throw new NotImplementedException(args[i]);
- }
- else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
- {
- throw new NotImplementedException(args[i]);
- }
- else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
- {
- throw new NotImplementedException(args[i]);
- }
- else if (args[i] == "--ssl")
- {
- useEncryption = true;
- }
- else
- {
- throw new ArgumentException(args[i]);
- }
- }
-
- }
- }
-
- public class TestServer
- {
- public static int _clientID = -1;
- public delegate void TestLogDelegate(string msg, params object[] values);
-
- public class MyServerEventHandler : TServerEventHandler
- {
- public int callCount = 0;
-
- public Task PreServeAsync(CancellationToken cancellationToken)
- {
- callCount++;
- return Task.CompletedTask;
- }
-
- public Task<object> CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken)
- {
- callCount++;
- return Task.FromResult<object>(null);
- }
-
- public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken)
- {
- callCount++;
- return Task.CompletedTask;
- }
-
- public Task ProcessContextAsync(object serverContext, TClientTransport transport, CancellationToken cancellationToken)
- {
- callCount++;
- return Task.CompletedTask;
- }
- };
-
- public class TestHandlerAsync : ThriftAsync.Test.ThriftTest.IAsync
- {
- public TBaseServer server { get; set; }
- private int handlerID;
- private StringBuilder sb = new StringBuilder();
- private TestLogDelegate logger;
-
- public TestHandlerAsync()
- {
- handlerID = Interlocked.Increment(ref _clientID);
- logger += testConsoleLogger;
- logger.Invoke("New TestHandler instance created");
- }
-
- public void testConsoleLogger(string msg, params object[] values)
- {
- sb.Clear();
- sb.AppendFormat("handler{0:D3}:", handlerID);
- sb.AppendFormat(msg, values);
- sb.AppendLine();
- Console.Write(sb.ToString());
- }
-
- public Task testVoidAsync(CancellationToken cancellationToken)
- {
- logger.Invoke("testVoid()");
- return Task.CompletedTask;
- }
-
- public Task<string> testStringAsync(string thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testString({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<bool> testBoolAsync(bool thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testBool({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<sbyte> testByteAsync(sbyte thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testByte({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<int> testI32Async(int thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testI32({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<long> testI64Async(long thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testI64({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<double> testDoubleAsync(double thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testDouble({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<byte[]> testBinaryAsync(byte[] thing, CancellationToken cancellationToken)
- {
- var hex = BitConverter.ToString(thing).Replace("-", string.Empty);
- logger.Invoke("testBinary({0:X})", hex);
- return Task.FromResult(thing);
- }
-
- public Task<Xtruct> testStructAsync(Xtruct thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing);
- return Task.FromResult(thing);
- }
-
- public Task<Xtruct2> testNestAsync(Xtruct2 nest, CancellationToken cancellationToken)
- {
- var thing = nest.Struct_thing;
- logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
- nest.Byte_thing,
- thing.String_thing,
- thing.Byte_thing,
- thing.I32_thing,
- thing.I64_thing,
- nest.I32_thing);
- return Task.FromResult(nest);
- }
-
- public Task<Dictionary<int, int>> testMapAsync(Dictionary<int, int> thing, CancellationToken cancellationToken)
- {
- sb.Clear();
- sb.Append("testMap({{");
- var first = true;
- foreach (var key in thing.Keys)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- sb.Append(", ");
- }
- sb.AppendFormat("{0} => {1}", key, thing[key]);
- }
- sb.Append("}})");
- logger.Invoke(sb.ToString());
- return Task.FromResult(thing);
- }
-
- public Task<Dictionary<string, string>> testStringMapAsync(Dictionary<string, string> thing, CancellationToken cancellationToken)
- {
- sb.Clear();
- sb.Append("testStringMap({{");
- var first = true;
- foreach (var key in thing.Keys)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- sb.Append(", ");
- }
- sb.AppendFormat("{0} => {1}", key, thing[key]);
- }
- sb.Append("}})");
- logger.Invoke(sb.ToString());
- return Task.FromResult(thing);
- }
-
- public Task<THashSet<int>> testSetAsync(THashSet<int> thing, CancellationToken cancellationToken)
- {
- sb.Clear();
- sb.Append("testSet({{");
- var first = true;
- foreach (int elem in thing)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- sb.Append(", ");
- }
- sb.AppendFormat("{0}", elem);
- }
- sb.Append("}})");
- logger.Invoke(sb.ToString());
- return Task.FromResult(thing);
- }
-
- public Task<List<int>> testListAsync(List<int> thing, CancellationToken cancellationToken)
- {
- sb.Clear();
- sb.Append("testList({{");
- var first = true;
- foreach (var elem in thing)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- sb.Append(", ");
- }
- sb.AppendFormat("{0}", elem);
- }
- sb.Append("}})");
- logger.Invoke(sb.ToString());
- return Task.FromResult(thing);
- }
-
- public Task<Numberz> testEnumAsync(Numberz thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testEnum({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<long> testTypedefAsync(long thing, CancellationToken cancellationToken)
- {
- logger.Invoke("testTypedef({0})", thing);
- return Task.FromResult(thing);
- }
-
- public Task<Dictionary<int, Dictionary<int, int>>> testMapMapAsync(int hello, CancellationToken cancellationToken)
- {
- logger.Invoke("testMapMap({0})", hello);
- var mapmap = new Dictionary<int, Dictionary<int, int>>();
-
- var pos = new Dictionary<int, int>();
- var neg = new Dictionary<int, int>();
- for (var i = 1; i < 5; i++)
- {
- pos[i] = i;
- neg[-i] = -i;
- }
-
- mapmap[4] = pos;
- mapmap[-4] = neg;
-
- return Task.FromResult(mapmap);
- }
-
- public Task<Dictionary<long, Dictionary<Numberz, Insanity>>> testInsanityAsync(Insanity argument, CancellationToken cancellationToken)
- {
- logger.Invoke("testInsanity()");
-
- /** from ThriftTest.thrift:
- * So you think you've got this all worked, out eh?
- *
- * Creates a the returned map with these values and prints it out:
- * { 1 => { 2 => argument,
- * 3 => argument,
- * },
- * 2 => { 6 => <empty Insanity struct>, },
- * }
- * @return map<UserId, map<Numberz,Insanity>> - a map with the above values
- */
-
- var first_map = new Dictionary<Numberz, Insanity>();
- var second_map = new Dictionary<Numberz, Insanity>(); ;
-
- first_map[Numberz.TWO] = argument;
- first_map[Numberz.THREE] = argument;
-
- second_map[Numberz.SIX] = new Insanity();
-
- var insane = new Dictionary<long, Dictionary<Numberz, Insanity>>
- {
- [1] = first_map,
- [2] = second_map
- };
-
- return Task.FromResult(insane);
- }
-
- public Task<Xtruct> testMultiAsync(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5,
- CancellationToken cancellationToken)
- {
- logger.Invoke("testMulti()");
-
- var hello = new Xtruct(); ;
- hello.String_thing = "Hello2";
- hello.Byte_thing = arg0;
- hello.I32_thing = arg1;
- hello.I64_thing = arg2;
- return Task.FromResult(hello);
- }
-
- public Task testExceptionAsync(string arg, CancellationToken cancellationToken)
- {
- logger.Invoke("testException({0})", arg);
- if (arg == "Xception")
- {
- var x = new Xception
- {
- ErrorCode = 1001,
- Message = arg
- };
- throw x;
- }
- if (arg == "TException")
- {
- throw new TException();
- }
- return Task.CompletedTask;
- }
-
- public Task<Xtruct> testMultiExceptionAsync(string arg0, string arg1, CancellationToken cancellationToken)
- {
- logger.Invoke("testMultiException({0}, {1})", arg0, arg1);
- if (arg0 == "Xception")
- {
- var x = new Xception
- {
- ErrorCode = 1001,
- Message = "This is an Xception"
- };
- throw x;
- }
-
- if (arg0 == "Xception2")
- {
- var x = new Xception2
- {
- ErrorCode = 2002,
- Struct_thing = new Xtruct { String_thing = "This is an Xception2" }
- };
- throw x;
- }
-
- var result = new Xtruct { String_thing = arg1 };
- return Task.FromResult(result);
- }
-
- public Task testOnewayAsync(int secondsToSleep, CancellationToken cancellationToken)
- {
- logger.Invoke("testOneway({0}), sleeping...", secondsToSleep);
- Thread.Sleep(secondsToSleep * 1000);
- logger.Invoke("testOneway finished");
-
- return Task.CompletedTask;
- }
- }
-
-
- private enum ProcessorFactoryType
- {
- TSingletonProcessorFactory,
- TPrototypeProcessorFactory,
- }
-
- internal static void PrintOptionsHelp()
- {
- Console.WriteLine("Server options:");
- Console.WriteLine(" --pipe=<pipe name>");
- Console.WriteLine(" --port=<port number>");
- Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
- Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
- Console.WriteLine(" --server-type=<type> one of threaded,threadpool (defaults to simple)");
- Console.WriteLine(" --processor=<prototype>");
- Console.WriteLine(" --ssl");
- Console.WriteLine();
- }
-
- public static int Execute(List<string> args)
- {
- var logger = new LoggerFactory().CreateLogger("Test");
-
- try
- {
- var param = new ServerParam();
-
- try
- {
- param.Parse(args);
- }
- catch (Exception ex)
- {
- Console.WriteLine("*** FAILED ***");
- Console.WriteLine("Error while parsing arguments");
- Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
- return 1;
- }
-
-
- // Transport
- TServerTransport trans;
- if (param.pipe != null)
- {
- trans = new TNamedPipeServerTransport(param.pipe);
- }
- else
- {
- if (param.useEncryption)
- {
- var certPath = "../../keys/server.p12";
- trans = new TTlsServerSocketTransport(param.port, param.useBufferedSockets, new X509Certificate2(certPath, "thrift"), null, null, SslProtocols.Tls);
- }
- else
- {
- trans = new TServerSocketTransport(param.port, 0, param.useBufferedSockets);
- }
- }
-
- ITProtocolFactory proto;
- if (param.compact)
- proto = new TCompactProtocol.Factory();
- else if (param.json)
- proto = new TJsonProtocol.Factory();
- else
- proto = new TBinaryProtocol.Factory();
-
- ITProcessorFactory processorFactory;
-
- // Processor
- var testHandler = new TestHandlerAsync();
- var testProcessor = new ThriftAsync.Test.ThriftTest.AsyncProcessor(testHandler);
- processorFactory = new SingletonTProcessorFactory(testProcessor);
-
-
- TTransportFactory transFactory;
- if (param.useFramed)
- throw new NotImplementedException("framed"); // transFactory = new TFramedTransport.Factory();
- else
- transFactory = new TTransportFactory();
-
- TBaseServer serverEngine = new AsyncBaseServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger);
-
- //Server event handler
- var serverEvents = new MyServerEventHandler();
- serverEngine.SetEventHandler(serverEvents);
-
- // Run it
- var where = (! string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port;
- Console.WriteLine("Starting the AsyncBaseServer " + where +
- " with processor TPrototypeProcessorFactory prototype factory " +
- (param.useBufferedSockets ? " with buffered socket" : "") +
- (param.useFramed ? " with framed transport" : "") +
- (param.useEncryption ? " with encryption" : "") +
- (param.compact ? " with compact protocol" : "") +
- (param.json ? " with json protocol" : "") +
- "...");
- serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
- Console.ReadLine();
- }
- catch (Exception x)
- {
- Console.Error.Write(x);
- return 1;
- }
- Console.WriteLine("done.");
- return 0;
- }
- }
-
-}
[6/9] thrift git commit: THRIFT-4434: .NET Core cleanup and the
beginnings of compiler unit tests Client: netcore
Posted by jk...@apache.org.
http://git-wip-us.apache.org/repos/asf/thrift/blob/54993296/compiler/cpp/tests/catch/catch.hpp
----------------------------------------------------------------------
diff --git a/compiler/cpp/tests/catch/catch.hpp b/compiler/cpp/tests/catch/catch.hpp
new file mode 100644
index 0000000..33d037e
--- /dev/null
+++ b/compiler/cpp/tests/catch/catch.hpp
@@ -0,0 +1,11508 @@
+/*
+ * Catch v1.9.4
+ * Generated: 2017-05-16 13:51:55.506519
+ * ----------------------------------------------------------
+ * This file has been merged from multiple headers. Please don't edit it directly
+ * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved.
+ *
+ * Distributed under the Boost Software License, Version 1.0. (See accompanying
+ * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+ */
+#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
+#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
+
+#define TWOBLUECUBES_CATCH_HPP_INCLUDED
+
+#ifdef __clang__
+# pragma clang system_header
+#elif defined __GNUC__
+# pragma GCC system_header
+#endif
+
+// #included from: internal/catch_suppress_warnings.h
+
+#ifdef __clang__
+# ifdef __ICC // icpc defines the __clang__ macro
+# pragma warning(push)
+# pragma warning(disable: 161 1682)
+# else // __ICC
+# pragma clang diagnostic ignored "-Wglobal-constructors"
+# pragma clang diagnostic ignored "-Wvariadic-macros"
+# pragma clang diagnostic ignored "-Wc99-extensions"
+# pragma clang diagnostic ignored "-Wunused-variable"
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Wpadded"
+# pragma clang diagnostic ignored "-Wc++98-compat"
+# pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
+# pragma clang diagnostic ignored "-Wswitch-enum"
+# pragma clang diagnostic ignored "-Wcovered-switch-default"
+# endif
+#elif defined __GNUC__
+# pragma GCC diagnostic ignored "-Wvariadic-macros"
+# pragma GCC diagnostic ignored "-Wunused-variable"
+# pragma GCC diagnostic ignored "-Wparentheses"
+
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wpadded"
+#endif
+#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
+# define CATCH_IMPL
+#endif
+
+#ifdef CATCH_IMPL
+# ifndef CLARA_CONFIG_MAIN
+# define CLARA_CONFIG_MAIN_NOT_DEFINED
+# define CLARA_CONFIG_MAIN
+# endif
+#endif
+
+// #included from: internal/catch_notimplemented_exception.h
+#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED
+
+// #included from: catch_common.h
+#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
+
+// #included from: catch_compiler_capabilities.h
+#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
+
+// Detect a number of compiler features - mostly C++11/14 conformance - by compiler
+// The following features are defined:
+//
+// CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported?
+// CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported?
+// CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods
+// CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported?
+// CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported
+// CATCH_CONFIG_CPP11_LONG_LONG : is long long supported?
+// CATCH_CONFIG_CPP11_OVERRIDE : is override supported?
+// CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr)
+// CATCH_CONFIG_CPP11_SHUFFLE : is std::shuffle supported?
+// CATCH_CONFIG_CPP11_TYPE_TRAITS : are type_traits and enable_if supported?
+
+// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported?
+
+// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported?
+// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
+// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
+// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
+// ****************
+// Note to maintainers: if new toggles are added please document them
+// in configuration.md, too
+// ****************
+
+// In general each macro has a _NO_<feature name> form
+// (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature.
+// Many features, at point of detection, define an _INTERNAL_ macro, so they
+// can be combined, en-mass, with the _NO_ forms later.
+
+// All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11
+
+#ifdef __cplusplus
+
+# if __cplusplus >= 201103L
+# define CATCH_CPP11_OR_GREATER
+# endif
+
+# if __cplusplus >= 201402L
+# define CATCH_CPP14_OR_GREATER
+# endif
+
+#endif
+
+#ifdef __clang__
+
+# if __has_feature(cxx_nullptr)
+# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
+# endif
+
+# if __has_feature(cxx_noexcept)
+# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
+# endif
+
+# if defined(CATCH_CPP11_OR_GREATER)
+# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ _Pragma( "clang diagnostic push" ) \
+ _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" )
+# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
+ _Pragma( "clang diagnostic pop" )
+
+# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
+ _Pragma( "clang diagnostic push" ) \
+ _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
+# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
+ _Pragma( "clang diagnostic pop" )
+# endif
+
+#endif // __clang__
+
+////////////////////////////////////////////////////////////////////////////////
+// We know some environments not to support full POSIX signals
+#if defined(__CYGWIN__) || defined(__QNX__)
+
+# if !defined(CATCH_CONFIG_POSIX_SIGNALS)
+# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
+# endif
+
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+// Cygwin
+#ifdef __CYGWIN__
+
+// Required for some versions of Cygwin to declare gettimeofday
+// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
+# define _BSD_SOURCE
+
+#endif // __CYGWIN__
+
+////////////////////////////////////////////////////////////////////////////////
+// Borland
+#ifdef __BORLANDC__
+
+#endif // __BORLANDC__
+
+////////////////////////////////////////////////////////////////////////////////
+// EDG
+#ifdef __EDG_VERSION__
+
+#endif // __EDG_VERSION__
+
+////////////////////////////////////////////////////////////////////////////////
+// Digital Mars
+#ifdef __DMC__
+
+#endif // __DMC__
+
+////////////////////////////////////////////////////////////////////////////////
+// GCC
+#ifdef __GNUC__
+
+# if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__)
+# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
+# endif
+
+// - otherwise more recent versions define __cplusplus >= 201103L
+// and will get picked up below
+
+#endif // __GNUC__
+
+////////////////////////////////////////////////////////////////////////////////
+// Visual C++
+#ifdef _MSC_VER
+
+#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
+
+#if (_MSC_VER >= 1600)
+# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
+# define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
+#endif
+
+#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015))
+#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
+#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
+#define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
+#define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
+#endif
+
+#endif // _MSC_VER
+
+////////////////////////////////////////////////////////////////////////////////
+
+// Use variadic macros if the compiler supports them
+#if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \
+ ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \
+ ( defined __GNUC__ && __GNUC__ >= 3 ) || \
+ ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L )
+
+#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
+
+#endif
+
+// Use __COUNTER__ if the compiler supports it
+#if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \
+ ( defined __GNUC__ && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3 ) || \
+ ( defined __clang__ && __clang_major__ >= 3 )
+
+#define CATCH_INTERNAL_CONFIG_COUNTER
+
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+// C++ language feature support
+
+// catch all support for C++11
+#if defined(CATCH_CPP11_OR_GREATER)
+
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR)
+# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
+# endif
+
+# ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
+# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
+# endif
+
+# ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
+# define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
+# endif
+
+# ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
+# define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
+# endif
+
+# ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE
+# define CATCH_INTERNAL_CONFIG_CPP11_TUPLE
+# endif
+
+# ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
+# define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
+# endif
+
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG)
+# define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG
+# endif
+
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE)
+# define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE
+# endif
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR)
+# define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
+# endif
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE)
+# define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
+# endif
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS)
+# define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
+# endif
+
+#endif // __cplusplus >= 201103L
+
+// Now set the actual defines based on the above + anything the user has configured
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_NULLPTR
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_NOEXCEPT
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_GENERATED_METHODS
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_IS_ENUM
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_TUPLE
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS)
+# define CATCH_CONFIG_VARIADIC_MACROS
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_LONG_LONG
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_OVERRIDE
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_UNIQUE_PTR
+#endif
+// Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for
+// analytics) because, at time of writing, __COUNTER__ is not properly handled by it.
+// This does not affect compilation
+#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__)
+# define CATCH_CONFIG_COUNTER
+#endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_SHUFFLE
+#endif
+# if defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_NO_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_NO_CPP11)
+# define CATCH_CONFIG_CPP11_TYPE_TRAITS
+# endif
+#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
+# define CATCH_CONFIG_WINDOWS_SEH
+#endif
+// This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
+#if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
+# define CATCH_CONFIG_POSIX_SIGNALS
+#endif
+
+#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
+# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
+# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
+#endif
+#if !defined(CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS)
+# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS
+# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
+#endif
+
+// noexcept support:
+#if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT)
+# define CATCH_NOEXCEPT noexcept
+# define CATCH_NOEXCEPT_IS(x) noexcept(x)
+#else
+# define CATCH_NOEXCEPT throw()
+# define CATCH_NOEXCEPT_IS(x)
+#endif
+
+// nullptr support
+#ifdef CATCH_CONFIG_CPP11_NULLPTR
+# define CATCH_NULL nullptr
+#else
+# define CATCH_NULL NULL
+#endif
+
+// override support
+#ifdef CATCH_CONFIG_CPP11_OVERRIDE
+# define CATCH_OVERRIDE override
+#else
+# define CATCH_OVERRIDE
+#endif
+
+// unique_ptr support
+#ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR
+# define CATCH_AUTO_PTR( T ) std::unique_ptr<T>
+#else
+# define CATCH_AUTO_PTR( T ) std::auto_ptr<T>
+#endif
+
+#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
+#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
+#ifdef CATCH_CONFIG_COUNTER
+# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
+#else
+# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
+#endif
+
+#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr
+#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
+
+#include <sstream>
+#include <algorithm>
+
+namespace Catch {
+
+ struct IConfig;
+
+ struct CaseSensitive { enum Choice {
+ Yes,
+ No
+ }; };
+
+ class NonCopyable {
+#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
+ NonCopyable( NonCopyable const& ) = delete;
+ NonCopyable( NonCopyable && ) = delete;
+ NonCopyable& operator = ( NonCopyable const& ) = delete;
+ NonCopyable& operator = ( NonCopyable && ) = delete;
+#else
+ NonCopyable( NonCopyable const& info );
+ NonCopyable& operator = ( NonCopyable const& );
+#endif
+
+ protected:
+ NonCopyable() {}
+ virtual ~NonCopyable();
+ };
+
+ class SafeBool {
+ public:
+ typedef void (SafeBool::*type)() const;
+
+ static type makeSafe( bool value ) {
+ return value ? &SafeBool::trueValue : 0;
+ }
+ private:
+ void trueValue() const {}
+ };
+
+ template<typename ContainerT>
+ inline void deleteAll( ContainerT& container ) {
+ typename ContainerT::const_iterator it = container.begin();
+ typename ContainerT::const_iterator itEnd = container.end();
+ for(; it != itEnd; ++it )
+ delete *it;
+ }
+ template<typename AssociativeContainerT>
+ inline void deleteAllValues( AssociativeContainerT& container ) {
+ typename AssociativeContainerT::const_iterator it = container.begin();
+ typename AssociativeContainerT::const_iterator itEnd = container.end();
+ for(; it != itEnd; ++it )
+ delete it->second;
+ }
+
+ bool startsWith( std::string const& s, std::string const& prefix );
+ bool startsWith( std::string const& s, char prefix );
+ bool endsWith( std::string const& s, std::string const& suffix );
+ bool endsWith( std::string const& s, char suffix );
+ bool contains( std::string const& s, std::string const& infix );
+ void toLowerInPlace( std::string& s );
+ std::string toLower( std::string const& s );
+ std::string trim( std::string const& str );
+ bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
+
+ struct pluralise {
+ pluralise( std::size_t count, std::string const& label );
+
+ friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
+
+ std::size_t m_count;
+ std::string m_label;
+ };
+
+ struct SourceLineInfo {
+
+ SourceLineInfo();
+ SourceLineInfo( char const* _file, std::size_t _line );
+# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
+ SourceLineInfo(SourceLineInfo const& other) = default;
+ SourceLineInfo( SourceLineInfo && ) = default;
+ SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
+ SourceLineInfo& operator = ( SourceLineInfo && ) = default;
+# endif
+ bool empty() const;
+ bool operator == ( SourceLineInfo const& other ) const;
+ bool operator < ( SourceLineInfo const& other ) const;
+
+ char const* file;
+ std::size_t line;
+ };
+
+ std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
+
+ // This is just here to avoid compiler warnings with macro constants and boolean literals
+ inline bool isTrue( bool value ){ return value; }
+ inline bool alwaysTrue() { return true; }
+ inline bool alwaysFalse() { return false; }
+
+ void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo );
+
+ void seedRng( IConfig const& config );
+ unsigned int rngSeed();
+
+ // Use this in variadic streaming macros to allow
+ // >> +StreamEndStop
+ // as well as
+ // >> stuff +StreamEndStop
+ struct StreamEndStop {
+ std::string operator+() {
+ return std::string();
+ }
+ };
+ template<typename T>
+ T const& operator + ( T const& value, StreamEndStop ) {
+ return value;
+ }
+}
+
+#define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
+#define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO );
+
+namespace Catch {
+
+ class NotImplementedException : public std::exception
+ {
+ public:
+ NotImplementedException( SourceLineInfo const& lineInfo );
+ NotImplementedException( NotImplementedException const& ) {}
+
+ virtual ~NotImplementedException() CATCH_NOEXCEPT {}
+
+ virtual const char* what() const CATCH_NOEXCEPT;
+
+ private:
+ std::string m_what;
+ SourceLineInfo m_lineInfo;
+ };
+
+} // end namespace Catch
+
+///////////////////////////////////////////////////////////////////////////////
+#define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO )
+
+// #included from: internal/catch_context.h
+#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED
+
+// #included from: catch_interfaces_generators.h
+#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED
+
+#include <string>
+
+namespace Catch {
+
+ struct IGeneratorInfo {
+ virtual ~IGeneratorInfo();
+ virtual bool moveNext() = 0;
+ virtual std::size_t getCurrentIndex() const = 0;
+ };
+
+ struct IGeneratorsForTest {
+ virtual ~IGeneratorsForTest();
+
+ virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0;
+ virtual bool moveNext() = 0;
+ };
+
+ IGeneratorsForTest* createGeneratorsForTest();
+
+} // end namespace Catch
+
+// #included from: catch_ptr.hpp
+#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
+
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wpadded"
+#endif
+
+namespace Catch {
+
+ // An intrusive reference counting smart pointer.
+ // T must implement addRef() and release() methods
+ // typically implementing the IShared interface
+ template<typename T>
+ class Ptr {
+ public:
+ Ptr() : m_p( CATCH_NULL ){}
+ Ptr( T* p ) : m_p( p ){
+ if( m_p )
+ m_p->addRef();
+ }
+ Ptr( Ptr const& other ) : m_p( other.m_p ){
+ if( m_p )
+ m_p->addRef();
+ }
+ ~Ptr(){
+ if( m_p )
+ m_p->release();
+ }
+ void reset() {
+ if( m_p )
+ m_p->release();
+ m_p = CATCH_NULL;
+ }
+ Ptr& operator = ( T* p ){
+ Ptr temp( p );
+ swap( temp );
+ return *this;
+ }
+ Ptr& operator = ( Ptr const& other ){
+ Ptr temp( other );
+ swap( temp );
+ return *this;
+ }
+ void swap( Ptr& other ) { std::swap( m_p, other.m_p ); }
+ T* get() const{ return m_p; }
+ T& operator*() const { return *m_p; }
+ T* operator->() const { return m_p; }
+ bool operator !() const { return m_p == CATCH_NULL; }
+ operator SafeBool::type() const { return SafeBool::makeSafe( m_p != CATCH_NULL ); }
+
+ private:
+ T* m_p;
+ };
+
+ struct IShared : NonCopyable {
+ virtual ~IShared();
+ virtual void addRef() const = 0;
+ virtual void release() const = 0;
+ };
+
+ template<typename T = IShared>
+ struct SharedImpl : T {
+
+ SharedImpl() : m_rc( 0 ){}
+
+ virtual void addRef() const {
+ ++m_rc;
+ }
+ virtual void release() const {
+ if( --m_rc == 0 )
+ delete this;
+ }
+
+ mutable unsigned int m_rc;
+ };
+
+} // end namespace Catch
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
+namespace Catch {
+
+ class TestCase;
+ class Stream;
+ struct IResultCapture;
+ struct IRunner;
+ struct IGeneratorsForTest;
+ struct IConfig;
+
+ struct IContext
+ {
+ virtual ~IContext();
+
+ virtual IResultCapture* getResultCapture() = 0;
+ virtual IRunner* getRunner() = 0;
+ virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0;
+ virtual bool advanceGeneratorsForCurrentTest() = 0;
+ virtual Ptr<IConfig const> getConfig() const = 0;
+ };
+
+ struct IMutableContext : IContext
+ {
+ virtual ~IMutableContext();
+ virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
+ virtual void setRunner( IRunner* runner ) = 0;
+ virtual void setConfig( Ptr<IConfig const> const& config ) = 0;
+ };
+
+ IContext& getCurrentContext();
+ IMutableContext& getCurrentMutableContext();
+ void cleanUpContext();
+ Stream createStream( std::string const& streamName );
+
+}
+
+// #included from: internal/catch_test_registry.hpp
+#define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED
+
+// #included from: catch_interfaces_testcase.h
+#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED
+
+#include <vector>
+
+namespace Catch {
+
+ class TestSpec;
+
+ struct ITestCase : IShared {
+ virtual void invoke () const = 0;
+ protected:
+ virtual ~ITestCase();
+ };
+
+ class TestCase;
+ struct IConfig;
+
+ struct ITestCaseRegistry {
+ virtual ~ITestCaseRegistry();
+ virtual std::vector<TestCase> const& getAllTests() const = 0;
+ virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
+ };
+
+ bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
+ std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
+ std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
+
+}
+
+namespace Catch {
+
+template<typename C>
+class MethodTestCase : public SharedImpl<ITestCase> {
+
+public:
+ MethodTestCase( void (C::*method)() ) : m_method( method ) {}
+
+ virtual void invoke() const {
+ C obj;
+ (obj.*m_method)();
+ }
+
+private:
+ virtual ~MethodTestCase() {}
+
+ void (C::*m_method)();
+};
+
+typedef void(*TestFunction)();
+
+struct NameAndDesc {
+ NameAndDesc( const char* _name = "", const char* _description= "" )
+ : name( _name ), description( _description )
+ {}
+
+ const char* name;
+ const char* description;
+};
+
+void registerTestCase
+ ( ITestCase* testCase,
+ char const* className,
+ NameAndDesc const& nameAndDesc,
+ SourceLineInfo const& lineInfo );
+
+struct AutoReg {
+
+ AutoReg
+ ( TestFunction function,
+ SourceLineInfo const& lineInfo,
+ NameAndDesc const& nameAndDesc );
+
+ template<typename C>
+ AutoReg
+ ( void (C::*method)(),
+ char const* className,
+ NameAndDesc const& nameAndDesc,
+ SourceLineInfo const& lineInfo ) {
+
+ registerTestCase
+ ( new MethodTestCase<C>( method ),
+ className,
+ nameAndDesc,
+ lineInfo );
+ }
+
+ ~AutoReg();
+
+private:
+ AutoReg( AutoReg const& );
+ void operator= ( AutoReg const& );
+};
+
+void registerTestCaseFunction
+ ( TestFunction function,
+ SourceLineInfo const& lineInfo,
+ NameAndDesc const& nameAndDesc );
+
+} // end namespace Catch
+
+#ifdef CATCH_CONFIG_VARIADIC_MACROS
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
+ static void TestName(); \
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); } \
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
+ static void TestName()
+ #define INTERNAL_CATCH_TESTCASE( ... ) \
+ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
+
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } \
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
+
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ namespace{ \
+ struct TestName : ClassName{ \
+ void test(); \
+ }; \
+ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \
+ } \
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
+ void TestName::test()
+ #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
+ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
+
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); \
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
+
+#else
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \
+ static void TestName(); \
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
+ static void TestName()
+ #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \
+ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc )
+
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } \
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
+
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ namespace{ \
+ struct TestCaseName : ClassName{ \
+ void test(); \
+ }; \
+ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \
+ } \
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
+ void TestCaseName::test()
+ #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\
+ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc )
+
+ ///////////////////////////////////////////////////////////////////////////////
+ #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \
+ CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
+ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); \
+ CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
+
+#endif
+
+// #included from: internal/catch_capture.hpp
+#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED
+
+// #included from: catch_result_builder.h
+#define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED
+
+// #included from: catch_result_type.h
+#define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED
+
+namespace Catch {
+
+ // ResultWas::OfType enum
+ struct ResultWas { enum OfType {
+ Unknown = -1,
+ Ok = 0,
+ Info = 1,
+ Warning = 2,
+
+ FailureBit = 0x10,
+
+ ExpressionFailed = FailureBit | 1,
+ ExplicitFailure = FailureBit | 2,
+
+ Exception = 0x100 | FailureBit,
+
+ ThrewException = Exception | 1,
+ DidntThrowException = Exception | 2,
+
+ FatalErrorCondition = 0x200 | FailureBit
+
+ }; };
+
+ inline bool isOk( ResultWas::OfType resultType ) {
+ return ( resultType & ResultWas::FailureBit ) == 0;
+ }
+ inline bool isJustInfo( int flags ) {
+ return flags == ResultWas::Info;
+ }
+
+ // ResultDisposition::Flags enum
+ struct ResultDisposition { enum Flags {
+ Normal = 0x01,
+
+ ContinueOnFailure = 0x02, // Failures fail test, but execution continues
+ FalseTest = 0x04, // Prefix expression with !
+ SuppressFail = 0x08 // Failures are reported but do not fail the test
+ }; };
+
+ inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
+ return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
+ }
+
+ inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
+ inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
+ inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
+
+} // end namespace Catch
+
+// #included from: catch_assertionresult.h
+#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED
+
+#include <string>
+
+namespace Catch {
+
+ struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
+
+ struct DecomposedExpression
+ {
+ virtual ~DecomposedExpression() {}
+ virtual bool isBinaryExpression() const {
+ return false;
+ }
+ virtual void reconstructExpression( std::string& dest ) const = 0;
+
+ // Only simple binary comparisons can be decomposed.
+ // If more complex check is required then wrap sub-expressions in parentheses.
+ template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( T const& );
+ template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( T const& );
+ template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( T const& );
+ template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( T const& );
+ template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T const& );
+ template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T const& );
+ template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T const& );
+
+ private:
+ DecomposedExpression& operator = (DecomposedExpression const&);
+ };
+
+ struct AssertionInfo
+ {
+ AssertionInfo() {}
+ AssertionInfo( std::string const& _macroName,
+ SourceLineInfo const& _lineInfo,
+ std::string const& _capturedExpression,
+ ResultDisposition::Flags _resultDisposition );
+
+ std::string macroName;
+ SourceLineInfo lineInfo;
+ std::string capturedExpression;
+ ResultDisposition::Flags resultDisposition;
+ };
+
+ struct AssertionResultData
+ {
+ AssertionResultData() : decomposedExpression( CATCH_NULL )
+ , resultType( ResultWas::Unknown )
+ , negated( false )
+ , parenthesized( false ) {}
+
+ void negate( bool parenthesize ) {
+ negated = !negated;
+ parenthesized = parenthesize;
+ if( resultType == ResultWas::Ok )
+ resultType = ResultWas::ExpressionFailed;
+ else if( resultType == ResultWas::ExpressionFailed )
+ resultType = ResultWas::Ok;
+ }
+
+ std::string const& reconstructExpression() const {
+ if( decomposedExpression != CATCH_NULL ) {
+ decomposedExpression->reconstructExpression( reconstructedExpression );
+ if( parenthesized ) {
+ reconstructedExpression.insert( 0, 1, '(' );
+ reconstructedExpression.append( 1, ')' );
+ }
+ if( negated ) {
+ reconstructedExpression.insert( 0, 1, '!' );
+ }
+ decomposedExpression = CATCH_NULL;
+ }
+ return reconstructedExpression;
+ }
+
+ mutable DecomposedExpression const* decomposedExpression;
+ mutable std::string reconstructedExpression;
+ std::string message;
+ ResultWas::OfType resultType;
+ bool negated;
+ bool parenthesized;
+ };
+
+ class AssertionResult {
+ public:
+ AssertionResult();
+ AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
+ ~AssertionResult();
+# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
+ AssertionResult( AssertionResult const& ) = default;
+ AssertionResult( AssertionResult && ) = default;
+ AssertionResult& operator = ( AssertionResult const& ) = default;
+ AssertionResult& operator = ( AssertionResult && ) = default;
+# endif
+
+ bool isOk() const;
+ bool succeeded() const;
+ ResultWas::OfType getResultType() const;
+ bool hasExpression() const;
+ bool hasMessage() const;
+ std::string getExpression() const;
+ std::string getExpressionInMacro() const;
+ bool hasExpandedExpression() const;
+ std::string getExpandedExpression() const;
+ std::string getMessage() const;
+ SourceLineInfo getSourceInfo() const;
+ std::string getTestMacroName() const;
+ void discardDecomposedExpression() const;
+ void expandDecomposedExpression() const;
+
+ protected:
+ AssertionInfo m_info;
+ AssertionResultData m_resultData;
+ };
+
+} // end namespace Catch
+
+// #included from: catch_matchers.hpp
+#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED
+
+namespace Catch {
+namespace Matchers {
+ namespace Impl {
+
+ template<typename ArgT> struct MatchAllOf;
+ template<typename ArgT> struct MatchAnyOf;
+ template<typename ArgT> struct MatchNotOf;
+
+ class MatcherUntypedBase {
+ public:
+ std::string toString() const {
+ if( m_cachedToString.empty() )
+ m_cachedToString = describe();
+ return m_cachedToString;
+ }
+
+ protected:
+ virtual ~MatcherUntypedBase();
+ virtual std::string describe() const = 0;
+ mutable std::string m_cachedToString;
+ private:
+ MatcherUntypedBase& operator = ( MatcherUntypedBase const& );
+ };
+
+ template<typename ObjectT>
+ struct MatcherMethod {
+ virtual bool match( ObjectT const& arg ) const = 0;
+ };
+ template<typename PtrT>
+ struct MatcherMethod<PtrT*> {
+ virtual bool match( PtrT* arg ) const = 0;
+ };
+
+ template<typename ObjectT, typename ComparatorT = ObjectT>
+ struct MatcherBase : MatcherUntypedBase, MatcherMethod<ObjectT> {
+
+ MatchAllOf<ComparatorT> operator && ( MatcherBase const& other ) const;
+ MatchAnyOf<ComparatorT> operator || ( MatcherBase const& other ) const;
+ MatchNotOf<ComparatorT> operator ! () const;
+ };
+
+ template<typename ArgT>
+ struct MatchAllOf : MatcherBase<ArgT> {
+ virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
+ for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
+ if (!m_matchers[i]->match(arg))
+ return false;
+ }
+ return true;
+ }
+ virtual std::string describe() const CATCH_OVERRIDE {
+ std::string description;
+ description.reserve( 4 + m_matchers.size()*32 );
+ description += "( ";
+ for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
+ if( i != 0 )
+ description += " and ";
+ description += m_matchers[i]->toString();
+ }
+ description += " )";
+ return description;
+ }
+
+ MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
+ m_matchers.push_back( &other );
+ return *this;
+ }
+
+ std::vector<MatcherBase<ArgT> const*> m_matchers;
+ };
+ template<typename ArgT>
+ struct MatchAnyOf : MatcherBase<ArgT> {
+
+ virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
+ for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
+ if (m_matchers[i]->match(arg))
+ return true;
+ }
+ return false;
+ }
+ virtual std::string describe() const CATCH_OVERRIDE {
+ std::string description;
+ description.reserve( 4 + m_matchers.size()*32 );
+ description += "( ";
+ for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
+ if( i != 0 )
+ description += " or ";
+ description += m_matchers[i]->toString();
+ }
+ description += " )";
+ return description;
+ }
+
+ MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
+ m_matchers.push_back( &other );
+ return *this;
+ }
+
+ std::vector<MatcherBase<ArgT> const*> m_matchers;
+ };
+
+ template<typename ArgT>
+ struct MatchNotOf : MatcherBase<ArgT> {
+
+ MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
+
+ virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
+ return !m_underlyingMatcher.match( arg );
+ }
+
+ virtual std::string describe() const CATCH_OVERRIDE {
+ return "not " + m_underlyingMatcher.toString();
+ }
+ MatcherBase<ArgT> const& m_underlyingMatcher;
+ };
+
+ template<typename ObjectT, typename ComparatorT>
+ MatchAllOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator && ( MatcherBase const& other ) const {
+ return MatchAllOf<ComparatorT>() && *this && other;
+ }
+ template<typename ObjectT, typename ComparatorT>
+ MatchAnyOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator || ( MatcherBase const& other ) const {
+ return MatchAnyOf<ComparatorT>() || *this || other;
+ }
+ template<typename ObjectT, typename ComparatorT>
+ MatchNotOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator ! () const {
+ return MatchNotOf<ComparatorT>( *this );
+ }
+
+ } // namespace Impl
+
+ // The following functions create the actual matcher objects.
+ // This allows the types to be inferred
+ // - deprecated: prefer ||, && and !
+ template<typename T>
+ inline Impl::MatchNotOf<T> Not( Impl::MatcherBase<T> const& underlyingMatcher ) {
+ return Impl::MatchNotOf<T>( underlyingMatcher );
+ }
+ template<typename T>
+ inline Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2 ) {
+ return Impl::MatchAllOf<T>() && m1 && m2;
+ }
+ template<typename T>
+ inline Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2, Impl::MatcherBase<T> const& m3 ) {
+ return Impl::MatchAllOf<T>() && m1 && m2 && m3;
+ }
+ template<typename T>
+ inline Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2 ) {
+ return Impl::MatchAnyOf<T>() || m1 || m2;
+ }
+ template<typename T>
+ inline Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2, Impl::MatcherBase<T> const& m3 ) {
+ return Impl::MatchAnyOf<T>() || m1 || m2 || m3;
+ }
+
+} // namespace Matchers
+
+using namespace Matchers;
+using Matchers::Impl::MatcherBase;
+
+} // namespace Catch
+
+namespace Catch {
+
+ struct TestFailureException{};
+
+ template<typename T> class ExpressionLhs;
+
+ struct CopyableStream {
+ CopyableStream() {}
+ CopyableStream( CopyableStream const& other ) {
+ oss << other.oss.str();
+ }
+ CopyableStream& operator=( CopyableStream const& other ) {
+ oss.str(std::string());
+ oss << other.oss.str();
+ return *this;
+ }
+ std::ostringstream oss;
+ };
+
+ class ResultBuilder : public DecomposedExpression {
+ public:
+ ResultBuilder( char const* macroName,
+ SourceLineInfo const& lineInfo,
+ char const* capturedExpression,
+ ResultDisposition::Flags resultDisposition,
+ char const* secondArg = "" );
+ ~ResultBuilder();
+
+ template<typename T>
+ ExpressionLhs<T const&> operator <= ( T const& operand );
+ ExpressionLhs<bool> operator <= ( bool value );
+
+ template<typename T>
+ ResultBuilder& operator << ( T const& value ) {
+ m_stream.oss << value;
+ return *this;
+ }
+
+ ResultBuilder& setResultType( ResultWas::OfType result );
+ ResultBuilder& setResultType( bool result );
+
+ void endExpression( DecomposedExpression const& expr );
+
+ virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE;
+
+ AssertionResult build() const;
+ AssertionResult build( DecomposedExpression const& expr ) const;
+
+ void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal );
+ void captureResult( ResultWas::OfType resultType );
+ void captureExpression();
+ void captureExpectedException( std::string const& expectedMessage );
+ void captureExpectedException( Matchers::Impl::MatcherBase<std::string> const& matcher );
+ void handleResult( AssertionResult const& result );
+ void react();
+ bool shouldDebugBreak() const;
+ bool allowThrows() const;
+
+ template<typename ArgT, typename MatcherT>
+ void captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString );
+
+ void setExceptionGuard();
+ void unsetExceptionGuard();
+
+ private:
+ AssertionInfo m_assertionInfo;
+ AssertionResultData m_data;
+ CopyableStream m_stream;
+
+ bool m_shouldDebugBreak;
+ bool m_shouldThrow;
+ bool m_guardException;
+ };
+
+} // namespace Catch
+
+// Include after due to circular dependency:
+// #included from: catch_expression_lhs.hpp
+#define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED
+
+// #included from: catch_evaluate.hpp
+#define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4389) // '==' : signed/unsigned mismatch
+#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
+#endif
+
+#include <cstddef>
+
+namespace Catch {
+namespace Internal {
+
+ enum Operator {
+ IsEqualTo,
+ IsNotEqualTo,
+ IsLessThan,
+ IsGreaterThan,
+ IsLessThanOrEqualTo,
+ IsGreaterThanOrEqualTo
+ };
+
+ template<Operator Op> struct OperatorTraits { static const char* getName(){ return "*error*"; } };
+ template<> struct OperatorTraits<IsEqualTo> { static const char* getName(){ return "=="; } };
+ template<> struct OperatorTraits<IsNotEqualTo> { static const char* getName(){ return "!="; } };
+ template<> struct OperatorTraits<IsLessThan> { static const char* getName(){ return "<"; } };
+ template<> struct OperatorTraits<IsGreaterThan> { static const char* getName(){ return ">"; } };
+ template<> struct OperatorTraits<IsLessThanOrEqualTo> { static const char* getName(){ return "<="; } };
+ template<> struct OperatorTraits<IsGreaterThanOrEqualTo>{ static const char* getName(){ return ">="; } };
+
+ template<typename T>
+ inline T& opCast(T const& t) { return const_cast<T&>(t); }
+
+// nullptr_t support based on pull request #154 from Konstantin Baumann
+#ifdef CATCH_CONFIG_CPP11_NULLPTR
+ inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; }
+#endif // CATCH_CONFIG_CPP11_NULLPTR
+
+ // So the compare overloads can be operator agnostic we convey the operator as a template
+ // enum, which is used to specialise an Evaluator for doing the comparison.
+ template<typename T1, typename T2, Operator Op>
+ class Evaluator{};
+
+ template<typename T1, typename T2>
+ struct Evaluator<T1, T2, IsEqualTo> {
+ static bool evaluate( T1 const& lhs, T2 const& rhs) {
+ return bool( opCast( lhs ) == opCast( rhs ) );
+ }
+ };
+ template<typename T1, typename T2>
+ struct Evaluator<T1, T2, IsNotEqualTo> {
+ static bool evaluate( T1 const& lhs, T2 const& rhs ) {
+ return bool( opCast( lhs ) != opCast( rhs ) );
+ }
+ };
+ template<typename T1, typename T2>
+ struct Evaluator<T1, T2, IsLessThan> {
+ static bool evaluate( T1 const& lhs, T2 const& rhs ) {
+ return bool( opCast( lhs ) < opCast( rhs ) );
+ }
+ };
+ template<typename T1, typename T2>
+ struct Evaluator<T1, T2, IsGreaterThan> {
+ static bool evaluate( T1 const& lhs, T2 const& rhs ) {
+ return bool( opCast( lhs ) > opCast( rhs ) );
+ }
+ };
+ template<typename T1, typename T2>
+ struct Evaluator<T1, T2, IsGreaterThanOrEqualTo> {
+ static bool evaluate( T1 const& lhs, T2 const& rhs ) {
+ return bool( opCast( lhs ) >= opCast( rhs ) );
+ }
+ };
+ template<typename T1, typename T2>
+ struct Evaluator<T1, T2, IsLessThanOrEqualTo> {
+ static bool evaluate( T1 const& lhs, T2 const& rhs ) {
+ return bool( opCast( lhs ) <= opCast( rhs ) );
+ }
+ };
+
+ template<Operator Op, typename T1, typename T2>
+ bool applyEvaluator( T1 const& lhs, T2 const& rhs ) {
+ return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
+ }
+
+ // This level of indirection allows us to specialise for integer types
+ // to avoid signed/ unsigned warnings
+
+ // "base" overload
+ template<Operator Op, typename T1, typename T2>
+ bool compare( T1 const& lhs, T2 const& rhs ) {
+ return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
+ }
+
+ // unsigned X to int
+ template<Operator Op> bool compare( unsigned int lhs, int rhs ) {
+ return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
+ }
+ template<Operator Op> bool compare( unsigned long lhs, int rhs ) {
+ return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
+ }
+ template<Operator Op> bool compare( unsigned char lhs, int rhs ) {
+ return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
+ }
+
+ // unsigned X to long
+ template<Operator Op> bool compare( unsigned int lhs, long rhs ) {
+ return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
+ }
+ template<Operator Op> bool compare( unsigned long lhs, long rhs ) {
+ return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
+ }
+ template<Operator Op> bool compare( unsigned char lhs, long rhs ) {
+ return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
+ }
+
+ // int to unsigned X
+ template<Operator Op> bool compare( int lhs, unsigned int rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( int lhs, unsigned long rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( int lhs, unsigned char rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
+ }
+
+ // long to unsigned X
+ template<Operator Op> bool compare( long lhs, unsigned int rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( long lhs, unsigned long rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( long lhs, unsigned char rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
+ }
+
+ // pointer to long (when comparing against NULL)
+ template<Operator Op, typename T> bool compare( long lhs, T* rhs ) {
+ return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
+ }
+ template<Operator Op, typename T> bool compare( T* lhs, long rhs ) {
+ return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
+ }
+
+ // pointer to int (when comparing against NULL)
+ template<Operator Op, typename T> bool compare( int lhs, T* rhs ) {
+ return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
+ }
+ template<Operator Op, typename T> bool compare( T* lhs, int rhs ) {
+ return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
+ }
+
+#ifdef CATCH_CONFIG_CPP11_LONG_LONG
+ // long long to unsigned X
+ template<Operator Op> bool compare( long long lhs, unsigned int rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( long long lhs, unsigned long rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( long long lhs, unsigned long long rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( long long lhs, unsigned char rhs ) {
+ return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
+ }
+
+ // unsigned long long to X
+ template<Operator Op> bool compare( unsigned long long lhs, int rhs ) {
+ return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( unsigned long long lhs, long rhs ) {
+ return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( unsigned long long lhs, long long rhs ) {
+ return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
+ }
+ template<Operator Op> bool compare( unsigned long long lhs, char rhs ) {
+ return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
+ }
+
+ // pointer to long long (when comparing against NULL)
+ template<Operator Op, typename T> bool compare( long long lhs, T* rhs ) {
+ return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
+ }
+ template<Operator Op, typename T> bool compare( T* lhs, long long rhs ) {
+ return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
+ }
+#endif // CATCH_CONFIG_CPP11_LONG_LONG
+
+#ifdef CATCH_CONFIG_CPP11_NULLPTR
+ // pointer to nullptr_t (when comparing against nullptr)
+ template<Operator Op, typename T> bool compare( std::nullptr_t, T* rhs ) {
+ return Evaluator<T*, T*, Op>::evaluate( nullptr, rhs );
+ }
+ template<Operator Op, typename T> bool compare( T* lhs, std::nullptr_t ) {
+ return Evaluator<T*, T*, Op>::evaluate( lhs, nullptr );
+ }
+#endif // CATCH_CONFIG_CPP11_NULLPTR
+
+} // end of namespace Internal
+} // end of namespace Catch
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+// #included from: catch_tostring.h
+#define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED
+
+#include <sstream>
+#include <iomanip>
+#include <limits>
+#include <vector>
+#include <cstddef>
+
+#ifdef __OBJC__
+// #included from: catch_objc_arc.hpp
+#define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED
+
+#import <Foundation/Foundation.h>
+
+#ifdef __has_feature
+#define CATCH_ARC_ENABLED __has_feature(objc_arc)
+#else
+#define CATCH_ARC_ENABLED 0
+#endif
+
+void arcSafeRelease( NSObject* obj );
+id performOptionalSelector( id obj, SEL sel );
+
+#if !CATCH_ARC_ENABLED
+inline void arcSafeRelease( NSObject* obj ) {
+ [obj release];
+}
+inline id performOptionalSelector( id obj, SEL sel ) {
+ if( [obj respondsToSelector: sel] )
+ return [obj performSelector: sel];
+ return nil;
+}
+#define CATCH_UNSAFE_UNRETAINED
+#define CATCH_ARC_STRONG
+#else
+inline void arcSafeRelease( NSObject* ){}
+inline id performOptionalSelector( id obj, SEL sel ) {
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
+#endif
+ if( [obj respondsToSelector: sel] )
+ return [obj performSelector: sel];
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+ return nil;
+}
+#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
+#define CATCH_ARC_STRONG __strong
+#endif
+
+#endif
+
+#ifdef CATCH_CONFIG_CPP11_TUPLE
+#include <tuple>
+#endif
+
+#ifdef CATCH_CONFIG_CPP11_IS_ENUM
+#include <type_traits>
+#endif
+
+namespace Catch {
+
+// Why we're here.
+template<typename T>
+std::string toString( T const& value );
+
+// Built in overloads
+
+std::string toString( std::string const& value );
+std::string toString( std::wstring const& value );
+std::string toString( const char* const value );
+std::string toString( char* const value );
+std::string toString( const wchar_t* const value );
+std::string toString( wchar_t* const value );
+std::string toString( int value );
+std::string toString( unsigned long value );
+std::string toString( unsigned int value );
+std::string toString( const double value );
+std::string toString( const float value );
+std::string toString( bool value );
+std::string toString( char value );
+std::string toString( signed char value );
+std::string toString( unsigned char value );
+
+#ifdef CATCH_CONFIG_CPP11_LONG_LONG
+std::string toString( long long value );
+std::string toString( unsigned long long value );
+#endif
+
+#ifdef CATCH_CONFIG_CPP11_NULLPTR
+std::string toString( std::nullptr_t );
+#endif
+
+#ifdef __OBJC__
+ std::string toString( NSString const * const& nsstring );
+ std::string toString( NSString * CATCH_ARC_STRONG const& nsstring );
+ std::string toString( NSObject* const& nsObject );
+#endif
+
+namespace Detail {
+
+ extern const std::string unprintableString;
+
+ #if !defined(CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK)
+ struct BorgType {
+ template<typename T> BorgType( T const& );
+ };
+
+ struct TrueType { char sizer[1]; };
+ struct FalseType { char sizer[2]; };
+
+ TrueType& testStreamable( std::ostream& );
+ FalseType testStreamable( FalseType );
+
+ FalseType operator<<( std::ostream const&, BorgType const& );
+
+ template<typename T>
+ struct IsStreamInsertable {
+ static std::ostream &s;
+ static T const&t;
+ enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) };
+ };
+#else
+ template<typename T>
+ class IsStreamInsertable {
+ template<typename SS, typename TT>
+ static auto test(int)
+ -> decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() );
+
+ template<typename, typename>
+ static auto test(...) -> std::false_type;
+
+ public:
+ static const bool value = decltype(test<std::ostream,const T&>(0))::value;
+ };
+#endif
+
+#if defined(CATCH_CONFIG_CPP11_IS_ENUM)
+ template<typename T,
+ bool IsEnum = std::is_enum<T>::value
+ >
+ struct EnumStringMaker
+ {
+ static std::string convert( T const& ) { return unprintableString; }
+ };
+
+ template<typename T>
+ struct EnumStringMaker<T,true>
+ {
+ static std::string convert( T const& v )
+ {
+ return ::Catch::toString(
+ static_cast<typename std::underlying_type<T>::type>(v)
+ );
+ }
+ };
+#endif
+ template<bool C>
+ struct StringMakerBase {
+#if defined(CATCH_CONFIG_CPP11_IS_ENUM)
+ template<typename T>
+ static std::string convert( T const& v )
+ {
+ return EnumStringMaker<T>::convert( v );
+ }
+#else
+ template<typename T>
+ static std::string convert( T const& ) { return unprintableString; }
+#endif
+ };
+
+ template<>
+ struct StringMakerBase<true> {
+ template<typename T>
+ static std::string convert( T const& _value ) {
+ std::ostringstream oss;
+ oss << _value;
+ return oss.str();
+ }
+ };
+
+ std::string rawMemoryToString( const void *object, std::size_t size );
+
+ template<typename T>
+ inline std::string rawMemoryToString( const T& object ) {
+ return rawMemoryToString( &object, sizeof(object) );
+ }
+
+} // end namespace Detail
+
+template<typename T>
+struct StringMaker :
+ Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {};
+
+template<typename T>
+struct StringMaker<T*> {
+ template<typename U>
+ static std::string convert( U* p ) {
+ if( !p )
+ return "NULL";
+ else
+ return Detail::rawMemoryToString( p );
+ }
+};
+
+template<typename R, typename C>
+struct StringMaker<R C::*> {
+ static std::string convert( R C::* p ) {
+ if( !p )
+ return "NULL";
+ else
+ return Detail::rawMemoryToString( p );
+ }
+};
+
+namespace Detail {
+ template<typename InputIterator>
+ std::string rangeToString( InputIterator first, InputIterator last );
+}
+
+//template<typename T, typename Allocator>
+//struct StringMaker<std::vector<T, Allocator> > {
+// static std::string convert( std::vector<T,Allocator> const& v ) {
+// return Detail::rangeToString( v.begin(), v.end() );
+// }
+//};
+
+template<typename T, typename Allocator>
+std::string toString( std::vector<T,Allocator> const& v ) {
+ return Detail::rangeToString( v.begin(), v.end() );
+}
+
+#ifdef CATCH_CONFIG_CPP11_TUPLE
+
+// toString for tuples
+namespace TupleDetail {
+ template<
+ typename Tuple,
+ std::size_t N = 0,
+ bool = (N < std::tuple_size<Tuple>::value)
+ >
+ struct ElementPrinter {
+ static void print( const Tuple& tuple, std::ostream& os )
+ {
+ os << ( N ? ", " : " " )
+ << Catch::toString(std::get<N>(tuple));
+ ElementPrinter<Tuple,N+1>::print(tuple,os);
+ }
+ };
+
+ template<
+ typename Tuple,
+ std::size_t N
+ >
+ struct ElementPrinter<Tuple,N,false> {
+ static void print( const Tuple&, std::ostream& ) {}
+ };
+
+}
+
+template<typename ...Types>
+struct StringMaker<std::tuple<Types...>> {
+
+ static std::string convert( const std::tuple<Types...>& tuple )
+ {
+ std::ostringstream os;
+ os << '{';
+ TupleDetail::ElementPrinter<std::tuple<Types...>>::print( tuple, os );
+ os << " }";
+ return os.str();
+ }
+};
+#endif // CATCH_CONFIG_CPP11_TUPLE
+
+namespace Detail {
+ template<typename T>
+ std::string makeString( T const& value ) {
+ return StringMaker<T>::convert( value );
+ }
+} // end namespace Detail
+
+/// \brief converts any type to a string
+///
+/// The default template forwards on to ostringstream - except when an
+/// ostringstream overload does not exist - in which case it attempts to detect
+/// that and writes {?}.
+/// Overload (not specialise) this template for custom typs that you don't want
+/// to provide an ostream overload for.
+template<typename T>
+std::string toString( T const& value ) {
+ return StringMaker<T>::convert( value );
+}
+
+ namespace Detail {
+ template<typename InputIterator>
+ std::string rangeToString( InputIterator first, InputIterator last ) {
+ std::ostringstream oss;
+ oss << "{ ";
+ if( first != last ) {
+ oss << Catch::toString( *first );
+ for( ++first ; first != last ; ++first )
+ oss << ", " << Catch::toString( *first );
+ }
+ oss << " }";
+ return oss.str();
+ }
+}
+
+} // end namespace Catch
+
+namespace Catch {
+
+template<typename LhsT, Internal::Operator Op, typename RhsT>
+class BinaryExpression;
+
+template<typename ArgT, typename MatcherT>
+class MatchExpression;
+
+// Wraps the LHS of an expression and overloads comparison operators
+// for also capturing those and RHS (if any)
+template<typename T>
+class ExpressionLhs : public DecomposedExpression {
+public:
+ ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {}
+
+ ExpressionLhs& operator = ( const ExpressionLhs& );
+
+ template<typename RhsT>
+ BinaryExpression<T, Internal::IsEqualTo, RhsT const&>
+ operator == ( RhsT const& rhs ) {
+ return captureExpression<Internal::IsEqualTo>( rhs );
+ }
+
+ template<typename RhsT>
+ BinaryExpression<T, Internal::IsNotEqualTo, RhsT const&>
+ operator != ( RhsT const& rhs ) {
+ return captureExpression<Internal::IsNotEqualTo>( rhs );
+ }
+
+ template<typename RhsT>
+ BinaryExpression<T, Internal::IsLessThan, RhsT const&>
+ operator < ( RhsT const& rhs ) {
+ return captureExpression<Internal::IsLessThan>( rhs );
+ }
+
+ template<typename RhsT>
+ BinaryExpression<T, Internal::IsGreaterThan, RhsT const&>
+ operator > ( RhsT const& rhs ) {
+ return captureExpression<Internal::IsGreaterThan>( rhs );
+ }
+
+ template<typename RhsT>
+ BinaryExpression<T, Internal::IsLessThanOrEqualTo, RhsT const&>
+ operator <= ( RhsT const& rhs ) {
+ return captureExpression<Internal::IsLessThanOrEqualTo>( rhs );
+ }
+
+ template<typename RhsT>
+ BinaryExpression<T, Internal::IsGreaterThanOrEqualTo, RhsT const&>
+ operator >= ( RhsT const& rhs ) {
+ return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs );
+ }
+
+ BinaryExpression<T, Internal::IsEqualTo, bool> operator == ( bool rhs ) {
+ return captureExpression<Internal::IsEqualTo>( rhs );
+ }
+
+ BinaryExpression<T, Internal::IsNotEqualTo, bool> operator != ( bool rhs ) {
+ return captureExpression<Internal::IsNotEqualTo>( rhs );
+ }
+
+ void endExpression() {
+ m_truthy = m_lhs ? true : false;
+ m_rb
+ .setResultType( m_truthy )
+ .endExpression( *this );
+ }
+
+ virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
+ dest = Catch::toString( m_truthy );
+ }
+
+private:
+ template<Internal::Operator Op, typename RhsT>
+ BinaryExpression<T, Op, RhsT&> captureExpression( RhsT& rhs ) const {
+ return BinaryExpression<T, Op, RhsT&>( m_rb, m_lhs, rhs );
+ }
+
+ template<Internal::Operator Op>
+ BinaryExpression<T, Op, bool> captureExpression( bool rhs ) const {
+ return BinaryExpression<T, Op, bool>( m_rb, m_lhs, rhs );
+ }
+
+private:
+ ResultBuilder& m_rb;
+ T m_lhs;
+ bool m_truthy;
+};
+
+template<typename LhsT, Internal::Operator Op, typename RhsT>
+class BinaryExpression : public DecomposedExpression {
+public:
+ BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs )
+ : m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {}
+
+ BinaryExpression& operator = ( BinaryExpression& );
+
+ void endExpression() const {
+ m_rb
+ .setResultType( Internal::compare<Op>( m_lhs, m_rhs ) )
+ .endExpression( *this );
+ }
+
+ virtual bool isBinaryExpression() const CATCH_OVERRIDE {
+ return true;
+ }
+
+ virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
+ std::string lhs = Catch::toString( m_lhs );
+ std::string rhs = Catch::toString( m_rhs );
+ char delim = lhs.size() + rhs.size() < 40 &&
+ lhs.find('\n') == std::string::npos &&
+ rhs.find('\n') == std::string::npos ? ' ' : '\n';
+ dest.reserve( 7 + lhs.size() + rhs.size() );
+ // 2 for spaces around operator
+ // 2 for operator
+ // 2 for parentheses (conditionally added later)
+ // 1 for negation (conditionally added later)
+ dest = lhs;
+ dest += delim;
+ dest += Internal::OperatorTraits<Op>::getName();
+ dest += delim;
+ dest += rhs;
+ }
+
+private:
+ ResultBuilder& m_rb;
+ LhsT m_lhs;
+ RhsT m_rhs;
+};
+
+template<typename ArgT, typename MatcherT>
+class MatchExpression : public DecomposedExpression {
+public:
+ MatchExpression( ArgT arg, MatcherT matcher, char const* matcherString )
+ : m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {}
+
+ virtual bool isBinaryExpression() const CATCH_OVERRIDE {
+ return true;
+ }
+
+ virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
+ std::string matcherAsString = m_matcher.toString();
+ dest = Catch::toString( m_arg );
+ dest += ' ';
+ if( matcherAsString == Detail::unprintableString )
+ dest += m_matcherString;
+ else
+ dest += matcherAsString;
+ }
+
+private:
+ ArgT m_arg;
+ MatcherT m_matcher;
+ char const* m_matcherString;
+};
+
+} // end namespace Catch
+
+
+namespace Catch {
+
+ template<typename T>
+ inline ExpressionLhs<T const&> ResultBuilder::operator <= ( T const& operand ) {
+ return ExpressionLhs<T const&>( *this, operand );
+ }
+
+ inline ExpressionLhs<bool> ResultBuilder::operator <= ( bool value ) {
+ return ExpressionLhs<bool>( *this, value );
+ }
+
+ template<typename ArgT, typename MatcherT>
+ inline void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher,
+ char const* matcherString ) {
+ MatchExpression<ArgT const&, MatcherT const&> expr( arg, matcher, matcherString );
+ setResultType( matcher.match( arg ) );
+ endExpression( expr );
+ }
+
+} // namespace Catch
+
+// #included from: catch_message.h
+#define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED
+
+#include <string>
+
+namespace Catch {
+
+ struct MessageInfo {
+ MessageInfo( std::string const& _macroName,
+ SourceLineInfo const& _lineInfo,
+ ResultWas::OfType _type );
+
+ std::string macroName;
+ SourceLineInfo lineInfo;
+ ResultWas::OfType type;
+ std::string message;
+ unsigned int sequence;
+
+ bool operator == ( MessageInfo const& other ) const {
+ return sequence == other.sequence;
+ }
+ bool operator < ( MessageInfo const& other ) const {
+ return sequence < other.sequence;
+ }
+ private:
+ static unsigned int globalCount;
+ };
+
+ struct MessageBuilder {
+ MessageBuilder( std::string const& macroName,
+ SourceLineInfo const& lineInfo,
+ ResultWas::OfType type )
+ : m_info( macroName, lineInfo, type )
+ {}
+
+ template<typename T>
+ MessageBuilder& operator << ( T const& value ) {
+ m_stream << value;
+ return *this;
+ }
+
+ MessageInfo m_info;
+ std::ostringstream m_stream;
+ };
+
+ class ScopedMessage {
+ public:
+ ScopedMessage( MessageBuilder const& builder );
+ ScopedMessage( ScopedMessage const& other );
+ ~ScopedMessage();
+
+ MessageInfo m_info;
+ };
+
+} // end namespace Catch
+
+// #included from: catch_interfaces_capture.h
+#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
+
+#include <string>
+
+namespace Catch {
+
+ class TestCase;
+ class AssertionResult;
+ struct AssertionInfo;
+ struct SectionInfo;
+ struct SectionEndInfo;
+ struct MessageInfo;
+ class ScopedMessageBuilder;
+ struct Counts;
+
+ struct IResultCapture {
+
+ virtual ~IResultCapture();
+
+ virtual void assertionEnded( AssertionResult const& result ) = 0;
+ virtual bool sectionStarted( SectionInfo const& sectionInfo,
+ Counts& assertions ) = 0;
+ virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
+ virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
+ virtual void pushScopedMessage( MessageInfo const& message ) = 0;
+ virtual void popScopedMessage( MessageInfo const& message ) = 0;
+
+ virtual std::string getCurrentTestName() const = 0;
+ virtual const AssertionResult* getLastResult() const = 0;
+
+ virtual void exceptionEarlyReported() = 0;
+
+ virtual void handleFatalErrorCondition( std::string const& message ) = 0;
+ };
+
+ IResultCapture& getResultCapture();
+}
+
+// #included from: catch_debugger.h
+#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
+
+// #included from: catch_platform.h
+#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
+
+#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+# define CATCH_PLATFORM_MAC
+#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+# define CATCH_PLATFORM_IPHONE
+#elif defined(linux) || defined(__linux) || defined(__linux__)
+# define CATCH_PLATFORM_LINUX
+#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
+# define CATCH_PLATFORM_WINDOWS
+# if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
+# define CATCH_DEFINES_NOMINMAX
+# endif
+# if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
+# define CATCH_DEFINES_WIN32_LEAN_AND_MEAN
+# endif
+#endif
+
+#include <string>
+
+namespace Catch{
+
+ bool isDebuggerActive();
+ void writeToDebugConsole( std::string const& text );
+}
+
+#ifdef CATCH_PLATFORM_MAC
+
+ // The following code snippet based on:
+ // http://cocoawithlove.com/2008/03/break-into-debugger.html
+ #if defined(__ppc64__) || defined(__ppc__)
+ #define CATCH_TRAP() \
+ __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
+ : : : "memory","r0","r3","r4" )
+ #else
+ #define CATCH_TRAP() __asm__("int $3\n" : : )
+ #endif
+
+#elif defined(CATCH_PLATFORM_LINUX)
+ // If we can use inline assembler, do it because this allows us to break
+ // directly at the location of the failing check instead of breaking inside
+ // raise() called from it, i.e. one stack frame below.
+ #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
+ #define CATCH_TRAP() asm volatile ("int $3")
+ #else // Fall back to the generic way.
+ #include <signal.h>
+
+ #define CATCH_TRAP() raise(SIGTRAP)
+ #endif
+#elif defined(_MSC_VER)
+ #define CATCH_TRAP() __debugbreak()
+#elif defined(__MINGW32__)
+ extern "C" __declspec(dllimport) void __stdcall DebugBreak();
+ #define CATCH_TRAP() DebugBreak()
+#endif
+
+#ifdef CATCH_TRAP
+ #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
+#else
+ #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
+#endif
+
+// #included from: catch_interfaces_runner.h
+#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED
+
+namespace Catch {
+ class TestCase;
+
+ struct IRunner {
+ virtual ~IRunner();
+ virtual bool aborting() const = 0;
+ };
+}
+
+#if defined(CATCH_CONFIG_FAST_COMPILE)
+///////////////////////////////////////////////////////////////////////////////
+// We can speedup compilation significantly by breaking into debugger lower in
+// the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER
+// macro in each assertion
+#define INTERNAL_CATCH_REACT( resultBuilder ) \
+ resultBuilder.react();
+
+///////////////////////////////////////////////////////////////////////////////
+// Another way to speed-up compilation is to omit local try-catch for REQUIRE*
+// macros.
+// This can potentially cause false negative, if the test code catches
+// the exception before it propagates back up to the runner.
+#define INTERNAL_CATCH_TEST_NO_TRY( macroName, resultDisposition, expr ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
+ __catchResult.setExceptionGuard(); \
+ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
+ ( __catchResult <= expr ).endExpression(); \
+ CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
+ __catchResult.unsetExceptionGuard(); \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
+// The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
+
+#define INTERNAL_CHECK_THAT_NO_TRY( macroName, matcher, resultDisposition, arg ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
+ __catchResult.setExceptionGuard(); \
+ __catchResult.captureMatch( arg, matcher, #matcher ); \
+ __catchResult.unsetExceptionGuard(); \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::alwaysFalse() )
+
+#else
+///////////////////////////////////////////////////////////////////////////////
+// In the event of a failure works out if the debugger needs to be invoked
+// and/or an exception thrown and takes appropriate action.
+// This needs to be done as a macro so the debugger will stop in the user
+// source code rather than in Catch library code
+#define INTERNAL_CATCH_REACT( resultBuilder ) \
+ if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
+ resultBuilder.react();
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
+ try { \
+ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
+ ( __catchResult <= expr ).endExpression(); \
+ CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
+ } \
+ catch( ... ) { \
+ __catchResult.useActiveException( resultDisposition ); \
+ } \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
+ // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CATCH_IF( macroName, resultDisposition, expr ) \
+ INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \
+ if( Catch::getResultCapture().getLastResult()->succeeded() )
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, expr ) \
+ INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \
+ if( !Catch::getResultCapture().getLastResult()->succeeded() )
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, expr ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
+ try { \
+ static_cast<void>(expr); \
+ __catchResult.captureResult( Catch::ResultWas::Ok ); \
+ } \
+ catch( ... ) { \
+ __catchResult.useActiveException( resultDisposition ); \
+ } \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::alwaysFalse() )
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, matcher, expr ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \
+ if( __catchResult.allowThrows() ) \
+ try { \
+ static_cast<void>(expr); \
+ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
+ } \
+ catch( ... ) { \
+ __catchResult.captureExpectedException( matcher ); \
+ } \
+ else \
+ __catchResult.captureResult( Catch::ResultWas::Ok ); \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::alwaysFalse() )
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \
+ if( __catchResult.allowThrows() ) \
+ try { \
+ static_cast<void>(expr); \
+ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
+ } \
+ catch( exceptionType ) { \
+ __catchResult.captureResult( Catch::ResultWas::Ok ); \
+ } \
+ catch( ... ) { \
+ __catchResult.useActiveException( resultDisposition ); \
+ } \
+ else \
+ __catchResult.captureResult( Catch::ResultWas::Ok ); \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::alwaysFalse() )
+
+///////////////////////////////////////////////////////////////////////////////
+#ifdef CATCH_CONFIG_VARIADIC_MACROS
+ #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
+ __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \
+ __catchResult.captureResult( messageType ); \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::alwaysFalse() )
+#else
+ #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, log ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
+ __catchResult << log + ::Catch::StreamEndStop(); \
+ __catchResult.captureResult( messageType ); \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::alwaysFalse() )
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CATCH_INFO( macroName, log ) \
+ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
+
+///////////////////////////////////////////////////////////////////////////////
+#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
+ do { \
+ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
+ try { \
+ __catchResult.captureMatch( arg, matcher, #matcher ); \
+ } catch( ... ) { \
+ __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \
+ } \
+ INTERNAL_CATCH_REACT( __catchResult ) \
+ } while( Catch::alwaysFalse() )
+
+// #included from: internal/catch_section.h
+#define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED
+
+// #included from: catch_section_info.h
+#define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED
+
+// #included from: catch_totals.hpp
+#define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED
+
+#include <cstddef>
+
+namespace Catch {
+
+ struct Counts {
+ Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {}
+
+ Counts operator - ( Counts const& other ) const {
+ Counts diff;
+ diff.passed = passed - other.passed;
+ diff.failed = failed - other.failed;
+ diff.failedButOk = failedButOk - other.failedButOk;
+ return diff;
+ }
+ Counts& operator += ( Counts const& other ) {
+ passed += other.passed;
+ failed += other.failed;
+ failedButOk += other.failedButOk;
+ return *this;
+ }
+
+ std::size_t total() const {
+ return passed + failed + failedButOk;
+ }
+ bool allPassed() const {
+ return failed == 0 && failedButOk == 0;
+ }
+ bool allOk() const {
+ return failed == 0;
+ }
+
+ std::size_t passed;
+ std::size_t failed;
+ std::size_t failedButOk;
+ };
+
+ struct Totals {
+
+ Totals operator - ( Totals const& other ) const {
+ Totals diff;
+ diff.assertions = assertions - other.assertions;
+ diff.testCases = testCases - other.testCases;
+ return diff;
+ }
+
+ Totals delta( Totals const& prevTotals ) const {
+ Totals diff = *this - prevTotals;
+ if( diff.assertions.failed > 0 )
+ ++diff.testCases.failed;
+ else if( diff.assertions.failedButOk > 0 )
+ ++diff.testCases.failedButOk;
+ else
+ ++diff.testCases.passed;
+ return diff;
+ }
+
+ Totals& operator += ( Totals const& other ) {
+ assertions += other.assertions;
+ testCases += other.testCases;
+ return *this;
+ }
+
+ Counts assertions;
+ Counts testCases;
+ };
+}
+
+#include <string>
+
+namespace Catch {
+
+ struct SectionInfo {
+ SectionInfo
+ ( SourceLineInfo const& _lineInfo,
+ std::string const& _name,
+ std::string const& _description = std::string() );
+
+ std::string name;
+ std::string description;
+ SourceLineInfo lineInfo;
+ };
+
+ struct SectionEndInfo {
+ SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
+ : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
+ {}
+
+ SectionInfo sectionInfo;
+ Counts prevAssertions;
+ double durationInSeconds;
+ };
+
+} // end namespace Catch
+
+// #included from: catch_timer.h
+#define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED
+
+#ifdef _MSC_VER
+
+namespace Catch {
+ typedef unsigned long long UInt64;
+}
+#else
+#include <stdint.h>
+namespace Catch {
+ typedef uint64_t UInt64;
+}
+#endif
+
+namespace Catch {
+ class Timer {
+ public:
+ Timer() : m_ticks( 0 ) {}
+ void start();
+ unsigned int getElapsedMicroseconds() const;
+ unsigned int getElapsedMilliseconds() const;
+ double getElapsedSeconds() const;
+
+ private:
+ UInt64 m_ticks;
+ };
+
+} // namespace Catch
+
+#include <string>
+
+namespace Catch {
+
+ class Section : NonCopyable {
+ public:
+ Section( SectionInfo const& info );
+ ~Section();
+
+ // This indicates whether the section should be executed or not
+ operator bool() const;
+
+ private:
+ SectionInfo m_info;
+
+ std::string m_name;
+ Counts m_assertions;
+ bool m_sectionIncluded;
+ Timer m_timer;
+ };
+
+} // end namespace Catch
+
+#ifdef CATCH_CONFIG_VARIADIC_MACROS
+ #define INTERNAL_CATCH_SECTION( ... ) \
+ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
+#else
+ #define INTERNAL_CATCH_SECTION( name, desc ) \
+ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) )
+#endif
+
+// #included from: internal/catch_generators.hpp
+#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
+
+#include <vector>
+#include <string>
+#include <stdlib.h>
+
+namespace Catch {
+
+template<typename T>
+struct IGenerator {
+ virtual ~IGenerator() {}
+ virtual T getValue( std::size_t index ) const = 0;
+ virtual std::size_t size () const = 0;
+};
+
+template<typename T>
+class BetweenGenerator : public IGenerator<T> {
+public:
+ BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){}
+
+ virtual T getValue( std::size_t index ) const {
+ return m_from+static_cast<int>( index );
+ }
+
+ virtual std::size_t size() const {
+ return static_cast<std::size_t>( 1+m_to-m_from );
+ }
+
+private:
+
+ T m_from;
+ T m_to;
+};
+
+template<typename T>
+class ValuesGenerator : public IGenerator<T> {
+public:
+ ValuesGenerator(){}
+
+ void add( T value ) {
+ m_values.push_back( value );
+ }
+
+ virtual T getValue( std::size_t index ) const {
+ return m_values[index];
+ }
+
+ virtual std::size_t size() const {
+ return m_values.size();
+ }
+
+private:
+ std::vector<T> m_values;
+};
+
+template<typename T>
+class CompositeGenerator {
+public:
+ CompositeGenerator() : m_t
<TRUNCATED>