Esempio n. 1
0
        public void MissingMemberHandlingIgnore()
        {
            var    dto  = ValueDto.Create(true);
            string json = "{\"booleanValue\":true,\"missing\":false}";

            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);
        }
Esempio n. 2
0
        public void MetadataPropertyHandlingIgnore()
        {
            var    dto  = ValueDto.Create(true);
            string json = "{\"$ref\":\"xyzzy\",\"booleanValue\":true}";

            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);
        }
Esempio n. 3
0
        public void ExtraFieldSuccessJson()
        {
            var    before = ServiceResult.Success(1337);
            string json   = "{\"values\":1337,\"value\":1337,\"valuex\":1337}";
            var    after  = ServiceJsonUtility.FromJson <ServiceResult <int> >(json);

            after.Should().BeResult(before);
        }
Esempio n. 4
0
        public void ExtraFieldFailureJson()
        {
            var    before = ServiceResult.Failure(new ServiceErrorDto());
            string json   = "{\"values\":1337,\"error\":{},\"valuex\":1337}";
            var    after  = ServiceJsonUtility.FromJson <ServiceResult <int> >(json);

            after.Should().BeResult(before);
        }
Esempio n. 5
0
        public void MissingValueIntegerSuccessJson()
        {
            var          before = ServiceResult.Success(default(int?));
            const string json   = "{}";
            var          after  = ServiceJsonUtility.FromJson <ServiceResult <int?> >(json);

            after.Should().BeResult(before);
        }
Esempio n. 6
0
 private static IActionResult CreateActionResultFromError(ServiceErrorDto error)
 {
     return(new ContentResult
     {
         Content = ServiceJsonUtility.ToJson(error),
         ContentType = HttpServiceUtility.JsonMediaType,
         StatusCode = (int)(HttpServiceErrors.TryGetHttpStatusCode(error.Code) ?? HttpStatusCode.InternalServerError),
     });
 }
Esempio n. 7
0
        public void NullIntegerSuccessJson()
        {
            var    before = ServiceResult.Success(default(int?));
            string json   = ServiceJsonUtility.ToJson(before);

            json.Should().Be("{\"value\":null}");
            var after = ServiceJsonUtility.FromJson <ServiceResult <int?> >(json);

            after.Should().BeResult(before);
        }
Esempio n. 8
0
        public void IntegerFailureJson()
        {
            var    before = ServiceResult.Failure(new ServiceErrorDto("Xyzzy", "Xyzzy unexpected."));
            string json   = ServiceJsonUtility.ToJson(before);

            json.Should().Be("{\"error\":{\"code\":\"Xyzzy\",\"message\":\"Xyzzy unexpected.\"}}");
            var after = ServiceJsonUtility.FromJson <ServiceResult <int> >(json);

            after.Should().BeResult(before);
        }
Esempio n. 9
0
        public void IntegerEmptyFailureJson()
        {
            var    before = ServiceResult.Failure(new ServiceErrorDto());
            string json   = ServiceJsonUtility.ToJson(before);

            json.Should().Be("{\"error\":{}}");
            var after = ServiceJsonUtility.FromJson <ServiceResult <int?> >(json);

            after.Should().BeResult(before);
        }
Esempio n. 10
0
        public void IntegerSuccessJson()
        {
            var    before = ServiceResult.Success(1337);
            string json   = ServiceJsonUtility.ToJson(before);

            json.Should().Be("{\"value\":1337}");
            var after = ServiceJsonUtility.FromJson <ServiceResult <int> >(json);

            after.Should().BeResult(before);
        }
Esempio n. 11
0
        public void NoValueSuccessJson()
        {
            var    before = ServiceResult.Success();
            string json   = ServiceJsonUtility.ToJson(before);

            json.Should().Be("{}");
            var after = ServiceJsonUtility.FromJson <ServiceResult>(json);

            after.Should().BeResult(before);
        }
        private void SerializePreference(PreferenceDto dto, string expectedJson = null)
        {
            string json = ServiceJsonUtility.ToJson(dto);

            if (expectedJson != null)
            {
                json.Should().Be(expectedJson);
            }
            ServiceJsonUtility.FromJson <PreferenceDto>(json).Should().BeDto(dto);
        }
Esempio n. 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddSingleton <IFacilityGeneratorApi, FacilityGeneratorApi>();
            services.AddSingleton <ServiceHttpHandlerSettings>();
            services.AddSingleton <FacilityGeneratorApiHttpHandler>();

            services.AddMvc()
            .AddJsonOptions(options => ServiceJsonUtility.ApplyJsonSerializerSettings(options.SerializerSettings));
        }
Esempio n. 14
0
        /// <summary>
        /// Creates a test provider from the specified directory path.
        /// </summary>
        public ConformanceTestProvider(string testsFilePath)
        {
            var conformanceTests = new Dictionary <string, ConformanceTestInfo>();
            var testsInfo        = ServiceJsonUtility.FromJson <ConformanceTestsInfo>(File.ReadAllText(testsFilePath));

            foreach (var testInfo in testsInfo.Tests)
            {
                conformanceTests.Add(testInfo.Test, testInfo);
            }
            m_conformanceTests = conformanceTests;
        }
Esempio n. 15
0
 /// <summary>
 /// Reads a DTO from the specified HTTP content.
 /// </summary>
 protected override async Task <ServiceResult <object> > ReadHttpContentAsyncCore(Type dtoType, HttpContent content, CancellationToken cancellationToken)
 {
     try
     {
         using (var stream = await content.ReadAsStreamAsync().ConfigureAwait(false))
             using (var textReader = new StreamReader(stream))
                 return(ServiceResult.Success(ServiceJsonUtility.FromJsonTextReader(textReader, dtoType)));
     }
     catch (JsonException exception)
     {
         return(ServiceResult.Failure(HttpServiceErrors.CreateInvalidContent(exception.Message)));
     }
 }
Esempio n. 16
0
        public void DateParseHandlingNone()
        {
            var    dto  = ValueDto.Create("2016-10-21T15:31:00Z");
            string json = $"{{\"stringValue\":\"{dto.StringValue}\"}}";

            ServiceJsonUtility.ToJson(dto).Should().Be(json);
            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);

            var token = ServiceJsonUtility.FromJson <JToken>(json);

            token["stringValue"].Type.Should().Be(JTokenType.String);
            ServiceJsonUtility.ToJson(token).Should().Be(json);
        }
Esempio n. 17
0
        public void NullValueHandlingIgnore()
        {
            var    dto  = ValueDto.Create(default(bool?));
            string json = "{}";

            ServiceJsonUtility.ToJson(dto).Should().Be(json);
            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);

            var token = ServiceJsonUtility.FromJson <JToken>(json);

            token["stringValue"].Should().BeNull();
            ServiceJsonUtility.ToJson(token).Should().Be(json);
        }
Esempio n. 18
0
        public void CamelCase()
        {
            var    dto  = ValueDto.Create(true);
            string json = "{\"booleanValue\":true}";

            ServiceJsonUtility.ToJson(dto).Should().Be(json);
            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);

            var token = ServiceJsonUtility.FromJson <JToken>(json);

            token["booleanValue"].Type.Should().Be(JTokenType.Boolean);
            ServiceJsonUtility.ToJson(token).Should().Be(json);
        }
        private ServiceResult <T> Execute <T>(ServiceDto request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (m_testInfo == null)
            {
                return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest("Facility test name is missing; set the FacilityTest HTTP header.")));
            }

            string uncapitalize(string value) => value.Substring(0, 1).ToLowerInvariant() + value.Substring(1);

            string methodName = uncapitalize(request.GetType().Name.Substring(0, request.GetType().Name.Length - "RequestDto".Length));

            if (methodName != m_testInfo.Method)
            {
                return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest($"Unexpected method name for test {m_testInfo.Test}. expected={m_testInfo.Method} actual={methodName}")));
            }

            var actualRequest = (JObject)ServiceJsonUtility.ToJToken(request);

            if (!JToken.DeepEquals(m_testInfo.Request, actualRequest))
            {
                return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest($"Request did not match for test {m_testInfo.Test}. expected={ServiceJsonUtility.ToJson(m_testInfo.Request)} actual={ServiceJsonUtility.ToJson(actualRequest)}")));
            }

            if (m_testInfo.Error != null)
            {
                var error          = ServiceJsonUtility.FromJToken <ServiceErrorDto>(m_testInfo.Error);
                var errorRoundTrip = ServiceJsonUtility.ToJToken(error);
                if (!JToken.DeepEquals(m_testInfo.Error, errorRoundTrip))
                {
                    return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest($"Error round trip failed for test {m_testInfo.Test}. expected={ServiceJsonUtility.ToJson(m_testInfo.Error)} actual={ServiceJsonUtility.ToJson(errorRoundTrip)}")));
                }
                return(ServiceResult.Failure(error));
            }
            else
            {
                var response          = ServiceJsonUtility.FromJToken <T>(m_testInfo.Response);
                var responseRoundTrip = ServiceJsonUtility.ToJToken(response);
                if (!JToken.DeepEquals(m_testInfo.Response, responseRoundTrip))
                {
                    return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest($"Response round trip failed for test {m_testInfo.Test}. expected={ServiceJsonUtility.ToJson(m_testInfo.Response)} actual={ServiceJsonUtility.ToJson(responseRoundTrip)}")));
                }
                return(ServiceResult.Success(response));
            }
        }
Esempio n. 20
0
        public void CamelCaseExceptDictionaryKeys()
        {
            var dto = ValueDto.Create(new Dictionary <string, bool> {
                ["Key"] = true
            });
            string json = "{\"booleanMapValue\":{\"Key\":true}}";

            ServiceJsonUtility.ToJson(dto).Should().Be(json);
            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);

            var token = ServiceJsonUtility.FromJson <JToken>(json);

            token["booleanMapValue"].Type.Should().Be(JTokenType.Object);
            ServiceJsonUtility.ToJson(token).Should().Be(json);
        }
        private ServiceResult <T> Execute <T>(ServiceDto request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var methodName          = Uncapitalize(request.GetType().Name.Substring(0, request.GetType().Name.Length - "RequestDto".Length));
            var testsWithMethodName = m_tests.Where(x => x.Method == methodName).ToList();

            if (testsWithMethodName.Count == 0)
            {
                return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest($"No tests found for method {methodName}.")));
            }

            var actualRequest            = (JObject)ServiceJsonUtility.ToJToken(request);
            var testsWithMatchingRequest = testsWithMethodName.Where(x => JToken.DeepEquals(x.Request, actualRequest)).ToList();

            if (testsWithMatchingRequest.Count != 1)
            {
                return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest(
                                                 $"{testsWithMatchingRequest.Count} of {testsWithMethodName.Count} tests for method {methodName} matched request: " +
                                                 $"{ServiceJsonUtility.ToJson(actualRequest)} ({string.Join(", ", testsWithMethodName.Select(x => ServiceJsonUtility.ToJson(x.Request)))})")));
            }
            var testInfo = testsWithMatchingRequest[0];

            if (testInfo.Error != null)
            {
                var error          = ServiceJsonUtility.FromJToken <ServiceErrorDto>(testInfo.Error);
                var errorRoundTrip = ServiceJsonUtility.ToJToken(error);
                if (!JToken.DeepEquals(testInfo.Error, errorRoundTrip))
                {
                    return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest($"Error round trip failed for test {testInfo.Test}. expected={ServiceJsonUtility.ToJson(testInfo.Error)} actual={ServiceJsonUtility.ToJson(errorRoundTrip)}")));
                }
                return(ServiceResult.Failure(error));
            }
            else
            {
                var response          = ServiceJsonUtility.FromJToken <T>(testInfo.Response);
                var responseRoundTrip = ServiceJsonUtility.ToJToken(response);
                if (!JToken.DeepEquals(testInfo.Response, responseRoundTrip))
                {
                    return(ServiceResult.Failure(ServiceErrors.CreateInvalidRequest($"Response round trip failed for test {testInfo.Test}. expected={ServiceJsonUtility.ToJson(testInfo.Response)} actual={ServiceJsonUtility.ToJson(responseRoundTrip)}")));
                }
                return(ServiceResult.Success(response));
            }
        }
Esempio n. 22
0
        public void ArraySerialization()
        {
            var invalidRequest = new ServiceErrorDto {
                Code = ServiceErrors.InvalidRequest
            };
            var invalidResponse = new ServiceErrorDto {
                Code = ServiceErrors.InvalidResponse
            };
            var dto = ValueDto.Create(new List <ServiceErrorDto>
            {
                invalidRequest,
                invalidResponse,
            });
            string json = "{\"errorArrayValue\":[{\"code\":\"InvalidRequest\"},{\"code\":\"InvalidResponse\"}]}";

            ServiceJsonUtility.ToJson(dto).Should().Be(json);
            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);

            var token = ServiceJsonUtility.FromJson <JToken>(json);

            token["errorArrayValue"].Type.Should().Be(JTokenType.Array);
            ServiceJsonUtility.ToJson(token).Should().Be(json);
        }
Esempio n. 23
0
        public void DictionarySerialization()
        {
            var invalidRequest = new ServiceErrorDto {
                Code = ServiceErrors.InvalidRequest
            };
            var invalidResponse = new ServiceErrorDto {
                Code = ServiceErrors.InvalidResponse
            };
            var dto = ValueDto.Create(new Dictionary <string, ServiceErrorDto>
            {
                ["request"]  = invalidRequest,
                ["response"] = invalidResponse,
            });

            string json = "{\"errorMapValue\":{\"request\":{\"code\":\"InvalidRequest\"},\"response\":{\"code\":\"InvalidResponse\"}}}";

            ServiceJsonUtility.ToJson(dto).Should().Be(json);
            ServiceJsonUtility.FromJson <ValueDto>(json).Should().BeDto(dto);

            var token = ServiceJsonUtility.FromJson <JToken>(json);

            token["errorMapValue"].Type.Should().Be(JTokenType.Object);
            ServiceJsonUtility.ToJson(token).Should().Be(json);
        }
Esempio n. 24
0
 /// <summary>
 /// Creates HTTP content for the specified DTO.
 /// </summary>
 protected override HttpContent CreateHttpContentCore(object content, string mediaType) =>
 new DelegateHttpContent(mediaType ?? DefaultMediaType, stream => ServiceJsonUtility.ToJsonStream(content, stream));
Esempio n. 25
0
 /// <summary>
 /// Returns the DTO as JSON.
 /// </summary>
 public override string ToString()
 {
     return(ServiceJsonUtility.ToJson(this));
 }
Esempio n. 26
0
 /// <summary>
 /// Load tests from JSON.
 /// </summary>
 public static ConformanceTestsInfo FromJson(string json) => ServiceJsonUtility.FromJson <ConformanceTestsInfo>(json);
Esempio n. 27
0
 /// <summary>
 /// Returns the DTO as JSON.
 /// </summary>
 public override string ToString() => ServiceJsonUtility.ToJson(this);
        /// <summary>
        /// Runs the test with the specified name.
        /// </summary>
        public async Task <ConformanceTestResult> RunTestAsync(string testName, CancellationToken cancellationToken)
        {
            try
            {
                ConformanceTestResult failure(string message) => new ConformanceTestResult(testName, ConformanceTestStatus.Fail, message);

                var testInfo = m_testProvider.TryGetTestInfo(testName);

                var api = m_getApiForTest(testName);

                string capitalize(string value) => value.Substring(0, 1).ToUpperInvariant() + value.Substring(1);

                var methodInfo = typeof(IConformanceApi).GetMethod(capitalize(testInfo.Method) + "Async", BindingFlags.Public | BindingFlags.Instance);
                if (methodInfo == null)
                {
                    return(failure($"Missing API method for {testInfo.Method}"));
                }

                var requestJObject          = testInfo.Request;
                var requestDto              = ServiceJsonUtility.FromJToken(requestJObject, methodInfo.GetParameters()[0].ParameterType);
                var requestRoundTripJObject = ServiceJsonUtility.ToJToken(requestDto);
                if (!JToken.DeepEquals(requestJObject, requestRoundTripJObject))
                {
                    return(failure($"Request round trip failed. expected={ServiceJsonUtility.ToJson(requestJObject)} actual={ServiceJsonUtility.ToJson(requestRoundTripJObject)}"));
                }

                var task = (Task)methodInfo.Invoke(api, new[] { requestDto, cancellationToken });
                await task.ConfigureAwait(false);

                dynamic    result                  = ((dynamic)task).Result;
                ServiceDto actualResponseDto       = (ServiceDto)result.GetValueOrDefault();
                var        expectedResponseJObject = testInfo.Response;
                var        expectedErrorJObject    = testInfo.Error;
                if (actualResponseDto != null)
                {
                    var actualResponseJObject = (JObject)ServiceJsonUtility.ToJToken(actualResponseDto);

                    if (expectedErrorJObject != null)
                    {
                        return(failure($"Got valid response; expected error. expected={ServiceJsonUtility.ToJson(expectedErrorJObject)} actual={ServiceJsonUtility.ToJson(actualResponseJObject)}"));
                    }
                    if (!JToken.DeepEquals(expectedResponseJObject, actualResponseJObject))
                    {
                        return(failure($"Response JSON did not match. expected={ServiceJsonUtility.ToJson(expectedResponseJObject)} actual={ServiceJsonUtility.ToJson(actualResponseJObject)}"));
                    }
                    var responseType        = methodInfo.ReturnType.GetGenericArguments()[0].GetGenericArguments()[0];
                    var expectedResponseDto = (ServiceDto)ServiceJsonUtility.FromJToken(expectedResponseJObject, responseType);
                    if (!expectedResponseDto.IsEquivalentTo(actualResponseDto))
                    {
                        return(failure($"Response DTO did not match. expected={expectedResponseDto} actual={ServiceJsonUtility.ToJson(actualResponseDto)}"));
                    }
                }
                else
                {
                    ServiceErrorDto actualErrorDto     = result.Error;
                    var             actualErrorJObject = (JObject)ServiceJsonUtility.ToJToken(actualErrorDto);

                    if (expectedErrorJObject == null)
                    {
                        return(failure($"Got error; expected valid response. expected={ServiceJsonUtility.ToJson(expectedResponseJObject)} actual={ServiceJsonUtility.ToJson(actualErrorJObject)}"));
                    }
                    if (!JToken.DeepEquals(expectedErrorJObject, actualErrorJObject))
                    {
                        return(failure($"Error JSON did not match. expected={ServiceJsonUtility.ToJson(expectedErrorJObject)} actual={ServiceJsonUtility.ToJson(actualErrorJObject)}"));
                    }
                    var expectedErrorDto = ServiceJsonUtility.FromJToken <ServiceErrorDto>(expectedErrorJObject);
                    if (!expectedErrorDto.IsEquivalentTo(actualErrorDto))
                    {
                        return(failure($"Error DTO did not match. expected={expectedErrorDto} actual={actualErrorDto}"));
                    }
                }

                return(new ConformanceTestResult(testName, ConformanceTestStatus.Pass));
            }
            catch (Exception exception)
            {
                return(new ConformanceTestResult(testName, ConformanceTestStatus.Fail,
                                                 $"Unhandled exception {exception.GetType().FullName}: {exception.Message}"));
            }
        }
Esempio n. 29
0
        public void ValueAndErrorThrows()
        {
            const string json = "{\"value\":1337,\"error\":{}}";

            Assert.Throws <JsonSerializationException>(() => ServiceJsonUtility.FromJson <ServiceResult <int?> >(json));
        }